Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I pass the current user id as a hidden field in a Django form?
    text
    copied!<p>The problem I'm having is I'm trying to create a form which passes the currently logged-in users ID by embedding it within a hidden field in a ModelForm.</p> <p>My model:</p> <pre><code>class Portfolios(models.Model): id = models.AutoField(primary_key=True) port_name = models.CharField(max_length=135, blank=True) port_type = models.ForeignKey(PortType, null=True, db_column='port_type', blank=True) user = models.ForeignKey(User) def __unicode__(self): return self.port_name; class Meta: db_table = u'tbl_portfolios' </code></pre> <p>My form:</p> <pre><code>class PortfoliosCreateForm(ModelForm): class Meta: model = Portfolios; </code></pre> <p>My template:</p> <pre><code>&lt;form action="" method="post"&gt; {% csrf_token %} {% for field in form %} &lt;div class="create_form_field"&gt; {{ field.errors }} {{ field.label_tag }}: {{ field }} &lt;/div&gt; {% endfor %} &lt;input type="submit" value="Create" /&gt;&lt;/p&gt; &lt;/form&gt; </code></pre> <p>I call the template using a generic create view:</p> <pre><code>url( r'^portfolios/create/$', 'django.views.generic.create_update.create_object', dict( form_class=PortfoliosCreateForm, post_save_redirect='/', template_name='portfolios/create.html' ) </code></pre> <p>),</p> <p>How can I best embed the user ID within that form so it's passed a hidden field? Or should I simply pass in a dummy field and fill the value in within a custom save function?</p> <p>Edit: The User model is the in-built Django User model.</p> <p>Thanks</p>
 

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