Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Generate random time in a within a specific day and insert multiple rows to database
I have a schedule for user in which it will generate randomly. For example I want to create and schedule for tomorrow, the admin will choose a day and N number of report a day. So the no_of_route is the # of rows to insert in database and also the # of generated hours and the # of route it will select from RoutePoints class. So, I really don't know to to generate hours. And this is where it should be. no_of_route = request.POST.get('no_of_route') date = request.POST.get('date') # generate hours, if no_of_route is 3, it would be 9AM, 1PM, 5PM hour = ... This is how I select random route id. items = list(RoutePoints.objects.all()) random_route = random.sample(items, no_of_route)[0] And this where I create multiple of rows. I'm not really sure how to do it. Schedule.objects.bulk_create(route=items.id, time=hour, date=date) Hope someone see this. Thank you in advance! -
Hosting a Django application on azure app service
After following the official host python with postgres tutorial, and making modifications in my gh actions file because my django apps isn't present in the root on the repo, I get a 404 error when trying to access it. Here is my settings.py """ Django settings for server project. Generated by 'django-admin startproject' using Django 5.0.3. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from decouple import config from os import environ from google.oauth2 import service_account from pathlib import Path from django.conf import global_settings # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config( "SECRET_KEY", default="django-insecure-g8khpcexyyb0q@p40^d5#r_j#ezf%(-90r-y^2@x1)2$wpch9+", ) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config("DEBUG", default=False, cast=bool) ALLOWED_HOSTS = ( [environ["WEBSITE_HOSTNAME"]] if "WEBSITE_HOSTNAME" in environ else config( "ALLOWED_HOSTS", cast=lambda v: [s.strip() for s in v.split(",")], default=[] ) ) CORS_ALLOWED_ORIGINS = config( "CORS_ALLOWED_ORIGINS", cast=lambda v: [s.strip() for s in v.split(",")], default="http://localhost:5173,http://127.0.0.1:5173", ) # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", … -
Invalid block tag on line ...: 'endblock', expected 'endwith'. Did you forget to register or load this tag?
I have a problem with my project on Python Here is a code, that located in Django template {% extends "base.html" %} {% load django_bootstrap5 %} {% block content %} <form method="post"> {% csrf_token %} {% bootstrap_form form %} {% bootstrap_button button_type="submit" content="Отправить" %} </form> **{% with data=request.POST %}** {% endblock %} When i reloading the page i receive an error on screenshot. error screen After the deleting this string, everything fine. {% with data=request.POST %} I dont understand what wrong ??? Iam trying to delete the string, that leads to an error, it helps, but according to the conditions of the task this string is must to be in this block of code -
How to Enable DEBUG Logging in Django?
I'm currently working on implementing logging in my Django project, but I'm encountering an issue where calls to logger.debug('log') do not output anything. I suspect there might be something wrong with my logging configuration. Below is the LOGGING configuration from my settings.py: logger = logging.getLogger(__name__) logger.debug(f"debug from logger") DJANGO_LOG_LEVEL = "DEBUG" LOGGING = { 'version': 1, 'disable_existing_loggers': False, "formatters": { "verbose": { "format": "{levelname}: {message} ({process:d}:{thread:d}::{filename}:{lineno}::{asctime})", "style": "{", 'datefmt': '%Y-%m-%d %H:%M:%S', }, "simple": { "format": "{levelname}: {message} ({filename}:{lineno})", "style": "{", }, }, 'handlers': { 'stdout': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple', }, "file": { "level": "INFO", "class": "logging.FileHandler", "formatter": "simple", "filename": logs_path.joinpath(f"{STAGE}-django.log").as_posix(), }, "mail_admins": { "level": "INFO", "class": "django.utils.log.AdminEmailHandler", "include_html": True, }, }, 'loggers': { '': { 'handlers': ['stdout', 'file'], 'level': 'DEBUG', 'propagate': True, }, 'django': { 'handlers': ['stdout', 'file'], 'level': 'WARNING', 'propagate': True, }, "django.request": { "handlers": ["mail_admins"], "level": "ERROR", "propagate": False, }, }, } Some can help me to figure out what's wrong with my logging configuration? -
DJANGO [WinError 10061] email features
I'm working in a Django project that uses the mail features. When try to send the mail I got this error message: [WinError 10061] No connection could be made because the target machine actively refused it. I'm using an email with godaddy domain. This is my configuration: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'mymail' EMAIL_HOST_PASSWORD = 'mypassword' I have tried all the related questions like: How to fix ConnectionRefusedError: [WinError 10061] the target machine actively refused it? (Django e.mails) I checked the firewall and none of the ports like 587, 25, 465, etc. were blocked. I also tried to connect with office365 server and didn't work. I don't know if this worth, but I have errors connecting with some pages for example when I run pip install library, gives an error related to SSL certification and only works if I bypass with --trusted-host. Maybe in this case I need to use something similar. -
Django - How to filter model objects by certain attribute and use it for front-end?
I am a beginner and building a website to showcase wines. This is the model for Wine: class Wine(models.Model): name = models.CharField(max_length=100) type = models.CharField(max_length=50) description = models.TextField() image = models.ImageField(upload_to='images/wines/') keywords = models.CharField(max_length=255, blank=True) def __str__(self): return self.name I added a page called "Advanced Search" which should initially show all the wines. I want to implement filtering functionality so when I select the corresponding checkboxes, the wines should be filtered by their keywords. Currently the keyword field accepts string as input. For example Wine1 has the following keywords: "red, plum, citrus". But the keywords field accepting string is not necessary (please suggest other approaches if needed). In my HTML file I added some checkboxes to test. The checkboxes correspond the keywords. So if I check the "plum" and "red" checkboxes, only the wines which contain those keywords should be shown. Here is the html part of the page: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false"> Filter </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="filterOptions"> <li><input class="form-check-input" type="checkbox" id="redCheckbox" value="red"><label class="form-check-label" for="redCheckbox">Red</label></li> <li><input class="form-check-input" type="checkbox" id="sparklingCheckbox" value="sparkling"><label class="form-check-label" for="sparklingCheckbox">Sparkling</label></li> <li><input class="form-check-input" type="checkbox" id="whiteCheckbox" value="white"><label class="form-check-label" for="whiteCheckbox">White</label></li> <li><input class="form-check-input" type="checkbox" id="sweetCheckbox" value="sweet"><label class="form-check-label" for="sweetCheckbox">Sweet</label></li> <li><input class="form-check-input" type="checkbox" id="dryCheckbox" value="dry"><label class="form-check-label" for="dryCheckbox">Dry</label></li> … -
i want some help to host my django Application on AWS LIGHT SAIL
I have tried hosting websites with sites like netlify but this time i want host my django application on AWS lightsail i need some help on how this can be archieved -
Running python manage.py commands tries to open a file in windows 10
As the title suggests, whenever i try to use python manage.py commands like runserver/ makemigrations, windows tries to open file for some reason any help is appreciated. -
Table does not exist with django
I'm facing an issue in my Django application when trying to delete a user through the REST API. I receive an internal server error with the message: Internal Server Error: /api/v1/user/30 Traceback (most recent call last): File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\mysql\base.py", line 75, in execute return self.cursor.execute(query, args) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\MySQLdb\connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb.ProgrammingError: (1146, "Table 'portobello.auth_user_groups' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\generics.py", line 291, in delete return self.destroy(request, *args, **kwargs) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\mixins.py", line 91, in destroy self.perform_destroy(instance) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\mixins.py", line 95, in perform_destroy instance.delete() File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", … -
Why are permissions not being overridden for a viewset?
I have created a viewset for authentication. Since this is the authentication viewset, I want this viewset to be accessible to unauthorized users as well. Following DRF documentation, this is what I have: class AuthenticationViewSet(viewsets.ViewSet): permission_classes = [AllowAny] def create_user(self, request: Request) -> Response: #code for creating a user Since I want the other viewsets to be accessible only to the authorized users, I set the following in settings.py: REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"], "DEFAULT_AUTHENTICATION_CLASSES": [ "authentication.token_auth.ExpiringTokenAuthentication" ] } When I make an API call to the create_user endpoint, I get an error saying: "No token found". Why is this happening? Shouldn't the permissions be overridden based on the permission_classes list in the viewset? For reference, my authentication class: class ExpiringTokenAuthentication(TokenAuthentication): def authenticate(self, request): if COOKIE_KEY in request.COOKIES: token_key = request.COOKIES[COOKIE_KEY] else: raise exceptions.AuthenticationFailed("No token found") try: token = Token.objects.get(key=token_key) except Token.DoesNotExist: return exceptions.AuthenticationFailed("Invalid token") if isTokenExpired(token): raise exceptions.AuthenticationFailed("Token has expired") user = token.user return (user, token) def isTokenExpired(token): currentTime = datetime.now(datetime.UTC) currentTimeUTC = currentTime.replace(tzinfo=pytz.UTC) return token.created < currentTimeUTC - timedelta(hours=TOKEN_EXPIRE_HOURS) -
django 'NoneType' object has no attribute 'userprofile' problem in related fileds
hi i have a django project and i have related database i can not reach for a two filed from database and the above mistake appear and this is models.py for app display class Display(models.Model) : url=models.URLField(unique=True) text = models.CharField(max_length=150) class Display_Data(models.Model) : displays = models.ManyToManyField(Display,related_name='display_data') users= models.ManyToManyField(User) choosenum=models.IntegerField() puplish_date =models.DateTimeField(default=datetime.now) and this is models.py for app account class UserProfile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) user_nickname=models.CharField(max_length=150) userphoto =models.ImageField(upload_to='imageprofile/%Y/%m/%d/') class UserUrl(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) url=models.URLField(default="https://www.facebook.com/profile.php? id=100068020764035") and this is views.py def check_url_exists_and_person(url_to_check): user_info_array = [] for i in range(1, 6): latest_successful_record = Display_Data.objects.filter(displays__url=url_to_check, choosenum=i).order_by('-puplish_date').first() if latest_successful_record: user_info = { 'user_nickname': latest_successful_record.users.first().userprofile.user_nickname, 'url': latest_successful_record.users.first().userurl.url } else: user_info = None user_info_array.append(user_info) return user_info_array -
Django 5.0: How to create an object without retrieving the Foreign object instance related to it?
Currently I have some Django models defined like this: Class Project(models.Model) data = ... Class Resource(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) In my views.py im trying to create a new Resource, having access to the Project id thanks to the URL: def create_resource(request, project_id): """ Create a resource for a given project """ new_resource = Resource.objects.create(project_id=proyecto_id) return render(request,"resource.html",{"new":new_resource}) Here I am trying to create the Resource without fetching the related Project (which seems more efficient to me given I don't need the project for anything). To do this i used the notation described in the docs project_id to get to the FK id. But it doesn't work, Django says the following when I try to render the page: ValueError at /create_resource/1 Cannot assign "1": "Resource.project" must be a "Project" instance. I've found similar questions online, and all of them use the foreignfield_id notation to do this, but in my case it doesn´t work. Granted, I've only found questions from 10-15 years ago, so did this change somewhere along the way? My Django version: 5.0.3 Related question posted 13 years ago: Post -
I am having problem in adding a product by the user for a online auction system that i am working on for my Final year project?
I am working on my final year project that is online auction system. I am having a problem in adding product for the auction by the logged in user, and also having the problem in profile updating and user deleting. Used Django react tailwind. Here is the all the code images of models, serializer, views, and other reacts that I have been doing. I can't put the code here because its so many so provided a link below: Here is the link of my GitHub of this project as well -
how do i solve this challange in django?
[18/Apr/2024 19:33:24] code 400, message Bad request version ('¼%-¼Iµ\x19\x87)Û\x81AWf;eÓÒNøíýg§\') [18/Apr/2024 19:33:24] You're accessing the development server over HTTPS, but it only supports HTTP. i changed the http setting from true to false but it insisted -
how to solve ModuleNotFoundError error in django code
I am developing a webtool using django. I have already installed and activated the virtual environment. I am getting the following error which seems to be very easy to fix: from .views import ( File "/home/example/views.py", line 8, in <module> from subscriptions.models import Subscription ModuleNotFoundError: No module named 'subscriptions' and tried to install the package using the following command: pip install subscription and imported using the following command: from subscriptions.models import Subscription but still getting the same error. how can I fix the issue? -
Django creating wrong SQL query for datetime
I'm trying to filter some objects from my model in Django but I noticed it returns incorrect information so I printed out the SQL query and as you can see the times are not right. This is my code: url_start_date = request.GET.get('start_date') url_end_date = request.GET.get('end_date') start_date = make_aware(datetime.strptime(url_start_date, '%Y-%m-%dT%H:%M')) end_date = make_aware(datetime.strptime(url_end_date, '%Y-%m-%dT%H:%M')) queryset = MyModel.objects.filter(date__range=(start_date, end_date)).order_by('guard', 'asset') print(url_start_date, url_end_date) print(start_date, end_date) print(queryset.query) The output is the following: 2024-04-18T13:00 2024-04-18T23:59 2024-04-18 13:00:00-04:00 2024-04-18 23:59:00-04:00 SELECT ... FROM ... WHERE `date` BETWEEN 2024-04-18 17:00:00 AND 2024-04-19 03:59:00 ... What should I do to fix it? -
Django TemplateDoesNotExist at /accounts/login/ Did not find form with a "login" button
I'm taking the "Django for Everybody Specialization" course at Coursera. I got a error in "Django Features and Library" Auto-grader: Autos CRUD: "Loading URL: http://gulnissa03.pythonanywhere.com/autos (Open URL) It appears that there is a Django error on this page TemplateDoesNotExist at /accounts/login/ 164946 characters of HTML retrieved Page may have errors, HTTP status=500 Did not find form with a "login" button Form with login button not found " I don't have a file settings.py Can you help me, this is really important for me to finish courses and no one to ask for help. I did everything on the video tutorial and I have everything right, I don't know how else to solve this problemtext -
Comment utiliser efficacement les templates dans Django pour une gestion claire et modulaire des pages?
i want to link my backend with python-django with Html files , there is any one can give me his code or example or give me any idea to do this and thank you i want to link my backend with the html files , templates in django -
How can I schedule the deletion of user_club?
I'm trying to implement the following logic: When the user clicks to delete a user_club, a prompt will appear allowing the user to undo this request. If they don't take any action within 5 seconds, we'll proceed with the deletion. Alternatively, if the user performs an undo action, I'll cancel the deletion request in the database. I'm trying to implement using PeriodicTask. However, I haven't been able to complete it yet. Please help me solve the issue I'm facing. Thank you in advance. This is what I've been trying to accomplish, but it hasn't been successful yet. models.py class UserClub(ItemBase): user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user_club') club = models.ForeignKey(Club, on_delete=models.CASCADE) roles = models.ManyToManyField(Role) membership_id = models.CharField(max_length=255, blank=True, null=True) membership_expiry_date = models.DateField(max_length=255, blank=True, null=True) subscription = models.ForeignKey(to=Subscription, on_delete=models.SET_NULL, blank=True, null=True, related_name='user_club_subscription') default = models.BooleanField(default=False) reputation_point = models.PositiveIntegerField(default=0) class Meta: db_table = "sport_user_club" verbose_name = 'User Club' verbose_name_plural = 'User Club' views.py def destroy(self, request, *args, **kwargs): user_club = self.get_object() task = task_schedule_del_user_club.apply_async(args=[user_club.uuid], countdown=10) self.response_format['data'] = { "task_id": task.id } self.response_format['message'] = "Club will be deleted after 5 seconds" return JsonResponse(data=self.response_format, status=status.HTTP_200_OK) @swagger_auto_schema(methods=['post'], request_body=UndoDeleteClubProcessSerializer) @action(methods=['post'], detail=False, url_path="undo-request", url_name='undo-request') def undo_request_remove_club(self, request, *args, **kwargs): serializer = UndoDeleteClubProcessSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer_data = serializer.validated_data if serializer_data['is_undo_request']: try: … -
Why does evaluating enviroment variable in setting.py does not work?
I set an environment variable here ~/.bashrc by adding export DJANGO_DEVELOPMENT='True' the committing the changes with source ~/.bashrc Then I checked if the value was correctly wrote with echo $DJANGO_DEVELOPMENT -->RESULT: true Now I'm simply triyng to accede this variabile during the server launch, so Django can figure out I'm in development and override the settings.py file with a settings_dev.py file. The code doing this in setting.py is: import os if os.getenv('DJANGO_DEVELOPMENT') == 'true': from .settings_dev import * The problem is that the server is always executed with DEBUG = False so I know as a fact that python is not reading properly the env. variable. I also double checked by putting a print(os.getenv('DJANGO_DEVELOPMENT')) but it's always None. Someone have any idea where my error is? Thanks in advantage. -
Cannot display as a guest user in ecommerce site in Python+Django
I was following a YouTube tutorial of Dennis Ivy,(https://www.youtube.com/playlist?list=PL-51WBLyFTg0omnamUjL1TCVov7yDTRng), where number of items in "cart-icon" and total amount information is rendered. Image of how it should be: correct_rendering Image of how it is: error_rendering In my case, those are not rendered. I am not sure what went wrong. I tried to search the issue in chatGpt, but couldn't solve the problem. Below is my code: views.py from django.shortcuts import render from django.http import JsonResponse import json from .models import * import datetime def store(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items # Corrected: Call the method to get cart items else: items = [] order = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': False} cartItems = order['get_cart_items'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() # total = sum(item.product.price * item.quantity for item in items) cartItems = order.get_cart_items # Corrected: Call the method to get cart items else: try: cart = json.loads(request.COOKIES['cart']) # Use .get() to avoid KeyError # cart = json.loads(request.COOKIES.get('cart', '{}')) # Use .get() to avoid KeyError except : # json.JSONDecodeError: … -
When run the be --version give me error of the ModuleNotFoundError: No module named 'imp'
Full error: Traceback (most recent call last): File "", line 198, in _run_module_as_main File "", line 88, in run_code File "C:\Users\arsalan\AppData\Local\Programs\Python\Python312\Scripts\eb.exe_main.py", line 4, in File "C:\Users\arsalan\AppData\Local\Programs\Python\Python312\Lib\site-packages\ebcli\core\ebcore.py", line 16, in from cement.core import foundation, handler, hook File "C:\Users\arsalan\AppData\Local\Programs\Python\Python312\Lib\site-packages\cement\core\foundation.py", line 11, in from ..core import output, extension, arg, controller, meta, cache, mail File "C:\Users\arsalan\AppData\Local\Programs\Python\Python312\Lib\site-packages\cement\core\extension.py", line 8, in from imp import reload # pragma: no cover ^^^^^^^^^^^^^^^^^^^^^^ ModuleNotFoundError: No module named 'imp' I try a lot and even uninstall and reinstall the package it doesn't work. -
Django UserViewSet not setting username and slug despite email being provided
I have a Django UserViewSet where I'm trying to create a new user along with an associated API key. However, despite providing the email, the username is always None, and the slug field is not being created. Additionally, the APIKey object is not being created. Here's my code: class UserViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = User.objects.all() serializer_class = UserSerializer def post(self, request): serializer = self.get_serializer(data=request.data) user = self.get_object() if serializer.is_valid(raise_exception=True): timezone.activate("UTC") api_key = create_hex_key(20) api_key_expiry_date = timezone.now() + timedelta( days=365242, milliseconds=0 ) user.email = user.email.lower() user.username = user.email.lower() if user.email else None user.first_name = user.first_name.lower() if user.first_name else None user.last_name = user.last_name.lower() if user.last_name else None if user.first_name and user.last_name: random_string = generate_random_string() slug = slugify(f"{user.first_name} {user.last_name} {random_string}") while User.objects.filter(slug=slug).exists(): random_string = generate_random_string() slug = slugify( f"{user.first_name} {user.last_name} {random_string}" ) user.slug = slug user.set_password(serializer.validated["password"]) APIKey.objects.create( user=user, name="Default Key", api_key=api_key, expiry_date=api_key_expiry_date.isoformat(), ) user.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And here's my serializer: class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField(validators=[]) password = serializers.CharField(validators=[]) class Meta: model = User fields = ["email", "first_name", "last_name", "password"] Despite providing the email in the request data, the username remains None, and the slug is not being created. Additionally, the APIKey object is not being created. What … -
Django Form Error "This field is required." only when trying to retrieve random objects
I get the form error "This field is required." only when trying to retrieve random objects like this: pks = list(QuizQuestion.objects.values_list('pk', flat=True)) random_pks = random.sample(pks, 2) questions = QuizQuestion.objects.filter(pk__in=random_pks) When I am using: questions = QuizQuestion.objects.all() everything works fine. This is the QuizForm: class QuizForm(forms.Form): """QuizForm used to display questions with their options.""" def __init__(self, *args, **kwargs): questions = kwargs.pop('questions') super(QuizForm, self).__init__(*args, **kwargs) for question in questions: choices = [ ('option1', question.option1), ('option2', question.option2), ('option3', question.option3), ('option4', question.option4), ] self.fields[str(question.id)] = forms.ChoiceField( label=question.question_text, choices=choices, widget=forms.RadioSelect(attrs={'class': 'form-check-input'}) ) And this is the html form: <form method="post"> {% csrf_token %} {% for field in form %} <div> <label class="question">{{ field.label }}</label> {% if field.errors %} <ul class="errors"> {% for error in field.errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} <div> {% for choice in field %} <label class="form-check-inline"> {{ choice }} </label> {% endfor %} </div> </div> {% endfor %} <button type="submit">Submit</button> </form> I also tried other methods for getting the random objects from here: Django get a random object and https://books.agiliq.com/projects/django-orm-cookbook/en/latest/random.html. I think the problem is within the QuizForm but i cannot figure out where. -
Is it worth studying django in 2024
I am a novice web developer and recently finished learning python, now I want to move on and try to make the first real project with a working backend. After reading about different frameworks, I liked Django. But recently, one of my friends told me that django is a big Clumsy machine, and if I really want to do backend, then it's better to study node.js or the same flask. I have not found any information from professionals on the Internet. And I decided to ask here, is django really so slow and outdated, and is it worth starting to study it now if I want to be competitive in the market? Tried to learn Django. Expecting good workplace.