I am trying to allow users to be able to create and edit their profiles once they have registered. I am using a model form. What I need to do is have the employer model field be filled with the current user.
Here is my view:
def update_profile(request, username):
if request.method == 'POST':
edit_profile_form=EditProfileForm(request.POST)
if edit_profile_form.is_valid():
editprofile = edit_profile_form.save(commit=False)
editprofile.employer = request.user.get_profile()
editprofile.save()
edit_profile_form = EditProfileForm()
context = {'edit_profile_form':edit_profile_form,}
return render(request, 'pandaboard/editprofile.html', context)
Here is my model:
class Profile(models.Model):
employer = models.ForeignKey(User)
company_name = models.CharField(max_length=100)
company_description = models.TextField()
company_website = models.URLField(max_length=200, blank=True)
contact_email = models.EmailField(max_length=100)
contact_name = models.CharField(max_length=100)
def __unicode__(self):
return self.company_name
Here is my Model Form
from django.forms import ModelForm
from pandaboard.models import JobPost, Profile
from django.contrib.auth.models import User
class EditProfileForm(ModelForm):
class Meta:
model = Profile
fields = ['company_name','company_description','company_website','contact_email','contact_name']
To hydrate your form with values from your existing model instance, you need to use the instance
argument on the model form:
def update_profile(request, username):
profile = request.user.get_profile()
edit_profile_form = EditProfileForm(request.POST or None,
current_user=request.user, instance=profile)
if request.method == 'POST':
if edit_profile_form.is_valid():
editprofile.save()
context = {'edit_profile_form': edit_profile_form}
return render(request, 'pandaboard/editprofile.html', context)
To inject the current request.user, you can override the __init__
of EditProfileForm
, passing in an extra keyword argument (or arg, it doesn't really matter), and the popping it out of the kwargs before calling super so you aren't passing the ModelForm a keyword argument it isn't expecting:
class EditProfileForm(ModelForm):
class Meta:
model = Profile
def __init__(self, *args, **kwargs):
current_user = kwargs.pop('current_user')
super(EditProfileForm, self).__init__(*args, **kwargs)
self.fields['employer'] = current_user
Now you don't have to pass commit=False
and manually set the value of employer
in the view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With