Note that there are some explanatory texts on larger screens.

plurals
  1. POSet form field value before is_valid()
    primarykey
    data
    text
    <p>I'm having a bit of trouble grasping how to do this. I've put my best effort into searching Google without any luck.</p> <p>I'll start with a bit of code and explain what I'm trying to do as I go:</p> <h1>models.py</h1> <pre><code>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 </code></pre> <h1>views.py</h1> <p>By default, there is a dropdown field for owner. I have an icon that allows the user to enter a new username in a text field instead for owner. I check to see if <code>owner_new</code> was submitted and if so, create that user. I then need to set the <code>owner</code> field to that value so that <code>form.is_valid()</code> will be true.</p> <pre><code>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}) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload