8

我在掌握如何做到这一点时遇到了一些麻烦。我已经尽我最大的努力搜索谷歌,但没有任何运气。

我将从一些代码开始,并解释我正在尝试做的事情:

模型.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})
4

2 回答 2

7

你可以试试这个:

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_or_create(username=request.POST.get('owner_new'))                

            updated_data = request.POST.copy()
            updated_data.update({'owner': user}) 
            form = MyForm(data=updated_data) 

        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})

一种更清洁的方法是:

添加required=Falseowner字段。现在,

if form.is_valid(): # THIS DOES NOT FAIL EVEN IF form.owner ISN'T SET
    action = form.save(commit=False)
    if 'owner_new' in request.POST:
        user, _ = User.objects.get_or_create(username=request.POST.get('owner_new'))                
        action.owner = user
    action.created_by = request.user
    action.modified_by = request.user
    action.save()
    return redirect('action_register:index')
于 2013-06-25T18:00:22.327 回答
1

我遇到了类似的情况,无法弄清楚如何按照我想要的方式去做。我最终得到的是放置一个链接到UserForm允许用户创建一个新的,然后在实例化表单时使用包含的参数owner重定向回。ActionForminitial={owner: new_owner}

于 2013-06-25T17:55:18.917 回答