我是Django的新手,我有2种模型,其中一种是Post,
class Post(models.Model):
unit = models.ForeignKey('Unit',on_delete=models.CASCADE, primary_key=False, blank = True)
接下来是单位模型
class Unit(models.Model):
name = models.CharField(max_length=120, unique = True)
def __str__(self):
return self.name
我使用ForeignKey,但是我有这样的问题。在我的网站中,我使用单元模型,如下拉列表
<div class="form-group">
<label for="id_unit">Unit</label>
<select class="selectpicker form-control" data-live-search="true" name="unit">
{%for unit in units%}
<option>{{ unit.name }}</option>
{%endfor%}
</select>
</div>
,当我尝试按站点创建新的帖子时,出现值错误“无法分配“'莫斯科'”:“ Post.unit”必须是“ Unit”实例。” < / p>
这是我在view.py中创建的函数。
def post_new(request):
posts = Post.objects.all()
units = Unit.objects.all()
if request.method == 'POST':
title = request.POST['title']
text = request.POST['text']
unit = request.POST['unit']
user = User.objects.first()
status = StatusOfPost.objects.first()
post = Post.objects.create(
author = user,
title = title,
text = text,
unit = unit,
status = status
)
return redirect('postsList')
return render(request, 'post_new.html', {'posts': posts, 'units': units})
我不知道该怎么办。如何将Unit.name值应用于Post.unit。 很抱歉这个愚蠢的问题,但我正在学习。
答案 0 :(得分:2)
您认为request.POST['unit']
不是Unit
对象,而是名称,您需要查询Unit
对象。
所以替换:
unit = request.POST['unit']
作者:
unit = Unit.objects.get(name=request.POST['unit'])