Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
placeholders inside plugin template not showing up - djangocms
I am trying to render placeholders inside the plugin template. flow should be: users add a plugin into already existing placeholder in base.html and inside that rendered plugin template, there should be another placeholders for text and image. I googled some but could not find a proper place to start. does somebody know how to get this working? -
Django FilteredSelectMultiple Right Half Does Not Render
I have the same problem as [@DHerls][1], but the given solution did not work for me. Django FilteredSelectMultiple not rendering on page Other similar questions with solutions I tried: Django FilteredSelectMultiple widget rendered with bootstrap Django admin's filter_horizontal not working Uncaught ReferenceError: django is not defined The problem is that only half of the FilteredSelectMultiple shows up: Things I have tried: syncdb checking that jQuery is running checked for jQuery imports conflicting, but I am new to it, so I am unsure about this. template.html {{ form.media }} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="{% static 'js/bootstrap.js' %}"></script> <script src="{% static '/admin/js/jquery.init.js' %}"></script> <script src="{% static '/js/SelectBox.js' %}"></script> <script src="{% static '/js/SelectFilter2.js' %}"></script> <link href="https://fonts.googleapis.com/css?family=Playfair+Display+SC" rel="stylesheet"> <link rel="shortcut icon" type="imgs/favicon.png" href="{% static 'imgs/favicon.png' %}"/> [...] <form action="{% url 'recipes' %}" id="add_ingredient" method="post" accept-charset="utf-8" style="width: 400px; margin-left: auto; margin-right: auto; padding: 10px 0 30px 0;" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <span class="input-group-btn"> <button class="btn btn-secondary" style="margin-left: 40%; margin-top: 20px; padding: -10px;" type="submit">Submit</button> </span> </form> views.py decorators = [login_required, transaction.atomic] @method_decorator(decorators, name='dispatch') class RecipeCreate(CreateView): model = Recipe form_class = RecipeCreateForm template_name = 'sous/new_recipe.html' def get_context_data(self, **kwargs): context = super(RecipeCreate, self).get_context_data(**kwargs) context['form'] = RecipeCreateForm() return context def form_valid(self, form): self.object = form.save() return render(self.request, … -
Django (djmoney): How do I get the original value from a MoneyField?
I have a modal field: client_cost = MoneyField( _('client cost'), max_digits=10, decimal_places=2, default_currency='AUD', null=True, ) Now i want to do some calculations on it so i converted it to int using int(client_cost) However I'm getting an error (obviously): int() argument must be a string, a bytes-like object or a number, not 'Money' Please help. -
Django vs Stripe: idempotency_key
I created a checkout form. It works quite well, but after testing card errors such as incorrect_cvc etc. I realized the idempotency_key I provide to stripe makes me issues. Once clicking on submit and receiving a card_error, Stripe still saves this in the system, and a second checkout with the corrected CVC leads to an idempotency erro (because it was already used). I think that's not the idea of the idempotency_key but I wonder how to correct it? The idempotency_key is coming from the session_order_reference which is unique for each order. def checkout_page(request): """ * Check if session and ReservedItem exist. * Generate order_item dict for every ReservedItem entry, that belongs to order_reference. If request.method is 'POST': * Check if ticket reservation is still valid. * Create entries in models OrderItem, Order & ReservedItem. """ session_order_reference = request.session.get('order_reference') if request.session.get('order_reference'): reserved_items = ReservedItem.objects.filter( order_reference=session_order_reference ) if not reserved_items: return redirect('website:index') else: return redirect('website:index') taxes_dict = {} total_gross = total_tax_amount = 0 order_items_list = [] for item in reserved_items: event = item.ticket.event timestamp_of_reservation = item.created total_gross += item.subtotal order_item = { 'ticket': item.ticket, 'ticket_name': item.ticket.name, 'quantity': item.quantity, 'subtotal': item.subtotal, 'type': OrderType.ORDER, } total_tax_amount += add_tax( item=item, taxes_dict=taxes_dict, order_item=order_item, ) order_items_list.append(dict(order_item)) total_net … -
Amazon S3 connection with Django Heroku for image upload
I am a newbie to DevOps and deployment. I have created a CMS in Django which has an image upload option. The application is already deployed on Heroku and it uses Postgres database. I then got to know that Heroku is an ephemeral filesystem and all my images uploaded will be lost. So I need to connect it with S3 for image storage. Can anyone give the exact minimal code specifics? I have searched and tried many tutorials but none of it seem to work completely. This might be silly question but please help. I'm a newbie. -
Saving model without writing to db in Django
I have a many-to-many to many type models. I use a script to populate the database. However I want to print the objects and save it only if i want it to be saved using a y/n style input. The problem is I can't create the objects without saving them as you can see below. >>> mov = Movie(name="completenothing") >>> direc = Director(name="Someone") >>> direc.movie_name.add(mov) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 513, in __get__ return self.related_manager_cls(instance) File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 830, in __init__ (instance, self.pk_field_names[self.source_field_name])) ValueError: "<Director: Someone>" needs to have a value for field "id" before this many-to-many relationship can be used. >>> direc.save() >>> direc.movie_name.add(mov) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 934, in add self._add_items(self.source_field_name, self.target_field_name, *objs) File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 1060, in _add_items (obj, self.instance._state.db, obj._state.db) ValueError: Cannot add "<Movie: completenothing N/A>": instance is on database "default", value is on database "None" >>> mov.save() >>> direc.movie_name.add(mov) Director and Movie are in a many-to-many relation and i want their information displayed before saving. Is there some mechanism to allow this ? -
Can't use search feature in datatables server-side processing with django-datatables-view
I want to implement datatables with server-side processing because I have a lot of data to present in a single page(simple datatables are taking a lot of time).I went through the documentation in django-datatables-view I tried to implement it in my project,I can now successfully retrieve data from the server side but cannot use 'search' feature. If I type some thing in searchbox,it showing processing for a while but not updating the list of data displayed in the tables. I used python 3.6.5 and Django 2.0.6 Below is the code which I used: html : <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var a = $('#tl').dataTable( { "bPaginate": true, "bProcessing": true, "bServerSide": true, "sAjaxSource": "{% url 'order_list_json' %}" }); }); </script> urls.py: from django.conf.urls import url from django.contrib import admin from .import views from .views import OrderListJson from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ . . . . url(r'^tabledata/$',OrderListJson.as_view(), name='order_list_json') ] #used to access files in static folder using url 'static/' urlpatterns += staticfiles_urlpatterns() views.py: from django_datatables_view.base_datatable_view import BaseDatatableView . . . . . class OrderListJson(BaseDatatableView): model = Network1 columns = ['barcode', 'volret', 'state', 'flags', 'capacity','typefull','ip'] order_columns = ['barcode', 'volret', 'state', 'flags', 'capacity','typefull','ip'] max_display_length = 100 def … -
Creating a Loading Screen in Django
I have searched all over for a simple solution to this problem, but have yet to find anything. Please let me know how you would approach this. I have a Django project and an app in which of the views for the app calls a function that takes a significant amount of time (upwards of 5-10 min) to run, so I would like to display a loading screen temporarily, and then have the results of the function display. I've looked into using JavaScript, IFrames, and other solutions, but nothing has yet to work. Please keep in mind that I'm a beginner/intermediate programmer, but I would like to know if there's a simple solution to what I thought was a simple and common problem, or if I need something more complex. -
Could not parse the remainder '%quiz_id' from '"/quiz/%d/api"%quiz_id'
Could not parse the remainder: '%quiz_id'' from "/quiz/%d/api"%quiz_id written in template as {{ "/quiz/%d/api"%quiz_id }} If quiz_id=2 then it should produce /quiz/2/api Any help? -
How to test DRF serializer when using additional keyword arguments?
I have a simple model and a serializer which uses additional keyword arguments(extra_kwargs) to limit max and min value for a field. I want to write two test cases in my tests.py to both test valid and invalid values for that field (weight). How should I do this? Model from django.db import models class Person(models.Model): name = models.CharField(max_length=100) weight = models.FloatField() Serializer from rest_framework import serializers from .models import Person class PersonSerializer(serializers.ModelSerializer): model = Person fields = ('name', 'weight') extra_kwargs = {'weight': {'min_value': 5, 'max_value': 1000}} tests.py from django.test import TestCase from .models import Person class ModelTestCase(TestCase): def setUp(self): self.person = Person(name='Sam', weight=150) def test_when_weight_isValid(self): #e.g. when weight = 200 def test_when_weight_notValid(self): #e.g. when weight = 3 -
def __str__ on model
I'm looking to return a str on this model that is equal to industry name + risk level (i.e. Low) RISKLEVEL = ( (0, "Low"), (1, "Medium"), (2, "High"), ) class IndustryIndex(models.Model): industry = models.CharField(max_length=200) risk = models.IntegerField(choices=RISKLEVEL) description = models.CharField(max_length=200) def __str__(self): return self.industry + self.page I know that my syntax on the line under def str(self): isn't correct. Do you know what it should be? Also, self.page only seems to return the integer, but I'm interested in returning the description (i.e. 'High'). Thanks! -
Putting link to child pages in Django 2.0
I am trying to provide a link on the "Home" page side bar for two child pages which enable the user to carry out database changes ("update" and "delete"). Tried putting the url for mapping "update" link in the base template like: <a href="{% url 'author_update' author.pk %}">Update Author</a> But ever since it's coming up with error: Reverse for 'author_update' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog\\/author\\/(?P<pk>[0-9]+)\\/update\\/$'] This is the (relevant part of the) views.py file: from django.http import HttpResponse from django.shortcuts import render from django.views import generic from .models import Book, Author, BookInstance, Genre from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import PermissionRequiredMixin from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse import datetime from django.contrib.auth.decorators import permission_required from .forms import RenewBookForm from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Author ## #.......... class AuthorUpdate(UpdateView): model = Author fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death'] And the app urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.CatIdx, name='CatIdx'), path('books/', views.BookListView.as_view(), name='books'), path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), path('authors/', views.AuthorListView.as_view(), name='authors'), path('author/<int:pk>', views.AuthorDetailView.as_view(), name='author-detail'), path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my_borrowed'), path(r'borrowed/', views.LoanedBooksAllListView.as_view(), name='all-borrowed'), path('book/<uuid:pk>/renew/', views.renew_book_librarian, name='renew-book-librarian'), path('author/create/', views.AuthorCreate.as_view(), name='author_create'), path('author/<int:pk>/update/', views.AuthorUpdate.as_view(), name='author_update'), … -
Django Admin - Dynamically pick list_display fields (user defined)
Some of my models have a lot of fields and the user may not need to see all of them at any given point in time. I am trying to add functionality to allow the user to select which fields are displayed from the front end without having to change the list_display definition in the admin.py file. I also don't want to just dump all of the fields out there for them either. I am hoping someone may be able to point me at something on github or give me some advice on how to go about doing this. Thanks in advance. -
Django Runserver and Workers
I'm hoping someone knows off the top of their head... but how do I use runserver without channel workers for Django? I'm running the workers on other images for scaling and I can't get passed an annoying socket connection error that only seems to happen on Daphne, so I am trying to test with runserver. I just can't seem to find the right command anywhere! -
In Django, how can I "not" return a HTTP response as to not reload a web page when a view function is called
How can I call my view function from a button click and have it return something that would result in my web page not reloading? It seems that I must return an HTTP request in some way or I get an error. I have a page with a long list of objects from my database that users can input quantities and click a button which sends the form data to a cart object. In doing this, the corresponding view function is triggered and returns some sort of HTTP Response which results in the page loading in some way. I would like it so that absolutely nothing happens when a button is clicked, other than the form data being submitted. Not even a redirect to the same page. This is because I don't want the user to lose there place on the page and have to scroll through a list of objects to find where they were. views def add_to_cart(request, product_id): return HttpResponse('') url path path('cart/add/<product_id>', home_views.add_to_cart, name='add_to_cart'), Quote <form action="{% url 'add_to_cart' product.id %}" method="post">{% csrf_token %}</form> -
When saving the generated access token in the oauth2_provider_accesstoken model the created and updated timestamp is null
So I have deployed my Django application which serves as a backend to my Angular 2 web application. Now when I'm authenticating my request it is supposed to generate an access token and save it in the oauth2_provider_accesstoken model. However it throws an integrity error stating that the created and updated columns are null (which are supposed to have an auto generated timestamp). Everything works on my local setup, so not sure what is wrong. Here is the stack trace:- return view(request, *args, **kwargs) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/utils/decorators.py", line 63, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/ubuntu/.local/lib/python2.7/site-packages/oauth2_provider/views/base.py", line 176, in post url, headers, body, status = self.create_token_response(request) File "/home/ubuntu/.local/lib/python2.7/site-packages/oauth2_provider/views/mixins.py", line 125, in create_token_response return core.create_token_response(request) File "/home/ubuntu/.local/lib/python2.7/site-packages/oauth2_provider/oauth2_backends.py", line 139, in create_token_response headers, extra_credentials) File "/home/ubuntu/.local/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/endpoints/base.py", line 64, in wrapper return f(endpoint, uri, *args, **kwargs) File "/home/ubuntu/.local/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/endpoints/token.py", line 118, in create_token_response request, self.default_token_type) File "/home/ubuntu/.local/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.py", line 121, in create_token_response self.request_validator.save_token(token, request) File "/home/ubuntu/.local/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/request_validator.py", line 246, in save_token return self.save_bearer_token(token, request, *args, **kwargs) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner return func(*args, **kwargs) File "/home/ubuntu/.local/lib/python2.7/site-packages/oauth2_provider/oauth2_validators.py", line 365, in save_bearer_token access_token = self._create_access_token(expires, request, token) File "/home/ubuntu/.local/lib/python2.7/site-packages/oauth2_provider/oauth2_validators.py", line 390, in _create_access_token access_token.save() File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/models/base.py", line 806, in save force_update=force_update, update_fields=update_fields) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/models/base.py", line 836, in … -
How can I override Django Rest Framework viewset perform_create() method to set a default value to a field
I have a model called Product and two viewsets that manage the same model in different ways. Each one must set a different value for field product_type, which is set read_only in the serializer SuplementSerializer. I trying to override perform_create() method and set the value for field product_type, but it always takes the default value. This is my mode: class Product(models.Model): ROOM = 'ROOM' SUPLEMENT = 'SUPLEMENT' PRODUCT_TYPE_CHOICES = ( (ROOM, _('Room')), (SUPLEMENT, _('Suplement')) ) hotel = models.ForeignKey(Hotel, on_delete=models.PROTECT, related_name='products', verbose_name=_('Hotel')) name = models.CharField(max_length=100, verbose_name=_('Name')) product_type = models.CharField(max_length=9, choices=PRODUCT_TYPE_CHOICES, default=ROOM, verbose_name=_('Product Type')) room_type = models.ForeignKey(RoomType, null=True, blank=True, on_delete=models.PROTECT, related_name='products', verbose_name=_('Room Type')) plan_type = models.ForeignKey(PlanType, null=True, blank=True, on_delete=models.PROTECT, related_name='products', verbose_name=_('Plan Type')) content_type = models.ForeignKey(ContentType, null=True, blank=True, on_delete=models.PROTECT, related_name='rate_base_products', verbose_name=_('Rate Base')) object_id = models.PositiveIntegerField(null=True, blank=True) rate_base = GenericForeignKey('content_type', 'object_id') class Meta: verbose_name = _('Product') verbose_name_plural = _('Products') def __str__(self): return "[{}][{}]{}".format(self.id, self.hotel, self.name) def save(self, *vars, **kwargs): self.full_clean() return super().save(*vars, **kwargs) def clean(self, *vars, **kwargs): if self.content_type != None: if self.content_type.model != 'ages' and self.content_type.model != 'roombase' and self.content_type.model != 'product': raise CustomValidation(_("rate_base must be an instance of either 'Ages' or a 'RoomBase'"), 'rate_base', status.HTTP_400_BAD_REQUEST) These are my viewsets: class SuplementViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated,) queryset = models.Product.objects.filter(product_type=models.Product.SUPLEMENT) serializer_class = serializers.SuplementSerializer filter_backends = … -
How does django-oscar call the image of the product in templates?
How does django-oscar call the image of the product in templates? Such as {{ product.title }}. I tried {{product.productimage_set.original}} but it didn't take effect. Can anyone help me with this? Thank you, thank you very much. -
Truncate links/<a> tags in Django?
I'm utilising Django's template tag urlize, which automatically converts URLs in a string to a clickable link. E.g: <p>{{ i.comment_text|urlize }}</p> I want to truncate those links. Is this possible using Django syntax? -
Django 2.0 Internationalization | i18n_patterns not working
I have been working with i18n so that the URL included the prefix "/en/" or "/es/" depending on the users preferred language. So far it was working fine while using Django 1.9 it even placed automatically the prefix even when the user didn't submit it in the URL (i.e. mySite.com would redirect to mySite.com/en/). Now that I upgraded to 2.0 it is not working and it shows a 404 error: Using the URLconf defined in smce.urls, Django tried these URL patterns, in this order: en/ ^static/(?P.*)$ ^images/(?P.*)$ The empty path didn't match any of these. At my root urls.py i have: urlpatterns = i18n_patterns( path('admin/', admin.site.urls), path('login/', anonymous_required(views.login), {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), path('', include('matrix.urls'), name='matrix'), ) Any help or guidance would be appreciated. -
Django 2.0, URL Routes Causing Max Recursion with check_method
I'm totally new to Django, and I'm having a problem adding a Django "app" to a created Django "project". I'm using Docker and Docker-Compose and when I try to build and spin up my instance with the "documents" app added it throws maximum recursion errors. This problem is NOT present if I remove the documents app from the project, so there's obviously something misconfigured with my app. Does anyone see what I'm doing wrong to set my default URL ('') to the Index view in documents? Directory Structure app/ |-django_nlp/ |-settings.py |-urls.py |-wsgi.py |-documents/ |-templates/ |-index.html |-apps.py |-views.py |-Dockerfile |-docker-compose.yml |-manage.py django_nlp/settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # /usr/src/app # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ixoz#2d4=m#k#%1#!hhr2ei82t4x$$e)n9oxrq66mzq556k59@' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'documents' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_nlp.urls' #Get the absolute path of the settings.py file's directory BASE_PATH = … -
Issue while saving object to database because model contains jsonfield sqlite3 django
I had a really tough time to get fix this issue please help if you know this. I have a project on django, It contain model with two fields, one is of type foreign key and other one is jsonfield. When it goes to save object in database, it doesn't get saved instead it throw exception. I don't know what's the issue is. But issue is only specific to sqlite3 database. it is working fine with other databases. I am pasting stack trace and code. it throws exception on this line student_record_obj.save() Internal Server Error: /tableapp/postdata/ Traceback (most recent call last): File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Python35\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Python35\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 85, in … -
Superimposing points on a pdf chart
I am trying to create an online app where specific data points need to superimposed or put on a specific chart (from WHO). https://www.dietitians.ca/Downloads/Public/LFA-WFA_Birth-24_BOYS_SET-2_EN.aspx What is the simplest way to accomplish this so points can be place on-top of this exact graph? The app will be built with Python/Django. Any suggestions would be greatly appreciated. -
Redirect POST request to URL already used (Django)
I have a table with a few products and next to each one there is a Add to cart button that changes the product.in_cart boolean value to true. When I click on the button, the value changes but I am not going to the URL I want (add_to_cart/product_id). I would like to be redirected to the index (list of products). How can I do that? I also receive an error message: The view products.views.add_to_cart didn't return an HttpResponse object. Here is my code: index.html <table> <tr> <th>List of car parts available:</th> </tr> <tr> <th>Name</th> <th>Price</th> </tr> {% for product in products_list %} <tr> <td>{{ product.id }}</td> <td>{{ product.name }}</td> <td>${{ product.price }}</td> <td>{% if not product.in_cart %} <form action="{% url 'add_to_cart' product_id=product.id %}" method="POST"> {% csrf_token %} <input type="submit" id="{{ button_id }}" value="Add to cart"> </form> {% else %} {{ print }} {% endif %} </td> </tr> {% endfor %} </table> <a href="{% url 'cart' %}">See cart</a> views.py def cart(request): if request.method == 'GET': cart_list = Product.objects.filter(in_cart = True) template_cart = loader.get_template('cart/cart.html') context = {'cart_list': cart_list} return HttpResponse(template_cart.render(context, request)) def add_to_cart(request, product_id): if request.method == 'POST': product = Product.objects.get(pk=product_id) product.in_cart = True product.save() urls.py urlpatterns = [ path('', views.index, name='index'), … -
How can I implement django-samrt-selects in mi html template
I have already done this steps. pip install django-smart-selects I added smart_selects to your INSTALLED_APPS I Binded the smart_selects urls into your project's urls.py. I set the Models according to the documentaction.