Search Results

Search found 134 results on 6 pages for 'modelform'.

Page 6/6 | < Previous Page | 2 3 4 5 6 

  • Django forms I cannot save picture file

    - by dana
    i have the model: class OpenCv(models.Model): created_by = models.ForeignKey(User, blank=True) first_name = models.CharField(('first name'), max_length=30, blank=True) last_name = models.CharField(('last name'), max_length=30, blank=True) url = models.URLField(verify_exists=True) picture = models.ImageField(help_text=('Upload an image (max %s kilobytes)' %settings.MAX_PHOTO_UPLOAD_SIZE),upload_to='jakido/avatar',blank=True, null= True) bio = models.CharField(('bio'), max_length=180, blank=True) date_birth = models.DateField(blank=True,null=True) domain = models.CharField(('domain'), max_length=30, blank=True, choices = domain_choices) specialisation = models.CharField(('specialization'), max_length=30, blank=True) degree = models.CharField(('degree'), max_length=30, choices = degree_choices) year_last_degree = models.CharField(('year last degree'), max_length=30, blank=True,choices = year_last_degree_choices) lyceum = models.CharField(('lyceum'), max_length=30, blank=True) faculty = models.ForeignKey(Faculty, blank=True,null=True) references = models.CharField(('references'), max_length=30, blank=True) workplace = models.ForeignKey(Workplace, blank=True,null=True) the form: class OpencvForm(ModelForm): class Meta: model = OpenCv fields = ['first_name','last_name','url','picture','bio','domain','specialisation','degree','year_last_degree','lyceum','references'] and the view: def save_opencv(request): if request.method == 'POST': form = OpencvForm(request.POST, request.FILES) # if 'picture' in request.FILES: file = request.FILES['picture'] filename = file['filename'] fd = open('%s/%s' % (MEDIA_ROOT, filename), 'wb') fd.write(file['content']) fd.close() if form.is_valid(): new_obj = form.save(commit=False) new_obj.picture = form.cleaned_data['picture'] new_obj.created_by = request.user new_obj.save() return HttpResponseRedirect('.') else: form = OpencvForm() return render_to_response('opencv/opencv_form.html', { 'form': form, }, context_instance=RequestContext(request)) but i don't seem to save the picture in my database... something is wrong, and i can't figure out what :(

    Read the article

  • Query distinct list of choices for Django form with App Engine Datastore

    - by Brian
    I've been trying to figure this out for hours across a couple of days, and can not get it to work. I've been everywhere. I'll continue trying to figure it out, but was hoping for a quicker solution. I'm using App Engine datastore + Django. Using a query in a view and custom forms, I was able to get a list to the form but then I was not able to post. I have been trying to figure out how to dynamically add the choices as part of the Django form... I've tried various ways with no success. Help! Below are the two models. I'd like to get a distinct list of address_id to show in the location field in InfoForm. This fields could (and maybe should) be named the same, but I thought it'd be easier if they were named different. class Info(db.Model): user = db.UserProperty() location = db.StringProperty() info = db.StringProperty() created = db.DateTimeProperty(auto_now_add=True) modified = db.DateTimeProperty(auto_now=True) class Locations(db.Model): user = db.UserProperty() address_id = db.StringProperty() address = db.StringProperty() class InfoForm(djangoforms.ModelForm): info = forms.ChoiceField(choices=INFO_CHOICES) location = forms.ChoiceField() class Meta: model = Info exclude = ['user','created','modified']

    Read the article

  • Cannot get MEDIA_URL from Django widget's template

    - by Eric
    Hi folks, I am a new Djangoer, and figuring out how to build custom widget, my problem is cannot get the MEDIA_URL in my widget's template, while the form use MySelectWidget able to get the MEDIA_URL itself. # #plus_sign.html # <a href="" class="" id="id_{{ field }}"> <img src="{{ MEDIA_URL }}images/plus_sign.gif" width="10" height="10" alt="Add"/> </a> *^ cannot load the {{ MEDIA_URL}} to this widget's template, and therefore I can't load the .gif image properly. :(* # #custom_widgets.py # from django import forms class MySelectMultiple(forms.SelectMultiple): def render(self, name, *args, **kwargs): html = super(MySelectMultiple, self).render(name, *args, **kwargs) plus = render_to_string("plus_sign.html", {'field': name}) return html+plus # #forms.py # from django import forms from myapp.custom_widgets.py import MySelectMultiple class MyForm(forms.ModelForm): contacts = forms.ModelMultipleChoiceField(Contact.objects, required=False, widget=MySelectMultiple) # #views.py # def AddContacts(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): cd = form.cleaned_data new = form.save() return HttpResponseRedirect('/addedContact/') else: form = MyForm() return render_to_response('shop/my_form.html', {'form': form}, context_instance=RequestContext(request)) # #my_form.html # {% extends "base.html" %} {% block content %} {{ form.contacts }} {% endblock %} Please let me know how can I load the widget's image properly. Thank you so much for all responses.

    Read the article

  • Django Save Incomplete Progress on Form

    - by jimbob
    I have a django webapp with multiple users logging in and fill in a form. Some users may start filling in a form and lack some required data (e.g., a grant #) needed to validate the form (and before we can start working on it). I want them to be able to fill out the form and have an option to save the partial info (so another day they can log back in and complete it) or submit the full info undergoing validation. Currently I'm using ModelForm for all the forms I use, and the Model has constraints to ensure valid data (e.g., the grant # has to be unique). However, I want them to be able to save this intermediary data without undergoing any validation. The solution I've thought of seems rather inelegant and un-django-ey: create a "Save Partial Form" button that saves the POST dictionary converts it to a shelf file and create a "SavedPartialForm" model connecting the user to partial forms saved in the shelf. Does this seem sensible? Is there a better way to save the POST dict directly into the db? Or is an add-on module that does this partial-save of a form (which seems to be a fairly common activity with webforms)? My biggest concern with my method is I want to eventually be able to do this form-autosave automatically (say every 10 minutes) in some ajax/jquery method without actually pressing a button and sending the POST request (e.g., so the user isn't redirected off the page when autosave is triggered). I'm not that familiar with jquery and am wondering if it would be possible to do this.

    Read the article

  • [Django] One single page to create a Parent object and its associated child objects

    - by ahmoo
    Hi all, This is my very first post on this awesome site, from which I have been finding answers to a handful of challenging questions. Kudos to the community! I am new to the Django world, so am hoping to find help from some Django experts here. Thanks in advance. Item model: class Item(models.Model): name = models.CharField(max_length=50) ItemImage model: class ItemImage(models.Model): image = models.ImageField(upload_to=get_unique_filename) item = models.ForeignKey(Item, related_name='images') As you can tell from the model definitions above, every Item object can have many ItemImage objects. My requirements are as followings: A single web page that allows users to create a new Item while uploading the images associated with the Item. The Item and the ItemImages objects should be created in the database all together, when the "Save" button on the page is clicked. I have created a variable in a custom config file, called NUMBER_OF_IMAGES_PER_ITEM. It is based on this variable that the system generates the number of image fields per item. Questions: What should the forms and the template be like? Can ModelForm be used to achieve the requirements? For the view function, what do I need to watch out other than making sure to save Item before ItemImage objects?

    Read the article

  • Django: What's an awesome plugin to maintain images in the admin?

    - by meder
    I have an articles entry model and I have an excerpt and description field. If a user wants to post an image then I have a separate ImageField which has the default standard file browser. I've tried using django-filebrowser but I don't like the fact that it requires django-grappelli nor do I necessarily want a flash upload utility - can anyone recommend a tool where I can manage image uploads, and basically replace the file browse provided by django with an imagepicking browser? In the future I'd probably want it to handle image resizing and specify default image sizes for certain article types. Edit: I'm trying out adminfiles now but I'm having issues installing it. I grabbed it and added it to my python path, added it to INSTALLED_APPS, created the databases for it, uploaded an image. I followed the instructions to modify my Model to specify adminfiles_fields and registered but it's not applying in my admin, here's my admin.py for articles: from django.contrib import admin from django import forms from articles.models import Category, Entry from tinymce.widgets import TinyMCE from adminfiles.admin import FilePickerAdmin class EntryForm( forms.ModelForm ): class Media: js = ['/media/tinymce/tiny_mce.js', '/media/tinymce/load.js']#, '/media/admin/filebrowser/js/TinyMCEAdmin.js'] class Meta: model = Entry class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = { 'slug': ['title'] } class EntryAdmin( FilePickerAdmin ): adminfiles_fields = ('excerpt',) prepopulated_fields = { 'slug': ['title'] } form = EntryForm admin.site.register( Category, CategoryAdmin ) admin.site.register( Entry, EntryAdmin ) Here's my Entry model: class Entry( models.Model ): LIVE_STATUS = 1 DRAFT_STATUS = 2 HIDDEN_STATUS = 3 STATUS_CHOICES = ( ( LIVE_STATUS, 'Live' ), ( DRAFT_STATUS, 'Draft' ), ( HIDDEN_STATUS, 'Hidden' ), ) status = models.IntegerField( choices=STATUS_CHOICES, default=LIVE_STATUS ) tags = TagField() categories = models.ManyToManyField( Category ) title = models.CharField( max_length=250 ) excerpt = models.TextField( blank=True ) excerpt_html = models.TextField(editable=False, blank=True) body_html = models.TextField( editable=False, blank=True ) article_image = models.ImageField(blank=True, upload_to='upload') body = models.TextField() enable_comments = models.BooleanField(default=True) pub_date = models.DateTimeField(default=datetime.datetime.now) slug = models.SlugField(unique_for_date='pub_date') author = models.ForeignKey(User) featured = models.BooleanField(default=False) def save( self, force_insert=False, force_update= False): self.body_html = markdown(self.body) if self.excerpt: self.excerpt_html = markdown( self.excerpt ) super( Entry, self ).save( force_insert, force_update ) class Meta: ordering = ['-pub_date'] verbose_name_plural = "Entries" def __unicode__(self): return self.title Edit #2: To clarify I did move the media files to my media path and they are indeed rendering the image area, I can upload fine, the <<<image>>> tag is inserted into my editable MarkItUp w/ Markdown area but it isn't rendering in the MarkItUp preview - perhaps I just need to apply the |upload_tags into that preview. I'll try adding it to my template which posts the article as well.

    Read the article

  • Django, want to upload eather image (ImageField) or file (FileField)

    - by Serg
    I have a form in my html page, that prompts user to upload File or Image to the server. I want to be able to upload ether file or image. Let's say if user choose file, image should be null, and vice verso. Right now I can only upload both of them, without error. But If I choose to upload only one of them (let's say I choose image) I will get an error: "Key 'attachment' not found in <MultiValueDict: {u'image': [<InMemoryUploadedFile: police.jpg (image/jpeg)>]}>" models.py: #Description of the file class FileDescription(models.Model): TYPE_CHOICES = ( ('homework', 'Homework'), ('class', 'Class Papers'), ('random', 'Random Papers') ) subject = models.ForeignKey('Subjects', null=True, blank=True) subject_name = models.CharField(max_length=100, unique=False) category = models.CharField(max_length=100, unique=False, blank=True, null=True) file_type = models.CharField(max_length=100, choices=TYPE_CHOICES, unique=False) file_uploaded_by = models.CharField(max_length=100, unique=False) file_name = models.CharField(max_length=100, unique=False) file_description = models.TextField(unique=False, blank=True, null=True) file_creation_time = models.DateTimeField(editable=False) file_modified_time = models.DateTimeField() attachment = models.FileField(upload_to='files', blank=True, null=True, max_length=255) image = models.ImageField(upload_to='files', blank=True, null=True, max_length=255) def __unicode__(self): return u'%s' % (self.file_name) def get_fields(self): return [(field, field.value_to_string(self)) for field in FileDescription._meta.fields] def filename(self): return os.path.basename(self.image.name) def category_update(self): category = self.file_name return category def save(self, *args, **kwargs): if self.category is None: self.category = FileDescription.category_update(self) for field in self._meta.fields: if field.name == 'image' or field.name == 'attachment': field.upload_to = 'files/%s/%s/' % (self.file_uploaded_by, self.file_type) if not self.id: self.file_creation_time = datetime.now() self.file_modified_time = datetime.now() super(FileDescription, self).save(*args, **kwargs) forms.py class ContentForm(forms.ModelForm): file_name =forms.CharField(max_length=255, widget=forms.TextInput(attrs={'size':20})) file_description = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':25})) class Meta: model = FileDescription exclude = ('subject', 'subject_name', 'file_uploaded_by', 'file_creation_time', 'file_modified_time', 'vote') def clean_file_name(self): name = self.cleaned_data['file_name'] # check the length of the file name if len(name) < 2: raise forms.ValidationError('File name is too short') # check if file with same name is already exists if FileDescription.objects.filter(file_name = name).exists(): raise forms.ValidationError('File with this name already exists') else: return name views.py if request.method == "POST": if "upload-b" in request.POST: form = ContentForm(request.POST, request.FILES, instance=subject_id) if form.is_valid(): # need to add some clean functions # handle_uploaded_file(request.FILES['attachment'], # request.user.username, # request.POST['file_type']) form.save() up_f = FileDescription.objects.get_or_create( subject=subject_id, subject_name=subject_name, category = request.POST['category'], file_type=request.POST['file_type'], file_uploaded_by = username, file_name=form.cleaned_data['file_name'], file_description=request.POST['file_description'], image = request.FILES['image'], attachment = request.FILES['attachment'], ) return HttpResponseRedirect(".")

    Read the article

  • Difficulty adding widgets to django form.

    - by codingJoe
    I have a django app that tracks activities that can benefit a classroom. Using the django examples, I was able to build a form to enter this data. But when I try to add widgets to that form, things get tricky. What I want is a calendar widget that lets the user enter the 'activity_date' field using a widget. If I use Admin interface. The AdminDateWidget works fine. however. This particular user isn't allowed access to the admin interface so I need a different way to present this widget. Also I couldn't figure out how to make the bring the admin widget over into non-admin pages. So I tried a custom widget. This is the first custom widget I've built, so I'm not quite sure what is supposed to be going on here. Any Expert Advice? How do I get my date widget to work? # The Model class Activity(models.Model): activity_date = models.DateField() activity_type = models.CharField(max_length=50, choices=ACTIVITY_TYPES) activity_description = models.CharField(max_length=200) activity_duration= models.DecimalField(decimal_places=2, max_digits=4) est_attendance = models.IntegerField("Estimated attendance") # The Form class ActivityForm(forms.ModelForm): # The following line causes lockup if enabled. # With the DateTimeWidget removed, the form functions correctly except that there is no widget. #activity_date = forms.DateField(label=_('Date'), widget=DateTimeWidget) ##!!! Point of Error !!! class Meta: model = Activity fields = ('activity_date', 'activity_type', 'activity_description', 'activity_duration', 'est_attendance') def __init__(self, *args, **kwargs): super(ActivityForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) edit_aid = kwargs.get('edit_aid', False) # On a different approach, the following also didn't work. #self.fields['activity_date'].widget = widgets.AdminDateWidget() # The Widget # Example referenced: http://djangosnippets.org/snippets/391/ calbtn = u""" <button id="calendar-trigger">...</button> <img src="%s/site_media/images/icon_calendar.gif" alt="calendar" id="%s_btn" style="cursor: pointer; border: 1px solid #8888aa;" title="Select date and time" onmouseover="this.style.background='#444444';" onmouseout="this.style.background=''" /> <script type="text/javascript"> Calendar.setup({ trigger : "calendar-trigger", inputField : "%s" }); </script>""" class DateTimeWidget(forms.widgets.TextInput): dformat = '%Y-%m-%d %H:%M' def render(self, name, value, attrs=None): print "DTWgt render name=%s, value=%s" % name, value if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': try: final_attrs['value'] = \ force_unicode(value.strftime(self.dformat)) except: final_attrs['value'] = \ force_unicode(value) if not final_attrs.has_key('id'): final_attrs['id'] = u'%s_id' % (name) id = final_attrs['id'] jsdformat = self.dformat #.replace('%', '%%') cal = calbtn % (settings.MEDIA_URL, id, id, jsdformat, id) a = u'<input%s />%s' % (forms.util.flatatt(final_attrs), cal) print "render return %s " % a return mark_safe(a) def value_from_datadict(self, data, files, name): print "DTWgt value_from_datadict" dtf = forms.fields.DEFAULT_DATETIME_INPUT_FORMATS empty_values = forms.fields.EMPTY_VALUES value = data.get(name, None) if value in empty_values: return None if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): return datetime.datetime(value.year, value.month, value.day) for format in dtf: try: return datetime.datetime(*time.strptime(value, format)[:6]) except ValueError: continue return None

    Read the article

  • Google App Engine + Form Validation

    - by Iwona
    Hi, I would like to do google app engine form validation but I dont know how to do it? I tried like this: from google.appengine.ext.db import djangoforms from django import newforms as forms class SurveyForm(forms.Form): occupations_choices = ( ('1', ""), ('2', "Undergraduate student"), ('3', "Postgraduate student (MSc)"), ('4', "Postgraduate student (PhD)"), ('5', "Lab assistant"), ('6', "Technician"), ('7', "Lecturer"), ('8', "Other" ) ) howreach_choices = ( ('1', ""), ('2', "Typed the URL directly"), ('3', "Site is bookmarked"), ('4', "A search engine"), ('5', "A link from another site"), ('6', "From a book"), ('7', "Other") ) boxes_choices = ( ("des", "Website Design"), ("svr", "Web Server Administration"), ("com", "Electronic Commerce"), ("mkt", "Web Marketing/Advertising"), ("edu", "Web-Related Education") ) name = forms.CharField(label='Name', max_length=100, required=True) email = forms.EmailField(label='Your Email Address:') occupations = forms.ChoiceField(choices=occupations_choices, label='What is your occupation?') howreach = forms.ChoiceField(choices=howreach_choices, label='How did you reach this site?') # radio buttons 1-5 rating = forms.ChoiceField(choices=range(1,6), label='What is your occupation?', widget=forms.RadioSelect) boxes = forms.ChoiceField(choices=boxes_choices, label='Are you involved in any of the following? (check all that apply):', widget=forms.CheckboxInput) comment = forms.CharField(widget=forms.Textarea, required=False) And I wanted to display it like this: template_values = { 'url' : url, 'url_linktext' : url_linktext, 'userName' : userName, 'item1' : SurveyForm() } And I have this error message: Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp_init_.py", line 515, in call handler.get(*groups) File "C:\Program Files\Google\google_appengine\demos\b00213576\main.py", line 144, in get self.response.out.write(template.render(path, template_values)) File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\template.py", line 143, in render return t.render(Context(template_dict)) File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\template.py", line 183, in wrap_render return orig_render(context) File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 168, in render return self.nodelist.render(context) File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 705, in render bits.append(self.render_node(node, context)) File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 718, in render_node return(node.render(context)) File "C:\Program Files\Google\google_appengine\lib\django\django\template\defaulttags.py", line 209, in render return self.nodelist_true.render(context) File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 705, in render bits.append(self.render_node(node, context)) File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 718, in render_node return(node.render(context)) File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 768, in render return self.encode_output(output) File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 757, in encode_output return str(output) File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\util.py", line 26, in str return self.unicode().encode(settings.DEFAULT_CHARSET) File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\forms.py", line 73, in unicode return self.as_table() File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\forms.py", line 144, in as_table return self._html_output(u'%(label)s%(errors)s%(field)s%(help_text)s', u'%s', '', u'%s', False) File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\forms.py", line 129, in _html_output output.append(normal_row % {'errors': bf_errors, 'label': label, 'field': unicode(bf), 'help_text': help_text}) File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\forms.py", line 232, in unicode value = value.str() File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\util.py", line 26, in str return self.unicode().encode(settings.DEFAULT_CHARSET) File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\widgets.py", line 246, in unicode return u'\n%s\n' % u'\n'.join([u'%s' % w for w in self]) File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\widgets.py", line 238, in iter yield RadioInput(self.name, self.value, self.attrs.copy(), choice, i) File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\widgets.py", line 212, in init self.choice_value = smart_unicode(choice[0]) TypeError: 'int' object is unsubscriptable Do You have any idea how I can do this validation in different case? I have tried to do it using this kind of: class ItemUserAnswer(djangoforms.ModelForm): class Meta: model = UserAnswer But I dont know how to add extra labels to this form and it is displayed in one line. Do You have any suggestions? Thanks a lot as it making me crazy why it is still not working:/

    Read the article

< Previous Page | 2 3 4 5 6