我在掌握如何做到这一点时遇到了一些麻烦。我已经尽我最大的努力搜索谷歌,但没有任何运气。
我将从一些代码开始,并解释我正在尝试做的事情:
模型.py
class Action(models.Model):
title = models.CharField(max_length=200)
owner = models.ForeignKey(User, related_name='actions')
created_by = models.ForeignKey(User, related_name='+', editable=False)
modified_by = models.ForeignKey(User, related_name='+', editable=False)
class ActionForm(ModelForm):
class Meta:
model = Action
视图.py
默认情况下,所有者有一个下拉字段。我有一个图标,允许用户在文本字段中输入新用户名而不是所有者。我检查是否owner_new
已提交,如果是,则创建该用户。然后我需要将该owner
字段设置为该值,这样form.is_valid()
就可以了。
def action_create(request):
if request.method == 'POST':
form = ActionForm(request.POST)
# check if new user should be created
if 'owner_new' in request.POST:
# check if user already exists
user = User.objects.get(username=request.POST.get('owner_new'))
if not user:
user = User.objects.create_user(request.POST.get('owner_new'))
# HERE IS WHERE I'M STUMPED
form.owner = user.id
if form.is_valid(): # THIS FAILS BECAUSE form.owner ISN'T SET
action = form.save(commit=False)
action.created_by = request.user
action.modified_by = request.user
action.save()
return redirect('action_register:index')
else:
form = ActionForm()
return render(request, 'actions/create.html', {'form': form})