Questions tagged [django-forms]

Specific questions related to forms within the Django web framework.

Specific questions related to Django forms.

Quote from the official documentation:

Handling forms is a complex business. Consider Django’s admin, where numerous items of data of several different types may need to be prepared for display in a form, rendered as HTML, edited using a convenient interface, returned to the server, validated and cleaned up, and then saved or passed on for further processing.

Django’s form functionality can simplify and automate vast portions of this work, and can also do it more securely than most programmers would be able to do in code they wrote themselves.

Django handles three distinct parts of the work involved in forms:

preparing and restructuring data to make it ready for rendering creating HTML forms for the data receiving and processing submitted forms and data from the client It is possible to write code that does all of this manually, but Django can take care of it all for you.

An example form from the documentation:

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

An example of how to validate a form with (validated) POST data:

from django.core.mail import send_mail

if form.is_valid():
    subject = form.cleaned_data['subject']
    message = form.cleaned_data['message']
    sender = form.cleaned_data['sender']
    cc_myself = form.cleaned_data['cc_myself']

    recipients = ['info@example.com']
    if cc_myself:
        recipients.append(sender)

    send_mail(subject, message, sender, recipients)
    return HttpResponseRedirect('/thanks/')

An example of how a form could be rendered in a template:

<form action="/your-name/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>
20047 questions
308
votes
9 answers

Django set default form values

I have a Model as follows: class TankJournal(models.Model): user = models.ForeignKey(User) tank = models.ForeignKey(TankProfile) ts = models.IntegerField(max_length=15) title = models.CharField(max_length=50) body =…
Mike
  • 7,769
  • 13
  • 57
  • 81
271
votes
9 answers

How do I filter ForeignKey choices in a Django ModelForm?

Say I have the following in my models.py: class Company(models.Model): name = ... class Rate(models.Model): company = models.ForeignKey(Company) name = ... class Client(models.Model): name = ... company = models.ForeignKey(Company) …
Tom
  • 42,844
  • 35
  • 95
  • 101
235
votes
9 answers

How do I add a placeholder on a CharField in Django?

Take this very simple form for example: class SearchForm(Form): q = forms.CharField(label='search') This gets rendered in the template: However, I want to add the placeholder attribute to this field…
Joelbitar
  • 3,520
  • 4
  • 28
  • 29
235
votes
2 answers

Create empty queryset by default in django form fields

I have this fields in form: city = forms.ModelChoiceField(label="city", queryset=MyCity.objects.all()) district = forms.ModelChoiceField(label="district", queryset=MyDistrict.objects.all()) area = forms.ModelChoiceField(label="area",…
TheNone
  • 5,684
  • 13
  • 57
  • 98
215
votes
11 answers

What's the best way to store a phone number in Django models?

I am storing a phone number in model like this: phone_number = models.CharField(max_length=12) The user would enter a phone number and I would use the phone number for SMS authentication. This application would be used globally. So I would also…
pynovice
  • 7,424
  • 25
  • 69
  • 109
210
votes
16 answers

Define css class in django Forms

Assume I have a form class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker = forms.BooleanField(required=False) Is there a way for me to define css classes on each field such that…
ashchristopher
  • 25,143
  • 18
  • 48
  • 49
198
votes
6 answers

How can I build multiple submit buttons django form?

I have form with one input for email and two submit buttons to subscribe and unsubscribe from newsletter:
{{ form_newsletter }}
veena
  • 2,023
  • 2
  • 13
  • 6
183
votes
17 answers

CSS styling in Django forms

I would like to style the following: forms.py: from django import forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) email = forms.EmailField(required=False) message =…
David542
  • 104,438
  • 178
  • 489
  • 842
175
votes
12 answers

Change a Django form field to a hidden field

I have a Django form with a RegexField, which is very similar to a normal text input field. In my view, under certain conditions I want to hide it from the user, and trying to keep the form as similar as possible. What's the best way to turn this…
Amandasaurus
  • 58,203
  • 71
  • 188
  • 248
162
votes
12 answers

Django Passing Custom Form Parameters to Formset

This was fixed in Django 1.9 with form_kwargs. I have a Django Form that looks like this: class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate =…
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
153
votes
8 answers

Creating a dynamic choice field

I'm having some trouble trying to understand how to create a dynamic choice field in django. I have a model set up something like: class rider(models.Model): user = models.ForeignKey(User) waypoint = models.ManyToManyField(Waypoint) class…
whatWhat
  • 3,987
  • 7
  • 37
  • 44
142
votes
9 answers

What is the equivalent of "none" in django templates?

I want to see if a field/variable is none within a Django template. What is the correct syntax for that? This is what I currently have: {% if profile.user.first_name is null %}

--

{% elif %} {{ profile.user.first_name }} {{…
goelv
  • 2,774
  • 11
  • 32
  • 40
141
votes
8 answers

Django Forms: if not valid, show form with error message

In Django forms, it can check whether the form is valid: if form.is_valid(): return HttpResponseRedirect('/thanks/') But I'm missing what to do if it isn't valid? How do I return the form with the error messages? I'm not seeing the "else" in…
user984003
  • 28,050
  • 64
  • 189
  • 285
140
votes
11 answers

Django templates: verbose version of a choice

I have a model: from django.db import models CHOICES = ( ('s', 'Glorious spam'), ('e', 'Fabulous eggs'), ) class MealOrder(models.Model): meal = models.CharField(max_length=8, choices=CHOICES) I have a form: from django.forms import…
Artur Gajowy
  • 2,018
  • 2
  • 18
  • 18
126
votes
7 answers

Django: multiple models in one template using forms

I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer…
neoice
  • 2,233
  • 3
  • 19
  • 15
1
2 3
99 100