I want to be able to use the request.user in the model form init. Here is my view:
def create(request, pk):
if request.method == 'POST':
form = CreateForm(request.POST)
if form.is_valid():
object = form.save()
object.save()
return render(request, 'going_create.html', {'object':object})
else:
form = CreateForm()
return render(request, 'being_create.html', {'form':form})
Basically, I need request.user to prefill a django form field. Here is my form:
class CreateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super(CreateForm, self).__init__(*args, **kwargs)
self.fields['first_name'].initial = self.request.user.first_name
class Meta:
model = creater
fields = (
'first_name',
)
Also, there are form = CreateForm(request.POST)
if request.method == 'POST', and form = CreateForm()
when else. So, as I am not familiar with using a function view, I hope you could tell me where I need to add the code so that I could use request.user to prefill a django field. Thank you, and please leave any questions you have.
CodePudding user response:
You pass it though a parameter:
class CreateForm(forms.ModelForm):
def __init__(self, *args, user=None, **kwargs):
super(CreateForm, self).__init__(*args, **kwargs)
if user is not None:
self.fields['first_name'].initial = user.first_name
class Meta:
model = creater
fields = (
'first_name',
)
In the view you then construct the form with:
from django.contrib.auth.decorators import login_required
@login_required
def create(request, pk):
if request.method == 'POST':
form = CreateForm(request.POST, user=request.user)
if form.is_valid():
object = form.save()
return render(request, 'going_create.html', {'object':object})
else:
form = CreateForm(user=request.user)
return render(request, 'being_create.html', {'form':form})
Note: In case of a successful POST request, you should make a
redirect
[Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.
Note: You can limit views to a view to authenticated users with the
@login_required
decorator [Django-doc].