Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign "OrderItem.product" must be a "Product" instance
I am trying to create a "create order" endpoint, i keep getting Cannot assign "<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7f50dad00f70>": "OrderItem.product" must be a "Product" instance. heres my models def product_images(instance, filename): return f"product/{instance.product_name}/{filename}" class Product(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=200, null=True, blank=True) description = models.TextField() date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) image = models.ImageField( storage=MediaRootS3BotoStorage(), upload_to="product_images", null=True, blank=True, ) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name def save(self, *args, **kw): self.slug = slugify(f"{self.name}") super(Product, self).save(*args, **kw) # Ecommerce Models Store and Product def store_images(instance, filename): return f"{instance.store_name}/{filename}" class Store(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=200, null=True, blank=True) description = models.TextField() date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) image = models.ImageField(upload_to="store_images", null=True, blank=True) delivery_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) address = models.CharField(max_length=100, null=True, blank=True) phone_number = models.CharField(max_length=100, null=True, blank=True) products = models.ManyToManyField("Product", through="StoresProduct") def __str__(self): return self.name def save(self, *args, **kw): self.slug = slugify(f"{self.name}") super(Store, self).save(*args, **kw) class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ManyToManyField("Product", through="StoresProduct") quantity = models.IntegerField(default=1) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.user.email def get_total(self): return self.product.price * self.quantity class StoresProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) seller = models.ForeignKey(Store, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) quantity = models.IntegerField(blank=True, null=True) date_created … -
Django printing variable in template that has been passed to it in python
I am trying to get 'date' which can be eg 2023/01/29 to print in my template file. def time_booking(request): if 'date' in request.COOKIES: context = { 'date':request.COOKIES['date'], } print("Run Run") return render(request, "path_to_file.html", context) <h1>Date will be here here</h1> {% if date != -1 or null %} <h1> Date is real {{date}}</h1> {% else %} <h1> Date is not real{{date}} </h1> {% endif %} <h1> complete run </h1> The code currently check if the variable 'date' exists and isn't -1 but I then go to print it and the content doesn't come out. I tried using a single set of {} as well as using print(content[date]), but again the variable was not output. I am trying to get it to output the date which has been entered before hand. Any help would be greatly apricated. -
Static Files not loading when DEBUG = False
I'm using namecheap shared hosting and I hosted my site using cpanel. My site is working fine but if i made DEBUG = False in project settings.py file the static files are not loading. My site url: https://drshahidabegum.com/ settings.py ----------- # Static files (CSS, JavaScript, Images) STATIC_DIR = [ BASE_DIR / "static", ] STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py in project folder ------------------------- """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('dr_shahida.urls')), ] # Configure Admin Titles admin.site.site_header = "DR. Shahida Begum" admin.site.site_title = "DR. Shahida Begum" admin.site.index_title = "Welcome to Admin Dashboard" handler404 = 'dr_shahida.views.error_404_view' urls.py in app folder ------- from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.index, name='index'), path('testimonial/', views.testimonial, name='testimonial'), path('contact/', views.contact, name='contact'), path('blog/', views.blog, name='blog'), path('blog/post/<int:post_id>', views.blogdetailview, name='blogdetailview'), path('set_language/<str:ln>', views.set_lang, name='set_lang'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I want my static files to work when DEBUG = False in project settings.py file. -
Truly dynamic DateField values in Django
Some of my app models define date ranges (e.g. of contracts), where the current instance has no fixed end date (i.e. it should always evaluate to today). Setting the default parameter on the end field – class Contract(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) begin = models.DateField() end = models.DateField(default=datetime.date.today) – will populate the field with a fixed value. A property to work around the problem – class Contract(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) begin = models.DateField() end = models.DateField(blank=True) @property def get_end(self): if not self.end: return datetime.date.today() return self.end – does not work with querysets. Is there any way to implement a truly dynamic value on the database level using Django's ORM? -
Django-graphene query sorting is not working
I have model Event which I want to sort by event_datetime column in resolver, but it doesn't work. My Event model looks like this: class Event(models.Model): name = models.CharField(db_index=True, max_length=255) event_type_id = models.ForeignKey(EventType, on_delete=models.PROTECT, default='friendly match', related_name='events_by_type') city = models.CharField(max_length=255, db_index=True, blank=False) country = models.CharField(max_length=255) place_id = models.ForeignKey(Place, on_delete=models.SET_NULL, null=True, related_name='events_by_place') event_datetime = models.DateTimeField() tournament_id = models.ForeignKey(Tournament, on_delete=models.PROTECT, blank=True, null=True, related_name='events_by_tournament') description = models.TextField(blank=True) organizer = models.ForeignKey(User, on_delete=models.PROTECT, related_name='organizer', blank=True) participants = models.ManyToManyField(User, blank=True, related_name='events_by_participant') creation_datetime = models.DateTimeField(auto_now_add=True, editable=False) update_datetime = models.DateTimeField(auto_now=True) And my Query object looks like this: class Query(graphene.ObjectType): events_by_organizer = graphene.List(EventType, id = graphene.ID(required=True)) def resolve_events_by_organizer(root, info, id): try: return Event.objects.filter(organizer=id).order_by('-event_datetime') except Event.DoesNotExist: return None In graphQL I get events query without sorting by event_datetime. How can I sort query in Django-graphene? -
How to fix django.db.utils.OperationalError: (1046, 'No database selected')
I have a column problem in the database when the yak uses python manage.py migrate. I want to write code to use DATABASE_URL in docker-compose.yml, how should I solve it? I've experimented with writing these codes. Can you advise me a bit? mysql> show databases; +--------------------+ | Database | +--------------------+ | DatabaseUBU | | information_schema | | mariadb | | mydb | | mysql | | performance_schema | | sys | +--------------------+ 7 rows in set (0.02 sec) mysql> create database mariadb; ERROR 1007 (HY000): Can't create database 'mariadb'; database exists docker-compose.yml version: '3.7' services: db: image: mariadb:10 command: --default-authentication-plugin=mysql_native_password restart: always environment: - MYSQL_ROOT_PASSWORD=mariadb - MYSQL_DATABASE=mariadb - MYSQL_USER=mariadb - MYSQL_PASSWORD=mariadb - MARIADB_ROOT_PASSWORD=mysecretpassword ports: - 3306:3306 volumes: - "mysqldata:/var/lib/mysql" web: build: . restart: always command: python manage.py runserver 0.0.0.0:8000 environment: - DATABASE_URL=mariadb+mariadbconnector://user:mariadb@db:3306/mariadb ports: - "8000:8000" depends_on: - db volumes: mysqldata: setting.py import dj_database_url import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', **dj_database_url.config(default=os.environ.get('DATABASE_URL')) } } -
How to write to Django FileField from a tempfile?
I am processing an image within a Django app. I used rasterio to process the geospatial image. I want to save the output directly to a FileField in a Model. I used a tempfile to write the output from rasterio, and used the method Model.FileField.save to hopefully write it with a reference to my Model instance. I have a simple model: class MaskedLayer(models.Model): name = models.CharField(max_length=250, blank=True) file = models.FileField( upload_to='masked', null=True, max_length=500) In my tasks, however this is an example: from celery import shared_task import rasterio import tempfile from app.models import MaskedLayer @shared_task def process_image(): mask_layer_name = 'processed_image.tif' masked_layer = MaskedLayer.objects.create() with rasterio.open('example.tif') as dataset: # only example of reading/processing of image out_image = dataset.read() with tempfile.NamedTemporaryFile() as tmpfile: tmpfile.write(out_image) with rasterio.open(tmpfile.name) as dataset: masked_layer.file.save(mask_layer_name, File(dataset)) pass I get this response. I am not sure of the error. Feel free to use the example file. Fatal Python error: Segmentation fault Current thread 0x00007f453b463740 (most recent call first): File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 232 in get_traceback_frame_variables File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 544 in get_exception_traceback_frames File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 490 in get_traceback_frames File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 320 in get_traceback_data File "/usr/local/lib/python3.11/site-packages/django/views/debug.py", line 403 in get_traceback_text File "/usr/local/lib/python3.11/site-packages/django/utils/log.py", line 125 in emit File "/usr/local/lib/python3.11/logging/init.py", line 978 in handle … -
VS Code + Pylance does not find venv-installed modules while venv is activated
I use VS Code Version: 1.74.3 on MacOS 13.2. python -V returns Python 3.11.1. I get the following error message: Import "django.shortcuts" could not be resolved from source Pylance(reportMissingModuleScource). As you can see in the screenshot, the correct venv is activated and includes Django. I checked also these threads: Import could not be resolved/could not be resolved from source Pylance in VS Code using Python 3.9.2 on Windows 10 and https://stackoverflow.com/a/65802367/2321643 but the suggested solution with reloading the windows did not help. Using Debug I can safely run my Django-application without any import issues. What do I need to do that Pylance does not issues these problems? -
Override response in Django Rest Framework serializer
I have a serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'name') And view: class UserListView(ListAPIView): model = User serializer_class = UserSerializer And as expected on a GET request i get a response like [ { "id": "1", "name": "First", }, { "id": "2", "name": "Second", } ] What should i change to get response like this: [ 'users': [ { "id": "1", "name": "First", }, { "id": "2", "name": "Second", }] ] I think it's easy, but can't understand how. -
how to extract the folder from zip file in upload with html and javascript and django
I am working on a django app in which the html code called tool.hmtl along with the javascript code called myscripts.js let the user upload the folder and then do some processing on that data. Relevant section of tool.hmtl is given as follows. <main class="tool mg-t-900"> <div id="folderUploadDiv"> <h1 class="tool__heading | text-center text-capitalize"> Upload your folder here </h1> <label for="folder" class="tool__upload | flex flex-center flex-column mg-t-500 text-center" > <i class="ri-upload-cloud-line tool__icon"></i> <p class="tool__txt text-capitalize">Browse folder to upload</p> </label> <input type="file" id="folder" webkitdirectory multiple /> .............some code...... <script src="{% static 'myscripts.js' %}"></script> <script src="{% static 'app.js' %}"></script> <script> const fileInput = document.querySelector("#folder"); const loder = document.querySelector(".loder"); const toggleLoder = function () { loder.classList.add("active"); setTimeout(() => { loder.classList.remove("active"); }, 30000); startTypingAnimation(); }; fileInput.addEventListener("change", toggleLoder); function startTypingAnimation() { new TypeIt("#loder-text", { strings: "Your file is being prepared...", speed: 75, loop: true, }).go(); } </script> <script> setTimeout(function () { location.reload(); }, 300000); // refresh every 5 minutes (300000 milliseconds) </script> </body> </html> {% endblock %} and relevant section of myscripts.js is as under. // const axios = require('axios'); $("#folderUploadDiv").show(); $("#selectorDiv").hide(); username = ""; contentType = ""; var dataToSend = [] var flag=1 document.getElementById("folder").addEventListener("change", function(event) { var output = document.querySelector("ul"); var files = event.target.files; var … -
How can I write function in views.py using rest_framework
I want to processing posted api data in views.py. How can I do it. I am getting error. My views.py: from django.shortcuts import render, redirect from rest_framework import viewsets from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Student, Teacher from .serializer import StudentSerializer, TeacherSerializer class StudentView(viewsets.ModelViewSet): @api_view(['GET', 'POST']) def index(self,request): if request.method == 'GET': queryset = Student.objects.all() serializer_class = StudentSerializer elif request.method == 'POST': pass class TeacherView(viewsets.ModelViewSet): queryset = Teacher.objects.all() serializer_class = TeacherSerializer My urls.py: from django.contrib import admin from django.urls import path, include from students import views from rest_framework import routers router = routers.DefaultRouter(trailing_slash = False) router.register(r'studentdetails', views.StudentView, basename='studentdetails') router.register(r'teacherdetails', views.TeacherView, basename='teacherdetails') urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)) ] when I'm opening http://localhost:7777/studentdetails I'm getting error: 'StudentView' should either include a queryset attribute, or override the get_queryset() method. How can I write it correct? -
How can I move an image element on the x-axis at keypress with Javascript?
In my Django project, I have a "sprite" which is an image element in the HTML template. I want to make a small interactive game on the page when clicked on "A" key, the image will move on the x-axis. How can I achieve that with JavaScript? I tried to change the offsetLeft value using .offsetLeft and the x position value by updating the .style attribute but couldn't manage it both ways. contact.html: {% load static %} {% block script %} <script src="{% static 'potbs/contact.js' %}"></script> {% endblock %} {% block body %} <div class="col"> <img src="media/images/phone.png" alt="phone" class="rounded floar-start"> <img src="media/images/stick.png" class="rounded float-end" id="sprite" alt="..." style="margin-top:100px;"> <img src="media/images/wasd.png" class="rounded float-end" id="wasd" alt="..." style="margin-top:100px;display: none;"> <button class="btn btn-primary float-end" id="start">Start</button> </div> {% endblock %} contact.js: document.addEventListener("DOMContentLoaded", function(){ const button = document.getElementById("start"); const wasd = document.getElementById("wasd"); const sprite = document.getElementById("sprite"); button.onclick = function(){ button.style.display = "none"; wasd.style.display = "block" document.addEventListener("keypress",function(event){ if(event.key == "a"){ wasd.style.display = "none"; sprite.offsetLeft = sprite.offsetLeft + 10; } }); }; }) -
How to return values that are NULL in database with Django?
I hava a django app and I try to write some api calls. So I have one table And I want to return the values where category_id is null. So this sql statement works: SELECT * FROM public.djangoadmin_category where djangoadmin_category.category_id is null ORDER BY id ASC returns as output: 11 "zoogdieren" "zoogdieren" "hoi" "photos/categories/1_eDJtmdP.jpg" "2023-01-27 18:25:18.624272+01" "2023-01-27 18:25:18.624272+01" 12 "amfibieen" "amfibieen" "kujhkjh" "photos/categories/1_KJDTBPc.jpg" "2023-01-27 18:25:38.444066+01" "2023-01-27 18:25:38.444066+01" 13 "vogels" "vogels" "kljhkjh" "photos/categories/1_FGkA44b.jpg" "2023-01-27 18:26:00.390812+01" "2023-01-27 18:26:00.390812+01" 21 "reptielen" "reptielen" "reptielen" "photos/categories/1_EoVggfL.jpg" "2023-01-27 18:55:04.565339+01" "2023-01-27 18:55:04.565339+01" 23 "schildpadden" "schildpadden" "schildpadden" "photos/categories/1_RkKQ5md.jpg" "2023-01-27 18:55:51.724641+01" "2023-01-29 12:40:45.014174+01" But now I want to write a API call for it, so that I can use it for the frontend. the model: from django.db import models class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) description = models.TextField(max_length=1000) images = models.ImageField(upload_to="photos/categories") category = models.ForeignKey( "Category", on_delete=models.CASCADE, related_name='part_of', blank=True, null=True) date_create = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) class Meta: verbose_name = "category" verbose_name_plural = "categories" def __str__(self): return self.name urls.py: from django.urls import path, include from rest_framework import routers from .views import CategoryViewSet router = routers.DefaultRouter() router.register('categories', CategoryViewSet) urlpatterns = [ path('', include(router.urls)) ] serializer: from rest_framework import serializers from .models import Animal, Category class CategorySerializer(serializers.ModelSerializer): animals = AnimalSerializer(many=True) … -
ModuleNotFoundError: No module named 'poststaggit' --- How do I make error?
ModuleNotFoundError: No module named 'poststaggit' ModuleNotFoundError: No module named 'poststaggit' -
Django with Bootsrap treeview
I’m trying to create a page to show a folder and its content using Tree-view Bootstrap. The folder may contain many sub-folders and files (child nodes). I want to implement one of those examples in a Django application. Bootstrap Tree-views page Let's say this one Animated Tree-views. where my model is: class Document(models.Model): Title = models.CharField(max_length=150) SHRPath = models.FileField(upload_to='Document/', validators= [validate_file_size]) def __str__(self): return self.Title and the views.py: def FileTree(request): documents = Document.objects.all()[:100] tree_data = [] for document in documents: shr_path_string= str(document.SHRPath) parents = shr_path_string.split('/') nodes = [{"text": parent} for parent in parents] tree_data.append({"text": document.Title, "nodes": nodes}) context = { 'tree_data': tree_data, } return render(request, 'filetree.html', context) and the HTML page is: <!DOCTYPE html> <div id="treeview"></div> <script> let data = {{ tree_data|safe }}; $(document).ready(function() { console.log("Tree data:", data); $('#treeview').treeview({ data: data, }); }); </script> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- Bootstrap Treeview CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css"> <!-- Bootstrap Treeview JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js"></script> This it doesn’t work however and it shows a blanc page!. Then to check if the data is rendered to the page I checked it by adding this code to page and its ok. <div class="row"> <div class="card card-body"> … -
nullable field default value django models in inhertiance
I have a model of product and another model called Course that inherits the product but has a video field and an author Which is a ForeignKey with A teacher model which inherits from the user model which inherits from AbstractUser Related Models: class User(AbstractUser): username = models.SlugField(default="", null=False, db_index=True, blank=True) # forced by django admin problems :( password = models.CharField(max_length=255, null=True) email = models.EmailField(max_length=255, unique=True) group = models.ManyToManyField(Group) is_teacher = models.BooleanField(default=False, null=False) is_seller = models.BooleanField(default=False, null=False) phoneNum = PhoneNumberField(null=False, unique=True, default='') USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username", "first_name", "last_name", "password"] def save(self, *args, **kwargs): self.username = slugify(self.first_name + self.last_name) super().save(*args, **kwargs) class Product(models.Model): name = models.CharField(max_length=100, null=False, blank=True) shoppers = models.ManyToManyField(User, related_name='shopper') tumb = models.ImageField(upload_to=course_tumb_directory_path, null=False) lastUpdate = models.DateTimeField(auto_now=True) price = models.DecimalField(null=False, default=1000000, max_digits=7, decimal_places=0) class Teacher(User): TOPICS = [ ("BP", "Basic Programming"), ("AP", "Advanced Programming"), ("CS", "Computer Science"), ("MS", "Mathematics"), ("CH", "Chemistry"), ("BL", "BioLogy"), ("PH", "physics"), ("EL", "Electronics"), ("RG", "Religious"), ("Or", "Other"), ] topic = models.CharField(max_length=2, choices=TOPICS, default=TOPICS[-1]) class Course(Product): video = models.FileField(upload_to=course_directory_path, null=True, validators=[ FileExtensionValidator(allowed_extensions=['MOV', 'avi', 'mp4', 'webm', 'mkv'])]) author = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=True) when I'm trying to make migrations it says this: It is impossible to add a non-nullable field 'product_ptr' to course without specifying a … -
django testing fails with DoesNotExist even though it works when actually running
I'm trying to test if my PlayerPoint model can give me the top 5 players in regards to their points. This is the Player model: class Player(AbstractUser): phone_number = models.CharField( max_length=14, unique=True, help_text="Please ensure +251 is included" ) first_name = models.CharField( max_length=40, help_text="please ensure that you've spelt it correctly" ) father_name = models.CharField( max_length=40, help_text="please ensure that you've spelt it correctly" ) grandfather_name = models.CharField( max_length=40, help_text="please ensure that you've spelt it correctly" ) email = models.EmailField( unique=True, help_text="please ensure that the email is correct" ) age = models.CharField(max_length=3) profile_pic = models.ImageField(upload_to='profile_pix', default='profile_pix/placeholder.jpg') joined_ts = models.DateTimeField(auto_now_add=True, null=False) username = None and this is the PlayerPoint model: class PlayerPoint(models.Model): OPERATION_CHOICES = (('ADD', 'ADD'), ('SUB', 'SUBTRACT'), ('RMN', 'REMAIN')) points = models.IntegerField(null=False, default=0) operation = models.CharField( max_length=3, null=False, choices=OPERATION_CHOICES, default=OPERATION_CHOICES[2][0] ) operation_amount = models.IntegerField(null=False) operation_reason = models.CharField(null=False, max_length=1500) player = models.ForeignKey( settings.AUTH_USER_MODEL, null=False, on_delete=models.PROTECT, to_field="phone_number", related_name="player_points" ) points_ts = models.DateTimeField(auto_now_add=True, null=False) I also have a pre-save signal handler. @receiver(signals.pre_save, sender=PlayerPoint) if sender is PlayerPoint: try: current_point = PlayerPoint.objects.filter(player=instance.player).latest() except PlayerPoint.DoesNotExist as pdne: if "new player" in instance.operation_reason.lower(): print(f"{pdne} {instance.player} must be a new") instance.operation_amount = 100 instance.points = int(instance.points) + int(instance.operation_amount) else: raise pdne except Exception as e: print(f"{e} while trying to get … -
Ajax POST request is not working in Django project
I was trying to build a E Commerce website as part of my project. But the ajax "POST" using jquery is not working. I am not sure where it went wrong. Please forgive for my poor English.... {% extends "store/base.html" %} {% load static %} {% block title %} {{ product.name }} {% endblock %} {% block content %} <div class="container"> <main class="pt-5"> <div class="row g-3"> <div class="col-md-5 col-lg-5 order-md-first bg-light"> <img class="img-fluid mx-auto d-block" width="200px" alt="Responsive image" src="{{ product.image.url }}"> </div> <div class="col-md-7 col-lg-7 ps-md-3 ps-lg-5"> <h1 class="mb-0 h4">{{ product.title }}</h1> <p><span class="lead">{{ product.author }}</span> (Author)</p> <p>{{ product.description|slice:":355" }}...</p> <div class="border"> <div class="col border-bottom"> <div class="row p-3"> <div class="col-6">Hardback</div> <div class="col-6 text-end"><span class="h4 fw-bold">£{{ product.price }}</span></div> </div> </div> <div class="col"> <div class="row p-3"> <div class="col-6"> <label for="select">Qty</label> <select id="select"> <option value="">1</option> <option value="">2</option> <option value="">3</option> <option value="">4</option> </select> </div> <div class="col-6 text-end"> <button type="button" id="add-button" value="{{ product.id }}" class="btn btn-secondary btn-sm">Add to basket</button> </div> </div> </div> </div> </div> </div> </main> </div> <script> $(document).on('click', '#add-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "basket:basket_add" %}', data: { productid: $('#add-button').val(), csrfmiddlewaretoken: "{{csrf_token}}", action: 'post', }, success: function (json) { }, error: function (xhr, errmsg, err) {} }); }) </script> … -
Django REST Framework how to allow DELETE only without pk
I need to create an endpoint: DELETE /users (deleted ids in the request body) So, i created a class UserViewSet, that extends mixins.DestroyModelMixin and GenericViewSet and implemented the method def delete(self, request), it works for request DELETE /users, but the problem is that user can send DELETE /users/5 request and then i got an error 'Not found`. I want to forbid send DELETE /users/{id} requests and allow only DELETE /users. How can i do this? I tried to use decorator @action(methods=['delete'], detail=True) for the delete method, but its doesn't change anything. Also i tried to use this signature: def delete(self, request, pk=None): if pk: return Response(data='PK is not allowed in DELETE method') For some reason it doesn't even match this method with DELETE/{id} and i still get the error 'Not found'. UPD. I delete mixins.DestroyModelMixin from the extend classes and now DELETE /users works but DELETE/{id} gives me 404 (Page not found) when i try to send DELETE with id. I would like something like method not allowed -
NameError: name 'jedi' is not defined
hello i keep getting error while writing django project. ***py manage.py shell *** for this code , I get this error ; NameError: name 'jedi' is not defined Please help me . hello i keep getting error while writing django project. ***py manage.py shell *** for this code , I get this error ; NameError: name 'jedi' is not defined Please help me . -
Unable to establish session to ssh gateway / ssh connection timeout (mySQL)
I have a paid pythonanywhere hacker account. I managed to setup my database with my django project as well as MySQL workbench. Everything was working fine up till the night of 28th Jan 2023. The next day (29 Jan 2023), when I tried to runserver from my project, I was hit with different errors: OperationalError 2013, unable to establish session to ssh gateway / ssh connection timeout / Lost connection to server at 'handshake: reading initial communication packet', system error: 0"). MySQL workbench also had the connection timeout error and was not able to establish a connection. I did not change any passwords or settings since I first set up my project and everything had been working fine up till yesterday. Is it possible that pythonanywhere's mysql server is down or something...? I have tried countless solutions from Google, Stackoverflow as well as PythonAnywhere forums and have yet to solve my issue. Please advise. :( -
Handle PageNotAnInteger error or Disable the elided notation
I want to make elided page pagination like 1,2,3...8,9,10. So here is my code in models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() in views.py from django.shortcuts import render from .models import Author from django.core.paginator import Paginator def author(request): authors = Author.objects.all() paginator = Paginator(authors, 10) page_number = request.GET.get("page") authors_data = paginator.get_page(page_number) elided_page = paginator.get_elided_page_range(page_number, on_each_side=3,on_ends=2) context = { "authors" : authors_data, "elided_data" : elided_page, } return render (request, "authors.html", context) in author.html # all authors {% for author in authors %} <p> {{authors}}</p> {% endfor %} # pagination part {% for i in elided_data %} <a href="?page={{i}}">{{i}}</a> {% endfor %} this way I get elided pagination like 1,2,3...9,10 perfectly. But problem is when i click on three dot (...) then it shows me pageNotAnInteger error. Is there any way to handle this error or disable the link of that three dot? -
Is there a way to create a Django model instance which has automatic primary key generation without passing named arguments?
I'm trying to create a generic function in Django, creating a bunch of model instances by calling an evaluated model constructor. I.e. I pass in a string model = "Model" which corresponds to an actual model in my database. Then I call Model = getattr(mymodule, model) to get the constructor for that model. Now I can call Model(list, of, arguments). These arguments will of course vary with the different models being passed in, but this is no problem as long as some field in my model is marked as primary_key=True. But when the model has an auto-generated id, the constructor will try to pass the first argument (in my case) to the id field, and it all falls apart and I get something like ValueError: Field 'id' expected a number but got 'some_string'. I found that one solution to this problem was passing named arguments, but I think this will make my code very elaborate since I'm trying to keep it generic for all my models. Another possibility is to pass in None as my first argument, and it works, but I think it is a wonky solution. Is there a way to create a model instance with automatic primary … -
Django video field contains url or file
How to make only one field of these two fields? is it possible? class MyModel(models.Model): field1 = models.FileField(blank=True) field2 = models.UrlField(blank=True) def clean(self): if not self.field1 and not self.field2: raise ValidationError({'field1': 'Even one of field1 or field2 should have a value.'}) elif self.field1 and self.field2: raise ValidationError({'field1': 'Even one of field1 or field2 should have a value.'}) #Example if self.field1: video = self.field1 else: video = self.field2``` -
Is there a way to plot a plotly chart in a backend server, and to send the interactive results on a webapp?
So, I'm actually making all computations in backend, generate a chart in (.png), save it to a pathfile, and communicate through AJAX the link to this newly generated image. However, such process allows me to transfer an image only. I'm basically converting the plot to an image. I wonder if there is a way to transfer the entire plotly output, as an interactive chart through AJAX. import yfinance as yf import plotly.graph_objects as go aapl = yf.Ticker('AAPL') ainfo = aapl.history(start=datemin, end=datemax) #Plot the Chart fig = go.Figure(data=go.Scatter(x=ainfo.index,y=ainfo.Close, mode='lines'),) #DB inject plot fig.write_image("/Users/Xlibidish/Desktop/Django/static/"+tickerZ+rx+".png") #And then communicate the path through AJAX etc. I'd like to send to my Webapp the plotly output. I have some hints: Generate the plot in my Webapp directly in JS, so the backend sends only the data from yfinance and a directive to generate it. (Quite complex, especially knowing that I have various types of plots, which are all generated in python so the Webappp is only receiving Images at this time without differentiating them). Create an iframe directing to the plotly output ports, but not sure about this one ! And also, I need to save the plot results in a DB. Just to clarify: #in …