Django中用newform保存当前用户为作者

#model.py

from django.contrib.auth.models import User
from django.db import models
class WhitePaper(models.Model):
    author = models.ForeignKey(User,editable=False)

#view.py

from django.newforms import form_for_model
from django.core.urlresolvers import reverse
from white_paper.models import WhitePaper

def create(request,template_name):
   
    WhitePaperForm=form_for_model(WhitePaper)
   
    if request.method == 'POST':
        form = WhitePaperForm(request.POST)
        if form.is_valid():
            result=form.save(commit=False)

            result.author = request.user
           
            result.save()

            return HttpResponseRedirect(reverse('submit_success'))
        else:
            return HttpResponseRedirect(reverse('submit_error'))

    else:
        return render_to_response(template_name,{"form":WhitePaperForm().as_table()})

#url.py

from django.conf.urls.defaults import *
from website.white_paper.views import create
from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
    url(
        r'^create/',
          create,
        {"template_name":"white_paper/whitepaper_form.html"},
        "white_paper_create"
     ),
    url(
        r'^submit_success/',
          direct_to_template,
        {"template":"white_paper/submit_success.html"},
        "submit_success"
     ),
    url(
        r'^submit_error/',
          direct_to_template,
        {"template":"white_paper/submit_error.html"},
        "submit_error"
     )
)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值