Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Duplicate action when I press Follow or Unfollow button
I am doing CS50w project4 problem, so I have to build a Social Media app. This problem has a part where in the profile of the user a follow and unfollow button has to be available. My problem is when I press the follow or unfollow button, this increase or decrease the followers and the people that the user follow. views.py def seguir(request): if request.method == 'POST': accion = request.POST.get('accion') usuario_accion = request.POST.get('usuario') usuario = request.user.username # Comprobación de si ya lo esta siguiendo y recuperación de información de usuarios perfil_usuario = User.objects.get(username=usuario) perfil_usuario_accion = User.objects.get(username=usuario_accion) esta_siguiendo = perfil_usuario.seguidos.filter(username=usuario_accion).exists() if accion == 'follow': # Si no lo esta siguiendo se añade a la lista de seguidos de uno y de seguidores del otro if esta_siguiendo == False: perfil_usuario_accion.seguidores.add(perfil_usuario) perfil_usuario.seguidos.add(perfil_usuario_accion) # Redirección a la página del usuario seguido return render(request, "network/profile.html", { "profile_user": perfil_usuario_accion, "logged_user": 0 }) else: # Comprobación de que lo siga if esta_siguiendo: perfil_usuario.seguidos.remove(perfil_usuario_accion) perfil_usuario_accion.seguidores.remove(perfil_usuario) return render(request, "network/profile.html", { "profile_user": perfil_usuario_accion, "logged_user": 0 }) profile.html {% extends "network/layout.html" %} {% block body %} <h1 id="titulo-perfil">{{ profile_user.username }} profile page</h1> <div id="contenedor-seguir"> <div id="seguidores">Followers: {{ profile_user.seguidores.count }}</div> <div id="seguidos">Following: {{ profile_user.seguidos.count }}</div> </div> {% if logged_user == 0 %} … -
Trouble Activating Conda Environment in Dockerized Django Application
I'm working on Dockerizing a Django application with a Conda environment, but I'm encountering issues. The issue is that when I run docker compose up my Django application does not start properly and hangs on system check. This is my DockerFile setup: # Use an official Python runtime as a parent image FROM continuumio/miniconda3 # Set the working directory to /webapp WORKDIR /webapp # Copy the conda environment file to the container COPY webapp/my_env.yml . # Create the conda environment RUN conda env create -f my_env.yml # Create the conda environment SHELL ["conda", "run", "-n", "my_env", "/bin/bash", "-c"] # Copy the current directory contents into the container at webapp COPY webapp . # List the contents of the directory RUN conda run -n my_env ls # Make port 8000 available to the world outside this container EXPOSE 8000 # Run the Django development server ENTRYPOINT ["conda", "run", "--no-capture-output", "-n", "my_env", "python", "manage.py", "runserver"] My docker-compose.yml: version: "3" services: db: image: postgres environment: POSTGRES_USER: postgres POSTGRES_DB: webapp_connect POSTGRES_PASSWORD: tcatca124 volumes: - pgdata:/var/lib/postgresql/data webapp: build: context: . dockerfile: Dockerfile # Replace with the actual path to your Dockerfile ports: - "8000:8000" depends_on: - db volumes: pgdata: And this is a snippet from … -
<select> returning empty if the value isn't edited
So, I am working on an ticket system using Html, Css, JavaScript and Django, and I needed an field that changed depending on another field, after some searching I found a good JavaScript implementation to my case and it worked perfectly on the ticket creation part, but as I was doing the ticket editing part I got stuck with a problem, if there is no changes on the <select> field it simply gets an blank value instead of the value it was previously holding, changing the value works just fine but not changing it doesn't, I can't think of a way of preventing this yet and would like to ask if anyone has dealt with an similar problem that could help me. verticket.html(form part) <form name="form-ticket" id="formTicket" method="POST" action="{% url 'eticket' ticket.pk %}"> <div class="col-4 mt-4 m-auto"> {% if msg %} <div class="alert {{class}}"> {{msg}} </div> {% endif %} {% csrf_token %} <input class="form-control mt-4" type="text" name="numctt" id="numctt" value="{{ticket.numctt}}" placeholder="{{ticket.numctt}}"> <input class="form-control mt-4" type="text" name="nomctt" id="nomctt" value="{{ticket.nomctt}}" placeholder="{{ticket.nomctt}}"> <select required name="areaserv" id="areaserv"> <option disabled selected hidden>{{ticket.areaserv}}</option> </select> <select required class="followup" name="tiposerv" id="tiposerv"> <option disabled selected hidden >{{ticket.tiposerv}}</option> </select> <input class="form-control mt-4" type="text" name="tickettext" id="tickettext" value="{{ticket.tickettext}}" placeholder="{{ticket.tickettext}}"> {% block usuario %} … -
I have a problem with annotate. I want to add a subset counter column, but it doesn't get added
class ProductGroupInstanceInlineAdmin(admin.TabularInline): model=ProductGroup @admin.register(ProductGroup) class ProductGroupAdmin(admin.ModelAdmin): list_display=('group_title','is_active','group_parents','slug','register_date','update_date',) list_filter=('group_title','group_parents',) search_fields=('group_title',) ordering=('group_title','group_title',) inlines=[ProductGroupInstanceInlineAdmin] def get_queryset(self, *args , **kwargs): qs=super(ProductGroupAdmin,self).get_queryset(*args,**kwargs) qs=qs.annotate(sub_group = Count('groups')) return qs def count_sub_group(self,obj): return obj.sub_group I tried to add an extra column using the annotate method, which counts the subsets of my groups, but this additional column does not appear at all. -
How to upload a file larger than 32MB from django admin panel hosted in Cloud Run?
Problem I need to upload zip files with a size of ~800MB to a GCP Cloud Storage bucket using Django's admin panel. My Django API is hosted in Cloud Run, and I just found out Cloud Run has a request size limit of 32MB. I want to know if there's any workaround for this. What I tried I have tried using signed URLs and chunking the file in 30MB chunks, but got the same "413: Request too large" error. It seems that when I upload the file from the admin panel, it still sends a request with the whole file instead of sending it chunked. Here's my code up until now, which works perfectly from my local machine using a Cloud SQL proxy: utils.py: from django.conf import settings from google.cloud import storage def generate_signed_url(file_name, chunk_number): storage_client = storage.Client(credentials=settings.GS_CREDENTIALS) bucket = storage_client.bucket(settings.GS_BUCKET_NAME) blob_name = f'zip_files/{file_name}_chunk_{chunk_number}' blob = bucket.blob(blob_name) url = blob.generate_signed_url( version="v4", expiration=3600, method="PUT" ) return url def combine_chunks(bucket_name, blob_name, chunk_count): storage_client = storage.Client(credentials=settings.GS_CREDENTIALS) bucket = storage_client.bucket(bucket_name) # Create a list of the blobs (chunks) to be composed blobs = [bucket.blob(f'zip_files/{blob_name}_chunk_{i}') for i in range(chunk_count)] # Create a new blob to hold the composed object composed_blob = bucket.blob(f'zip_files/{blob_name}') # Compose the … -
Django // contact form connect to gmail
I would to know if someone has a good tuto about that, cause i find anything about that. I got only old tutos and google change his security about apps and when i create a special password for my app, it still doesn't work. connect contact form to gmail -
How can I filter an annotated query set
I have the code below that returns an aggregate of authors that have a book and the total amount of authors. This works well, but I want to get the count of authors that have a particular type of book and the total count of books. I have tried so many ways but giving wrong results. I would like to achieve this using annotate and aggregate as it will help performance. Below is my current code that works but it returns all authors with a book and total books, but I want authors with a particular type of book. from django.db.models import Count, Case, When, IntegerField, Sum data = self.author_set.annotate( total_books=Count("book", distinct=True), ).annotate( has_book=Case( When(total_books__gt=0, then=1), default=0, output_field=IntegerField(), ) ).aggregate( authors_with_books=Sum("has_book", default=0), authors_count=Count("pk", distinct=True), ) My Book model class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(null=True, blank=True, max_length=50) narration = models.CharField(null=True, blank=True, max_length=200) book_type = models.IntegerField(default=1) released = models.DateField() I have tried many tweaks but it returns wrong data. Please help -
language changed in django project but django-modeltranslation do not change
i used django-modeltranslation, the issue is when the language change, it does not affect and just one language shown, even than language was changed in the cookies these are my codes: class MenuItems(MPTTModel): title = models.CharField(max_length=50,verbose_name=_('Title')) url = models.CharField(max_length=100,verbose_name=_('Url Name')) parent = models.ForeignKey( 'self', null=True, blank=True, related_name='children', on_delete=models.CASCADE,verbose_name=_('Parent Menu')) order = models.IntegerField(default=0, verbose_name=_('Order')) class MPTTMeta: order_insertion_by = ['order'] def __str__(self): return self.title class Meta: verbose_name=_('Menu Item') verbose_name_plural = _('Menu Items') <!--ACCORDION Systematic START--> {% recursetree menu_items %} {% if not node.parent %} <div data-kt-menu-trigger="click" class="menu-item menu-accordion hover"> <!--begin:Menu link--> <span class="menu-link"> <span class="menu-icon"> <i class="ki-duotone ki-user fs-2"> <span class="path1"></span> <span class="path2"></span> </i> </span> <span class="menu-title">{{ node.title }}</span> <span class="menu-arrow"></span> </span> <!--end:Menu link--> <!--begin:Menu sub--> {% for child in node.get_children %} <div class="menu-sub menu-sub-accordion" kt-hidden-height="542" style=""> <!--begin:Menu item--> <div data-kt-menu-trigger="click" class="menu-item menu-accordion"> <!--begin:Menu link--> <span class="menu-link"> <span class="menu-bullet"> <span class="bullet bullet-dot"></span> </span> <span class="menu-title">{{ child.title }}</span> <span class="menu-arrow"></span> </span> <!--end:Menu link--> <!--begin:Menu sub--> <div class="menu-sub menu-sub-accordion menu-active-bg" kt-hidden-height="209" style="display: none; overflow: hidden;"> <!--begin:Menu item--> <!--begin:Menu link--> <div class="menu-item"> {% for instance in child.get_children %} {% if instance.is_leaf_node %} <a class="menu-link" href={% url instance.url %}> <span class="menu-bullet"> <span class="bullet bullet-dot"></span> </span> <span class="menu-title">{{ instance }}</span> </a> {% endif %} {% endfor %} … -
How can I display data from one page onto another page in django
So I am creating an expense tracking and budgeting app, and I have an idea that I want to implement. So I created a page (or app in Django) called "Budgets" and what I want to see when I select it is a table with columns 'Project Name', 'Budget (currency)', 'Expenses (currency)', 'Profit/Loss (currency)'. Now I have added a button on top which says "Add Budgets" and when I click it a form appears which I only have to feed 'Project Name' and 'Budget' and NOT the other two. I also have another page/app called "Expenses" which has every expense for the particular project. Now what I want is: To transfer the sum of all the expenses from the "Expenses" page/app and display it under the column 'Expenses' in the Budgets page. To make an automatic calculation of the profit/loss (i.e. Budget - Expenses) and have it display under the column 'Profit/Loss' in the Budgets page. I know for some people the question might not be clear and maybe extra information or attachments may be required, please don't hesitate to ask. I have not provided any code because I am unsure of what might be needed in particular. -
Unable to Terminate Django 2.1 Project Running on Ubuntu 20.04.2 LTS with NGINX, UWSGI, and Celery
I have a test project (a 'zombie' project) on the same server as the production version of my app. Both projects use Celery for background tasks, but they share the same RabbitMQ port. I noticed that some tasks from the production Celery instance were executed in the test environment. Attempting to resolve this, I tried to terminate the uwsgi process of the test project, but it was unsuccessful – the Django admin console for the test project remained accessible. Further attempts, such as renaming the project directory and restarting the server while ensuring the deletion of the relevant .pid file, also failed. I'm currently out of ideas and looking for help to resolve this issue. -
dj-rest-auth, django-allauth, mongodb authentication
i want to integrate user authencation in my django projet, i'm using dj-rest-auth, django-allauth and my db is mongodb but when i execute python manage.py migrate i get this error: File "/Users/venv/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 830, in __iter__ raise exe from e djongo.exceptions.SQLDecodeError: Keyword: FAILED SQL: SELECT %(0)s AS "a" FROM "django_site" LIMIT 1 Params: (1,) Version: 1.3.6 Sub SQL: None FAILED SQL: None Params: None Version: None -
Django (DRF) ORM - Simple left join with reverse relation
I am trying to select data from my postgreSQL database using Django 3.2.9 and DRF 3.12.4. Here are my models : class Headpiece(ValidatedModelbase): class Types(models.TextChoices): POWDER = "Powder" SOLUTION = "Solution" id_headpiece = models.AutoField(primary_key=True) name = models.TextField(null=False) structure = models.TextField(null=False) total_structure = models.TextField(null=False) molecular_weight = models.FloatField(null=False) type = models.CharField(null=False, choices=Types.choices, max_length=255) status = models.BooleanField(default=True) comment = models.TextField(null=True, blank=True) class Meta: db_table = "headpiece" managed = True def __str__(self): return self.name class Matter(ValidatedModelbase): id_matter = models.AutoField(primary_key=True) dna_tag = models.ForeignKey(DNATag, on_delete=models.DO_NOTHING, null=True, blank=True) headpiece = models.ForeignKey(Headpiece, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='matter') class Meta: db_table = "matter" managed = True class Vial(ValidatedModelbase): id_vial = models.AutoField(primary_key=True) rack = models.ForeignKey(Rack, on_delete=models.DO_NOTHING) matter = models.ForeignKey(Matter, on_delete=models.DO_NOTHING, related_name='vial') barcode = models.CharField(null=False, max_length=255) position_column = models.IntegerField(null=False) position_row = models.IntegerField(null=False) quantity_left = models.FloatField(null=False) project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, null=True, blank=True) reserving_business_entity_name = models.CharField(null=True, max_length=255) origin_name = models.CharField(null=True, max_length=255) class Meta: db_table = "vial" unique_together = ["rack", "position_column", "position_row"] managed = True def __str__(self): return self.barcode The data i need is a list of Headpieces, joined with their Vials data. I want a new line for each Vial, and if no Vial is related, the Headpiece data only. In SQL, it translates to this : SELECT headpiece.*, vial.* FROM headpiece LEFT JOIN … -
Gofiber + Django - Template Recursion Issue
So I am generating a folder structure that uses accordion from bootstrap. This is working as intended for 1 level of depth. As soon as I want to go into 2+ levels of depth it does not work as intended. I get it working by tricking the handler. I run this via docker containers. I have a main for loop in the root of the structure. I that calls a template. I keep this template in partials folder. This works fine. within this template that is in the partials folder I once again call the template file as it should be a recursive loop until there is no need to call it again. I start my server using the following within the template: {% include "partials/subfolder_template.django" with folder=folder %} This holds the server from starting but I quickly modify this line to this: {% include "subfolder_template.django" with folder=folder %} Removing the partials/ makes the server work and boom - This server now starts and when I go to my handler the depth levels work as intended. The issue with this is that if the container fails or gets restarted then this will fail and show the following error on the … -
How can I post data to django import_export
I would like to test the import function from import_export django. When I run my test the code says I provide no dataset (None) even though I do provide a proper CSV file. Thus, my assertions (starting from self.assertIn('result', response.context)) fail. Why don't my resource class and def import_data see the dataset I provide in response = self.client.post(import_url, data=data)? My test: class ImportUserCase(TestCase): def setUp(self) -> None: self.admin = User.objects.create(login='admin', email='admin@example.com', password='password', is_staff=True, is_superuser=True) self.client = Client() self.client.force_login(self.admin) self.resource = UserImportResource() def test_import_action(self) -> None: import_url = '/admin/core/user/import/' process_url = '/admin/core/user/process_import/' input_format = '0' filename = 'users.csv' with open('users.csv', 'w') as f: writer = csv.writer(f) writer.writerow(UserImportResource.Meta.fields) writer.writerow('test', 'test@gmail.com', 'test, 'test', 'test) with open(filename, "rb") as f: data = { 'input_format': input_format, 'import_file': f, } response = self.client.post(import_url, data=data) self.assertEqual(response.status_code, 200) self.assertIn('result', response.context) self.assertFalse(response.context['result'].has_errors()) self.assertIn('confirm_form', response.context) confirm_form = response.context['confirm_form'] data = confirm_form.initial self.assertEqual(data['original_file_name'], 'books.csv') response = self.client.post(process_url, data,follow=True) self.assertEqual(response.status_code, 200) My resource: class UserImportResource(resources.ModelResource): class Meta: model = User instance_loader_class = UserLoader fields = ('login', 'email', 'first_name', 'last_name', 'gender') use_transactions = False def get_import_id_fields(self): return ['email'] def get_import_fields(self): return [self.fields[f] for f in self.get_import_field_names()] def get_import_field_names(self): return ('login', 'email', 'first_name', 'last_name', 'gender') def before_import(self, dataset, using_transactions, dry_run, **kwargs): to_delete = [] … -
In mutually selected data, how do you ask for the delete confirmation - Python, Django, HTML?
I want to select certain data and delete it from a code that has a check box. I can remove it, but I am unable to request a message of confirmation. Here is my view.py code. def expens(request): data = '' number = '' if 'delete_all' in request.POST: choosen = request.POST.getlist('x[]') if choosen: for selected in choosen: picked = Expenses.objects.filter(id=selected) picked.delete() messages.info( request, "Expens data has been deleted successfully.", extra_tags='success') else: messages.info(request, "Please select to delete.", extra_tags='error') if 'save' in request.POST: return render(request, 'expens.html', {'data': data, 'number': number}) And my HTML code: {% for expens in picked %} <div class="alert alert-danger" role="alert"> Do you want to delete: <b>{{ expens.assignment }} {{ expens.amount }}</b>?<br> <a class="btn btn-success" href="{% url 'expens_delete_config' expens.id %}">Yes</a> <a class="btn btn-danger" href="{% url 'expens' %}">No</a><br> </div> {% endfor %} <form method="post"> {% csrf_token %} <table class="table table-success table-striped" id="table"> <thead> <th>#</th> <th>Assignments</th> <th>Amount</th> <th>Date</th> <th><button class="btn btn-danger btn-sm" name="delete_all">Delete selected</button></th> </thead> <tbody> {% for info in data %} <tr> <td><input type="checkbox" name="x[]" value="{{info.id}}"> {{forloop.counter}}</td> <td>{{info.assignment}}</td> <td>{{info.amount}}</td> <td>{{info.add_date}}</td> <td> <a class="btn btn-danger btn-sm" href="{% url 'expens_delete' info.id %}"><i class="bi bi-x"></i></a> <a class="btn btn-warning btn-sm" href="{% url 'expens_edit' info.id %}"><i class="bi bi-pencil"></i></a> </tr> {% endfor %} </tbody> </table> </form> … -
Change div text from select dataset
I want the selected dataset to appear at the beginning and then the selected ones to appear in the div.I don't know Java. I try someting like this. not work :( <script> $(document).ready(function() { const div = document.getElementById("nitelik3") div.on('change', function() { from_text.html(div.dataset.fiyat); }) }); </script> {{ key|safe }}-{% translate 'Price' %} €<div id='from'></div> <select id='nitelik3' name="nitelik3" class="form-control mb-3"> {% for vl in val %} <option value={{ vl.0 }} data-fiyat='{{ vl.3 }}' style="font-size:15px">{{ vl.1 }} - €{{ vl.3 }}</option> {% endfor %} </select> -
How do I stop CKEditor from stripping out Adsense Ads <ins> tag in my Django admin backend?
I have implemented a standard CKEditor configuration on my Django site's admin backend. The default CKEDITOR_CONFIGS in settings.py is: CKEDITOR_CONFIGS = { 'default': { 'allowedContent': True, }, } In the article model I have: description = RichTextField() The problem I am having is that when I try to insert a Google Adsense Ad unit code in the CKEditor source and save it like so: The CKEditor is stripping the ins tag from the Adsense ad code after saving as seen here: How do I prevent the CKEditor from stripping the tag from the Adsense code? I have tried implementing the solution suggested here by adding the two lines to the CKEditor's config.js file but that doesn't have any effect: How to push a protectedSource in django-ckeditor? /** * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. * For licensing, see https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.protectedSource.push( /<ins[\s|\S]+?<\/ins>/g ); config.protectedSource.push( /<ins class=\"adsbygoogle\"\>.*?<\/ins\>/g ); }; This leads to another question: how do I make sure that the CKEditor's config.js file is being applied as it seems its currently not … -
Problem with query optimization in Django admin
I came across the fact that when I try to open the object creation window FriendlyMatch, it takes a lot of time. About 2 minutes. Through the django debug toolbar I found out that there were 4300 SQL queries. Here are my models: class Player(models.Model): """Модель игрока""" user = models.ForeignKey( User, related_name="player", on_delete=models.CASCADE, verbose_name="Игрок" ) created = models.DateTimeField(auto_now_add=True) team = models.ForeignKey( Team, related_name="team_player", null=True, on_delete=models.SET_NULL, verbose_name="Команда", ) class Meta: """Мета класс модели Игрока""" verbose_name = "Игрок" verbose_name_plural = "Игроки" def __str__(self): return f"Игрок {self.user.username}" class FriendlyMatch(models.Model): """Модель Дружеского матча""" date_start = models.DateTimeField( verbose_name="Дата и время начала", null=True, blank=True ) date_end = models.DateTimeField( verbose_name="Дата и время окончания", null=True, blank=True ) duration_macth = models.SmallIntegerField( verbose_name="Длительность дружеского матча", default=3, null=True, blank=True ) creator = models.ForeignKey( User, related_name="creator_friendly_match", null=True, on_delete=models.SET_NULL, verbose_name="Создатель", ) player_1 = models.ForeignKey( Player, related_name="friendly_match_player1", null=True, on_delete=models.SET_NULL, verbose_name="Игрок 1", ) player_2 = models.ForeignKey( Player, related_name="friendly_match_player2", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Игрок 2", ) first_game_winner = models.ForeignKey( Player, related_name="first_game_winner_friendly_match", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Победитель первой игры", ) second_game_winner = models.ForeignKey( Player, related_name="second_game_winner_friendly_match", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Победитель второй игры", ) third_game_winner = models.ForeignKey( Player, related_name="third_game_winner_friendly_match", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Победитель третьей игры", ) fourth_game_winner = models.ForeignKey( Player, related_name="fourth_game_winner_friendly_match", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Победитель четвертой игры", ) fifth_game_winner = models.ForeignKey( … -
Handling File Uploads in Django: How Can I Improve Security and User Experience?
`I'm currently working on a Django web application, and I need to implement a file upload feature. While the basic functionality is clear, I want to ensure that the file upload process is both secure and provides a good user experience. What are the best practices for handling file uploads securely in Django? How can I prevent common security vulnerabilities related to file uploads? Are there any Django packages or libraries that enhance the user experience when uploading files? I've done some research, but I'd appreciate insights from the community to ensure I'm on the right track. Any code examples or recommended resources would be greatly appreciated. Thanks! ` Handling file uploads securely in Django is crucial, and there are several best practices you can follow to achieve this. Here's a comprehensive guide to help you improve both security and user experience: Use Django's Built-in File Handling: Django provides a FileField for handling file uploads in models. This field automatically handles file storage, and you can specify the storage backend, such as FileSystemStorage or S3Boto3Storage for Amazon S3. Example model: from django.db import models class MyModel(models.Model): upload = models.FileField(upload_to='uploads/') -
DJANGO, update button is not working in frontend but in admin panel, i can change the status. Help me fix it guys im going crazy
When i click the update button, it should change the remarks/status of the submitted file in submission, however i dont know why it is working in my frontend but it works in my django admin panel. Please help me huhu, and also i dont want to use AJAX cause it's so complicated to use html {% extends "base/room_home.html" %} {% block content %} <div class="container d-flex align-items-center justify-content-center" style="min-height: 100vh;"> <div class="text-center"> <h1>{{ room_bills.title }}</h1> <p>Due: {{ room_bills.due }}</p> <div class="col-3"> <h3>Paid Members: </h3> <ul> {% for submission in submissions %} <li> <a href="proof/{{ submission.user.id }}" target="_blank">{{ submission.user.username }}</a> {% if submission %} <form method="POST" class="update-form" data-room-id="{{ room_bills.room.id }}" data-bills-slug="{{ room_bills.slug }}" data-submission-id="{{ submission.id }}"> {% csrf_token %} <select name="status"> <option value="P" {% if submission.status == 'P' %}selected{% endif %}>Pending</option> <option value="A" {% if submission.status == 'A' %}selected{% endif %}>Accepted</option> <option value="R" {% if submission.status == 'R' %}selected{% endif %}>Rejected</option> </select> <button type="submit" class="btn btn-primary">Update</button> </form> {% endif %} </li> {% endfor %} </ul> </div> <div class="col-3"> <h3>Did not pay members: </h3> <ul> {% for user in did_not_submit %} <li>{{ user.username }}</li> {% endfor %} </ul> </div> </div> </div> <script> function getCookie(name) { const value = `; ${document.cookie}`; const parts … -
Django Compare passwords with Bcrypt
I have a problem with bcrypt... How I compare the String saved in the db with the String from the user input this: >>> import bcrypt >>> salt = bcrypt.gensalt() >>> hashed = bcrypt.hashpw('secret', salt) >>> hashed.find(salt) 0 >>> hashed == bcrypt.hashpw('secret', hashed) True >>> and this doesn't work at least I save my passwords raw in the db -_- Somebody know how to do it? -
How to find duplicate FK entries in Django using query
I have a GeneralLedger that is comprised of JournalLineItems and AccountsPayableLineItems. When either a JournalLineItem or AccountsPayableLineItem gets stored, I save it in the GeneralLedger as a referece. I have an issue to where, while setting everything up I guess, I added 10 duplicate FK entries for either a JournalLineItem or AccountsPayableLineItem. I am trying to determine which they are, but I am having issues figureing out the query to use. For example: print(GeneralLedger.objects.count()) # 2416448 print(JournalLineItem.objects.count()) # 2414902 print(AccountsPayableLineItem.objects.count()) # 1536 Overall the important structure of my model would be: class GeneralLedger(models.Model): journal_line_item = models.ForeignKey('accounting.JournalLineItem', null=True, on_delete=models.CASCADE, related_name='general_ledger', db_index=True) accounts_payable_line_item = models.ForeignKey('accounting.AccountsPayableLineItem', null=True, on_delete=models.CASCADE, related_name='general_ledger', db_index=True) How do I write a query to see which journal_line_item or accounts_payable_line_item has duplicate entries in the GeneralLedger? -
Can I use `JWTStatelessUserAuthentication` instead of `JWTAuthentication` in my Django project, even without multiple applications?
I'm currently working on a Django project, and I'm exploring the use of authentication mechanisms provided by Simple-JWT. In the documentation, I noticed the option of using JWTStatelessUserAuthentication for single sign-on (SSO) between separate Django apps that share the same token secret key. My project doesn't involve multiple applications, but I'm intrigued by the potential benefits of JWTStatelessUserAuthentication, especially in avoiding database queries for user info in each API call, which seems to be a characteristic of JWTAuthentication. I'd appreciate any insights, experiences, or recommendations regarding the use of these authentication methods in a Django project. Thanks! Specific Questions: Is it advisable to use JWTStatelessUserAuthentication in a project without multiple applications? Are there any specific considerations or limitations associated with using JWTStatelessUserAuthentication in a project context like mine? -
Limiting choices in django dynamically (call-back function?)
I am relatively new to Django and this is my first question on Stackoverflow. So pleas bear with me if not ideally formulated. My Problem: I have a Model Animal with two fields that are ForeignKey based (species,breed) . Only those breeds should be shown that are available as per the entered/given species. This reduction of choice options shall take place when a) a new Animal record is created, b) the specie value is changed and the breed options are looked up newly and c) when the breed for a given animal shall be changed. This shall happen both in the Admin UI as well as in the apps UI via Django Forms Originally I thought the the limit_choices_to attribute in conjunction with a Q could do the trick but it did not, neither I was able to got it working callable defined. By reading various posts I have found a way to interfere for method c) which does not work for a) and b) Here are my data: Models.py class Specie(models.Model): specie = models.CharField(primary_key=True, max_length=1, ) specieText = models.CharField( max_length=24,) class Meta: ordering = ['specieText'] def __str__(self): return self.specieText class Breed(models.Model): specie = models.ForeignKey('Specie', on_delete=models.CASCADE,) breed = models.CharField(max_length=2,) breedText … -
Django models troubles in admin
I was trying to build database connections for an online school project. It turned out that I have 2 entities Student and Course, they have a many-to-many relationship. At the same time, if I delete a student from a course, the course will not be deleted and also, when I delete a course, the students will not be deleted. I had an idea to make a related model through which I can assign courses to students and vice versa, but after creating the connection, when I try to disconnect a student from it, I get an error IntegrityError at /admin/student/studentcourse/1/change/ NOT NULL constraint failed: student_studentcourse.student_id Request Method:POSTRequest URL:http://127.0.0.1:8000/admin/student/studentcourse/1/change/Django Version:4.2.7Exception Type:IntegrityErrorException Value:NOT NULL constraint failed: student_studentcourse.student_idException Location:C:\Users\amane\PycharmProjects\StudyHome\.venv\Lib\site-packages\django\db\backends\sqlite3\base.py, line 328, in executeRaised during:django.contrib.admin.options.change_viewPython Executable:C:\Users\amane\PycharmProjects\StudyHome\.venv\Scripts\python.exePython Version:3.11.4Python Path:['C:\\Users\\amane\\PycharmProjects\\StudyHome', 'C:\\Users\\amane\\PycharmProjects\\StudyHome', 'C:\\Program Files\\JetBrains\\PyCharm ' '2022.2\\plugins\\python\\helpers\\pycharm_display', 'C:\\Users\\amane\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\amane\\AppData\\Local\\Programs\\Python\\Python311\\DLLs', 'C:\\Users\\amane\\AppData\\Local\\Programs\\Python\\Python311\\Lib', 'C:\\Users\\amane\\AppData\\Local\\Programs\\Python\\Python311', 'C:\\Users\\amane\\PycharmProjects\\StudyHome\\.venv', 'C:\\Users\\amane\\PycharmProjects\\StudyHome\\.venv\\Lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2022.2\\plugins\\python\\helpers\\pycharm_matplotlib_backend']Server time:Mon, 27 Nov 2023 13:10:21 +0000 My project code student/models.py from django.db import models class Student(models.Model): GENDER_CHOICES = [ ('М', 'Мужской'), ('Ж', 'Женский'), ] student_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, blank=False) surname = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) age = models.IntegerField() gender = models.CharField(max_length=1, choices=GENDER_CHOICES) parents_phone = models.CharField(max_length=100) parents_email = models.EmailField(max_length=100, blank=False) phone = models.CharField(max_length=20) email = models.EmailField(max_length=100, blank=False) description …