Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
New Relic python agent + gunicorn + gevent crashing
I am switching my application over to use gevent instead of threads with gunicorn. I have also been using New Relic to monitor my application successfully. However, when I using the combination of both of them, my application becomes really laggy ans also crashes. In the moment, I remove gevent or New Relic, everyhing works fine. This would be my goal to work: web: newrelic-admin run-program gunicorn config.wsgi_gevent:application -c config/gunicorn_gevent.config.py --worker-class gevent --worker-connections 100 --max-requests=100 --max-requests-jitter=50 --bind 0.0.0.0:8000 As said, that one does not work. These ones do: New relic + threads web: newrelic-admin run-program gunicorn config.wsgi:application --bind 0.0.0.0:8000 Gunicorn with gevent web: gunicorn config.wsgi_gevent:application -c config/gunicorn_gevent.config.py --worker-class gevent --worker-connections 100 --max-requests=100 --max-requests-jitter=50 --bind 0.0.0.0:8000 Logs before the browser is just loading and nothing happens anymore: 12:05:53 AM web.1 | [2023-04-19 00:05:53 +0300] [14496] [INFO] Starting gunicorn 20.1.0 12:05:53 AM web.1 | [2023-04-19 00:05:53 +0300] [14496] [INFO] Listening at: http://0.0.0.0:8000 (14496) 12:05:53 AM web.1 | [2023-04-19 00:05:53 +0300] [14496] [INFO] Using worker: gevent 12:05:53 AM web.1 | [2023-04-19 00:05:53 +0300] [14499] [INFO] Booting worker with pid: 14499 12:06:07 AM web.1 | [2023-04-18 21:06:07 +0000] [14499] [INFO] Autorestarting worker after current request. 12:06:08 AM web.1 | [2023-04-18 21:06:08 +0000] [14499] [INFO] … -
Issue with finding a rival in a Django web page
I am working on a Django web application that allows users to register teams, add players to those teams, and then find a rival team. However, I am experiencing an issue when users click the "Find Rival" button, as the system does not seem to find an appropriate rival team and leaves the user waiting. Here's an overview of the web page structure: The homepage (index.html) allows users to register a team by entering their details and location. In the create_players.html page, users can register players for the previously created team. After registering the players, users can click the "Find Rival" button to find a rival team. The issue seems to be related to the following code: The JavaScript function findRival() in the create_players.html template is responsible for finding a rival. When the "Find Rival" button is clicked, this function sends a POST request to the /find_rival/ route on the Django server. Potential causes of the issue include the findRival() function not sending the team data to the Django server correctly, the find_rival view on the Django server not properly processing the received data and/or not returning the rival information in the expected format, and the JavaScript code in the … -
Having trouble with View Function in Django, how can I fix it?
The Save function and the Search function are not working for some reason. I keep getting redirected to the error.html template in the converter function. Here's views.py: from django.shortcuts import render from . import util from markdown2 import Markdown import random def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def New(request): return render(request, "encyclopedia/new.html") def save(request): if request.method == 'POST': title = request.POST.get('title','') content = request.POST.get('content', '') entry = util.list_entries() if title in entry: return render(request, "encyclopedia/exists.html") else: util.save_entry(title, content) return converter(request, title) def Random1(request): entry = util.list_entries() rand_entry = random.choice(entry) return converter(request, rand_entry) def converter(request, title): entry = util.list_entries() markdowner = Markdown() if title in entry: content = util.get_entry(title) data = markdowner.convert(content) return render(request, "encyclopedia/entry.html", { "data": data }) else: return render(request, "encyclopedia/error.html") def search(request): if request.method == 'POST': input = request.POST.get('q', '') html = converter(request,input) entries = util.list_entries() if input in entries: return render(request, "encyclopedia/entry.html", { "data": html, }) else: search_pages = [] for entry in entries: if input in entry: search_pages.append(entry) return render(request, "encyclopedia/search.html", { "entries": search_pages, }) I want the save function to be able to save a new entry made by the user and search function to be able to search for any entry … -
Zappa deployment "cannot import name 'discovery_cache' from 'googleapiclient'
I have a zappa/django AWS deployment that is mostly working, but it fails with this stack trace: File "/var/task/help_desk/models.py", line 409, in send_emails service = gmail.get_service(sender_id="coach" if self.thread.cat==Thread.CAT_COACH else None) File "/var/task/help_desk/gmail.py", line 22, in get_service service = build('gmail', 'v1', credentials=delegated_credentials) File "/var/task/googleapiclient/_helpers.py", line 130, in positional_wrapper return wrapped(*args, **kwargs) File "/var/task/googleapiclient/discovery.py", line 287, in build content = _retrieve_discovery_doc( File "/var/task/googleapiclient/discovery.py", line 387, in _retrieve_discovery_doc from . import discovery_cache ImportError: cannot import name 'discovery_cache' from 'googleapiclient' (/var/task/googleapiclient/__init__.py) This does not fail when running it on a local copy. I have hunted around, and this module is installed in the google-api-python-client package. This package is listed in my requirements.txt and is present in my local virtual env. I am not sure why it is not present in the zappa deployment or how to get it there. If I list the lib/googleapiclient/discovery_cache, it is present on my local project and it is also present if I run the 'pip show -f google-api-python-client' command locally. -
TypeError at /signin/ 'module' object is not callable
As I'm working on django for the first time, so I was trying to create a user authentication page. Everything works fine but when I try to signin Im getting an error. app name : authentication views.py from django.shortcuts import redirect, render from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import login, logout import authentication def home(request): return render(request, "authentication/index.html") def signup(request): if request.method == "POST": username = request.POST['username'] fname = request.POST.get('fname') lname = request.POST.get('lname') email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] myuser = User.objects.create_user(username,email,pass1) myuser.first_name = fname or '' myuser.last_name = lname or '' myuser.save() messages.success(request, "Your account has been successfully created.") return redirect('signin') return render(request, "authentication/signup.html") def signin(request): if request.method == "POST": username = request.POST['username'] pass1 = request.POST['pass1'] user = authentication (request,username=username,password=pass1) if user is not None: login(request,user) fname = user.first_name return render(request,"authentication/index.html", {'fname':fname}) else: messages.error(request,"Bad credentials!") return redirect('home') return render(request, "authentication/signin.html") def signout(request): logout(request) messages.success(request, "logged out successfully!") return redirect('home') urls.py from django.urls import path from . import views urlpatterns = [ path('signup/', views.signup, name='signup'), path('signin/', views.signin, name='signin'), path('signout/', views.signout, name='signout'), ] templates/signin.html <!DOCTYPE html> <html> <body> <h3>SignIn</h3> {% for message in messages %} <div class="alert alert-{{ message.tags }} … -
Return fake dates for every blog post - bypass django's auto now
I am testing whether my blog posts are in reverse chronological order. To do so, I must set random dates for each post created. I'm using faker to set the dates. I am getting back a fake date, but it's the same date for every post. Is auto now still the issue here, or am I not using Faker correctly? Factory: fake = Faker() mocked = fake.date_time() class BlogPageFactory(wagtail_factories.PageFactory): class Meta: model = models.BlogPage with patch('django.utils.timezone.now', mocked): date = mocked # date = datetime.date.today() author = factory.SubFactory(UserFactory) slug = factory.sequence(lambda n: f"post{n}") snippet = factory.sequence(lambda n: f"Article {n} snippet...") body = "Test post..." featured_image = factory.SubFactory(wagtail_factories.ImageFactory) featured_article = False Models: class BlogPage(Page): date = models.DateField("Post date") snippet = models.CharField( max_length=250, help_text="Excerpt used in article list preview card." ) body = RichTextField(blank=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) featured_image = models.ForeignKey("wagtailimages.Image", on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) featured_article = models.BooleanField(default=False) content_panels = Page.content_panels + [ MultiFieldPanel( [ FieldPanel("date"), FieldPanel("tags"), ], heading="Blog Information", ), FieldPanel("snippet"), FieldPanel("featured_image"), FieldPanel("body"), FieldPanel("author"), InlinePanel("page_comments", label="Comments"), ] search_fields = Page.search_fields + [index.SearchField("body")] parent_page_types = ["CategoryIndexPage"] subpage_types = [] def serve(self, request, *args, **kwargs): """ Method override to handle POST conditions for blog comments, ``BlogComment``. """ from .forms import CommentForm if request.method … -
Django cookies not being saved in Safari nor Firefox
I recently started to test cookies in my development environment as I need it for token storage and csrf token. I came accross the issue of firefox and safari not setting the cookies in their storage tabs. If safari's 'prevent cross-site tracking' is off the behavior is the same with Firefox. However, not all users if any will have this setting off. With the previous mentioned, both browsers do not save the cookies in the storage tab. But, the cookies are received as when I click in an api testing button I have after loggin in, it works and the resources are accessed since cookies are sent. But, neither Safari nor Firefox show it in the cookies tab. Here is the response after log in. Response HTTP/1.1 200 OK Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: https://localhost:3000 Access-Control-Expose-Headers: Content-Type, X-CSRFToken Allow: POST, OPTIONS Connection: close Content-Length: 714 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Tue, 18 Apr 2023 17:11:05 GMT Referrer-Policy: same-origin Server: Werkzeug/2.2.3 Python/3.9.6 Set-Cookie: auth1=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9; expires=Tue, 18 Apr 2023 17:21:05 GMT; HttpOnly; Max-Age=600; Path=/; SameSite=None; Secure Set-Cookie: csrftoken=Y1GzI80DfRc3lMkUnboTYeA3AZBY4aih; expires=Tue, 16 Apr 2024 17:11:05 GMT; Max-Age=31449600; Path=/; Secure Vary: Accept, Cookie, Origin X-Content-Type-Options: nosniff X-Frame-Options: DENY I am using Django and React both on localhost, … -
my elastic beanstalk application doesn't reflect the latest commit in the live environment
I am deploying my Django app via the eb CLI. I commit my changes to git and deploy (with eb deploy). In the past I would see my changes reflected after a deploy, now I do not. It is as if the application version is being cached on EB's side.Thanks in advance for any help. I checked the source on S3 and it is the latest version, so I have no idea why the live site (also accessed via eb open after deployment to be sure) doesn't reflect. I added some simple console logging to be certain, and it is missing. I've tried restarting the server and rebuilding the environment. Nothing has worked. I also deleted all previous application versions, so the only remaining one has the changes I want, then redeployed and restarted. Still not the version I want running on the environment. -
A form with fields that are associated with different database tables does not pass validation and does not create the necessary record in the db
I need to create an object in a database table using the form. This table is linked to other tables by means of a One-to-Many relationship. that is, through the ForeignKey. The fields are filled in by means of a drop-down list, which displays the objects that are in the tables associated with these fields. When I try to send data from the form, it does not pass validation and does not send anything. forms.py: class receiptForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['is_apartment'].empty_label = "Не выбрано" self.fields['is_owner'].empty_label = "Не выбрано" self.fields['is_receipt_type'].empty_label = "Не выбрано" class Meta: model = receipt fields = ['is_apartment', 'is_owner', 'is_receipt_type', 'date', 'receipt_file'] views.py: def create(request): error = '' if request.method == "POST": form = receiptForm(request.POST) if form.is_valid(): form.save() return redirect('main') else: error = "Форма была неверной" form = receiptForm() data = { 'form': form, 'error': error } if (request.GET.get('error')): return render(request, "main/main.html", context={'error': request.GET.get('error')}) return render(request, "main/main.html", data) models.py: class apartment(models.Model): address = models.TextField("Адрес квартиры", max_length=500, default="") def __str__(self): return self.address class owner(models.Model): surname = models.CharField("Фамилия", max_length=50, default="") name = models.CharField("Имя", max_length=50, default="") middle_name = models.CharField("Отчество", max_length=50, default="") email = models.EmailField("Email", max_length=254) def __str__(self): return f'{self.surname} {self.name} {self.middle_name}' class receipt_type(models.Model): pattern = models.FileField("Шаблон", upload_to='pattern') title … -
Testing a Consumer is failing when use database_sync_to_async Djagno Channels
So, I didn't use channels for a very long time, so let's be that this is a first time that I have tried to do something. I am trying to create 1 Consumer, wrapped with 1 custom Auth middleware and I want to test my Consumer, if it behaves properly in various test cases. Django==4.1.7 channels==4.0.0 middleware.py @database_sync_to_async def get_user(email): user = User.objects.get(email=email) if not user.is_active: raise AuthenticationFailed("User is inactive", code="user_inactive") return user class OktaASGIMiddleware(BaseMiddleware): def __init__(self, inner): super().__init__(inner) self.okta_auth = OKTAAuthentication() async def __call__(self, scope, receive, send): try: # token checking and retrieval claims = self.okta_auth.jwt_verifier.parse_token(token)[1] user = await get_user(claims["email"]) scope["user"] = user except Exception as exc: await send({"type": "websocket.close"}) raise return await self.inner(scope, receive, send) tests.py @aioresponses() async def test_connect_with_correct_token_edit_resource_draft( self, mocked_io_request ): mocked_io_request.get( # mocked request/respones ) communicator = WebsocketCommunicator( application, f"/ws/draft/1/?token={sometoken}" ) connected, subprotocol = await communicator.connect() self.assertTrue(connected) So, the issue is, when I use database_sync_to_async as Docs suggests, I am getting: django.db.utils.InterfaceError: connection already closed. When I use from asgiref.sync import sync_to_async, everything works fine and I can test my consumer properly. Also, i an attempt to avoid database_sync_to_async, I switched from JsonWebsocketConsumer to AsyncJsonWebsocketConsumer, but still no help. NOTE: Both of this code works … -
How can i manage leveldb database to cope with Django framework
i am trying to develop a web application that uses leveldb as a database, knowing that leveldb doesn't support an SGBD,how can i deal with it in order to manage data on django framework I suggest to use a relational data base to manage users,sessions and other standard data, and try to use leveldb just for that purpose that i am using for. -
Incrementing an IntegerField in Django
I'm trying to implement the Polls app like the one in the Django documentation. I have an IntegerField to represent the number of votes an option has in my Polls app but if I try to add the voter to the list of voters and increment it by one in my views.py ever time a user votes, it adds to the user to the list of voters but the vote count doesn't increase. This is my Choice model... votes = models.IntegerField(default=0) voters = models.ManyToManyField(UserProfile, blank=True, related_name="my_votes") This is my vote function in views.py option.votes += 1 user = UserProfile.objects.get(user = request.user) option.voters.add(user) How do i fix this please? -
Django: while updating record: ValueError: Cannot force an update in save() with no primary key
There are similar issues on SO, but none alike this. I would like to update a field in a record of a m2m model which has a unique constraint on attendee + training. This model is defined as (model.py): class Occurrence(models.Model): attendee = models.ForeignKey(Attendee, on_delete=models.CASCADE) training = models.ForeignKey(Training, on_delete=models.CASCADE) attended_date = models.DateField(default=date(1900, 12, 31)) class Meta: constraints = [ models.UniqueConstraint(fields=['attendee', 'training'], name='unique_attendee_training') ] Now, consider e.g. that John has taken the Python course and already exists as record in the db. If I try get the date of when the training occurred, I would go like this: from trainings.models import Attendee, Training, Occurrence from datetime import date, datetime attendee = Attendee.objects.get(pk='john@gmail.com') training = Training.objects.get(pk='python310') occurrence = Occurrence.objects.get(attendee=attendee, training=training) print(occurrence.attended_date) # datetime.date(2021, 11, 4) However, if I try to update the date of this record, I get the error. occurrence = Occurrence(attendee=attendee, training=training, attended_date=date(2021, 11, 5)) occurrence.save(update_fields=["attendee", "training", "attended_date"]) The error being: ValueError: Cannot force an update in save() with no primary key. How do I update this record? Note I believe this should be enough to understand the question. But if you want to reproduce the whole issue, I post here the models (model.py) for Attendees and Trainings. class Attendee(models.Model): …