如何更新现有的配置文件Django模型表单

时间:2013-10-13 02:13:32

标签: django django-models django-views django-forms

我试图让用户在注册后能够创建和编辑他们的个人资料。我正在使用模型表格。我需要做的是让雇主模型字段填充当前用户。

以下是我的观点:

def update_profile(request, username):
    if request.method == 'POST':
        edit_profile_form=EditProfileForm(request.POST)
        if edit_profile_form.is_valid():
            editprofile = edit_profile_form.save(commit=False)
            editprofile.employer = request.user.get_profile()
            editprofile.save()
    edit_profile_form = EditProfileForm()
    context = {'edit_profile_form':edit_profile_form,}
    return render(request, 'pandaboard/editprofile.html', context)

这是我的模特:

class Profile(models.Model):
    employer = models.ForeignKey(User)
    company_name = models.CharField(max_length=100)
    company_description = models.TextField()
    company_website = models.URLField(max_length=200, blank=True)
    contact_email = models.EmailField(max_length=100)
    contact_name = models.CharField(max_length=100)
    def __unicode__(self):
        return self.company_name

这是我的模型表格

from django.forms import ModelForm
from pandaboard.models import JobPost, Profile
from django.contrib.auth.models import User

class EditProfileForm(ModelForm):
    class Meta:
        model = Profile
        fields = ['company_name','company_description','company_website','contact_email','contact_name']

1 个答案:

答案 0 :(得分:9)

要使用现有模型实例中的值来水合表单,您需要在模型表单上使用instance参数:

def update_profile(request, username):
    profile = request.user.get_profile()
    edit_profile_form = EditProfileForm(request.POST or None,
        current_user=request.user, instance=profile)

    if request.method == 'POST':
        if edit_profile_form.is_valid():
            editprofile.save()

    context = {'edit_profile_form': edit_profile_form}
    return render(request, 'pandaboard/editprofile.html', context)

要注入当前的request.user,你可以覆盖__init__的{​​{1}},传入一个额外的关键字参数(或arg,它并不重要),然后弹出它在调用super之前的kwargs,所以你没有传递ModelForm一个关键字参数,它没有预料到:

EditProfileForm

现在您不必传递class EditProfileForm(ModelForm): class Meta: model = Profile def __init__(self, *args, **kwargs): current_user = kwargs.pop('current_user') super(EditProfileForm, self).__init__(*args, **kwargs) self.fields['employer'] = current_user 并在视图中手动设置commit=False的值。