简体   繁体   中英

Accessing form attributes in Django form

I am trying to get django's generic FormView function to work. But can't figure out what's teh problem.

This is my form:

class JobCreateForm(forms.Form):
title = forms.CharField(max_length=200)
description = forms.CharField(widget=forms.Textarea)

def save(self, user):
    data = self.cleaned_data
    company = user.get_profile().get_company()

    # create job
    job = Job(title=data.title, description=data.description, company=company, user=user)
    job.save()

This is my view:

class JobCreate(FormView):

form_class = JobCreateForm
template_name = "jobs/create.html"

def form_valid(self, form):
    form.save(self.request.user)
    return super(JobCreate, self).form_valid(form)

and this is my template:

<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Create" />
</form>

When I try to do form.save(...), I get an error: 'dict' object has no attribute 'title' . What's wrong there?

This is because self.cleaned_data is not an object but a dictionary. Eg. you can't access it by .(dot) notation.

You have to select it from dict like:

title = data['title']

or better way:

title = data.get('title',None)

which will try to obtain the title from dictionary and if it doesn't succeed, it will set the None to the title.

您需要将dict.title更改为dict['title']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM