Reputation: 44638
Let's say we have a basic Contact
and Call
log model:
Update: It seems my initial question did not provide enough detail to explain my problem, I've updated it with a more complete example and details about what I want.
# Models.py
class Contact(model.Models):
First = ...
Last = ...
Phone = ...
class Log(model.Models):
contact = fields.Foreignkey(Contact)
date = ...
notes = ...
# urls.py
url(r'^logcall/(?P<contact_id>\d+)/$', 'myapp.views.log_call',name='log_call'),
# views.py
def log_call(request, contact_id):
formset = modelform_factory(Log)
form = formset(queryset=Log.objects.none(),initial={'contact':contact_id})
if request.method == 'POST':
form = formset(request.POST,request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/some/place')
else:
form = formset(queryset=Log.objects.none(), initial = {'contact':respondent_id,})
return render_to_response('myform.html', {'formset':form,})
# myform.html
<form method="post" action="">
{{ formset.management_form }}
{% for form in formset %}
{{ form.id }}
{{ form.callid.as_hidden }}
{{ form.contact.as_hidden }}
{{ form.date }}
{{ form.notes }}
{% endfor %}
<button>Submit</button>
</form>
What I get is:
<form method="post" action="">
<select id="id_form-0-contact" name="form-0-contact">
<option value="" selected="selected">---------</option>
<option value="1011">1011</option>
<option value="31736">31736</option>
<option value="19729">19729</option>
<option value="8818">8818</option>
<option value="19731">19731</option>
<option value="1468">1468</option>
... and so on
...
<button>Submit</button>
</form>
What I WANT from this is the following:
<form method="post" action="">
<input type="hidden" id="id_form-0-contact" name="form-0-contact" value="contact_id" />
...
<button>Submit</button>
</form>
So, everytime I load the page - it calls all the relationship data when I only need it to include a hidden value for the contact the identifies the id based on the value passed from the URL.
Upvotes: 0
Views: 81
Reputation: 3488
You want to have a view to update your model, What you're looking for is UpdateView
A view that displays a form for editing an existing object, redisplaying the form with validation errors (if there are any) and saving changes to the object. This uses a form automatically generated from the object’s model class (unless a form class is manually specified). -- Django docs
Example:
from django.views.generic.edit import UpdateView
from myapp.models import Author
class AuthorUpdate(UpdateView):
model = Author
These might be helpful too:
Upvotes: 0
Reputation: 8354
You load the form with the data...
MyModelForm(instance=myInstanceModel)
You can make use of instance parameter to instantiate form which will put initial data in the form from that object, instead of providing dict of attributes.
another example
object = myModel.objects.get(id=1)
MyModelForm(instance=object)
Upvotes: 1