验证 Django 中的唯一字段
我不知道我是否以正确的方式解决这个问题。预期的结果是拥有一个仅显示名称
和描述
的表单。用户提交表单后,我想将当前用户添加为 owner
并检查是否已有具有相同 name
和 user
的条目。如果有,我想返回有错误的表格。如果没有,我想保存状态
。
我的模型:
class Status(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
owner = models.ForeignKey(User)
active = models.BooleanField(default=True)
class Meta:
unique_together = ('name','owner')
我的观点:
def settings_status(request):
status_form = StatusForm()
if request.method == 'POST':
status_form = StatusForm(request.POST)
if status_form.is_valid():
new_status = Status()
new_status.name = status_form.cleaned_data['name']
new_status.description = status_form.cleaned_data['description']
new_status.owner = request.user
new_status.save()
return render_to_response('base/settings_status.html',{
'status_form' : status_form,
}, context_instance=RequestContext(request))
我已经尝试了很多方法,但我一直遇到这样的问题:如果我单独将 owner
添加到对象,则模型的 clean
无法使用它code> 函数,因此不能用于检查 name
和 owner
是否唯一。
I don't know if I'm approaching the problem in the right way. The intended outcome is to have a form that displays only name
and description
. Once the user submits the form I want to add the current user as owner
and check if there's already an entry that has the same name
and user
. If there is, I want to return the form with errors. If not, I want to save Status
.
My model:
class Status(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
owner = models.ForeignKey(User)
active = models.BooleanField(default=True)
class Meta:
unique_together = ('name','owner')
My View:
def settings_status(request):
status_form = StatusForm()
if request.method == 'POST':
status_form = StatusForm(request.POST)
if status_form.is_valid():
new_status = Status()
new_status.name = status_form.cleaned_data['name']
new_status.description = status_form.cleaned_data['description']
new_status.owner = request.user
new_status.save()
return render_to_response('base/settings_status.html',{
'status_form' : status_form,
}, context_instance=RequestContext(request))
I have tried numerous things, but I keep running into the problem that if I add owner
to the object separately then it isn't available to the model's clean
function and therefore can't be used to check if name
and owner
are unique.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有几种方法可以做到这一点:
例如,将用户(所有者)传递到表单:
forms.py:views.py
:
还要查看根据表单设置设置初始数据并考虑使用 ModelForm。
Several ways to do this:
for example, passing in the user (owner) to the form:
forms.py:
views.py:
Also look at setting initial data depending on your form setup and consider using a ModelForm.