Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement navigation DB data in Django?
got this code from a friend, we use django and bootstrap to make a rather simple site that displays job offers, until now we displayed the job offers in a row and each offer had a button "apply" that sent the resume etc.. But we would like to change that and only display one job at a time, each job would have 2 buttons "apply" and "next". We tried in a barbaric way to do all this but we have a problem, the next button works well thanks to a little javascript incorporated by my friend but the "apply" button we would like to move to the next offer after clicking on it, for now it only applies we can't get it to display the next offer, how to do? Thank you very much for simplifying your answers I am a beginner in web development, here is the code of my Django template: {% extends 'base2.html' %} {% load static %} {% block title %} Dashboard {% endblock %} {% block content %} <body class="hold-transition light-mode layout-fixed layout-navbar-fixed layout-footer-fixed"> <div class="wrapper" > <div class="content-wrapper" > <!-- Content Header (Page header) --> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> … -
Inline Images are also being attached
I am using templated_email package to send emails and embedding images using the below code block. Inline images are also being added as attachments in some devices. I don't want them to added as attachments. Is there any solution? with open(path_to_img, 'rb') as image: image = image.read() inline_image = InlineImage(filename=image_name, content=image) This is the documentation of the templated_email package https://pypi.org/project/django-templated-email/#:~:text=with%20open(%27pikachu.png%27%2C%20%27rb%27)%20as%20pikachu%3A I found a solution where if we use MIMEMultipart('related') it will solve the issue if we are using MIME to embed images directly. I want to implement the same while using Django's templated_email package. -
ferrocarrilFormulario() missing 1 required positional argument: 'request'
I need help with my code, I'm making a form in django and I can't solve this error. views.py: def ferrocarrilFormulario(request): if request.method =="POST": miFormulario = ferrocarrilFormulario(request.POST) print(miFormulario) if miFormulario.is_valid: informacion = miFormulario.cleaned_data ferrocarril = ferrocarril(request.POST["tipo"], request.POST["precio"]) ferrocarril.save() return render (request, "AppCoder/inicio.html") Forms.py: from django import forms class ferrocarrilFormulario(forms.Form): tipo= forms.CharField() precio = forms.IntegerField() Form HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Agrega un ferrocarril</title> </head> <body> {% if.miFormulario.errors %} <p style="color: red;"> Datos mal ingresados</p> {% endif %} <form action="" method="POST"{% csrf_token %} <table> {{ miFormulario.as_tabble }} </table> <input type="submit" value="Enviar"> ></form> </body> </html> urls.py: from django.urls import path from AppCoder import views urlpatterns = [ path('',views.inicio, name="Inicio"), path("ferrocarril/", views.ferrocarril, name="ferrocarril"), path("vias/", views.vias, name="vias"), path("manodeobra/", views.manodeobra, name="manodeobra"), path("tables.html/", views.tables, name="tables"), path("ferrocarrilFormulario/", views.ferrocarrilFormulario, name="ferrocarrilFormulario") thank you <3 I wanted the form to work after that, but that is not the case. PS: if I put the request, it generates another error, and in the tutorial it appears without the request. Thanks again. -
How can I sort by calculated fields in Django Admin?
I have a calculated method in my model, and in admin page want to add sort functionality for that calculated field. For now, I am using aggregation for model calculated fields and displaying that in admin. How can I add sort function for this field in admin page? class CoinWallet(Account): student = models.OneToOneField( 'students.Student', on_delete=models.PROTECT, related_name="coinWallet", null=True) @admin.display(description='Total Coins') def total_coins(self): positive_movements_aggregate = self.movement_set.filter( side=self.positive_side, ).aggregate(models.Sum('amount')) positive_movements_balance = positive_movements_aggregate[ 'amount__sum'] if positive_movements_aggregate['amount__sum'] else 0 return f'{positive_movements_balance}' @admin.register(CoinWallet) class CoinWalletAdmin(admin.ModelAdmin): list_display = ('id', 'student', 'balance', 'total_coins', 'answer_coins', 'bonus_coins', ) search_fields = ('id', 'student') def get_queryset(self, request): queryset = super(CoinWalletAdmin, self).get_queryset(request) queryset = queryset.annotate(_total_coins=ExpressionWrapper(F('balance'), output_field=DecimalField())).order_by('_total_coins') return queryset def total_coins(self, obj): return obj._total_coins total_coins.admin_order_field = '_total_coins' I tried this, but, instead of balance, i want to add sortable for total_coins. What should I do in this admin class? -
What is the best way to send field values for model creation in URL in DRF?
I have and app with books, where I want to have POST request with field's value in URL like POST URL:BOOKS/NINETEEN_EIGHTY_FOUR HTTP/1.1 content-type: application/json { "description": "my favorite book" } RESPONSE { "description": "my favorite book", "book_name": "NINETEEN_EIGHTY_FOUR" } What is the best way to do it in DRF? I have my book model with 2 field: description and book_name And in my views.py I have viewset (connected to router book) which is working with books: for example GET books/ will return full list of books and through @action decorator I get GET/POST books/{book_name} requests class BookViewSet(ListViewSet): queryset = Book.objects.all() serializer_class = BookSerializer @action(methods=['get', 'post', ], detail=False, url_path=r'(?P<book_name>\w+)',) def get_or_create_book(self, request, book_name): if request.method == 'GET': book = get_object_or_404(Book, book_name=book_name) etc book, create = Book.objects.get_or_create(book_name=book_name) Are there something better ways? -
Request.urlopen does not work after moving the server to the cloud. use docker-compose django, nginx
Yesterday, I moved to the cloud while running the server locally. Based on ubuntu 20, the server is operated using docker, django, nginx, mariadb, certbot in docker-compose. is configured and operational. It has opened both 80:port and 443post to the cloud, and outbound is allowed in the cloud itself. In docker-compose, if you receive a request from 80 or 433 from nginx.conf to upstream django_nginx server container name: 8000 after mapping from docker-compose to 80 or 433 for the application --bind 0.0.0.0:8000 Jango. Proxy_pass http://django_nginx; is passing. The problem is that when an external api is called from a running django inside the docker container (e.g. request.urlopen(url) header included or not included), there is no response. So I gave the option request.url, timeout=3 and checked, and the https request causes We failed to reach a server /Reason: _ssl.c: 980: The handshake operation timed out http request causes We failed to reach a server /Reason: timed out. I used to run a server locally as a virtual machine, but it was a logic that was going on without a problem before, so I'm very embarrassed because it didn't work after the cloud transfer. I'm inquiring because I haven't made any progress … -
Stripe Subscription Update with Django and React
I have developed backend implementation for Stripe API calls to handle the following requests : urlpatterns = [ path('subscription', SubscriptionCreate.as_view(), name="create_subscription"), path('add_payment_method', PaymentIntentCreate.as_view(), name="add_payment_method"), path('delete_payment_method', PaymentIntentDelete.as_view(), name="add_payment_method"), path('customer', CustomerView.as_view(), name="customerview"), path('webhook', stripe_webhook, name="stripe_webhook") ] Here below are my models in Django backend to handle information regarding products and the customer : class Product(models.Model): class Plan(models.IntegerChoices): FREE = 0, _('Free') BASIC = 1, _('Basic') PREMIUM = 2, _('Premium') ENTENPRISE = 3, _('Enterprise') plan = models.PositiveSmallIntegerField(choices=Plan.choices, null=False, blank=False, default=Plan.FREE) stripe_plan_id = models.CharField(max_length=40) class Customer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40, default="") product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) stripe_subscription_id = models.CharField(max_length=40, default="") clientsecret = models.CharField(max_length=80, default="") active = models.BooleanField(default=True) Also I have a post_save function that is triggered by "User Creation in Django" which also creates a Stripe Customer associated with each user and a subscription with a FREE plan that does not require payment / card information : post_save.connect(post_save_customer_create, sender=settings.AUTH_USER_MODEL) stripe_subscription = stripe.Subscription.create( customer=customer.stripe_customer_id, items=[{"price": customer.product.stripe_plan_id},], payment_behavior='default_incomplete', payment_settings={'save_default_payment_method': 'on_subscription'}, expand=['latest_invoice.payment_intent'], ) However, when the user wants to upgrade their subscription from Free to Paid models (Basic, Premium, Enterprise) then payment method / card information is required. In this case I want the subscription get into a "Incomplete" state until the payment is … -
how to insert images from database to html jinja
I'm trying to pull the link from the database in the src part, but I couldn't. im using django. images are in s3 storage. i append link to sqlite database in django. normally, {{project.ac}} is working. but <img src=> is not working. JİNJA TEMPLATE CODE <figure class="glitch-filter-example"> <figcaption class="glitch-filter-example__heading">{{ project.ac }}</figcaption><br/><br/> <img src={{ project.image }}> <img src={{ project.image2 }}> <p class="glitch-filter-example__filtered-text">HTML text</p> </figure> <script src="{% static 'icerik/js/script.js' %}"></script> PAGE SOURCE <figcaption class="glitch-filter-example__heading">MY TEXT</figcaption><br/><br/> <img src=> <img src=> -
How to generate Django / Python Test for view with LoginRequiredMixin and UserPassesTestMixin
I am trying for some time to test a view of mine that I have protected from access via LoginRequiredMixin and UserPassesTestMixin. Unfortunately I do not manage to write the appropriate test. here is the view. The special thing is, that the user must not only be logged in, but he must also belong to the group "Administrator" or "Supervisor". With this combination I have not yet managed to write a test. Please who can help me. Here is my View: class FeatureListView(LoginRequiredMixin, UserPassesTestMixin, ListView): model = FeatureFilm template_name = "project/feature-list.html" def test_func(self): if self.request.user.groups.filter(name="Administrator").exists(): return True elif self.request.user.groups.filter(name="Supervisor").exists(): return True elif self.request.user.groups.filter(name="Operator").exists(): return True else: return False def handle_no_permission(self): return redirect("access-denied") and here is a snippet of the url.py: urlpatterns = [ path("feature/list/", FeatureListView.as_view(), name="feature-list"), path( "feature/<int:pk>/date", FeatureDetailViewDate.as_view(), name="feature-detail-date", ), how would you test this FeatureListView and the template belongs to thank you very much! -
Django: How does one mock a method called in an api test?
I keep hitting a method scan_file() that should be mocked. It happens while calling self.client.post() in a django api test. The app setup is below, I've tried mocked the imported scan_file patch("myapp.views.scan_file") as well as the source location patch("myapp.utils.scan_file") neither work. # myapp.views.py from myapp.utils import scan_file class MyViewset(): def scan(): scan_file() # <- this should be mocked but its entering the code #myapp.utils.py def scan_file() -> bool: boolean_result = call_api() return boolean_result #test_api.py class MyAppTest(): def test_scan_endpoint(self): patcher = patch("myapp.views.scan_file") MockedScan = patcher.start() MockedScan.return_value = True # This post hits the scan_file code during the api # call but it should be mocked. resp = self.client.post( SCAN_ENDPOINT, data={ "file" :self.text_file, "field1" : "Progress" } ) I've also tried the following syntax for mocking, and tried including it in the test setup() as well: self.patcher = patch("myapp.views.scan_file") self.MockedScan = self.patcher.start() self.MockedScan.return_value = True -
How are Django's form assets (Media class) served?
The "Form Assets" page of Django says Django allows you to associate different files – like stylesheets and scripts – with the forms and widgets that require those assets. For example, if you want to use a calendar to render DateFields, you can define a custom Calendar widget. This widget can then be associated with the CSS and JavaScript that is required to render the calendar. When the Calendar widget is used on a form, Django is able to identify the CSS and JavaScript files that are required, and provide the list of file names in a form suitable for inclusion on your web page. Okay, but what component of Django takes those form assets and actually puts them in the page? I ask because I'm trying to use django-autocomplete-light (DAL) with django-bootstrap5 on a multi-select form with a many-to-many field. I've done all the installing, put the widget on my form field: class SomeForm(forms.ModelForm): class Meta: model = Something fields = ['things'] widgets = { 'things': autocomplete.ModelSelect2Multiple( url='myapp:things-autocomplete') } I can see the HTML for the form widget includes autocomplete-light stuff to multi-select "things" with "things" autocomplete: ... <select name="things" class="form-select" required id="id_things" data-autocomplete-light-language="en" data-autocomplete-light-url="/thing-autocomplete/" data-autocomplete-light-function="select2" multiple> </select> ... … -
Will I be able to use a wordpress site domain as a django website on a VPS?
I deleted all the files and folders associated with the Wordpress site I intend to write from scratch using standard HTML, JavaScript, CSS and with Django framework. My question is if I can use this domain with this newly created site in a VPS. At first I had erased the files and folders and recreated it with the Django app right onto the Wordpress structure, and that does not seem to be working. I am most likely doing something wrong anyways, but I am after the right way of accomplishing this. -
Django cannot migrate on Galera but MariaDB standalone works
I'm using Django together with MariaDB, I now moved my application to K8s and my Django migration don't want to run through, instead the whole migration process fails. On my local development system I'm using a standalone MariaDB instance where everything is working fine. How can it be that the same process is not working against a Galera-Cluster, here the output of my application is the following while trying to migrate all the tables: python manage.py migrate Operations to perform: Apply all migrations: App, App_Accounts, App_Storages, admin, auth, contenttypes, database, django_celery_results, sessions, sites Running migrations: Applying contenttypes.0002_remove_content_type_name... OK Applying App_Storages.0001_initial... OK Applying App_Accounts.0001_initial...Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django_prometheus/db/common.py", line 71, in execute return super().execute(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) ^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/venv/lib/python3.11/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb.OperationalError: (1170, "BLOB/TEXT column 'avatar_path' used in key specification without a key length") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/strics/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line … -
I want to make a checkbox type filter on the items of an e-commerce
I have a simple e-commerce where I want to filter items. This will be done in a form checkbox, but the form's categories are user-created, ie it's a "for" of Cor.objects.all() . The filter only works for the last selected color. So I wanted it to have multiple filters. index.html: <div class="widgets-item"> <form id="widgets-checkbox-form" action="{% url 'carro_filtro' %}" method="GET"> <ul class="widgets-checkbox"> {% for cor in cores %} <li> <input class="input-checkbox" type="checkbox" id="color-selection-{{ cor.id }}" name="termo" value="{{ cor.nome_cor }}"> <label class="label-checkbox mb-0" for="color-selection-{{ cor.id }}"> {{ cor.nome_cor }} </label> </li> {% endfor %} </ul> <input type="submit" class="btn btn-custom-size lg-size btn-primary w-100 mb-5 mt-5" value="Filtrar"> </form> </div> urls.py from django.urls import path from . import views urlpatterns = [ path('', views.CarView.as_view(), name='shop'), path('filtro/', views.CarroFiltro.as_view(), name='carro_filtro'), ] views.py class CarView(ListView): model = Car template_name = 'shop/index.html' paginate_by = 12 context_object_name = 'cars' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['personalizacoes'] = Shop.objects.filter( publicado_shop=True).order_by('-id').first() context['categorias'] = Categoria.objects.all() context['cores'] = Cor.objects.all() return context def get_queryset(self): qs = super().get_queryset() categoria = self.kwargs.get('nome_categoria', None) if not categoria: qs = qs.filter(publicado=True).order_by('-id') return qs qs = qs.filter( categoria_carro__nome_categoria__iexact=categoria, publicado=True).order_by('-id') return qs class CarroFiltro(CarView): def get_queryset(self): qs = super().get_queryset() color_selection = self.request.GET.get('termo') print("X"*100) print(color_selection) print("X"*100) if not color_selection or color_selection is … -
Django custom selection HTML page for django admin form
I have created a custom html template with basic checkboxes to select a value and return the value to the Django admin page. I have done a 100 times before, but now the value of the selected superprofile does not get captured by the variable "selected_value" in the admin.py The if statement "if request.method == 'POST':" is getting triggered but i keep getting the value of "selected_value" as none Driving me crazy, I cannot find anything wrong in the code The Html template {% extends "admin/base_site.html" %} {% load i18n admin_urls static admin_modify %} {% block extrahead %} {{ media }} {% endblock %} {% block content %} <form class="change_superprofile_parent_form" method="POST" class="change_superprofile_parent_form">{% csrf_token %} {% for superprofile in superprofiles %} <input type="checkbox" name="superprofile_selected" {{ superprofile.checked }} value="{{ superprofile }}"> {{ superprofile }}<br> {% endfor %} <input type="submit" value="Submit"> </form> {% endblock %} Django admin.py def change_superprofile_parent(self, request, queryset): """ Action to change the superprofile of the selected """ queryset = queryset.values_list("id", flat=True) if request.method == 'POST': selected_value = request.POST.getlist('superprofile_selected') eligible_superprofiles = SuperProfile.objects.filter(status='Active') return render( request, 'admin/auth/user/change_superprofile_parent.html', context={ 'superprofiles': eligible_superprofiles, } ) -
Django: Pass non-editable data from the client to the server
I am building a media tracker for TV shows and movies. When the user makes a query on the front-end, on the server I make a request with an API in which I get TV shows/movies with id, title, image link, media type, seasons, etc. After that, I display the result of the query on the front-end with the name and image: Then the user can select one of the results and get a simple form: The thing is that after submitting the form, I want to save the score and progress with the id, media type and other parameters that aren't shown on the front-end but are related to the media submitted. At the moment I am using to pass the values to the server: <input type="hidden" name="id" value="{{media.response.id}}"> The problem with this is that the user could change the id value with the developer tool (inspector), which would cause problems. I don't really know how to validate the form as the id could be any number. Is there a better and still simple approach? Thanks in advance -
Django_filter: filtering using current value of another field
So I was tasked with creating a events page where my company can post upcoming events and visitors can filter based on location, title or event type based on other 'is_virtual' which can be in person, virtual or hybrid. Now they want to 'ignore' the location filter if the event is virtual or hybrid but to keep it if the event is in person. I've been having issues accessing the value of the is_virtual field of the current object to create the conditional filtering based on it's value. here's the filter code: import django_filters from django import forms from .models import EventsPage class EventsFilter(django_filters.FilterSet): event_type = django_filters.ChoiceFilter( choices=EventsPage.event_choices, empty_label='Event Type', widget=forms.Select(attrs={'class': 'custom-select mb-2'}) ) location = django_filters.ChoiceFilter( choices=EventsPage.location_choices, empty_label='All Locations', widget=forms.Select(attrs={'class': 'custom-select mb-2'}) ) title = django_filters.CharFilter( lookup_expr='icontains', widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Search Events'}) ) class Meta: model = EventsPage fields = ['event_type', 'location', 'title'] any ideas helps! thanks in advance. tried using the method keyword argument built in django_filter library and the values passed to the helper method only show the value of the current field but I can't see the current value of the is_virtual field. here's what I tried to do: location = django_filters.ChoiceFilter( method='location_filtering', choices=EventsPage.location_choices, empty_label='All … -
Django show exception in webpage instead of on console
I am launching a Django API from the console via the following command line: python3.10 manage.py runserver 0.0.0.0:8080 However, sometimes, when there is an error on one of the pages, like for instance if I import a python package that was not installed via pip, the webserver does not get launched, I get a python exception on the console, but no webserver is launched (the network port is not even listening). Is there a way to still have the webserver running and showing any exceptions or errors that might arise ? This API is for learning purposes, the students should only be able to deploy their code by doing a git push and the new code is deployed. But in case of an error that is not shown in the webpages they would not know what went wrong, they do not have access to the server to see the console. Thank you for your help. -
Use a nested dict (or json) with django-environ?
I've got a nested dict format that I wanted to setup in an environment. It looks like this: DEPARTMENTS_INFORMATION={ "Pants": { "name": "Pants Department", "email": "pants@department.com", "ext": "x2121" }, "Shirts": { "name": "Shirt Department", "email": "shirts@department.com", "ext": "x5151" }, "Socks": { "name": "Sock Department", "email": "socks@department.com", "ext": " " } } I am using django-environ for this and tried using it like this: DEPARTMENTS = env.dict("DEPARTMENTS_INFORMATION", default={}) But it's giving me this error: ValueError: dictionary update sequence element #0 has length 1; 2 is required I'm not sure how to make the nested dictionary an environment variable - any help appreciated! -
Is there a away to make a Django SaaS app without subdomains?
i would like to ask if there's a way to make a django app with 2 roles (me as a django admin that can use /admin panel to manage the website) and customers (who have access to the app) but without using subdomains or subfolders ? thank you so much. -
Modify the structure of a table in html provided from a listview and j in django
Good night, RESUME: When I tried add a new field of the model in the html table with js and listview, the header of the table YES is modified, but the rows of it NOT are modified. I would clarify that JS is not my native develop. now I am starting with it. Then, the history of my attempts and the codes, in the source ant with the modifications. I have a table that is sourcing from a data object in js script, and render in a template of django. The data of the model is read from models.ListView. How I can to modify the structure of it??? I have tried to do, on the one hand in the js changing the "columns" property. It not modify nothing. To modify the header of the table, I have to modify the list html addint tr/td but the rows structure not add the new fields, the colums are in distinct order. without modifications: without modifications for example, if add the field 'types' that exists in model, first, in the js : columns: [ {"data": "position"}, {"data": "name"}, {"data": "types"}, {"data": "desc"}, {"data": "options"}, then, in the html add a th in the … -
Django: unable to login user with correct email/password
I am very new to Django and this is my first project. I am trying to build a simple login/registration with MySQL as db and a custom user model. The user is successfully signing up but unable to login using correct pw and email. I tried redoing my signup function and index function (login) and changed username to email in my custom model and index function. view.py: from django.shortcuts import render, redirect from django.contrib.auth import login, logout, authenticate from django.shortcuts import render, redirect from .models import CustomUser from .forms import CustomUserCreationForm, EmailAuthenticationForm from django.contrib.auth.forms import AuthenticationForm from .backends import EmailBackend # sign up def signup(request): if request.user.is_authenticated: # if user is already logged in, redirect to the appropriate page return redirect('/home') if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=True) # Hash the password user.set_password(user.password) user.save() else: form = CustomUserCreationForm() return render(request, 'signup.html', {'form': form}) # login def index(request): if request.method == 'POST': form = EmailAuthenticationForm(data=request.POST) if form.is_valid(): email = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = EmailBackend().authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect('home') else: return redirect('error') else: form = EmailAuthenticationForm() return render(request, 'index.html', {'form': form}) forms.py: from django import forms from django.contrib.auth.forms … -
JSONDecodeError in Django after Paypal payment
I keep getting the below error when I complete payment via Paypal in development: JSONDecodeError at /checkout/thankyou Expecting value: line 1 column 1 (char 0) I have looked around and I can see that there is some issue with the format of the JSON, and my view can't process it. I can't figure out what the issue with my data is exactly, however. I want to use my Json data to create an order on my Django model once it has pulled through, however I can't get to that stage yet. checkout.html script: let bagContents = '{{ bag_products|safe }}'; const csrftoken = getCookie('csrftoken'); const paymentAmount = '{{ total | safe }}'; // Parse bagContents, then for each create a variable for name, id and quantity let bag = JSON.parse(bagContents); for (let i = 0; i < bag.length; i++) { let itemName = bag[i].name; let itemId = bag[i].id; let itemQuantity = bag[i].quantity; console.log(itemName); console.log(itemId); console.log(itemQuantity); } function completeOrder(){ let url = '{{ success_url }}' fetch(url, { method: 'POST', headers:{ 'Content-type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'bagContents': 'bagContents'}) }) } paypal.Buttons({ // Sets up the transaction when a payment button is clicked createOrder: (data, actions) => { return actions.order.create({ purchase_units: [{ amount: { value: … -
django icontains doesnt work with line beakes
im using django 2.1.8 model.py class Article(models.Model): title = models.CharField("title", default="", max_length=20) text = models.CharField("comment", default="", max_length=120) the one object i have [ { "id": 1, "title": "test", "comment": "there is a linebrake" } ] views.py a = Article.objects.filter(text__icontains="\r\n").all() b = Article.objects.filter(text__icontains="there").all() It finds a but not b. As long as icontains includes the "\r\n" i can find all things normal. But a user wont search for "\r\n linebrake". how does it work without "\r\n"? -
Auto add pages for image gallery django
I have a Django website which is basically an image gallery. I want to be able to limit the amount of images that can be posted per page, and when this limit is reached, create a new one. Firstly, can this be done? If so how? TYIA