1👍
✅
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].
Source:stackexchange.com