Set form field value before is_valid()

后端 未结 2 1996
挽巷
挽巷 2021-01-12 07:20

I\'m having a bit of trouble grasping how to do this. I\'ve put my best effort into searching Google without any luck.

I\'ll start with a bit of code and explain wha

相关标签:
2条回答
  • 2021-01-12 08:03

    You can try this:

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

    A cleaner way of doing this is:

    add required=False to the owner field. Now,

    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')
    
    0 讨论(0)
  • 2021-01-12 08:03

    I came into a similar situation and couldn't figure out how to do it the way I wanted. What I ended up with was putting a link to a UserForm which allows a user to create a new owner, and then redirect back to the ActionForm with the argument initial={owner: new_owner} included when instantiating the form.

    0 讨论(0)
提交回复
热议问题