I have implemented a Python form/view/template that lets you configure different notifications for a product:
models.py
class PNotification(models.Model):
add = models.BooleanField(default=False, help_text='Receive messages when an engagement is
added')
delete = models.BooleanField(default=False, help_text='Receive
class Product(models.Model):
forms.py
class PNotificationForm(forms.ModelForm):
class Meta:
model = PNotification
exclude = ['']
class ProductForm(forms.ModelForm):
The PNotification has an own view and template:
<h3> Edit Notifications for {{ product.name }}</h3>
<form class="form-horizontal" method="post">{% csrf_token %}
{% include "dojo/form_fields.html" with form=form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input class="btn btn-primary" type="submit" value="Submit"/>
</div>
</div>
</form>
When I call the page (edit/product_id/notifications) to edit an products notifications, the h3
is set correct, so the product is passed to the form/template.
My problem is: I need to link PNotification with a product.
How can I pass product.id
to my PNotificationForm
so I can save it there? This field should be the primary key of PNotification.
Here is my view.py:
def edit_product_notifications(request, pid):
prod = Product.objects.get(pk=pid)
logger.info('Editing product')
if request.method == 'POST':
pnotification = PNotificationForm(request.POST, instance=prod)
if pnotification.is_valid():
pnotification.save()
logger.info('saved')
else:
pnotification = PNotificationForm()
if pnotification.is_valid():
pnotification.save()
logger.info('saved')
logger.info(PNotification.objects.get(id=1).msteams)
logger.info('returning')
return render(request,
'dojo/edit_product_notifications.html',
{'form': pnotification,
'product': prod
}).
I am passing the product id and then getting it from objects.get()
.
In urls.py
the path to that view needs to have <int:pk>
. The path would look like this edit/<int:pn_pk>/notifications
In your view you need to get the kwargs
which is the argument passed by the url.
In a function based view:
def your_view_name(request, pk):
# use pk how you want.
PN = PNotification.objects.get(pk=pn_pk)
return render(...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.