How do i pass the currently logged in user as default to a form?
I want the form to be pre-populated with the current user, but at the same time allow the user to change it (eg add the Customer for another user).
Here is my model:
class Customer (models.Model):
shortname = models.CharField(max_length=30)
name = models.CharField(max_length=50, blank=True)
[...]
user = models.ForeignKey(User)
nextstep = models.DateField(auto_now=False, auto_now_add=False, default=(date.today() + timedelta(days=10)))
def due_in(self):
due_time = self.nextstep - date.today()
overdue = due_time.days < 0
return {'days': abs(due_time.days), 'overdue': overdue}
def get_absolute_url(self):
"""Absolute URL des Partners"""
return reverse('kundencenter:partner_detail', kwargs={'pk': self.pk}, current_app='kundencenter')
And my form:
class CustomerForm(forms.ModelForm):
class Meta:
model = Customer
fields = [
"shortname",
"name",
[...]
"user",
]
labels = {
"shortname": 'Customer Shortname',
"name": 'Full Name',
}
And my view:
class CustomerCreateView(SuccessMessageMixin, CreateView):
"""Adds a new customer."""
model = Customer
template_name = 'customercenter/generic_new.html'
form_class = CustomerForm
success_message = "Customer %(name)s added."
You can use initial in your form while rendering the form.
form = CustomerForm(initial={'user':request.user})
See the docs for more details.
Extending Arpit Solanki's answer, you can add/override get_initial
method since you are using a Class Based View:
def get_initial(self):
initial_data = super(CustomerCreateView, self).get_initial()
initial_data.update({'user':self.request.user})
return initial_data
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.