Django - 验证后更改/初始化表单字段

时间:2014-08-06 02:01:16

标签: python django forms

我正在制作一个简单的CMS。为此,在撰写新文章时,文章必须包含作者用户名。我使用 request.user.username 获取用户名。但我无法使用用户名设置字段。 我试过做

form.fields['author'] = request.user.username 
form.data['author'] = request.user.username
form.cleaned_data['author'] = request.user.username

他们中没有人工作。在form.is_valid()

之前和之后尝试了它们

编辑:在尝试了Levis解决方案后,它仍然无法正常工作。让我详细说明我的模型和错误。

我收到错误

IntegrityError at /snips/create/
snips_snippet.author_id may not be NULL
Request Method: POST
Request URL:    http://127.0.0.1:8000/snips/create/
Django Version: 1.6.5
Exception Type: IntegrityError
Exception Value:    
snips_snippet.author_id may not be NULL
Exception Location: C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 451
Python Executable:  C:\Python27\python.exe
Python Version: 2.7.8
Python Path:    
['C:\\Users\\Shaurya\\PycharmProjects\\codeshare',
 'C:\\Python27\\lib\\site-packages\\distribute-0.6.49-py2.7.egg',
 'C:\\Python27\\lib\\site-packages\\pygments-1.6-py2.7.egg',
 'C:\\windows\\SYSTEM32\\python27.zip',
 'C:\\Python27\\DLLs',
 'C:\\Python27\\lib',
 'C:\\Python27\\lib\\plat-win',
 'C:\\Python27\\lib\\lib-tk',
 'C:\\Python27',
 'C:\\Python27\\lib\\site-packages',
 'C:\\Python27\\lib\\site-packages\\setuptools-0.6c11-py2.7.egg-info']
Server time:    Wed, 6 Aug 2014 10:15:06 +0530

我的模特

class Snippet(models.Model):
title = models.CharField(max_length=255)
language = models.ForeignKey(Language)
author = models.ForeignKey(User)
description = models.TextField()
description_html = models.TextField(editable=False)
code = models.TextField()
high_code = models.TextField(editable=False)
tags = TagField()
pub_date = models.DateTimeField(editable=False)
updated_date = models.DateTimeField(editable=False)

class Meta:
    ordering = ['-pub_date']

def __unicode__(self):
    return self.title

def save(self, force_insert=False, force_update=False):
    if not self.id:
        self.pub_date = datetime.datetime.now()
    self.updated_date = datetime.datetime.now()
    self.description_html = markdown(self.description)
    self.high_code = self.highlight()
    super(Snippet,self).save(force_insert,force_update)

def highlight(self):
    return highlight(self.code,self.language.get_lexer(),HtmlFormatter(linenos=True))

我的表格

class Snippet_Form(forms.ModelForm):

class Meta:
    model = Snippet
    fields = ('title', 'language', 'description', 'code', 'tags')

我在视图中的表单

@login_required
def create_snippet(request):
    if request.POST:
        data = request.POST.copy()
        data['author'] = request.user.username
        form = Snippet_Form(data)
        if form.is_valid():
            print "this is it"
            print form.cleaned_data
            print "this is it"
            form.save()
            return HttpResponseRedirect('/snips/all/')
    else:
        form = Snippet_Form()
    args = dict()
    args['form'] = form
    args.update(csrf(request))
    return render_to_response('createsnippet.html',args)

1 个答案:

答案 0 :(得分:1)

复制request.POST dict,添加用户然后填充表单

data = request.POST.copy()
data["author"] = request.user.username
form = YourCustomForm(data)
if form.is_valid():
     print form.cleaned_data['author']