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



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

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

他们都不工作。在form.is_valid()

之前和之后都试过了

EDIT:在尝试了Levis Solution之后,它仍然不起作用。让我详细说明一下我的模型和我的错误。

Error I am Receiving:

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:Python27libsite-packagesdjangodbbackendssqlite3base.py in execute, line 451
Python Executable:  C:Python27python.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))
<<p> 我的形式/strong>

类Snippet_Form (forms.ModelForm):

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

My Form in a View

@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)

复制请求。POST字典,添加用户,然后填充表单

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

最新更新