我一直在尝试研究如何在django中创建编辑视图,但我尝试的所有内容都会失败而不能让我能够编辑已保存的对象。问题会很好地创建并保存和显示但我只是无法加载它们进行编辑。代码如下所示,任何帮助或建议都会很好。
views.py
class FormView(FormView):
template_name = 'issuetracker/form.html'
form_class = CreateIssueForm
success_url = '/issue/'
def form_valid(self, form):
obj = Issue.objects.create(
submitter=form.cleaned_data.get('submitter'),
description=form.cleaned_data.get('description'),
status=form.cleaned_data['status'],
category=form.cleaned_data.get('category'),
)
return super().form_valid(form)
class IssueUpdateView(UpdateView):
context_object_name = 'issue-update'
form_class = CreateIssueForm
template_name = 'issuetracker/update.html'
success_url = 'issuetracker/issue_list.html'
# get object
def get_object(self):
return self.request.user
# override form_valid method
def form_valid(self, form):
# save cleaned post data
clean = form.cleaned_data
context = {}
self.object = context.save(clean)
return super(IssueUpdateView, self).form_valid(form)
forms.py
class CreateIssueForm(forms.ModelForm):
STATUS = (
('Assigned', 'Assigned'),
('Closed', 'Closed'),
)
CATEGORY = (
('Bug', 'Bug'),
('Enhancements', 'Enhancements'),
('Documentation', 'Documentation')
)
submitter = forms.CharField(required=False)
solver = forms.CharField(required=False)
description = forms.CharField(widget=forms.Textarea,required=False)
status = forms.ChoiceField(required=False,choices=STATUS)
category = forms.ChoiceField(required=False,choices=CATEGORY)
class Meta:
model = Issue
fields = ('submitter', 'solver', 'description','status','category')
models.py
class Issue(models.Model):
STATUS = (
('A', 'Assigned'),
('C', 'Closed'),
)
CATEGORY = (
('B', 'Bug'),
('E', 'Enhancements'),
('D', 'Documentation')
)
submitter = models.CharField(max_length=30)
solver = models.CharField(max_length=30, null=True, blank=True)
description = models.CharField(max_length=500)
status = models.CharField(max_length=1, choices=STATUS)
category = models.CharField(max_length=1, choices=CATEGORY)
opened = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.description
urls.py
url(r'^$', StatView.as_view(), name='stat_view'),
url(r'^(?P<slug>\w+)/$', IssueListView.as_view()),
url(r'^/create/$', FormView.as_view(), name='create_issue'),
url(regex=r'^issues/edit$',
view= IssueUpdateView.as_view(),
name='issue-update')
答案 0 :(得分:0)
下面:
class IssueUpdateView(UpdateView):
# ...
def get_object(self):
return self.request.user
我不知道你为什么要回到这里request.user
(这可能是你完全不了解的一些例子的复制粘贴吗?) - 但无论如何:
UpdateView.get_object()
应该返回要编辑的对象。您通常从一个从url到视图的参数传递的唯一ID中获取此对象:
url(regex=r'^issues/edit/(?P<issue_id>\d+)/$',
view= IssueUpdateView.as_view(),
name='issue-update')
class IssueUpdateView(UpdateView):
# ...
def get_object(self, queryset=None):
return Issue.objects.get(id=self.kwargs["issue_id"])