EzDevInfo.com

django-forms interview questions

Top django-forms frequently asked interview questions

How does Django Know the Order to Render Form Fields?

If I have a Django form such as:

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

And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.

My question is how does Django know the order that class variables where defined?

(Also how do I override this order, for example when I want to add a field from the classe's init method?)


Source: (StackOverflow)

How do I use CSS in Django?

I am creating my application using Django, and am wondering how I can make Django use my CSS file? What settings do I need to do to make Django see the css file?

NB: On a local machine


Source: (StackOverflow)

Advertisements

Inject errors into already validated form?

After my form.Form validates the user input values I pass them to a separate (external) process for further processing. This external process can potentially find further errors in the values.

Is there a way to inject these errors into the already validated form so they can be displayed via the usual form error display methods (or are there better alternative approaches)?

One suggestions was to include the external processing in the form validation, which is not ideal because the external process does a lot more than merely validate.


Source: (StackOverflow)

Django Imagefield not working properly via ModelForm

I'm certain I'm doing something really obviously stupid, but I've been trying to figure it out for a few hours now and nothing is jumping out at me.

I'm using a ModelForm so I can expose a few fields from a model for editing. 2x ImageField, 1x TextField. The Form is processed and the TextField works. The two ImageFields do not work and they're why I'm here today.

I'm using Django 1.0.2

Here's the relevant code (ask if you need more -- and I'm not including the HTML because that part appears to work fine):

Model:

class Company(models.Model):
    #...
    logo = models.ImageField(upload_to='logos', blank=True)
    intro_pic = models.ImageField(upload_to='intropics', blank=True)
    intro_text = models.TextField(blank=True)

View and form:

def admin_edit(request, company_slug):
    company = get_object_or_404(Company, slug = company_slug)

    f = AdminEditForm(instance = company)
    if request.method == 'POST':
        f = AdminEditForm(request.POST, instance = company)
        if f.is_valid():
            print "Processing form"
            print f.cleaned_data['intro_pic']
            f.save()

    return render_to_response('uadmin/edit.html', {'company':company, 'f':f}, RequestContext(request))


class AdminEditForm(ModelForm):
    class Meta:
        model = Company
        fields = ['logo', 'intro_pic', 'intro_text']

Source: (StackOverflow)

How to get form field's id in Django?

Is there any way to get the id of a field in a template?

In the HTML i get: <input name="field_name" id="id_field_name"...

I know I can get the name with {{ field.html_name }}, but is there anything similar for getting the id?
Or can I only get it like this: id_{{ field.html_name }}?


Source: (StackOverflow)

Multiple Models in a single django ModelForm?

Is it possible to have multiple models included in a single ModelForm in django? I am trying to create a profile edit form. So I need to include some fields from the User model and the UserProfile model. Currently I am using 2 forms like this

class UserEditForm(ModelForm):

    class Meta:
        model = User
        fields = ("first_name", "last_name")

class UserProfileForm(ModelForm):

    class Meta:
        model = UserProfile
        fields = ("middle_name", "home_phone", "work_phone", "cell_phone")

Is there a way to consolidate these into one form or do I just need to create a form and handle the db loading and saving myself?


Source: (StackOverflow)

Django BooleanField as radio buttons?

Is there a widget in Django 1.0.2 to render a models.BooleanField as two radio buttons instead of a checkbox?


Source: (StackOverflow)

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", queryset=MyArea.objects.all())

district comes from click on city and area comes from click on area. With queryset=MyDistrict.objects.all() and queryset=MyArea.objects.all() form will be very heavy. How can I make querysets empty by default?

Thanks in advance


Source: (StackOverflow)

Django forms, inheritance and order of form fields

I'm using Django forms in my website and would like to control the order of the fields.

Here's how I define my forms:

class edit_form(forms.Form):
    summary = forms.CharField()
    description = forms.CharField(widget=forms.TextArea)


class create_form(edit_form):
    name = forms.CharField()

The name is immutable and should only be listed when the entity is created. I use inheritance to add consistency and DRY principles. What happens which is not erroneous, in fact totally expected, is that the name field is listed last in the view/html but I'd like the name field to be on top of summary and description. I do realize that I could easily fix it by copying summary and description into create_form and loose the inheritance but I'd like to know if this is possible.

Why? Imagine you've got 100 fields in edit_form and have to add 10 fields on the top in create_form - copying and maintaining the two forms wouldn't look so sexy then. (This is not my case, I'm just making up an example)

So, how can I override this behavior?

Edit:

Apparently there's no proper way to do this without going through nasty hacks (fiddling with .field attribute). The .field attribute is a SortedDict (one of Django's internal datastructures) which doesn't provide any way to reorder key:value pairs. It does how-ever provide a way to insert items at a given index but that would move the items from the class members and into the constructor. This method would work, but make the code less readable. The only other way I see fit is to modify the framework itself which is less-than-optimal in most situations.

In short the code would become something like this:

class edit_form(forms.Form):
    summary = forms.CharField()
    description = forms.CharField(widget=forms.TextArea)


class create_form(edit_form):
    def __init__(self,*args,**kwargs):
        forms.Form.__init__(self,*args,**kwargs)

        self.fields.insert(0,'name',forms.CharField())

That shut me up :)


Source: (StackOverflow)

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 this from the user, and trying to keep the form as similar as possible.

What's the best way to turn this field into a HiddenInput field? I know I can set attributes on the field with form['fieldname'].field.widget.attr['readonly'] = 'readonly', and I can set the desired initial value with form.initial['fieldname'] = 'mydesiredvalue'. However that won't change the form of the widget.

What's the best/most django-y/least hacky way to make this field a <input type="hidden" field?


Source: (StackOverflow)

Customize/remove Django select box blank option

I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:

<option value="">---------</option>

What I'd like to know is:

  1. What is the cleanest way to remove this auto-generated option from the select box?
  2. What is the cleanest way to customize it so that it shows as:

    <option value="">Select Item</option>
    

In searching for a solution I came across Django ticket 4653 which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.

Thanks for any help,

Jeff

Edit: I've configured the ForeignKey field as such:

verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)

This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.


Source: (StackOverflow)

Unique BooleanField value in Django?

Suppose my models.py is like so:

class Character(models.Model):
    name = models.CharField(max_length=255)
    is_the_chosen_one = models.BooleanField()

I want only one of my Character instances to have is_the_chosen_one == True and all others to have is_the_chosen_one == False . How can I best ensure this uniqueness constraint is respected?

Top marks to answers that take into account the importance of respecting the constraint at the database, model and (admin) form levels!


Source: (StackOverflow)

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 Waypoint(models.Model):
     lat = models.FloatField()
     lng = models.FloatField()

What I'm trying to do is create a choice Field whos values are the waypoints associated with that rider (which would be the person logged in).

Currently I'm overriding init in my forms like so:

class waypointForm(forms.Form):
     def __init__(self, *args, **kwargs):
          super(joinTripForm, self).__init__(*args, **kwargs)
          self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.all()])

But all that does is list all the waypoints, they're not associated with any particular rider. Any ideas? Thanks.


Source: (StackOverflow)

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 ModelForm

class MealOrderForm(ModelForm):
    class Meta:
        model = MealOrder

And I want to use formtools.preview. The default template prints the short version of the choice ('e' instead of 'Fabulous eggs'), becuase it uses

{% for field in form %}
<tr>
<th>{{ field.label }}:</th>
<td>{{ field.data }}</td>
</tr>
{% endfor %}.

I'd like a template as general as the mentioned, but printing 'Fabulous eggs' instead.

[as I had doubts where's the real question, I bolded it for all of us :)]

I know how to get the verbose version of a choice in a way that is itself ugly:

{{ form.meal.field.choices.1.1 }}

The real pain is I need to get the selected choice, and the only way coming to my mind is iterating through choices and checking {% ifequals currentChoice.0 choiceField.data %}, which is even uglier.

Can it be done easily? Or it needs some template-tag programming? Shouldn't that be available in django already?


Source: (StackOverflow)

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 (that's a whole separate project) OR creating a new Customer, then creating a Ticket and finally creating a Note assigned to the new ticket.

Since I'm fairly new to Django, I tend to work iteratively, trying out new features each time. I've played with ModelForms but I want to hide some of the fields and do some complex validation. It seems like the level of control I'm looking for either requires formsets or doing everything by hand, complete with a tedious, hand-coded template page, which I'm trying to avoid.

Is there some lovely feature I'm missing? Does someone have a good reference or example for using formsets? I spent a whole weekend on the API docs for them and I'm still clueless. Is it a design issue if I break down and hand-code everything?


Source: (StackOverflow)