mercredi 25 juillet 2018

how to fillout a form in an updateView before presenting a form to a user

I an update view for a user so that they can change their settings. I want to make it so that when a user clicks the edit my info button they are taken to a form with the fields already filled out with what is in the database for the user. I have been able to update the database with new information when the users data isn't displayed. I have also been able to display the users data in the form, but then the updating no longer works.

I have tried multiple suggestions from stack overflow, so I know something has to be wrong in my code cause everything I am finding says the same thing. I am pretty new to django though so I am a bit confused and would appreciate all the help I could get.

Here is the relevant code in my views.py

class ProfileUpdate(UpdateView):
# model = Prof
# fields = ['privacy_level', 'bio', 'profile_picture']
model = Prof
form_class = ProfForm
template_name = 'user/prof_form.html'

# def form_valid(self, form):
#     user = form.save(commit=True)
#     # password = form.cleaned_data['password']
#     # print(form)
#     self.fields['bio'].required = False
#     self.fields['bio'].initial = "sadfasdf"
#     # user.set_password(password)
#     user.save()
#     return redirect('user:index')

def get(self, request, pk, *args, **kwargs):
    try:
        prof = Prof.objects.get(id=self.kwargs['pk'])
        print(prof)
        print("hello")
        return redirect('user:index')
    except:
        return redirect('user:index')


def get_initial(self):
    return {
        'privacy_level': '1',
        'bio': 'Hi there',
        'profile_picture': '1',
        }

def get_form(self, form_class=ProfForm):

    prof = Prof.objects.get(id=self.kwargs['pk'])
    form = ProfForm() #breaks updating, but allows the filling in of the forms
    form.fields['privacy_level'].initial = prof.privacy_level
    form.fields['bio'].initial = prof.bio
    form.fields['profile_picture'].initial = prof.profile_picture

    form = super(ProfileUpdate, self).get_form(form_class) # will update, won't autofill
    return form

Here is the code in my forms:

class ProfForm(forms.ModelForm):

class Meta:
    model = Prof
    fields = ['privacy_level', 'bio', 'profile_picture']

Thanks in advance




Aucun commentaire:

Enregistrer un commentaire