How to update an existing Django form profile

I am trying to allow users to create and edit their profiles after registering them. I am using a model form. I need the employer model field to be populated by the current user.

Here is my opinion:

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'] 
+8
django django-models django-forms django-views
source share
1 answer

To remove your form with values ​​from an existing model instance, you need to use the instance argument in 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 enter the current request.user, you can override __init__ of EditProfileForm by passing an additional keyword argument (or arg, it doesn't really matter), and slip out of kwargs before calling super, so you don't pass ModelForm a keyword argument that it doesn't expects:

 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 do not need to pass commit=False and manually set the value of employer in the view.

+9
source share

All Articles