Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I was doing a "questions site" from the Django docs and I'm having a problem
There is problems i terminal and dashboard I want build quiz site with Django docs -
I deployed a Django project packaged with Zappa to AWS Lambda, but it always returns null
I'm trying to use a zip file created with zappa package instead of zappa deploy to match my CI/CD process. AWS Lambda settings: Runtime: Python 3.9 Handler: handler.lambda_handler Architecture: x86_64 When I access the HTTP endpoint, it always returns null in the browser. I created a Django project. It's a basic project, and you can check this project on the following GitHub repository. https://github.com/hongmingu/zappa1sample I used the zappa package dev command to create a zip file and uploaded it to S3. Then, I set the S3 URL as the source in AWS Lambda. Here's my zappa_settings.json file: { "dev": { "aws_region": "ap-northeast-2", "django_settings": "zappa1sample.settings", "project_name": "zappa1sample", "runtime": "python3.9", "s3_bucket": "lambda-saver12123" }, "production": { "aws_region": "ap-northeast-2", "django_settings": "zappa1sample.settings", "project_name": "zappa1sample", "runtime": "python3.9", "s3_bucket": "lambda-saver12123" } } AWS CloudWatch logs are as follows: INIT_START Runtime Version: python:3.9.v19 Runtime Version ARN: arn:aws:lambda:ap-northeast-2::runtime:e73d5f60c4282fb09ce24a6d3fe8997789616f3a53b903f4ed7c9132a58045f6 START RequestId: ae67fca5-6afa-4a2c-a920-2440bae5af2b Version: $LATEST Instancing.. [DEBUG] 2023-04-19T07:44:36.009Z ae67fca5-6afa-4a2c-a920-2440bae5af2b Zappa Event: {'version': '2.0', 'routeKey': '$default', 'rawPath': '/', 'rawQueryString': '', 'headers': {'sec-fetch-mode': 'navigate', 'x-amzn-tls-version': 'TLSv1.2', 'sec-fetch-site': 'cross-site', 'accept-language': 'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7,ar;q=0.6,zh-CN;q=0.5,zh;q=0.4', 'x-forwarded-proto': 'https', 'x-forwarded-port': '443', 'x-forwarded-for': '222.111.140.167', 'sec-fetch-user': '?1', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'x-amzn-tls-cipher-suite': 'ECDHE-RSA-AES128-GCM-SHA256', 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"', 'sec-ch-ua-mobile': '?0', 'x-amzn-trace-id': 'Root=1-643f9be1-1f1cb40742c78d566ab0c546', 'sec-ch-ua-platform': '"macOS"', 'host': 'wzzdsza2liopkemzy7h4q3okyu0gsusx.lambda-url.ap-northeast-2.on.aws', 'upgrade-insecure-requests': '1', 'accept-encoding': 'gzip, deflate, br', 'sec-fetch-dest': 'document', … -
How to only show related objects in Django Admin screens
I have an app where I want administrators to be able to create events via the admin view. I have members, who will have multiple cars and attend multiple meets. I want to record which vehicle they used at a meet. In the django admin view for a member, I can manage their cars successfully and only cars belonging to that member show up in the inline on the Member Admin page, but when attempting to manage meets, all cars are listed, not only cars belonging to that member. I want the same list of cars from the CarInline to appear in the MeetInline - i.e. cars registered to the member. Any ideas how to achieve this? I think that the issue is that the Meet model has a ManyToMany relationship with the Car model but wasn't sure how else to model this. models.py class Member(models.model): member_number = models.CharField(primary_key=True, max_length=30) is_active = models.BooleanField(default=True) class Car(models.model) member = models.ForeignKey(Member) registration = models.CharField(max_length=80) class Meet(models.model) meet_date = models.DateTimeField() member = models.ForeignKey(Member) car = models.ManyToManyField(Car) admin.py class CarInline(admin.TabularInline): model = Car extra = 0 fields = ["registration"] class MeetInline(admin.TabularInline): model = Meet extra = 0 fields =["meet_date", "car"] class MemberAdmin(admin.ModelAdmin): list_filter = [ … -
Django limit query not working in get_queryset
I overwrite get_queryset as below: def get_queryset(self, request): qs = super().get_queryset(request) qs.order_by('-id').all()[:3] print(qs) print() qs2 = CreditsTransaction.objects.all()[:3] print(qs2) return qs This is my output: [2023-04-19 08:53:52 +0000] [1178] [INFO] Booting worker with pid: 1178 <QuerySet [<CreditsTransaction: CreditsTransaction object (623267)>, <CreditsTransaction: CreditsTransaction object (623266)>, <CreditsTransaction: CreditsTransaction object (623265)>, <CreditsTransaction: CreditsTransaction object (623264)>, <CreditsTransaction: CreditsTransaction object (623263)>, '...(remaining elements truncated)...']> <QuerySet [<CreditsTransaction: CreditsTransaction object (623267)>, <CreditsTransaction: CreditsTransaction object (623266)>, <CreditsTransaction: CreditsTransaction object (623265)>]> So in qs.order_by('-id').all()[:3] the number of results is not limited to 3. Whereas in CreditsTransaction.objects.all()[:3] it is. I want to know why. -
ImportError: from django.conf import DEFAULT_STORAGE_ALIAS, settings
am trying to run my django app on local server and instead am getting this error: ImportError, cannot import name 'DEFAULT_STORAGE_ALIAS' from 'django.conf' -
python subprocess - google-chrome headless - self-signed certificate - screenshot
When opening a django shell: python manage.py shell and typing in: import subprocess command = [ f'google-chrome', '--headless=new', f'--screenshot=/home/user/tmp/screen.png', f'--window-size={800,1700}', '--no-first-run', '--allow-http-screen-capture', '--force-device-scale-factor=1', '--ignore-certificate-errors', '--ignore-urlfetcher-cert-requests', '--disable-test-root-certs', '--allow-running-insecure-content', '--hide-scrollbars', '--allow-insecure-localhost', '--disable-system-font-check', '--disable-gpu', '--disable-extensions', '--disable-dev-shm-usage', '--disable-software-rasterizer', '--disable-notifications', '--user-data-dir=/tmp/chromium-home', '/home/user/tmp/screen.html', ] subprocess.run(command, **{}) The console output is the following: [32873:32901:0419/083534.872076:ERROR:bus.cc(399)] Failed to connect to the bus: Failed to connect to socket /run/user/0/bus: Permission denied [32873:32901:0419/083534.884135:ERROR:bus.cc(399)] Failed to connect to the bus: Failed to connect to socket /run/user/0/bus: Permission denied [32873:32901:0419/083534.970536:ERROR:bus.cc(399)] Failed to connect to the bus: Failed to connect to socket /run/user/0/bus: Permission denied [32873:32901:0419/083534.970630:ERROR:bus.cc(399)] Failed to connect to the bus: Failed to connect to socket /run/user/0/bus: Permission denied (process:32873): dconf-CRITICAL **: 08:35:35.289: unable to create directory '/run/user/0/dconf': Permission denied. dconf will not work properly. (process:32873): dconf-CRITICAL **: 08:35:35.314: unable to create directory '/run/user/0/dconf': Permission denied. dconf will not work properly. (process:32873): dconf-CRITICAL **: 08:35:35.350: unable to create directory '/run/user/0/dconf': Permission denied. dconf will not work properly. [32873:32899:0419/083537.631303:ERROR:cert_verify_proc_builtin.cc(679)] CertVerifyProcBuiltin for 127.0.0.1 failed: ----- Certificate i=0 (<snip>) ----- ERROR: No matching issuer found [32873:32897:0419/083537.639022:ERROR:cert_verify_proc_builtin.cc(679)] CertVerifyProcBuiltin for 127.0.0.1 failed: ----- Certificate i=0 (<snip>) ----- ERROR: No matching issuer found 572051 bytes written to file /home/user/tmp/screen.png CompletedProcess(args=['google-chrome', '--headless=new', '--screenshot=/home/user/tmp/screen.png', '--window-size=(800, 1700)', '--no-first-run', '--allow-http-screen-capture', '--force-device-scale-factor=1', '--ignore-certificate-errors', '--ignore-urlfetcher-cert-requests', … -
Flowbite component not working when loaded via HTMX (Django project)
For my Django application I am using Flowbite to make interactive UI components. I am also using HTMX to dynamically load some html content from the back-end (Django) into the page without refresh. Basically I have a button that sends a HTMX get requests to the backend and then targets a modal window (a Flowbite component) with the received html (nothing ground-breaking). The mechanism works well, however here is the twist: the html code that my backend returns, contains another Flowbite component i.e. a dropdown menu. <!-- MODAL BTN --> <button hx-get="{% url '<myurl>' %}" hx-target="#newItemModal" data-modal-target="newItemModal" data-modal-toggle="newItemModal" class="block text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center" type="button"> Modal open </button> <!-- MODAL WINDOW --> <div id="newItemModal" tabindex="-1" aria-hidden="true" class="fixed top-20 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] md:h-full"> </div> The HTML returned by the backend with the hx-get is as follows: <div> ... <!-- MENU BTN --> <button type="button" data-dropdown-toggle="dropdownEditMenu" class="aspect-square h-10 ml-2 rounded-lg text-white drop-shadow-[0_1.2px_1.2px_rgba(0,0,0,0.8)] hover:text-slate-100"> <span class="mdi mdi-dots-vertical text-3xl"></span> </button> <!-- DROPDOWN MENU --> <div id="dropdownEditMenu" class="z-10 hidden rounded-lg shadow w-48 max-h-48 lg:max-h-none bg-slate-600 overflow-auto"> <ul class="text-sm text-white"> <li class="hover:bg-slate-700 px-4 py-2 truncate"> <a href="{% url <myurl> %}" class="w-full inline-flex … -
Django ModelAdmin/ModelForm readonly permissions flow
I have a Django admin application and I have a particular issue with one of the admin pages. I have a model which looks like this. class Quote(CommonModel, models.Model): amount = models.IntegerField(blank=True, null=True, verbose_name="Approved credit amount") The form looks like this: class QuoteForm(django.forms.ModelForm): amount = django.forms.CharField(widget=django.forms.TextInput()) and the ModelAdmin looks like this: class QuoteAdmin(admin.ModelAdmin): form = QuoteForm Now I need to amend this amount to format it so that it reads in dollars and cents from the int value in the database, this is not an issue in the form when the user has change permissions to the ModelAdmin, I have ammended the form to look like this: class QuoteForm(django.forms.ModelForm): amount = django.forms.CharField(widget=django.forms.TextInput()) def clean_approved_amount_amount(self, value: str): return self.convert_string_float_dollar_representation_to_cent_integer( self.cleaned_data['approved_amount_amount'] ) def __init__(self, *args, **kwargs): super(QuoteForm, self).__init__(*args, **kwargs) self.initial['amount'] = kwargs['instance'].integer_values_in_dollar_format(kwargs['instance']['amount']) But if the user only has read only permissions to the ModelAdmin the form flow is different and fails and I can't seem to figure out when the ModelAdmin picks up that the form is readonly so that I can convert the value in the DB to a dollar and cent amount. There is no documentation on this conditional flow that I can find to understand when I should … -
Sent notification to external application from online food order application
After placing an order the web application should sent notification to all subscribed users about order details.How to achieve it in django web application using django push notification? Signalpy and django push notification -
Django: Save API data to model
Relative new to Django / python. I have a API call request and i got JSON data from it: [{'node': 'node01', 'cpu': 0.0193098516002146, 'mem': 92328939520, 'status': 'online'}, {'node': 'node02', 'cpu': 0.0100098516002146, 'mem': 72823919520, 'status': 'online'}, {'node': 'node03', 'cpu': 0.0023498516002146, 'mem': 92328939520, 'status': 'online'}] If i make i more human-readable: [{'node': 'node01', 'cpu': 0.0193098516002146, 'mem': 92328939520, 'status': 'online'}, {'node': 'node02', 'cpu': 0.0100098516002146, 'mem': 72823919520, 'status': 'online'}, {'node': 'node03', 'cpu': 0.0023498516002146, 'mem': 92328939520, 'status': 'online'}] I have the following model: class Node(models.Model): node = models.CharField(max_length=2000, null=True, blank=True) cpu = models.FloatField(null=True, blank=True) mem = models.FloatField(null=True, blank=True) status = models.CharField(max_length=2000, null=True, blank=True) Now i want to save the API data into the model, so in this case 3 "records" in the DB. I tried with the following: for node in r: print(node['node']) a = PxmxNode( cpu=node['cpu'], level=node['level'], maxcpu=node['maxcpu'], maxmem=node['maxmem'], mem=node['mem'], node=node['node'], ssl_fingerprint=node['ssl_fingerprint'], status=node['status'], uptime=node['uptime'] ) a.save() r is the API call data. But this saves only the last API data (node03). Also the records have to be updated when i do the API call again (to reflect mem changes etc) -
Django zebra label printing
I am trying to create a script for printing labels with zebra printers. I can send ZPL commands, using sockets. def zebra_print(format, printer_option): mysocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) printer = printer_option host = Printers.objects.get(name = printer).ip if host == '': host = Printer.objects.get(name = printer).path port = 9100 try: mysocket.connect((host, port)) # connecting to host mysocket.send(bytes(format, encoding='ascii')) # using bytes mysocket.close () #closing connection except Exception as e: print(e) Both network path or IP work, but only if the printer has an ethernet connection. For printers which do not have ethernet (directly plugged to pc) I am unable to connect. Tried to use PC ip or printer shared path with no success. How can I achieve this? -
django-constance not setting up database backend
I'm trying to add django-constance to an existing Django 3.2.9 project and am completely unable to get the database backend to set up. I've added constance to INSTALLED_APPS before my apps, as the docs state. In [1]: from django.conf import settings In [2]: 'constance' in settings.INSTALLED_APPS Out[2]: True I've specified the backend and limited to one of the two dbs the project is using: CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend' CONSTANCE_DBS = ['default'] CONSTANCE_CONFIG = {'TESTVAR': ('testing constance', 'This is a test field only')} However, no migration happens: # ./manage.py migrate Operations to perform: Apply all migrations: admin, adminactions, api, audit, auscert_website, auth, axes, contenttypes, db, failure, flatpages, images, lock, malurlfeed, members, notifications, oldnodes, otp_static, otp_totp, ourforms, redirects, reversion, sessions, sites, two_factor Running migrations: No migrations to apply. And I'm then unable to change the value of TESTVAR: # ./manage.py constance list TESTVAR # ./manage.py constance set TESTVAR test # ./manage.py constance get TESTVAR # I feel like I'm missing something obvious but I've scoured the docs and the repo's issues and am at a loss for how to proceed. -
Why is there nothing left in the session the next time you request the backend?
Why do I use a function to store the session after the login operation, and the table has a session, but the back end can't get the session for another html request? I tried a lot of things but it didn't work out -
Generation of random numbers at no cost to the database
Hello everything is fine? I will build a raffle site and it needs to support several simultaneous people. For this, any optimization is welcome. Testing or verifying available numbers in the database can be a little damaging. As they are random numbers, I need to insert them with the certainty that they are not drawn to avoid repetitive queries. One solution would be to store the undrawn numbers in some complementary file and faster than a database and after adding the numbers, update the file and remove the used numbers. Thank you for your time and attention! :) -
Django Template is not displaying the table data
I am hoping someone can show me where I am going wrong. In one template I have a table that displays a few rows of data. I want a link in one of the fields to open a separate template for that field. The print commands display the correct information: print(vendor) displays: Sandpiper print(searchresult) displays: <QuerySet [<Vendor: Sandpiper>]> Sandpiper matches the name of the vendor in the vendor table, but when executed the detail page loads but does not display any of the data from the Vendors table. views.py def utilvendorview(request, vendor): searchresult = Vendor.objects.filter(search=vendor) print(vendor) print(searchresult) return render(request,'utilityrentals/vendors_detail.html',{"searchresult":searchresult}) urls.py path('utilvendorview/<vendor>/', views.utilvendorview, name='utilityvendor'), index.html (main template) <td><a href="utilvendorview/{{ results.Vendor }}">{{ results.Vendor }}</a></td> vendors_detail.html - Trying to have this populate {% extends "maintenance_base.html" %} {% load static from static %} {% block body %} <div class="album py-5 bg-light"> <div class="container"> <div class="row"> <div class="col-md-4"> <div class="card mb-4 box-shadow"> <div class="card-body"> <h5 class="card-title">{{ Vendor.company }}</h5> <h6 class="card-subtitle mb-2 text-muted">Email Address: {{ searchresult.email1 }} </h6> <h6 class="card-subtitle mb-2 text-muted">Email Address: {{ searchresult.email2 }} </h6> <h6 class="card-subtitle mb-2 text-muted">Phone: {{ searchresult.phone1 }} </h6> <h6 class="card-subtitle mb-2 text-muted">Mobile: {{ searchresult.phone2 }} </h6> <h6 class="card-subtitle mb-2 text-muted">Category: {{ searchresult.category }} </h6> <h6 class="card-subtitle mb-2 text-muted">Address1: {{ … -
Django customizable file path based off an user(Profile) name
thanks for any help in advanced. I am creating a personal website with Django, and I am coming from a Drupal background. I just started to learn the framework. I am looking help with... a suggestion for a package or direction on how to get started on how to create a customizable file (image, video) path based off an user(Profile) name. So, a new directory would be created, when the user(Profile) is created, and the media for that user is stored in their directory. Then it would also get broken down into, if its a image or video with their own directory. In theses files below, so far I have it setup like this. settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'`` users/models.py `class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile'` Thanks. I am new to the Django framework, and was hoping for some direction to point me in the right direction. -
My ip Finder program in django don’t work
Hey i was making a User ip Finder , but in the YouTube Video Tutorial there was the „META.get“ In Color“ And in my Programm it stays white and „Funktion any“ How i get That Implated enter image description here Iam new in Coding please help -
@login_required doesn't seem too recognize that I'm authenticated - django app
I'm a newbie python developer and I'm trying to develop a simple language school management app. I've created login page, which works and compares credentials to user's credentials provided in database. But even after succsessful authentication ('Success' is printed out in terminal) it seems that @login_required decorator doesn't see me as authenticated. What could be the reason? I'll provide all the data you need. Here's my simple views.py: from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required def login_view(request): if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") user = authenticate(request, username=username, password=password) print(user) if user is not None: login(request, user) print('Success') return redirect("dashboard") else: error_message = "Invalid login credentials" return render(request, "login.html", {"error_message": error_message}) return render(request, "login.html") def logout_view(request): logout(request) return redirect("login") @login_required() def dashboard(request): return render(request, "dashboard.html") I used custom models and my custom authentication func looks like that: from django.contrib.auth.backends import ModelBackend from .models import Teacher class TeacherBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: teacher = Teacher.objects.get(username=username) except Teacher.DoesNotExist: return None if teacher.check_password(password): return teacher return None -
why does custom user causes the error django.core.exceptions.AppRegistryNotReady: Models aren’t loaded yet.” in fresh project
I had a project all of a sudden I started seeing this error django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. i tried fixing it i failed miserably using all stack overflow i came across and django forum. So i started a new project, to see where I got it wrong, a very fresh project but as soon as i added in custom user model, the error wouldn't allow me even make migrations or migrate note: this is the only file i have added besides adding in the settings: """ Database models """ from django.db import models from django.contrib.auth.models import( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils import timezone class UserManager(BaseUserManager, PermissionsMixin): """ minimum fields for all users""" def create_user( self, email, telephone, username, first_name, last_name, password=None, **extra_fields): if not email: raise ValueError('You need to provide an email address') if not telephone: raise ValueError('You need to provide a telephone') if not username: raise ValueError('You need to set a username') """ calling the model this manager is responsible for with self.model.""" user = self.model( email= self.normalize_email(email), telephone =telephone, username = username, first_name = first_name, last_name = last_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_superuser( self, email, … -
Django EmailMultiAlternatives safe tag problem in html version
I'm trying to pass urls with safe tag in my emails, but it seems like Django ignores it. I'm using Django==4.1.6 I have the next code for email sending: from config.celery_app import app from smtplib import SMTPException from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import mark_safe @app.task(autoretry_for=(SMTPException,)) def user_created(context, send_to): email_html_message = render_to_string("email/activation_email.html", context) email_plaintext_message = render_to_string("email/activation_email.txt", context) from_email = settings.EMAIL_HOST_USER msg = EmailMultiAlternatives( # title: "Please confirm your registration in {title}".format( title=settings.PROJECT_NAME ), # message: email_plaintext_message, # from: from_email, # to: send_to, ) msg.attach_alternative(mark_safe(email_html_message), "text/html") msg.send() This is "email/activation_email.html": <a target="_blank" href="{{activate_url|safe}}">{{activate_url|safe}}</a> And this is "email/activation_email.txt": {% autoescape off %} Hello {{ name }}, Please click on the link to confirm your registration: {{activate_url|safe}} {% endautoescape %} In email/activation_email.txt I have working activate_url like "http://localhost:8000/activate-account?token=bmviz3-14727ab7a3e4946117f9efa98ab03ea1&uid=MTZjY2E5MjMtNjNhYi00YzhkLTg0MTEtMjIwZTI0MGNlNGZj" But in HTML variant of email I have wrong url like "http://localhost:8000/activate-account?token=3Dbmv=iz3-14727ab7a3e4946117f9efa98ab03ea1&uid=3DMTZjY2E5MjMtNjNhYi00YzhkLTg0MTEt=MjIwZTI0MGNlNGZj" What's happens with my urls in HTML template? Why they are different? Under activate_url I have: "http://localhost:8000/activate-account?token=bmviz3-14727ab7a3e4946117f9efa98ab03ea1&uid=MTZjY2E5MjMtNjNhYi00YzhkLTg0MTEtMjIwZTI0MGNlNGZj" -
Wrong image URL on django
I am new to django and am having an issue with images. When i stay when I view the main page of my blog with all the articles everything is fine with the images, but as soon as I want to view one specific article, then the problems with the images start due to the wrong url/ urls.py (project) from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py from django.shortcuts import render from .models import * def index(request): posts = Post.objects.all() topics = Topic.objects.all() return render(request, "index.html", {"posts": posts, "topics": topics}) def post(request, postinf): post = Post.objects.get(title=postinf) return render(request, "post.html", {"post": post} ) urls.py (app) from django.urls import path from . import views urlpatterns = [ path('blog', views.index), path('blog/<str:postinf>/', views.post, name="postdetail"), ] settings.py STATICFILES_DIRS = [ BASE_DIR / "main/static/", ] STATIC_URL = 'main/static/' models.py from django.db import models from django.contrib.auth.models import User class Topic(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) user_avatar = models.ImageField(null=True, blank=True, upload_to="main/static/images") def __str__(self): return str(self.user) class Post(models.Model): profile = models.ForeignKey(Profile, on_delete=models.DO_NOTHING) title = models.CharField(max_length=20, verbose_name="Название поста") post_text = … -
django IntegrityError: FOREIGN KEY constraint failed with get_or_create
I've been working to a django project for 2 moths, but now it gives me this error: Internal Server Error: /exams/26 Traceback (most recent call last): File "C:\Users\doniy\PycharmProjects\WebScraping\venv\lib\site- packages\django\db\models\query.py", line 916, in get_or_create return self.get(**kwargs), False File "C:\Users\doniy\PycharmProjects\WebScraping\venv\lib\site- packages\django\db\models\query.py", line 637, in get raise self.model.DoesNotExist( exams.models.Exam.DoesNotExist: Exam matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\doniy\PycharmProjects\WebScraping\venv\lib\site- packages\django\db\backends\base\base.py", line 313, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\doniy\PycharmProjects\WebScraping\venv\lib\site- packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\doniy\PycharmProjects\WebScraping\venv\lib\site- packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\doniy\PycharmProjects\WebScraping\exams\views.py", line 47, in f createExam(nome=getExam(),anno=getAnno(),semestre=getSemestre(),facoltà=None) File "C:\Users\doniy\PycharmProjects\WebScraping\exams\views.py", line 19, in createExam Exam.objects.get_or_create(nome=nome[i],anno=anno[i],semestre=semestre[i], Facoltà=Facoltà.objects.get(id=27)) File "C:\Users\doniy\PycharmProjects\WebScraping\venv\lib\site- packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\doniy\PycharmProjects\WebScraping\venv\lib\site- packages\django\db\models\query.py", line 921, in get_or_create with transaction.atomic(using=self.db): File "C:\Users\doniy\PycharmProjects\WebScraping\venv\lib\site- packages\django\db\transaction.py", line 263, in __exit__ connection.commit() File "C:\Users\doniy\PycharmProjects\WebScraping\venv\lib\site- packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\doniy\PycharmProjects\WebScraping\venv\lib\site- packages\django\db\backends\base\base.py", line 337, in commit self._commit() File "C:\Users\doniy\PycharmProjects\WebScraping\venv\lib\site- packages\django\db\backends\base\base.py", line 312, in _commit with debug_transaction(self, "COMMIT"), self.wrap_database_errors: File "C:\Users\doniy\PycharmProjects\WebScraping\venv\lib\site-packages\django\db\utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value … -
Updating quantity in javascript
Items are been added to the cart successfully and when clicking a button with data-action add it successfully adds +1 to the quantity, how ever when i click a button with a data action of remove it still adds +1 to quantity, it seems that the PATCH request is never been initialized but I cannot see why. So currently: data action add = +1 to item quantity data action add = +1 to item quantity I want: data action add = +1 to item quantity data action add = -1 to item quantity const updateBtns = document.querySelectorAll(".update-cart"); const user = "{{request.user}}"; for (let i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener("click", function () { event.preventDefault(); // prevent page from refreshing const productId = this.dataset.product; const action = this.dataset.action; console.log("productId:", productId, "action:", action); console.log("USER:", user); createCart(productId, action); }); } function createCart(productId, action, cartId) { var csrftoken = getCookie('csrftoken'); console.log('User is logged in, sending data...'); fetch('/get_cart_id/') .then(response => response.json()) .then(data => { const cartId = data.cart_id; console.log('Cart ID:', cartId); // log cartId in console // get the cart items for the given cart fetch(`/api/carts/${cartId}/items/`) .then(response => response.json()) .then(data => { let itemExists = false; let cartItemId = null; let quantity = … -
Unsure what goes in 'self.room_group_name = "..." and How it works
I have a django project where I'm trying to connect users using websockets, I've been following tutorials to understand it, but most people's workflow is 2 pages (start at / then go to the room), mine is 3: start at login -> go to home -> go to room. I keep getting a WebSocket connection failed error and Not Found: /ws/home/room/ and have been struggling to figure out why, I'm assuming I just don't understand what's happening enough. this is my urls.py urlpatterns = [ path('', views.login, name='login'), path('home/', views.home, name='home'), path('home/<str:room_name>/', views.room, name='room'), ] this is routing.py websocket_urlpatterns = [ re_path(r'^ws/home/(?P<room_name>\w+)/$', consumers.GameConsumer), ] and this is my consumers.py class GameConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.room_name = None self.room_group_name = None async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = '_%s' % self.room_name # unsure about '_%s' <--- unsure what to put here ''' create new group ''' await self.channel_layer.group_add( self.room_group_name, self.channel_name, ) await self.accept() await self.channel_layer.group_send( self.room_group_name, { 'type': 'tester_message', 'tester': 'hello world', } ) async def tester_message(self, event): tester = event['tester'] await self.send(text_data=json.dumps({ 'tester': tester })) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name, ) I feel like it has something to do with the room_group_name, but … -
dropdown menu with django-mptt in template
I want to make django mptt model dropdown menu. But I'm having trouble applying it to templates. I wrote the code at a certain level, but sometimes it works, sometimes it doesn't. <div class="u-custom-menu u-nav-container"> <ul class="u-custom-font u-nav u-spacing-30 u-text-font u-unstyled u-nav-1"><li class="u-nav-item"><a class="u-border-3 u-border-active-palette-1-base u-border-hover-palette-1-light-1 u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-radius-25 u-text-active-grey-90 u-text-grey-90 u-text-hover-grey-90" href="" style="padding: 10px 0px;">Ana Sayfa</a> </li><li class="u-nav-item"><a class="u-border-3 u-border-active-palette-1-base u-border-hover-palette-1-light-1 u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-radius-25 u-text-active-grey-90 u-text-grey-90 u-text-hover-grey-90" href="Hakkında.html" style="padding: 10px 0px;">Hakkında</a> </li><li class="u-nav-item"><a class="u-border-3 u-border-active-palette-1-base u-border-hover-palette-1-light-1 u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-radius-25 u-text-active-grey-90 u-text-grey-90 u-text-hover-grey-90" href="İletişim.html" style="padding: 10px 0px;">İletişim</a> </li><li class="u-nav-item"><a class="u-border-3 u-border-active-palette-1-base u-border-hover-palette-1-light-1 u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-radius-25 u-text-active-grey-90 u-text-grey-90 u-text-hover-grey-90" href="Hesap-Sayfaları/Hesap-örnek-sayfa.html" style="padding: 10px 0px;">matematik</a> <div class="u-nav-popup"><ul class="u-h-spacing-15 u-nav u-unstyled u-v-spacing-5 u-nav-2"> <li class="u-nav-item"><a class="u-button-style u-nav-link u-palette-1-base">Alan Hesaplama</a> <div class="u-nav-popup"><ul class="u-h-spacing-15 u-nav u-unstyled u-v-spacing-5 u-nav-3"> <li class="u-nav-item"><a class="u-button-style u-nav-link u-palette-1-base">KARE hesaplama</a></li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-palette-1-base">DAİRE HESAPLA</a></li> </ul></div></li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-palette-1-base">çevre hesaplama</a> </li><li class="u-nav-item"><a class="u-button-style u-nav-link u-palette-1-base">dair</a> </li><li class="u-nav-item"><a class="u-button-style u-nav-link u-palette-1-base">kare</a> </li></ul> </div> </li><li class="u-nav-item"><a class="u-border-3 u-border-active-palette-1-base u-border-hover-palette-1-light-1 u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-radius-25 u-text-active-grey-90 u-text-grey-90 u-text-hover-grey-90" href="Hesap-Sayfaları/Hesap-örnek-sayfa.html" style="padding: 10px 0px;">Finans</a> <div class="u-nav-popup"><ul class="u-h-spacing-15 u-nav u-unstyled u-v-spacing-5 u-nav-2"> <li class="u-nav-item"><a class="u-button-style u-nav-link u-palette-1-base">bileşik getiri hesapla</a></li> <li class="u-nav-item"><a class="u-button-style …