passing a parameter through CreateView to a be an initial value in a form

2,170 views
Skip to first unread message

Patrick Carra

unread,
Feb 19, 2020, 4:51:17 PM2/19/20
to Django users
Hello I am trying to pass a value from a link into CreateView and use that value as an inital value in a form.  I am not having much success and am not sure that I am doing this correctly.  Here is what I have so far:
Link:
<a href="/viewlit/addXC/{{ record.pk }}" target="blank" class="edit-item" title="Add"><img src="{% static "images/plus.png" %}" alt="Add" title="Add" style="width: 4%;"></a>Circuit Ref: {{ record.id1 }}<br>

urls.py
path('addXC/<path:circuitref>/', views.addXC.as_view(), name='addXC'),

views.py
class addXC(CreateView):
    model
= Xcinventorytable
    fields
= ['circuitref', 'circuitid', 'vendor', 'legacy', 'address', 'city', 'state', 'ciopsticket', 'notes']
    success_url
="/thanks/xcadded/"


   
def get_form_kwargs(self):
        kwargs
=super(addXC, self).get_form_kwargs()
        kwargs
.update({'circuitref': circuitref})
       
return kwargs

forms.py
class XcinventorytableForm(ModelForm):
   
class Meta:
        model
= Xcinventorytable
        widgets
= {'notes': forms.TextInput(attrs={'size':200, 'rows':2})}
        help_texts
= {'Circuitref': ('Enter the circuitref listed at the top of the last screen')}
        fields
= '__all__'


   
def __init__(self, *args, **kwargs):
        circuitref
= kwargs.pop('circuitref')
       
super(XcinventoryForm, self).__init__(*args, **kwargs)
       
self.fields['circuitref'].initial = circuitref


Any help or suggestions are appreciated

Sam Hefer

unread,
Feb 19, 2020, 10:35:16 PM2/19/20
to Django users
Hey Patric,

Have a look at stackoverflow.

https://stackoverflow.com/a/60273100/7063031

I used form_valid in the createview to get the form instance field, passed the pk through the URL to the template, then used get_context in the view so the template can get the pk from the URL. You’ll understand better when you use it and play around with it.
Reply all
Reply to author
Forward
0 new messages