如何在django中正确创建ModelForm?

时间:2015-10-26 08:24:00

标签: python django

有我的模特:

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    street_address = models.CharField(max_length=511, blank=True)
    photo = models.ImageField(upload_to='images/userpics/', blank=True)
    phone_number = models.CharField(max_length=50, blank=True)
    about_me = models.TextField(blank=True)
    status = models.CharField(max_length=140, blank=True)

形式:

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        exclude = ('user_id', )

查看:

@login_required
def update_profile(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = ProfileForm(request.POST)
        form.data['user_id'] = str(request.user.id)
        # check whether it's valid:
        if form.is_valid():
            profile = form.save(commit=False)
            # commit=False tells Django that "Don't send this to database yet.
            # I have more things I want to do with it."

            profile.user = request.user # Set the user object here
            profile.save() # Now you can send it to DB
        else:
            return render(request, "dashboard/account.html", {"form_profile": form, "form_password": ChangePasswordForm(), 'balance': get_user_balance(request.user)})

我想要的只是简单的UpdateProfileForm,其中User可以更新他们的信息。实现这个的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

您最好只使用更新视图

class ProfileFormView(UpdateView):
    template_name = 'dashboard/account.html'
    form_class = ProfileForm
    success_url = '#'

    def get_object(self, queryset=None):
        return Profile.objects.get(self.kwargs['id'])

url(r'^update_profile/(?P<id>\d+)/$', ProfileFormView.as_view(), name="update_profile"),

Django文档目前正在关闭..当我可以时,我会更新文档链接

然后你的模板就变成了

<form method="post">
        {% csrf_token %}
        {{ form }}
            <button id="submit" type="submit">Submit</button>
</form>