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.
My model:
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'
My form:
class PortfoliosCreateForm(ModelForm):
class Meta:
model = Portfolios;
My template:
<form action="" method="post">
{% csrf_token %}
{% for field in form %}
<div class="create_form_field">
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}
<input type="submit" value="Create" /></p>
</form>
I call the template using a generic create view:
url(
r'^portfolios/create/$',
'django.views.generic.create_update.create_object',
dict(
form_class=PortfoliosCreateForm,
post_save_redirect='/',
template_name='portfolios/create.html'
)
),
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?
Edit: The User model is the in-built Django User model.
Thanks
It is much safer to get the current user from the request after the form has been submitted. You could rewrite the generic view to something like this: