Reputation: 147
How to implement a form to update the quantity Car? I have no idea how to do it. Thanks
class Car(models.Model):
name = models.CharField(max_length=50)
price = models.DecimalField()
class GarageCar(models.Model):
car = models.ForeignKey('Car')
garage = models.ForeignKey('Garage')
quantity = models.IntegerField()
class Garage(models.Model):
name = models.CharField("Garage_Name", max_length=30)
cars = models.ManyToManyField('Car', through='GarageCar', blank=True, null=True)
owner = models.ForeignKey(User, related_name='owner_garage', verbose_name='Owner Garage')
In this way updates the quantity:
In [2]: c = Car.objects.get(id=1) #here I need car ID
In [3]: g = Garage.objects.get(owner=1)
In [4]: q = 33 #here I need data from form
In [5]: c= GarageCar.objects.filter(car=c, garage=g).update(quantity=q)
views:
def show(request):
user = request.user
garage = Garage.objects.get(owner=user)
return render_to_response('garage.html', {'garage': garage, 'form':form})
in garage.html:
{% for item in garage.garagecar_set.all %}
Car: {{item.car.name}}
Price: {{item.car.price}}
Quantity: {{item.quantity}}
ID: {{item.car.id}}
{% endfor %}
in forms.py:
from django import forms
class QuantityForm(forms.Form):
q = forms.IntegerField
How to create ORM query to update quantity?
How to display a form field next to each car in template (with button "Update")?
Upvotes: 0
Views: 548
Reputation: 5230
It looks like you'll be interested in FormSets, specifically InlineFormSets:
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view
If you want to make it stupidly easy (possibly at the expense of understanding how it all works), you can use my generic views for exactly this use case.
My library: https://github.com/AndrewIngram/django-extra-views
Then...
views.py:
import extra_views
class EditProductReviewsView(extra_views.InlineFormSetView):
model = Garage
inline_model = GarageCar
fields = ('quantity', )
template_name = 'garage.html'
garage.html:
<form action="." method="post">
{% csrf_token %}
{{ formset.management_form }}
<table>
{% for form in formset %}
<tr>
<td>{{ form.instance.car.name }}</td>
<td>{{ form.instance.car.price }}</td>
{% for field in form.visible_fields %}
<td>
{{ field }}
</td>
{% endfor %}
<div style="display: none;">
{% for field in form.hidden_fields %}{{ field }}{% endfor %}
</div>
<td>{{ form.quantity }}</td>
<td>{{ form.instance.car.id }}</td>
</tr>
{% endfor %}
</table>
<input type="submit" />
</form>
I've not tested this example, I can't remember if you'll need to add the id field to the fields
tuple or not. But the basic gist should be right.
Upvotes: 1