Home > OS >  form.instance doesn't populate field
form.instance doesn't populate field

Time:02-21

I have the following form for creating a user:

class CreateAccount(UserCreationForm):

   class Meta:
       model = USER
       fields = ['first_name','last_name','username','email','employee_id','is_active','is_staff']

and it's view:

class CreateAccountView(CreateView):

   model = USER
   form_class = CreateAccount
   template_name = 'createaccount.html'

   def form_valid(self, form):

    form.instance.employee_id = Employee.objects.get(username=self.kwargs.get('username'))
    return super().form_valid(form)


   def get_success_url(self):
       return reverse('People')

I used form.instance to pass it an employee object, but it doesn't work and I get 'This field is required. ' error, I used it in the exact same way in my other apps and it worked fine, does anyone have any idea what seems to be different here?

CodePudding user response:

def post(self, request, pk):
    id = YourModelName.objects.get(id=pk)
    form = ModelForm(request.POST, instance = id)
    if form.is_valid(): 
        form.save()
    return redirect(reverse('templateName'))

def get(self, request, pk, *args, **kwarg,):  
    id = YourModelName.objects.get(id=pk)
    form = QuestionForm(instance = id)
    context = {'form':form}
    return render(request, 'TemplateName', context)

First You have to get id with data and then Post it or update this is the way i do that

CodePudding user response:

for anyone wondering i removed the two fields I was trying to populate from my form's fields list and it worked

  • Related