2017-05-11 194 views
1

我試圖創建一個允許用戶編輯他們的配置文件數據的表單。因此,我希望在用戶編輯表單時顯示來自數據庫的最新數據。繼承人是我到目前爲止有:Django從數據庫中獲取數據

# models.py 
class Profile(models.Model): 
    user = models.OneToOneField(User, on_delete=models.CASCADE) 
    location = models.CharField(max_length=30, blank=True) 
    birthdate = models.DateField(null=True, blank=True) 

    def __str__(self): 
     return self.user.username 

# forms.py 
class EditProfileForm(forms.ModelForm): 
    class Meta: 
     model = Profile 
     fields = ['location', 'birthdate'] 

# views.py 
class EditProfileFormView(View): 
    form_class = EditProfileForm 
    template_name = 'forums/edit-profile.html' 

    def get(self, request, username): 

     try: 
      user = User.objects.get(username=username) 
     except User.DoesNotExist: 
      raise Http404('The User "' + username + '" could not be found.') 

     if (not request.user.is_authenticated): 
      return HttpResponseForbidden() 
     elif (user.id is not request.user.id): 
      return HttpResponseForbidden() 

     form = self.form_class(None) 
     return render(request, self.template_name, {'form': form}) 

設置形式form_class(無)就是給我一個空的形式,但在同一個地點下探user.profile給我一個錯誤「檔案」對象沒有屬性「得到」

回答

3

嘗試填充表格的實例

form = self.form_class(instance=user.profile) 

注:這可能會更容易與標準UpdateView