我是 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
我使用外键,我有这样的问题。在我的站点中,我使用像下拉列表这样的单元模型
<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>
当我尝试通过站点创建新帖子时出现值错误“无法分配“'Moscow'”:“Post.unit”必须是“Unit”实例。”
这是我在 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。 抱歉这个愚蠢的问题,但我正在学习。
请您参考如下方法:
在你看来,request.POST['unit']不是一个Unit对象而是一个名称,你需要查询Unit 对象。
所以替换:
unit = request.POST['unit']
通过:
unit = Unit.objects.get(name=request.POST['unit'])
