Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I get an error { "error": "Invalid email or password" }
I want to implement the ability to log in to my account, he says that I have the wrong email or password, but I checked the correct email and password through the administrative line. help me understand why the error comes out and how to fix it class LoginView(APIView): serializer_class = LoginSerializer # def get(self, request): # return render(request, 'login.html') def post(self, request): email = request.data.get('email') password = request.data.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=status.HTTP_200_OK) return Response({'error': 'Invalid email or password'}, status=status.HTTP_401_UNAUTHORIZED) class LoginSerializer(serializers.Serializer): email = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate( username=data['email'], password=data['password'] ) if not user: raise serializers.ValidationError('Неверные учетные данные') data['user'] = user return data class User(models.Model): email = models.EmailField(max_length=255, unique=True) password = models.CharField(max_length=128) -
Changing Year, Month, or Day in a Django model's date field using annotate
I have a Django model MyModel class MyModel(models.Model): """My Model that stores date.""" date = models.DateField() In my API I am receiving a param, review_month I need to get all the entries in MyModel and replace their date's year value. I have the following condition for what year to add: -> If date__month is greater than review_month the year will be current year otherwise the year will be previous year. I need these new date fields with updated years for every entry of the MyModel queryset MyModel.objects.annotate( updated_year=Case( When( Q(review_date__month__gt=review_month.month), then=previous_year), default=current_year, output_field=IntegerField(), ), ) ) This only give me year separately but I want an updated_date that has day and month of date field and this new updated year in it and must be a DateField as I need to apply sorting to it. -
user match query does not exist
I have been tasked to create separate user model for third_party users who are to access our endpoint so i created separate user named ApiCliet and inherited the Abstract user model of Django i also created a custom authentication for that user model only and then crated two mutation to create an api client and also generate and access_toekn for the existing user how ever i get user matching query does not exist which is baffling after debugging i get the username is correct and the password is correct below is my code . Model class ApiClientManager(BaseUserManager): def create_user(self, username, email=None, password=None, **extra_fields): if not username: raise ValueError("The Username field must be set") email = self.normalize_email(email) if email else None user = ApiClient(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(username, email, password, **extra_fields) class ApiClient(AbstractBaseUser, PermissionsMixin): id = models.AutoField(db_column="Api_client_ID", primary_key=True) uuid = models.CharField(db_column="Api_clientUUID", max_length=36, default=uuid.uuid4, unique=True) username = models.CharField(db_column="Api_client_username", max_length=100, unique=True, default='test_username') email = models.EmailField(db_column="Api_client_email", blank=True, null=True) access_token = models.CharField(db_column="Api_client_access_token", max_length=100, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) … -
Compare Python Dictionary values with Django Database fields
I'm looking for a way to compare a python dictionary values with Django ORM entries. I have a dictionary contains product information like following: product_1 = { "ProductId": "552049", "BarCode": "552049", "Height": 200, "WholesalePrice": 10.65, "RetailPrice": 18.78, "Length": 62, "LongDescription": "Spray 400ml", "ShortDescription": "Spray 400ml", "Volume": 818, "Weight": 354, "Width": 66, } These values stored on a Django database. The number of products are very big, about 200.000 products and after a few days I need to compare and update the products if something change. I know that a way is to iterate to products and compare values but I'm looking for a better approach to compare products more faster. I'm thinking about to create a checksum and stored as a field in database and later when I update the products, first compare the checksum and if is different then update the database field. But I don't know if this the best way. Can someone suggest me a fast way for this? -
Django forms value getting the last id but wanted specfic id and first save is working the rest is not working
**I have a Django code where i am retrieving the tin number and tin type ** ``if ("_generate_form_1099" in self.request.POST) and self.request.POST["_generate_form_1099"] == "Generate Form 1099": elif ("_send-bulk-email" in self.request.POST) and self.request.POST["self-bulk-email"] == "Send Bulk Email": elif ("action" in self.request.POST) and self.request.POST["action"] == "Save Tin": user_id = self.request.POST.get('user_id') tin = self.request.POST.get('tin_value') tin_type = self.request.POST.get('tin_type') input_name = f"tin_value{{ user.id }}" if input_name in self.request.POST: tin_value = self.request.POST[input_name] user = CustomUser.objects.get(id=user_id) user.seller_tin = tin user.tin_type = tin_type user.save() context = {'user_contexts': user_contexts} return render(self.request, 'admin/generate_form.html', context) elif ("_send-tin-email" in self.request.POST) and self.request.POST["_send-tin-email"] == "Send Email": user_id = self.request.POST.get('user_id') user_name = self.request.POST.get('user_name') email_mess = {"seller": user_name} send_notification([user_id], 'notification_31', email_mess) ` `{% extends "admin/base_site.html" %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div> <input type="submit" class="action-button" value="Generate Form 1099" name="_generate_form_1099"> </div><br> {% if download_link %} <a href="{{ download_link }}" target="_blank" class="download-button"> <div style="display:inline-block">Download</div> </a> {% elif download_link %} <div><p>The Form 1099 has not been generated for the specified fiscal year. Click on Generate Form 1099</p></div> {% endif %} {{ block.super }} </form> <div> <h2>Seller Information Without Tin</h2> <table> <tr> <th class="header-table">USER ID</th> <th class="header-table">Name</th> <th class="header-table">Email</th> <th class="header-table">TIN Details</th> <th class="header-table">Actions</th> </tr> {% for user in user_contexts %} … -
dj-rest-auth patch and put not working in custom user model
I am developing an API for a mobile app and using dj-rest-auth to handle authentication logic. I have created a custom user model and a custom user serializer. Registration, login, and retrieving user details are functioning correctly. However, I'm encountering an issue with PUT and PATCH requests when attempting to update user information, I get error looks like this. UserSerializer.save() missing 1 required positional argument: 'request' Request Method: PATCH Custom User Model Code from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyUserManager(BaseUserManager): def create_user(self, email, password=None): user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email, password): user = self.create_user( email=self.normalize_email(email), password=password, ) user.is_staff = True user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): username= None is_superuser = models.BooleanField(default=False) email= models.EmailField(max_length=255, unique=True, primary_key=True) name = models.CharField(max_length=255) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) phone = models.CharField(max_length=20, unique=True) with_facebook = models.BooleanField(default=False, blank=True) with_google = models.BooleanField(default=False, blank=True) latitude = models.DecimalField(max_digits=11, decimal_places=8, blank=True, default=None, null=True) longitude = models.DecimalField(max_digits=11, decimal_places=8, blank=True, default=None, null=True) created_at = models.DateTimeField(auto_now_add=True) notification_token = models.CharField(max_length=255) isSoon = models.BooleanField(default=False) id_image = models.ImageField(upload_to='id_image/', blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = MyUserManager() def __str__(self): return … -
use of Django-gTTS to say multiple text in one audio
I am building a simple quiz app and I am using Django-gTTS to read out some text on my webpage but the problem that I am having is I cannot join regular text and text from my views in one audio tag. For example, I want my code to be something like this: <audio src="{% say 'en-us' 'Course name' test.course_name 'Total Marks' total_marks %}" controls ></audio> although this exact code will give an error. Is there any way I can implement this? -
Django properly add foreign key from newly created model
I am trying to create a foreign key in my Project Model. The foreign key is from a newly created model. class Status: name = models.CharField(max_length=100) def __str__(self): return self.name class Project(models.Model): projectID = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) projectBrief = models.TextField(default="") status = models.ForeignKey(Status, blank=True, null=True, on_delete=models.SET_NULL) Getting the following error line 939, in __init__ raise TypeError( TypeError: ForeignKey(<class 'projects.models.Status'>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' PS: I have been working on JSP from a long (I know pretty bad, where I can just add remove db fields without issue). Recently started learning Django. So please guide accordingly. Thanks. I am using the following commands python manage.py makemigrations python manage.py migrate I am not able to successfully migrate. -
How to remove newline created by { % if %} in django
I am generating email using email template in django. email_template.txt Some random string Some other string ----------------------------------------- {% if 'firstname' in data %}firstname: {{data['firstname']}}{% endif %} {% if 'lastname' in data %}lastname: {{data['lastname']}}{% endif %} {% if 'dob' in data %}dob: {{data['dob']}}{% endif %} {% if 'route' in data %}route: {{data['route']}}{% endif %} {% if 'mobile' in data%}mobile: {{data['mobile']}}{% endif %} {% if 'mail' in data%}mail: {{data['mail']}}{% endif %} I can not use spaceless because it will also remove spaces which i want to keep. In some cases if condition in template is not true then it gives new line. How can I stop the extra new line if condition is not true. -
Why does a button show in virtual environment but not in Django project in VS Code?
I am searching for a button name in VS Code in a Django Project. But the button is not showing in the Django project. Instead it is showing in it's virtual environment. and if i change something like that button's name in the virtual environment then it works fine. I want the button to be found in the Django project and not in it's virtual environment. Kindly help please. -
Print as pdf using python django
Check Image First I need assist in creating the code to create each record from the list to print as pdf using Django or JavaScript as seen from the picture the edit code is properly working but got stuck on pdf feature. assist only with pure django, pure javascript or any other library from both. -
Does csrf protection is required in django api?
Im currently making an app with flutter, and to communicate with mysql server using django for restAPI. Also Im using session for protection. In this case d I also need to use CSRF protection? If I plan to build an website with flutter in the future, does CSRF Protection is required? -
Could you guys tell How to import 'reflections and multiFunctionCall
ImportError: cannot import name 'reflections' from 'chatbot' Let show me How to import name 'reflections' from 'chatbot' ImportError: cannot import name 'reflections' from 'chatbot' ImportError: cannot import name 'reflections' from 'chatbot' -
Erreur "cannot planifier de nouveaux futurs après l'arrêt de l'interpréteur" lors de l'utilisation de vues asynchrones dans Django
Je travaille sur un projet Django où j'utilise des vues asynchrones pour récupérer des données à partir de différentes sources et les afficher via une API REST. J'ai suivi les étapes pour activer les vues asynchrones dans Django, mais je suis confronté à une erreur que je ne parviens pas à résoudre. Lorsque j'accède à une vue asynchrone qui récupère et traite des données à partir de sources externes, j'obtiens l'erreur suivante : RuntimeError: cannot schedule new futures after interpreter shutdown Code de ma vue asynchrone class CiscoCVEListView(APIView): async def save_cve_to_database(self, cve_data): # ... async def process_cisco_data(self): # ... async def get(self, request): try: cisco_data = await self.process_cisco_data() return Response(cisco_data, status=status.HTTP_200_OK) except Exception as e: return Response({"error": "Failed to fetch data"}, status=status.HTTP_500_INT **Environnement : Version Django : 4.1.7 Version Python : 3.11.0 Système d'exploitation : Windows **Étapes que j'ai essayées : *J'ai suivi les étapes pour activer les vues asynchrones dans Django en installant les bibliothèques appropriées. *J'ai modifié mon code pour utiliser des fonctions asynchrones et await pour gérer les opérations asynchrones. J'ai vérifié les forums de Django et de Python pour des solutions similaires, mais je n'ai pas encore trouvé de solution. Je ne suis pas sûr de … -
Writing to a database in django
In django I can find a lot of examples of reading a database and displaying the data accordingly on a webpage. I can find no example of writing back to the database though (according to user input, or to the result of a computation). Can you point me to example code, or a tutorial or help me on how to do this? -
Vscode configure path intellisense with django templates
Is it possible to configure path intellisense to work with django template? i just installed the extension and it works perfectly if you only use html but when you use django-html it doesn't work :( it's work <img class="avatar avatar-sm rounded-circle"alt="User Image"src="../static/img/patients/patient1.jpg"> Doesn't work <img class="avatar avatar-sm rounded-circle"alt="User Image" src="{% static 'img/Patients/patient1.jpg' %}"> Intellisense for html does not work if file association set to django-html I thought it was a configuration problem, but I see that it is not, since it works perfectly when I do not use the syntax for django static files https://github.com/ChristianKohler/PathIntellisense -
Django Rest FrameWork: detail : "Authentication credentials were not provided."
I can fetch data but cannot post as I receive that error Heres what i have: https://github.com/ryan-howard-hc/Howti -
Unknown field(s) specified for a Page model in Wagtail at content_panels
Wagtail Django class AboutPage(Page): header_image = ImageChooserBlock() body = blocks.StreamBlock([ ('title', blocks.CharBlock()), ('content', blocks.RichTextBlock()), ]) content_panels = Page.content_panels + [ FieldPanel('header_image'), FieldPanel('body'), ] I keep getting this error, and I can't even begin to understand how to debug Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/wagtail/admin/checks.py", line 70, in get_form_class_check if not issubclass(edit_handler.get_form_class(), WagtailAdminPageForm): File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/wagtail/admin/panels/base.py", line 134, in get_form_class return get_form_for_model( File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/wagtail/admin/panels/base.py", line 48, in get_form_for_model return metaclass(class_name, tuple(bases), form_class_attrs) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/permissionedforms/forms.py", line 30, in __new__ new_class = super().__new__(mcs, name, bases, attrs) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/modelcluster/forms.py", line 259, in __new__ new_class = super().__new__(cls, name, bases, attrs) File "/home/khophi/Development/Photograph/venv/lib/python3.10/site-packages/django/forms/models.py", line 321, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (body, header_image) specified for AboutPage 9:43 Anyone with Wagtail Django experience should help -
How to count related objects
I am trying for a model to count related items and save that number into a interger field however it returns an error message: TypeError: default_order() missing 1 required positional argument: 'obj' Is there a better way to solve this problem and save the number of existing items related to a "level" field? Below is what I intend to be my code: def default_order(obj): n = Schedules.objects.filter(level=obj.level).count() return n class Schedules(models.Model): level = models.ForeignKey(Levels,related_name='levels',blank=False,null=False,on_delete=models.CASCADE) order = models.IntegerField(default=default_order) -
Django: Command to execute other commands?
I've created commands to create objects from my models. Can we have a command to execute them all? Or execute the all the commands in a folder, in a specific order? Example fo command: app/management/commands/products.py import pandas as pd import csv from shop.models import Product, Category from django.core.management.base import BaseCommand tmp_data_products = pd.read_csv('static/data/products.csv', sep=';', encoding='iso-8859-1').fillna(" ") class Command(BaseCommand): def handle(self, **options): products = [ Product( category=Category.objects.get(name=row['category']), name=row['product'], slug=row['slug'], sku=row['sku'], description=row['description'], available=row['available'], image=row['image'] ) for _, row in tmp_data_products.iterrows() ] Product.objects.bulk_create(products) -
im not able to migrate the files from my django app to AWS RDS
py manage.py makemigrations C:\Python311\Lib\site-packages\django\core\management\commands\makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "database-1.cf9dt6lrnclf.eu-north-1.rds.amazonaws.com" (172.31.42.207), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? warnings.warn() py manage.py makemigrations C:\Python311\Lib\site-packages\django\core\management\commands\makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "database-1.cf9dt6lrnclf.eu-north-1.rds.amazonaws.com" (172.31.42.207), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? warnings.warn() py manage.py makemigrations C:\Python311\Lib\site-packages\django\core\management\commands\makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "database-1.cf9dt6lrnclf.eu-north-1.rds.amazonaws.com" (172.31.42.207), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? warnings.warn() py manage.py makemigrations C:\Python311\Lib\site-packages\django\core\management\commands\makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "database-1.cf9dt6lrnclf.eu-north-1.rds.amazonaws.com" (172.31.42.207), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? warnings.warn() py manage.py makemigrations C:\Python311\Lib\site-packages\django\core\management\commands\makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "database-1.cf9dt6lrnclf.eu-north-1.rds.amazonaws.com" (172.31.42.207), port 5432 failed: Connection … -
Loop through dictionary of lists django
Working on porting over a personal project of mine from flask to django, an issue I've been struggling with for a bit now is not being able to directly call index. Below is the code from my flask: {% for item in time_period %} <div class="col-lg-3 col-sm-4"> <div class="card h-100 border border-dark rounded"> <img class="card-image" src={{temp_icon[loop.index0]}}> </img> <div class="card-body"> <h2>{{item}}, {{temperature[loop.index0]}} F</h2> <p class="card-text">{{forecast[loop.index0]}}</p> </div> </div> </div> {% endfor %} In Django views, I have created this as. The weather.py module returns each variable as a list. def forecast(request): # Utilize weather.py to grab the forecast for the next three time periods as defined by NWS time_period, temperature, forecast, temp_icon = weather() context = {} context = {'time_period': time_period, 'temperature': temperature, 'forecast': forecast, 'temp_icon': temp_icon} print(context) return render(request, "forecast.html", context) sample data looks like 'time_period': ['This Afternoon', 'Tonight', 'Friday', 'Friday Night'], 'temperature': [88, 70, 95, 72], 'forecast': ['Partly Sunny', 'Slight Chance Showers And Thunderstorms', 'Chance Showers And Thunderstorms', 'Chance Showers And Thunderstorms'], 'temp_icon': ['https://api.weather.gov/icons/land/day/bkn?size=medium', 'https://api.weather.gov/icons/land/night/tsra_hi,20?size=medium', 'https://api.weather.gov/icons/land/day/rain_showers,20/tsra_hi,40?size=medium', 'https://api.weather.gov/icons/land/night/tsra_hi,30?size=medium'] Currently in my template I have been having a hard time looping through each list in parallel. My view shows the time_period piece correctly but unfortunately I have been unable to utilize the … -
Can Django be 100 times faster than Laravel?
Can Django be 100 times faster than Laravel (1 ms vs 100 ms) in performing REST CRUD operations? Same database, etc. Default settings as provided when starting the framework. Run on localhost, no docker. I tried turning off middleware and whatnot. -
django sqlmigrate stuck in a buggy migration
I have a small model for restaurants where I added an item_image attribute that receives url string. But instead of CharField I defined it as IntegerField . Then I ran python manage.py makemigrations food and python manage.py sqlmigrate food 0002 . I gave an error ValueError: Field 'item_image' expected a number but got 'https://cdn-icons-png.flaticon.com/512/1377/1377194.png'. I noticed the typo and fixed it( changed IntegerField to CharField). from django.db import models # Create your models here. class Item(models.Model): def __str__(self) -> str: return self.item_name item_name = models.CharField(max_length=200) item_desc = models.CharField(max_length=200) item_price = models.IntegerField() item_image = models.CharField(max_length=500, default='https://cdn-icons-png.flaticon.com/512/1377/1377194.png') but after I ran python manage.py sqlmigrate food 0002 the error is still there and when I change it to python manage.py sqlmigrate food 0003 and then run it. it gives no error but now for changes to take place I have to run python manage.py migrate which still gives the error on migration no.0002 How can I ignore this migration? -
could not be created because the data didn't validate
I'm trying to use a ModelForm to create and save an object to my database, but I keep getting a ValueError telling me my data isn't validated once I submit the POST data. when I fill date from form I get a error, "could not be created because the data didn't validate" This is in models.py class BookPublishedOrder(models.Model): author_name = models.CharField( max_length=100, verbose_name="Author Name") author_summary = models.TextField( max_length=100, verbose_name="Author summary") book_title = models.CharField( max_length=100, verbose_name="Book Title") book_subtitle = models.CharField( max_length=100, verbose_name="Book Sub Title", blank=True) book_category = models.CharField(max_length=100, verbose_name="Book Category", blank=True) book_summary = models.TextField( max_length=100, verbose_name="Book summary") book_picture = models.ImageField( upload_to='Book Published Order', verbose_name="Book Picture", blank=True) email_address = models.CharField( max_length=100, verbose_name="Email Address") phone_number = models.CharField( max_length=100, verbose_name="Phone Number") facebook_account = models.CharField( _("Facebook Account"), max_length=200, blank=True) instgram_account = models.CharField( _("Instgram Account"), max_length=200, blank=True) twitter_account = models.CharField( _("Twitter Account"), max_length=200, blank=True) book_PDF = models.FileField( upload_to="Book PDF", verbose_name="Book PDF") class Meta: verbose_name = 'كتاب مطلوب للنشر' verbose_name_plural = 'الكتب المطلوبة للنشر' This is in forms.py class BookPublishedOrderForm(forms.ModelForm): author_name = forms.CharField( max_length=100, label="إسم الكاتب") author_summary = forms.CharField(label="ملخص عن الكاتب") book_title = forms.CharField( max_length=100, label="عنوان الكتاب") book_subtitle = forms.CharField( max_length=100, label="عنوان الفرعي للكتاب", required=False) book_category = forms.CharField( max_length=100, label="نوع الكتاب", help_text="100 characters max.", required=False) book_summary = …