我試圖用Django爲我的用戶創建一個用戶配置文件。總體而言,它似乎有主要工作,我能夠看到管理頁面中的一切正確。在我的實際HTML頁面上,我正確地看到了我需要的模型字段,但是他們沒有填充任何數據,並且我放入的數據實際上並不會保存,即使它說明了這一點。爲什麼我的Django視圖顯示沒有數據的正確模型字段?
views.py
class DemoUserEditView(UpdateView):
form_class = DemoUserEditForm
template_name = "user/profile.html"
view_name = 'account_profile'
success_url = '/member/'
def get_object(self):
return self.request.user
def form_valid(self, form):
form.save()
messages.add_message(self.request, messages.INFO, 'User profile updated')
return super(DemoUserEditView, self).form_valid(form)
account_profile = login_required(DemoUserEditView.as_view())
models.py。
class UserProfile(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
avatar_url = models.CharField(max_length=256, blank=True, null=True)
skills = models.CharField(max_length=256, blank=True, null=True)
avatarpic = models.ImageField(_('avatar photo'),
blank=True, null=True,
upload_to=user_directory_path, validators=[validate_img_extension])
Bio = models.TextField(_('Bio'),
max_length=200, blank=True, null=True, unique=False)
EDUCATION_CHOICES = (
('0', "Didn't complete High School"),
('1', 'High School or GED'),
('2', 'Associate Degree'),
('3', 'Batchlors Degree'),
('4', 'Masters Degree'),
('5', 'PhD Degree'),
('6', 'Professional Degree'),
)
Education = models.CharField(_('Education'),
max_length=100, blank=True, null=False,
choices=EDUCATION_CHOICES, unique=False,
help_text="Level of Education")
urls.py
url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/profile/$', 'base.views.account_profile', name='account_profile'),
我試圖使用通用視圖,和我想的UpdateView將是該適當的標籤。我已經通過Generic View docs以及幾個this stackoverflow問題和this one。我的大問題是我沒有收到錯誤消息,它說這個表單是有效的,並且保存,但它不是,我不知道還有什麼可以嘗試。
那麼如何使用現有的用戶數據填充我的模型?
命令self.request.user返回正確的用戶字符串。我仍然認爲這個命令是錯誤所在,但我不確定還有什麼要返回。 – RknRobin
好的,然後嘗試使那樣def get_object(self,queryset = None): –
好吧,現在我們正在某處。添加queryset =無...沒有!這顯示在[這裏](https://ccbv.co.uk/projects/Django/1.4/django.views.generic.edit/UpdateView/),但這是因爲queryset = None是默認的,並且需要定義查詢集在get_object內。我已經添加了queryset = UserProfile.objects.all(),但它沒有修復前端。 – RknRobin