我的視圖是一個基於函數的視圖(這是一個遺留問題,由於內聯formset的使用,更容易保持它的方式而不是CBV)。我的目標是能夠爲模型對象Article.objects.get(user = user).latest(「id」)和POST方法渲染ModelForm,更新已渲染的同一個對象。問題是ModelForm「不記得」它所對應的對象。將關於對象的信息傳遞給POST方法中使用的視圖的正確方法是什麼?在Django視圖中跟蹤對象ID
下面是views.py的簡化版本和urls.py
views.py
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.template import RequestContext
from specify.models import Article
from specify.forms import ArticleForm
def index(request):
user = User.objects.get(username=request.user.username)
if request.method == "POST":
a_form = ArticleForm(request.POST, instance= *???*)
a_form.save()
else:
a = Article.objects.get(user=user).latest("id")
a_form = ArticleForm(instance=a)
return render_to_response(
"specify/index.html",
{
"a_form" : a_form,
},
context_instance=RequestContext(request)
)
urls.py
from django.conf.urls import patterns, url
from specify import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index')
)
EDIT1:加入models.py和forms.py
models.py
from django.db import models
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
forms.py
from django.forms import ModelForm
from specify.models import Article
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['pub_date', 'headline', 'content']
目前尚不清楚你想在這裏做'a_form = ArticleForm(request.POST,例如= * ??? *)什麼' ?你想保存到數據庫? – Khamidulla
好的我明白你能否在這裏發佈你的模型和ArticalForm定義? – Khamidulla
@Phoenix:剛剛添加了models.py和forms.py。謝謝。 – jazzblue