I have problems understanding how to do this. I did my best to search Google without much success.
I will start with the code and explain what I'm trying to do when I go:
models.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
views.py
By default, the owner has a drop-down field. I have an icon that allows the user to enter a new username in the text box instead for the owner. I check if owner_new sent, and if so, create this user. Then I need to set the owner field to this so that form.is_valid() true.
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})
Jared source share