FAQ Database Discussion Community


Display image from ImageField by means of form

django,django-models,django-forms,django-uploads
prelude: Here's the simpliest way to display an ImageField. Lets assume I have 10 fields in my form and I don't wanna iterate over all of them in template.html just to check if it's an imageField and display it in a different way. I want to handle it via form...

Correct

django,django-forms,django-templates,django-views
I have been having some trouble getting a Django SessionWizardView to submit data to my database and I am trying to isolate the issue. I note from the Form documentation As well as its elements, a form must specify two things: where: the URL to which the data corresponding to...

Replace ArrayField for several fields from other models in django-admin

django,django-models,django-forms,django-admin
I want to store model fields as array of foreign keys to other atomic-Models. It makes model more flexible: I can add/remove/inherit(if it's tree node) any of predefined properties without programming. Let's start with atomic-Models. It contain some classified properties. class Liquid(models.Model): volume = models.DecimalField(max_digits=12, decimal_places=6) class Granular(models.Model): weight =...

Return error message to custom form in Django

python,django,forms,django-models,django-forms
The fields in my custom registration form looks something like this: <div class="form-group"> {{ form.email.errors }} label for="{{form.email.id_for_label}}"> <b>Email</b> </label> {{ form.email }} </div> My views.py looks like this: def registration(request): registered = False if request.method == 'POST': form = RegForm(data=request.POST) if form.is_valid(): email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] password...

How to make a RadioSelect non manditory and remove default option in a ModelForm?

django,django-models,django-forms
EDIT The reason my question is different to the possible duplicate is because that does not address the issue of making it non manditory while also removing the default option "-------" I want to make a RadioSelect survey question non mandatory in a forms.ModelForm To use RadioSelect I am...

Django form for querying database. Is form.py needed and how to leave fields empty for query?

forms,validation,python-3.x,django-forms
I would like to have an input form where a user inputs either an incident_id or a equipment_id or both. The problem I have now is for example, if I fill in incident_id and leave equipment_id blank, the query will return no hits even when incident_id finds a match, because...

ManagementForm Data is Missing When Using Formset Prefix

python,django,django-forms,django-views,formset
Anyone know why this raise a ManagementForm Data is Missing when I use Formset Prefix? From Shell >>> from django import forms >>> from django.forms.formsets import formset_factory >>> >>> class CheckBox (forms.Form): ... overwrite = forms.BooleanField (required = False) ... >>> >>> data = { ... 'form-TOTAL_FORMS': '2', ... 'form-INITIAL_FORMS':...

User specific data in automatic generated forms

django,django-forms,django-templates
My code is pretty simple and straight forward. These are my forms class LearningObjectiveForm( ModelForm ): class Meta: model = LearningObjective fields = ( 'learning_objective', 'topic', ) this is a snippet from my template <form method="POST" action="."> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="Speichern"/> </form> this...

Django Form Submit Update HTML

python,html,django,django-forms
Instead of redirecting to a thank you page I would like to update the html of the current contact page after the response redirect. For example, when the user hits the submit button they are brought back to the same page, however, the page now has a tag thanking them....

DateField — “enter a valid date” message

django,django-forms,django-views
I'm a bit confused as why it keeps returning the 'enter a valid date' message. Is it my formatting? I've tried different combinations of %m-%d-%Y, but still no luck. models.py class DeliveryDate(models.Model): cart = models.ForeignKey('Cart', null=True, blank=True) date = models.DateField() def __str__(self): return str(self.cart.id) return self.date views.py def add_delivery_date(request): the_id...

How to Check for Unique Data in Django Form?

python,django,forms,django-forms,formset
I'm following the examples posted on Django Formset Documents regarding custom formset validation with a slight modification. I found a flaw in the example but unsure how to fix it. Is there a way to check for uniqueness in the data if the 1 of 3 input field is not...

How to check field type in django form?

django,django-forms
I'm writing a template for django form. I would like to determine the type of field when iterating over all form fields (type attribute inside input tag). When I write {{ field }} it gives me <input id="id_file" name="file" type="file"> and it's ok, but I would like to override input...

Django. UserCreationForm not rendering correctly

python,django,django-forms
For me this is weird, maybe it isn't and I'm missing something obvious: forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class formRegistro(UserCreationForm): class Meta: model = User fields = ("first_name", "last_name", "email", "username", "password1", "password2") widgets = { 'first_name': forms.TextInput(attrs={'class':'form-control'}), 'last_name': forms.TextInput(attrs={'class':'form-control'}), 'email': forms.TextInput(attrs={'class':'form-control'}),...

Form Widget for CommaSeparatedIntegerField

django,django-models,django-forms
I have a question in a form in which someone can select multiple options from the given set. Like so: What is A? B C D Here, the person filling the form can select any combination of the 3 options. For example, B, C, BC, BCD I am trying to...

Pass json and deserialize form in django

json,django,django-forms,django-serializer
The issue is next: I send some post data with ajax to server. This data looks like: data = { form : $(this).serialize(), some_array: [2,3,4,1] } How to get form object in django? request.POST['form'] returns a string with a form. I'm trying to use import json library. But, when I...

Django save form with User foreign key

django,django-forms
I am probably burt out because I don't see the problem here, and I'm sure it's something trivial. I have a model form who's model is Profile (Profile is user through many forms on the site, works normally). In this particular form, I'm using only one field. When I try...

Setting an example answer in a text input field

python,django,django-forms
I'm trying to set a default value in a text input field which gives the user an example of what to enter. This should be greyed-out and should disappear as soon as they start typing. I've tried setting an initial value but this isn't automatically replaced when the user starts...

Render a template instead a success_url in form_valid with FormView django

django,django-forms,django-class-based-views
as the title says: I need to render a template after submit a form, this form is handled with FormView with the method form_valid. With the method post I can render a template afer submit it but maybe with form_valid I can do it in a cleanest way. How can...

Django: set_password isn't hashing passwords?

python,django,hash,django-forms,django-views
I've made a custom User registration form/view in Django so that I can include an additional user attributes through a different model. I've used set_password to set the password of the newly created user to the password entered in the form, but I've found that the passwords that are saved...

Form fields are not shown in django templates, only submit button

python,django,django-forms
Hello everybody!!! I have a problem with forms, below is the code, any help will be appreciated... views.py def my_registration_view(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): user = User.objects.create_user(username=form.cleaned_data['username'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], email=form.cleaned_data['email'], password=form.cleaned_data['password'],) user.save() return HttpResponseRedirect(reverse('profile', args=[user.id])) else: return...

Django: Form check if field has no error

python,django,django-forms
I want to add the has-success if a field has no error. What I tried: <div class="form-group{% if field.errors %} has-error{% elif not field.errors} has-success{% endif %}"> But it is not working. If the field has errors the has-error is added (this part works). BUT not field.errors is also true...

django rest_auth extend User with UserProfile

django-models,django-forms,django-rest-framework
I'm on django 1.7.5 with allauth and rest_auth. Success on create a custom SignupForm with new field, but can't get value stored at signup time. company_name is the field that is ignored, first and last name are stored... 1) rest_auth/forms.py class SLCustomSignupForm(forms.Form): """ in settings ACCOUNT_SIGNUP_FORM_CLASS='rest_auth.forms.SLCustomSignupForm' """ first_name = forms.CharField(max_length=30,...

How to pass attrs to forms.DateField?

django,django-forms
In forms.py I have this: date_of_birth = forms.DateField(widget=extras.SelectDateWidget( years=range(datetime.date.today().year - 15, 1920, -1))) to create a select. I want to pass to it, attrs={'class': 'form-control'} I tried in different ways but with no results....

DjangoRestFramework - How to pass a serializer form to the frontend?

django,angularjs,django-models,django-forms,django-rest-framework
I'm using the DjangoRestFramework. I have a UserSerialzer in my serializers.py file: from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email', ) This is my urls.py file: urlpatterns = [ url(r'^$', views.HomePageView.as_view()), url(r'^users$', views.user_list.as_view()), url(r'^users/(?P<pk>[0-9]+)$', views.user_detail.as_view()), ] and this is my views.py file:...

Adding another model to a form?

django,django-forms,django-views
I'm trying to setup a form which draws in fields from 2 models. I tired to add the model's together like below but keep getting an error. model = Server, Tag The backend admin picks up the relationship between the 2 models and I can update it from the backend...

In Django-admin, how to show foreignkey's foreignkey in the same page?

python,django,django-models,django-forms,django-admin
I got a Paper and its foreignkey ChoiceQuestion model, and its foreignkey Choices model. I'm wondering if django-admin show Choices in the change-form page of Paper. class Paper(models.Model): """pagers""" # ... class ChoiceQuestion(models.Model): paper = models.ForeignKey(Paper) name = models.CharField(max_length=256) class Choice(models.Model): choice_question = models.ForeignKey(ChoiceQuestion) text = models.CharField(max_length=256) normally we can...

django admin filter data after selection

django,django-forms,django-admin
In the admin, would it be possible to filter selection from a live input in a field: class ReadtToday(models.Model): author = models.ForeignKey(Authors) # field 1) book = models.OneToOneField(Books, related_name='bookofday') # field 2) Now in the admin for 1) and 2) got a list of all of them, how I should...

Replacing ManyToMany-Relation with ModelChoiceField

python,django,django-models,django-forms
I'm stuck trying to render a ManyToMany-Relation as a ModelChoiceField instead of a ModelMultipleChoiceField. So I tried the following (simplified): models.py: class Project(models.Model): name = models.CharField(max_length=20, unique=True) manager = models.ManyToManyField(User, related_name="manager_related") forms.py: class ProjectForm(forms.ModelForm): manager = forms.ModelChoiceField(queryset=User.objects.all(), empty_label='Choose Manager', required=False) class Meta: model = Project fields = ['name', 'manager'] The...

Django Form Wizard With Fieldsets

django,forms,django-forms,django-formwizard
I'm using the Django Form Wizard (From 1.8 located in formtools) to split a form into multiple steps. This works fine and all. But I'm interested in making fieldsets in my form and splitting my form into multiple different groups on each page. A good example would be this. I...

Persistence of Redirect URL when redirecting after a POST and passing data

django,django-forms,http-post,http-redirect
Upon successful submission of a form, I redirect to a "success" page that display a 'thank you' message along with some information about the submission. To do this, I put the POST data in session, Redirect to the appropriate URL, and then render the template using the session data. But,...

Django forms: How do I make it necessary to fill out one field but not possible to fill out both?

python,django,django-forms
I want to have an option to link to a file OR upload a file. Obviously you can't do both. How can I implement this?

Show related model info in Django form

python,django,django-forms
Say, for example, I have two models: class Person: name = models.CharField(max_length=20) address = models.CharField(max_length=20) class PhoneNumber: person = models.ForeignKey(Person) number = models.CharField(max_length=20) So, when a user is going to modify a PhoneNumber, I'd like to show, in the form, the address of the person. I'm doing the editing through...

Complex multi-model object creation with CreateView in Django

django,django-forms,formset,inline-formset
I have a setup where the user can define products (like 'MacBook Pro'). Each Product gets "instantiated" to create a physical item (ProductInstance) which gets a serial number. Pretty simple so far. I want the user to be able to define other types of unique identifiers, like MAC addresses, VIN,...

Django - How do form template tags work?

django,django-forms,django-templates
This is a simple question, but I can't find the answer. The django docs show the following example for calling a form in template just using {{ form }}: <form action="/your-name/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> This doesn't fully explain how the {{...

django override model save() method

django,django-models,django-forms,django-views
I want to get request as a parameter in save() method. models.py class Profile(models.Model): uuid = UUIDField(auto=True) user = models.ForeignKey(User) name = models.CharField(max_length=128) dob = models.DateField() class Meta: db_table = 'profile' def save(self,*args,**kwargs): if not self.pk: self.user_id = 2 #here i need request.user instead of 2 super(Profile,self).save(*args,**kwargs) forms.py class ProfileForm(forms.ModelForm):...

authentication in django with extending one-to-one relationship

django,django-forms,django-views,django-authentication,django-login
i've made authentication system that user can login based on User Models. In User Models, it's extended with one-to-one relationship. When i insert login with username and password, it works. But when i insert login with username, password, and hak_akses. It doesn't work properly. I want authentication can work with...

'unicode' object has no attribute 'get' Django beginner

django,python-2.7,django-forms
I have a very simple code in Django and I've this error which comes everytime. The content of the form is well saved in the model but this error shows up when I want to use reverse: 'unicode' object has no attribute 'get' There is my code: views.py: class PastaView(View):...

Form not showing in html - django

python,django,django-models,django-forms,modelform
I have a model that extends the User model in django, that model is a userprofile, I'll use to asociate aditional information to User model. I have the model, the form, the view, the url and the html, but the html is not showing the fiels, only shows the submit...

Django does not render my forms' fields

django,django-models,django-forms,django-templates,django-views
I have this model in models.py: class Life_events(models.Model): patient = models.ForeignKey(Demographic) HSCT_date = models.DateField('HSCT date',null=True,blank=True) HSCT_outcome = models.CharField('HSCT outcome',max_length=100, null=True, blank=True) partaker_in_clinical_trial= models.CharField('Partaker in clinical trial',max_length=200, null=True, blank=True) date_of_input= models.DateField(null=True,blank=True) def __str__(self): return str(self.patient) My forms.py contains: class LifeEventsForm(forms.Form): def __init__(self,...

How to Display Django form errors using AngularJS?

angularjs,django,validation,django-forms
I'm working with the built-in Django User model. This is my serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email', ) This is my view: class HomePageView(TemplateView): template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) return context class user_list(APIView): #called when I go to...

Display multiple rows as grid in django template

django,twitter-bootstrap,django-forms
I need to display a few rows from database to user. For example I have table Fruits with columns: name, color, price. So I want my form generate the html like compact grid view: <table> <tr> <th>Name</th> <th>Color</th> <th>Price</th> </tr> <tr> <td>apples</td> <td>yellow</td> <td>100$</td> </tr> <tr> <td>pears</td> <td>green</td> <td>$80</td> </tr>...

django_countries does not display in the form on template

python,django,django-forms,django-countries
I used {{ form }} as seen here template.html <h4>Change your details</h4><br> <form id="edit_form" method='post'> {% csrf_token %} {{ form }} <div class='section group'> <input id="update_details_button" type='submit' class='btn btn-primary wide' value='Change'/> </div> </form> views.py def user_view(request, is_admin): user = request.user form = myForm() if request.method == 'POST' and is_admin: form...

form.cleaned_data returns empty set

django,forms,django-models,django-forms
I've got a form: class OrderForm(forms.Form): delivery_time = models.CharField(max_length=100) address_city = models.CharField(max_length=40) address_street = models.CharField(max_length=40) address_building = models.CharField(max_length=40) Here's my view: def submit(request): args = {} args['form'] = OrderForm() if request.POST: order_form = OrderForm(request.POST) if order_form.is_valid(): user = request.user address_city = order_form.cleaned_data.get('address_city') address_street = order_form.cleaned_data.get('address_street')...

The right way to send some data alongside with form

ajax,django,django-forms
I have a page of user oders, where displayed products in cart and a form with fields like: address, mobile number etc. I catch submit with jquery, and I need to send next data to server: my form and a dictionary {id_of_product:choosen_ammount}. I need to send that dictionary, because I...

How to set User-based form field choices in a django ModelForm (with django-allauth)

django,django-models,django-forms,django-allauth
I'm using Django 1.8 and django-allauth. I have a simple form with a dropdown menu that allows my Users to choose a Character model. I have a UserCharacter model that looks like this: class UserCharacter(models.Model): user = models.ForeignKey(User) character = models.ForeignKey(Character) is_default = models.BooleanField(default=False) In my main Form I'm only...

How to dynamically initialise FilteredSelectMultiple in django

jquery,django,django-forms,django-admin
I am trying to use the FilteredSelectMultiple widget on a custom non-admin site with a dynamic formset. I have gotten the widget to display properly for the existing entries in the formset by including: <script type="text/javascript" src="/static/admin/js/jquery.min.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="/admin/jsi18n"></script> However, when I add another entry in...

How do you load a custom field in django

python,django,django-models,django-forms,django-admin
note : This is closely related to the answer in this question : django admin - add custom form fields that are not part of the model In Django it is possible to create custom ModelForms that have "rouge" fields that don't pertain to a specific database field in any...

Error saving all valid forms from a formset in django

python,django,django-forms,django-views
I have a formset but I can only save the last form: my view: @login_required(login_url='/login/') def CCView(request): newAdFormSet = formset_factory(CodigoCortoForm) if request.method == 'POST': formset = newAdFormSet(request.POST, request.FILES) if formset.is_valid(): for form in formset.forms: if form.is_valid(): form.save() return HttpResponseRedirect('/home/') else: formset = newAdFormSet() return render_to_response("codcorto.html", {'form':formset}, context_instance=RequestContext(request)) Th view only...

Django ClearableFileInput - how to detect whether to delete the file

django,django-forms,django-crispy-forms
I'm using Django Crispy Forms for my form with an option to upload an image (ImageField in my Model) The forms renders as I'd expect, with the checkbox to clear an existing file. However when processing the form submission the 'image-clear' checkbox always gives me a 'None' value. image_clear =...

Where did Django form wizard go in django 1.8?

django,django-forms,django-views
There is a documentation about form wizard for version 1.7 but not for 1.8. I have looked at release notes and there is no mention of this. So where did it go? (Also there seems to be no class named SessionWizardView anywhere in 1.8).

How to use ModelMultipleChoiceField in django-admin and django-form for SelectMultiple widget

django,django-forms,django-admin
I need to use SelectMultiple widget with ModelMultipleChoiceField in Django-admin. It's not selecting proper value in django-admin at the time of editing. Please share a working example if possible. Thanks in advance!!! In this issue I was not getting desired result and there was no error in my project, so...

request.GET vs request.POST/Redirect/GET in django

django,django-forms
In dealing with forms with multiple input parameters and pagination, where user can choose any number of parameters (like a search form) which approach is better and why? receiving data straight from request.GET in one view or implementing a Post/Redirect/Get (2 views). using Post/Redirect/Get, one can easily sanitize data using...

Using a FormSet in a ClassBasedView in django

python,django,django-forms,django-class-based-views,formset
I'm trying to set up a django form consisting solely of a formset. In forms.py I have: class StudentEnrolmentForm(forms.ModelForm): school_class = forms.ModelChoiceField(SchoolClass.objects.currently_enrolling()) class Meta: model = StudentApplication fields = [] StudentEnrolmentFormSet = modelformset_factory(StudentApplication, StudentEnrolmentForm, extra=0) but I'm unclear how to incorporate the FormSet into a CBV (In this case I've...

Error on raising ValidationError as dictionary

python,django,python-2.7,django-models,django-forms
Django newbie here. I am trying to raise an error for email field in my custom form. My forms.py has following code to validate email: def clean_email(self): email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise ValidationError({'email':'Email already registered. Login to continue or use another email.'}) On entering existing...

How to save the value of a jQuery sliderbar into a Person model?

jquery,django,django-models,django-forms,django-views
I am trying to save the value of an jQuery element I added to my SurveyWizardForm into my class Person(models.Model): and therefore my database. All of the other elements in my form were created the normal way, by creating the necessary fields and widgets in my forms.py and the data...

Extend Django ModelForm with a class

python,django,inheritance,django-models,django-forms
I have multiple model forms in my Django project and want to add three fields to all of them. But when I write a simple form and then subclass it, I get an error. class PersonForm(forms.Form): person_name = forms.CharField( label=u'Entregado por', max_length=64, ) person_document_number = forms.CharField( label=u'Número de Documento', max_length=15,...

Django validate field based on value from another field

django,django-forms
I have this django field called is_private indicating whether the posting done by the user is private or not. If the posting is private then a certain field called private_room must be mentioned otherwise a field called public_room is required. In the clean_private_room and clean_public_room fields I'm doing a check...

How to save a form which has been generated by overriding __init__?

django,forms,django-forms
I have a form - class PermissionForm(forms.Form): def __init__(self, *args, **kwargs): super(PermissionForm, self).__init__(*args, **kwargs) permissions = Permissions.objects.all() for permission in permissions: self.fields[permission.name] = forms.CharField() Now since I don't know the field names, so how do I write the save method for this form?...

In Django-admin, how to add filter or search for foreign key select box?

python,django,django-models,django-forms,django-admin
I got a foreign key model with about 100,000 date. It's too difficult to select the wanted data. So I'm wondering if there is a humanized way to add foreign key in django admin. I have tried the raw_id_fields, it's useless. this don't work....

Django template/form for user input

python,django,django-forms,django-rest-framework
I have a basic django-rest API running for a program I wrote. The program retrieves data from a database and displays it on the browser. The database is queried using two input values 'a' and 'b'. Ex: a = raw_input('Enter A.') b = raw_input('Enter B.') response = HttpResponse() for post...

Add extra field to the formset while saving the formset

django,django-models,django-forms,django-views
I want to know the alternate method to save data to the database that are not coming from the html form. This is my models.py: class product(models.Model): user = models.ForeignKey("user") product = models.CharField(max_length=128) cost = models.IntegerField() This is my forms.py: class productform(forms.ModelForm): class Meta: model = product fields = ["product","cost"]...

update / edit function in django one-to-one models

python,django,django-models,django-forms,django-views
i've made an edit form in django, and i have trouble in my update function. There is a relational models that using one-to-one relationship. When i run this function, data in User models stored properly, but not in the UserProfile models. This is my urls.py url(r'^update_user/(?P<pk>\d+)$', views.update_user, name='update_user'), This is...

Overriding class attribute in Django ChoiceField / select

django,django-forms
I'd like to add class="form-control" (Bootstrap 3) to my custom Django form. My fields need to be rendered as follows in my template (just to show I'm not using {{form}}: {% for field in form.visible_fields %} {{ field }} {% endfor %} I realize the Meta class should be used...

Django - Allow User to Edit Profile and then Show Updated Profile fields

django-forms,user
I have the form populating with the user profile information, but when I click save, it doesn't actually update. Any clues/hints as to which part I need to modify is greatly appreciated. Thanks in advance! views.py def profile_view(request): user = request.user form = EditProfileForm(initial={'first_name':user.first_name, 'last_name':user.last_name}) context = { "form": form...

Django ModelForm - form display values

django,django-forms
I have a model: class SchedulerProfile(models.Model): user = models.ForeignKey(User, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __unicode__(self): return u'%s' % (self.user) I also have a model that has a M2M relationship with the Scheduler: class OfficialProfile(models.Model): user = models.ForeignKey(User, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) schedulers = models.ManyToManyField(SchedulerProfile,...

Error saving records from ModelChoice Field in django form

django,django-forms,django-views,django-widget
I have a FormModel with an modelchoice field. The modelchoice widget is filtered based on the logged user class ProcFTPForm(forms.ModelForm): #id_archivo = forms.ModelMultipleChoiceField(queryset=Archivo_Descarga.objects.all(),required=True,widget=FilteredSelectMultiple("Archivo",is_stacked=False),label='') class Media: css = {'all':('/admin/css/widgets.css',),} js = ('/admin/jsi18n/','admin/jquery.js') def __init__(self,usuario, *args, **kwargs): super(ProcFTPForm, self).__init__(*args, **kwargs) self.fields['id_archivo'] =...

Posting data from a form into the database using Django

django,django-models,django-forms
I am trying to have a user input a task from the frontend and have that data instantiate a new model and add this new field in the database associated with their account. I have tried the following; Profile HTML <form id="taskitem_form" method="post" action="/"> {% csrf_token %} {% for hidden...

Django: form to query database

django,django-forms,django-templates,django-views,django-queryset
I want a user be able to make this query: Tell me all the people, without Phd, with full time contract with a contract among two dates. that translated into Django is: Contract.objects.filter( person__is_doctor = False, type_contract = 'full', starting_date__gte = start_date, ending_date__lte = end_date ) How could I make...

How to create Django form for a photo grid?

python,django,django-forms,django-templates,django-views
I'm trying to create a Django form that will contain a grid of one to ten photos. There will be two radio button groups below each photo, one to indicate if the viewer approves or rejects that photo and a second group to indicate if the photo needs to be...

Django form validation: required fields not displaying errors when blank

python,django,django-forms,django-validation
im trying to build a simple form with some simple validation rules. the problem i am having is that fields that are supposed to be required are not causing any validation prompts to appear in the form page when i try to submit the form. As in, when i submit...

Django ModelForm: Making an “Other” Textarea manditory when the user selects “Other” from RadioSelect

django,django-models,django-forms
I am converting a survey from a Form to a ModelForm in Django 1.6.2. I want to create an "Other" forms.Textarea which the user has to fill out if they select "Other" from the forms.RadioSelect. I want this to be mandatory only if the user selects "Other" from the forms.RadioSelect....

Django form data not submitting/visable in mysql database

django,django-models,django-forms
I designed and built a Django 1.6.2 survey application using a SessionWizardView which is connected to a MySQL database. The problem is that (as far as I can see) the submitted form data is not getting saved to the database. This is my first time building an application like this...

Get the django user in save while using django.form

python,django,django-models,django-forms,user-permissions
I have a problem getting the user in django when I use django forms. My code looks something like this. The view: @login_required def something(request): item = ItemForm(request.POST) item.save(user=request.user) The form: class ItemForm(ModelForm): class Meta: model = Item fields = '__all__' def save(self, *args, **kwargs): user = kwargs['user'] super(ItemForm, self).save(user=user)...

Cannot assign “u'2'”: “CartItem.product” must be a “Product” instance

django,django-models,django-forms,django-views
I'm trying to allow the customer to add an item (CartItem) to their cart. The CartItem is linked to my Products model via ForeignKey. I've created a list of products through the admin. I'm able to get the form (AddItemForm) to populate on the .html page and show the list...

django form field regex validation for alphanumeric characters

python,django,django-forms
I have a django form, which contains a password field, I want to validate the field that it must contain a combination of alphabets and numbers. class AuthorizationForm(forms.Form): email = forms.CharField() password = forms.CharField(min_length=7) I am validating the password field like this: def clean_password(self): password = self.cleaned_data['password'] if not re.match(r'^[A-Za-z0-9]+$',...

Form confirmation ValidationError for similar objects

django,django-forms
Before saving an object, I'd like to add a validation warning message to ask the end user whether he/she does want to continue or not, given similar data returned from the database. For example, when the end user is adding a Hospital, and one or more Hospital objects already exists...

Django - ModelForm: Add a field not belonging to the model

python,django,django-forms,django-crispy-forms
Note: Using django-crispy-forms library for my form. If you have a solution to my problem that involves not using the cripsy_forms library, I accept it all the same. Not trying to be picky just need a solution / work around. Thanks In my form's Meta class I set the model,...

Why is Django widgets for TimeInput not showing

django,django-forms,django-templates,django-views
I'm trying to create a TimeInput field in a form and noticed that the widget isn't showing correctly. But when I check the localhost:8000/admin, I see the widget showing up correctly. My code is as follows. For models.py, class TimeLimit(models.Model): before = models.TimeField(blank=True, default=time(7, 0)) # 7AM after = models.TimeField(blank=True,...

admin registered staff user can't login django admin, form registered staff user can't

python,django,django-forms,django-admin,django-authentication
When I create a user via django admin panel, and mark it staff it can login django admin page as it should, but when I create user vie UserForm and mark it as staff it can not login. It says invalid username password for staff and so on. I suspect...

Unable to access upvote/downvote input in a Django template

html,django,django-forms,django-templates
I am reading upvote/downvote from a Django template in the following manner: <form method="POST" action="{% url 'vote' %}" class="vote_form"> {% csrf_token %} <input type="hidden" id="id_value" name="value" class="hidden_id" value="{{ btn1.value }}" /> <button type="input" name="btn1" value="1">upvote</button> <button type="input" name="btn1" value="-1">downvote</button> </form> Note: The object being voted on and the user_id creating...

Django administration panel filter list

django,django-forms,django-admin,django-filter
I have my django model: Post Any Post has an author (User|Admin) I would to add post's administration in my Django administration panel but I would to show in Posts list ONLY posts with author=Admin. Is possible this?...

create input form for 540 fields in django. Best approach?

python,django,django-forms,django-formwizard
I'm new to django and would like to hear your opinion on how to create a form for a table with 540 fields. What would be the best approach? Is it best to split the modelform into multiple components or create a template that collects the input in parts (multiple...

How to DRY (myself) in Django form for Create and Edit Form

django,django-forms,django-templates,dry
I created two forms in Django for the same model, named AccountCreateForm and AccountEditForm. The Account model has say three fields and each of them has a few form attributes such as max_length, help_text, error_messages. For example, class AccountCreateForm(forms.Modelform): name = forms.CharField(max_length=50, required=True, label='Account Name', help_text='50 characters max', error_messages={'required': 'Please...

Custom Django Widgets/Fields: object has no attribute 'attrs'

django,django-forms
I'm trying to make a custom form field in Django that allows a user to link a file or upload a file. To do this, I'm creating a subclass of the MultiValueField with the fields property set to (URLField(), FileField()). I'm not sure this is the right approach, but I...

Django ValueError when trying to save ManyToMany Values from a Form

django,django-models,django-forms,manytomanyfield
I get the error "" needs to have a value for field "dataset" before this many-to-many relationship can be used." when trying to assign values to a ManyToMany field in my views. I've looked at many related questions here on SO that say I must save my Dataset object first....

How to get a Django Prepopulated Model Form for User to *not* populate password

django,django-forms,modelform
I have a ModelForm for the User model that I want to use to allow the user to update some of their settings (first name, last name, email, and, of course, password). It's a very basic form and I did the UserForm(instance=user) so the user would see their current values....

Django:int() argument must be a string or a number, not 'list'

django,django-models,django-forms,django-authentication
This may be same be an alreday asked error but in my case error is same but a different question, Hi every one i have already writtem one django apllication in which i have a set of templates they are Login.html Logout.html dashboards.html After authentication in login form user will...

Django: Passing value from template to view

django,django-forms,django-views,streaming,httpresponse
I HAD this situation: Clicking on a html submit button, I call views.stream_response which "activates" views.stream_response_generator which "activates" stream.py and return a StreamingHttpResponse and I see a progressive number every second up to m at /stream_response/: 1 2 3 4 5 6 7 8 //e.g. my default max value for...

Django 1.8 model form fields not showing when rendering template

python,html,django,django-models,django-forms
I am trying to create a form which will allow users to input data into my database. I have followed many tutorials which may have lead to my confusion. The problem is that my page is showing up with all the html elements, but the form is not being displayed....

add foreign key fields to form

django,django-forms
I'm trying to create a form from this model: class A(models.Model): u = models.OneToOneField(User) and then create this form: class AForm(ModelForm): class Meta: model = A fields = ['u'] then i create an instance of that form in my view and send it to my template as a context I'll...

Why does my Django form keep saying “this field is required”

django,django-forms
Does anyone know why my form (filepicker) is constantly returning "this field is required" when it worked in a simpler version? My view is def add_attempt(request, m_id, a_id): template = loader.get_template('add_attempt.html') if request.method == 'POST': import pprint pprint.pprint(request.POST) pprint.pprint(request.FILES) form = UploadAttemptForm(data=request.POST, files=request.FILES) if form.is_valid(): form.instance.pub_date = datetime.datetime.now() form.instance.user_id =...

Django add an attribute class form in __init__.py

python,django,forms,django-forms
My form class from django import forms class Form(forms.Form): your_name = forms.CharField(label='Your name ', max_length=100) My app file __init__.py from django import forms from my_app.forms import Form from captcha.fields import ReCaptchaField def register(form): form.captcha=CaptchaField() register(Form) Code in __init__.py add an attribute captcha but it is not on the page. I...

Render in django can't passing an argument

django,django-forms,django-templates,django-views
i'm new in django and i'm trying to create an application that user can change his/her password based on his/her id. So far is good, but when i'm trying to passing an argument from my views.py, there is a trouble that an argument can't passing to the html template. This...

Filter queryset between two or more models for search form in django

django,django-forms,django-class-based-views
Im building a search form in django, Im doing it with filter querysets, this form is like a "advance search form", I mean, form could has more than two inputs, but problem is that each input corresponding of a field of different model, I have this and works fine if...

How to specify Select and RadioSelect in a ModelForm?

django,django-models,django-forms
I am converting a survey from a Form to a ModelForm in Django 1.6.2. Can anyone tell me what is the equal of forms.ChoiceField(widget=forms.Select(), and forms.ChoiceField(widget=forms.RadioSelect() using ModelForm? I have tried widget=models.Select() or widget=models.RadioSelect() but it keeps giving the error AttributeError: 'module' object has no attribute 'Select' AttributeError: 'module' object...

Django Model Design - Many-To-Many Fields

python,django,django-models,django-forms
Coming from a php background, I know how I would do this 'by hand' but I can't seem to get my head round how to structure my database with Django ORM. The app centres around a checklist. A Checklist has some identifying features, lets say Name, DateOfBirth and ChecklistType There...

Reset field value in case of a ValidationError

django,django-forms
I have a custom form field (subclassed from CharField). The underlying model has an is_approved() method. Now if the field is already approved (is_approved() returns True), I raise ValidationError and render the field as read only. The drawback here is that the HTML field has a value that I entered...

How to use models associated with a user in Django when rendering an HTML page

django,django-models,django-forms
I'm in the learning stages of django. I just dived into a project to learn the framework and am having a series of questions throughout the process. I basically want to have individual pages for users who create a task list and have them post tasks to their own page....

Django forms - how to override field validation

python,django,validation,django-forms
In a form I have certain fields, that are not validated correctly. I wish to override the django validation and put my own instead. When I override the clean() method, the field self.errors is already filled with errors from the wrongly validated fields. Which method should I override, where are...

modelformset_factory: display more fields for specific instances

django,django-forms
I'm using a modelformset_factory to edit multiple instances of Product in the same form: ProductFormSet = modelformset_factory(Product, fields=('code', 'state')) form_products = ProductFormSet() It works well. But now I need to display an additional field of the Product model in the form but only for a specific instance of Product. I'm...