How to modify Django form before save?
<p>In my project each user can have multiple enemies, like this:</p>

<p><strong>models</strong></p>

<pre><code>class EnemyModel(models.Model):
   name = models.CharField(max_length=128)
   weapon = models.CharField(max_length=128)
   related_user = models.ForeignKey(UserProfile)

class UserProfile(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)
</code></pre>

<p>Only user can add enemies to his profile, so I made a form like this:</p>

<p><strong>forms</strong></p>

<pre><code>class AddEnemyForm(forms.ModelForm):
    class Meta:
        model = EnemyModel
        exclude = ['related_user'] # only current user
</code></pre>

<p>My idea was to modify the excluded field in a view, but it doesn't work:</p>

<p><strong>views</strong></p>

<pre><code>def add_enemy(request):
    args={}
    if request.method == "POST":
        form = AddEnemyForm(request.POST)
        form.related_user = request.user # error
        # form.related_user_id = request.user.id # also error
        if form.is_valid():
            form.save()
            return HttpResponse("&lt;h1&gt;Done!&lt;/h1&gt;")
        else:
            args.update(csrf(request))
            args["form"]=form
            return render_to_response("add_enemy.html",args)
    args.update(csrf(request))
    args["form"]=AddEnemyForm()
    return render_to_response("add_enemy.html",args)
</code></pre>

<p>How to modify a form before save?</p>

<p>Use <code>form.instance</code>:</p>

<pre><code>def add_enemy(request):
    args={}
    if request.method == "POST":
        form = AddEnemyForm(request.POST)
        # form.instance is the instance to be saved
        form.instance.related_user = request.user.userprofile
        if form.is_valid():
            form.save()
            return HttpResponse("&lt;h1&gt;Done!&lt;/h1&gt;")
        else:
            args.update(csrf(request))
            args["form"]=form
            return render_to_response("add_enemy.html",args)
    args.update(csrf(request))
    args["form"]=AddEnemyForm()
    return render_to_response("add_enemy.html",args)
</code></pre>

<p>Note that <code>enemymodel.related_user</code> should be a <code>UserProfile</code>, and <code>request.user</code> is a <code>User</code>. You need to use <code>request.user.userprofile</code>. </p>

python django