啊。大家好,我有一个简单的 django 问题:
啊,对不起,我已经读了又读了,我确信这在某个地方非常明显,但我还没有找到它!
如何使用 django 编辑/更新模型?比如,数据值?不是模型字段?
这是我的代码!(我正在使用自制版本的东西!)
这是网址:
url(r'^editStory/(?P<id>\d+)$',
StoryModelView.as_view(
context_object_name='form',
template_name ='stories/editStory.html',
success_template= 'stories/editStorySuccess.html'
),
{},
'editStory'
),
这是视图:
def get(self,request,id=None):
form = self.getForm(request,id)
return self.renderValidations(form)
def getForm(self, request,id):
if id:
return self.getModelById(request,id)
return StoryForm()
def getModelById(self,request,id):
theStory = get_object_or_404(Story, pk=id)
if theStory.user != request.user:
raise HttpResponseForbidden()
return StoryForm(theStory)
def renderValidations(self,form):
if self.context_object_name:
contextName = self.context_object_name
else:
contextName = 'form'
if self.template_name:
return render_to_response(self.template_name,{contextName:form})
else :
return render_to_response('stories/addStory.html',{contextName:form})
def getPostForm(self,request,id):
if id:
theStory = self.idHelper(request,id)
return StoryForm(request.POST,theStory)
return StoryForm(request.POST)
def processForm(self,form,request):
theStory = form.save(commit=False)
theStory.user = request.user
return theStory
这是模板代码:
{% block content %}
<h3>Edit story</h3>
<form action="" method="post">
{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endfor %}
<input type="submit" value="Submit"/>
</form>
{% endblock %}
尽我所能,我要么:
- 得到一个错误
- 一无所获
我收到显示的代码错误,由这一行引起
{% for field in form %}
并有以下错误:
Caught AttributeError while rendering: 'Story' object has no attribute 'get'
或者我什么也得不到——根本没有数据——如果我将“getModelById”方法更改为:
def getModelById(self,request,id):
theStory = get_object_or_404(StoryForm, pk=id)
if theStory.user != request.user:
raise HttpResponseForbidden()
return theStory
StoryForm 是那些“ModelForm”事物之一,它的模型是“Story”。
所以!问题:
如何修复此代码以使其正常工作?我做错了什么?