2015-10-26 51 views
-1

有我的模型:如何在django中正確創建ModelForm?

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這裏用戶將能夠更新他們的信息。什麼是實施這個最好的方法?

+1

您可以使用@Sayse建議的更新視圖,但基於常規功能的視圖也應該可以。你已經顯示了你的代碼,但你沒有說過什麼是不工作的。 'request.method =='GET''會發生什麼?你的表單應該排除'user'字段而不是'user_id'。您不需要'form.data ['user_id'] = str(request.user.id)',因爲您從表單中排除了用戶字段。 – Alasdair

回答

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> 
+0

試過你的方式。有ProfileFormView缺少一個QuerySet。定義ProfileFormView.model,ProfileFormView.queryset或重寫ProfileFormView.get_queryset()。 –

+0

@VassiliyVorobyov - 抱歉,試圖從內存中輸入此內容,([docs are down](https://isitup.org/djangoproject.com))。您可以按照錯誤建議的方式進行操作,也可以覆蓋'get_queryset'或者還有一個名爲'get_object'的方法。當文檔再次活躍時,我會嘗試更新我的答案。同時,您可以嘗試使用這兩種方法之一設置斷點並查看您擁有的選項 – Sayse

+0

非常感謝!我會等! –

相關問題