当前位置: 代码迷 >> python >> 如何在 Django 中正确创建 ModelForm?
  详细解决方案

如何在 Django 中正确创建 ModelForm?

热度:21   发布时间:2023-06-16 10:24:24.0

有我的模型:

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,用户可以在其中更新他们的信息。 实现这一点的最佳方法是什么?

你最好只使用更新视图

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>