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

0 投票
1 回答
1068 浏览
提问于 2025-04-18 16:10

我正在制作一个简单的内容管理系统(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 个回答

1

复制请求中的POST数据字典,添加用户信息,然后填充表单。

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

撰写回答