0

I ended up using get_initial as it was mentioned here How to subclass django's generic CreateView with initial data?

So my view changed to look like thus:

 class VlanFormView(FormView):
    template_name = 'vlan_form.html'
    model = Vlan
    form_class = VlanForm

    def get_initial(self):
        initial = {}
        default_vlan = Vlan.objects.get(pk=1)
        initial['vlan_name'] = default_vlan.vlan_name
        initial['vlan_number'] = default_vlan.vlan_number
        return initial

    def get_success_url(self):
        self.group = get_object_or_404(Group, group=self.kwargs['groupname'])
        # Redirect to vlan list
        return '/ipmgmt/%s/vlans/' % self.group

I'm looking to be able to have a pre-filled form based off a template of entered data.

So my template is based off first entry in the Vlan table which is 1...

I tried setting the instance on the form_class:

form_class = VlanForm(instance=Vlan.objects.get(pk=1))

I get a TypeError:

'VlanForm' object is not callable

Something tells me I am not using the CBV right, how can I set my initial data? Thanks

My Model:

 class Vlan(models.Model):
    vlan_name = models.CharField(max_length=30)
    vlan_number = models.CharField(max_length=6)
    group = models.ForeignKey(Group)

My Form:

class VlanForm(forms.ModelForm):
    class Meta:
        model = Vlan

My View:

class VlanFormView(FormView):
    template_name = 'vlan_form.html'
    model = Vlan
    form_class = VlanForm(instance=Vlan.objects.get(pk=1))

    def get_success_url(self):
        self.group = get_object_or_404(Group, group=self.kwargs['groupname'])
        # Redirect to vlan list
        return '/ipmgmt/%s/vlans/' % self.group
Community
  • 1
  • 1
Ryan Currah
  • 1,067
  • 6
  • 15
  • 30

1 Answers1

1

You can implement the method get_form_kwargs on your view, for example:

class YourView(FormView):
    #[...]
    def get_form_kwargs(self):
        kwargs = super(YourView, self).get_form_kwargs()
        kwargs['instance'] = Vlan.objects.get(pk=1)
        return kwargs

Or you can use an UpdateView and implement get_object

Edit: I think I misread your question, as you want to pre-fill the form; so passing instance= would not do what you want, as it would also save to that object. For using another object as a template, you could implement the get_initial method and return the fields of your object as a dict

sk1p
  • 6,645
  • 30
  • 35