簡體   English   中英

如何在 Django 中正確創建 ModelForm?

[英]How to properly create ModelForm in 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,用戶可以在其中更新他們的信息。 實現這一點的最佳方法是什么?

你最好只使用更新視圖

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM