Ali Aref
Ali Aref

Reputation: 2402

pass form instance in django formview

I have a forms.py file as

class SocialMediaForm(forms.ModelForm):
    class Meta:
        model = SocialMedia
        fields = "__all__"
        exclude = ("doctor",)
        labels = {}
        widgets = {
            "whatsapp": forms.TextInput(attrs={"class": "form-control"}),
            "telegram": forms.TextInput(attrs={"class": "form-control"}),
            "facebook": forms.TextInput(attrs={"class": "form-control"}),
            "instagram": forms.TextInput(attrs={"class": "form-control"}),
            "linkedin": forms.TextInput(attrs={"class": "form-control"}),
        }

with a view.py file

class SocialMediaProfile(FormView):
    model = DoctorSocialMedia
    form_class = SocialMediaForm
    success_url = "."
    template_name = "doctor/social_media_profile.html"

the question is how could i pass a form instance to template in FormView view as SocialMediaForm(instace=someInstance) # in fun based views.

Upvotes: 0

Views: 1201

Answers (1)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21787

To update an instance of a model one should ideally be using UpdateView:

from django.views.generic.edit import UpdateView

class SocialMediaProfile(UpdateView):
    model = DoctorSocialMedia
    form_class = SocialMediaForm
    success_url = "."
    template_name = "doctor/social_media_profile.html"

This would automatically get the instance from the keyword arguments passed from the urls if they are named as pk or slug. You can set slug_url_kwarg or pk_url_kwarg if they are passed with a different name in the url to the view.

If you really need to pass some of your own keyword arguments to the form you should override get_form_kwargs (Note: This method would automatically pass the model instance (if exists) if the view inherits from ModelFormMixin). Example:

class SocialMediaProfile(FormView):
    model = DoctorSocialMedia
    form_class = SocialMediaForm
    success_url = "."
    template_name = "doctor/social_media_profile.html"

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs.update({'some_extra_kwarg': 'my_data'})
        return kwargs

Upvotes: 1

Related Questions