使用request.user保存Formsets

时间:2014-10-14 16:10:58

标签: django django-forms

如何使用request.user保存formset?在使用Django Formsets时,我似乎无法使用我的表单来保存request.user对象。

forms.py

class CreditOptionsForm(forms.ModelForm):
    crew_position = forms.ModelChoiceField(CrewPosition.objects.all(), 
        widget=autocomplete_light.ChoiceWidget('CrewPositionAutocomplete'), required=False)

    class Meta:
        model = CreditOptions
        exclude = ('user',)

OptionFormset = formset_factory(CreditOptionsForm, extra=3)

models.py

class CrewPosition(models.Model):
    name = models.CharField(max_length=150)

    def __unicode__(self):
        return self.name


class CreditOptions(models.Model):
    year = models.IntegerField(max_length=4, help_text='e.g. 1995', null=True, blank=True)
    project_name = models.CharField(max_length=150, null=True, blank=True)
    crew_position = models.ForeignKey(CrewPosition, null=True, blank=True)
    user = models.ForeignKey(User, null=True, blank=True)

views.py

from .forms import CreditForm, SkillsForm, OptionFormset

@login_required(login_url='/')
def add_skills(request, template_name):
    user = request.user
    formset = OptionFormset(user=user)
    if request.method == 'POST':
        formset = OptionFormset(request.POST, user=user)
        if formset.is_valid():
            for form in formset.forms:
                form.save()
            messages.success(request, "Successfully created your profile.")
            return redirect(urlresolvers.reverse('skills'))
    return render(request, template_name, {
        'formset': formset
    })

保存时,用户永远不会被保存。我试过我的for循环:

form.save(commit=False)
form.user = user
form.save()

但这也不能保存用户。

1 个答案:

答案 0 :(得分:1)

将用户作为参数传递无效,因为您已明确地将其排除。 只需在保存时添加用户,如下所示:

@login_required(login_url='/')
def add_skills(request, template_name):
    user = request.user
    formset = OptionFormset()
    if request.method == 'POST':
        formset = OptionFormset(request.POST)
        if formset.is_valid():
            for form in formset.forms:
                f = form.save(commit=False)
                f.user = user
                f.save()
            messages.success(request, "Successfully created your profile.")
            return redirect(urlresolvers.reverse('skills'))
    return render(request, template_name, {
        'formset': formset
    })

同样form.save(commit=False)返回一个模型对象。因此,您应该将user分配给此返回对象的user字段。