在Django视图中跟踪对象id

时间:2014-01-09 00:19:58

标签: python django-models django-views django-urls django-forms

我的观点是基于功能的视图(它是一种遗留物,由于内联formset的使用,它更容易保持这种方式,而不是CBV)。我的目标是能够为模型对象Article.objects.get(user = user).latest(“id”)呈现ModelForm,并使用POST方法更新已呈现的同一对象。问题是ModelForm“不记得”它对应的对象。将有关对象的信息传递给视图以便在POST方法中使用的正确方法是什么?

以下是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']

1 个答案:

答案 0 :(得分:1)

首先,您应该在view.py

中将文章ID传递给模板
def index(request):

user = User.objects.get(username=request.user.username)

if request.method == "POST":
     #Explained later 
else:
    a = Article.objects.get(user=user).latest("id")
    a_form = ArticleForm(instance=a)
    article_id = a.id   

return render_to_response(
    "specify/index.html",
    {
        "a_form" : a_form,
        "article_id": article_id,
    }, 
    context_instance=RequestContext(request)
)

在您的表格html元素内的模板中,您应该处理文章ID

{% if article_id %}
<input type="hidden" value='{{ article_id }}' id='article_id' name='article_id'/>
{% endif %}

第三,在更新处理中,您应该执行以下操作:

if request.method == "POST":            
    article_id = request.POST.get('article_id') # You are getting passed article id
    a = Article.objects.get(pk=article_id)      # You are getting instance by id
    a_form = ArticleForm(request.POST, instance=a)
    a_form.save()

尝试以上步骤,如果您遇到问题,请发表评论