Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured" Error in my site
The error: (venv) gamedeveloper@animechatapp:~$ sudo journalctl -u gunicorn -n 50 [sudo] password for gamedeveloper: Sep 30 13:10:33 animechatapp gunicorn[510664]: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not co> Sep 30 13:10:33 animechatapp gunicorn[510664]: [2023-09-30 13:10:33 +0000] [510664] [INFO] Worker exiting (pid: 510664) Sep 30 13:10:33 animechatapp systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Sep 30 13:10:33 animechatapp systemd[1]: gunicorn.service: Failed with result 'exit-code'. Sep 30 13:19:35 animechatapp systemd[1]: Started gunicorn.service - gunicorn daemon. Sep 30 13:19:35 animechatapp gunicorn[510824]: [2023-09-30 13:19:35 +0000] [510824] [INFO] Starting gunicorn 21.2.0 Sep 30 13:19:35 animechatapp gunicorn[510824]: [2023-09-30 13:19:35 +0000] [510824] [INFO] Listening at: unix:/run/gunicorn.sock (510824) Sep 30 13:19:35 animechatapp gunicorn[510824]: [2023-09-30 13:19:35 +0000] [510824] [INFO] Using worker: sync Sep 30 13:19:35 animechatapp gunicorn[510825]: [2023-09-30 13:19:35 +0000] [510825] [INFO] Booting worker with pid: 510825 Sep 30 13:19:35 animechatapp gunicorn[510826]: [2023-09-30 13:19:35 +0000] [510826] [INFO] Booting worker with pid: 510826 Sep 30 13:19:35 animechatapp gunicorn[510827]: [2023-09-30 13:19:35 +0000] [510827] [INFO] Booting worker with pid: 510827 Sep 30 13:19:40 animechatapp gunicorn[510827]: - - [30/Sep/2023:13:19:40 +0000] "POST /update_active_status/ HTTP/1.0" 200 21 "http://194.195.119.23> Sep 30 13:19:43 animechatapp gunicorn[510826]: - - [30/Sep/2023:13:19:43 +0000] "POST /update_active_status/ HTTP/1.0" 200 21 "http://194.195.119.23> Sep 30 13:20:01 animechatapp gunicorn[510826]: - - [30/Sep/2023:13:20:01 +0000] "POST /update_active_status/ HTTP/1.0" … -
How save the result from task in database using django_celery_results?
I am beginner with Celery, and i need to save the result of the task in the database here is tasks.py: from __future__ import absolute_import, unicode_literals from celery import shared_task import hashlib from project.celery import app from .models import Puzzle @shared_task(ignore_result=False) def solve_puzzle(data, level): # try to find a nounce value that makes the SHA-1 hash of the data and the nounce start with a certain number of zeros solution = "" nounce = 0 while not solution.startswith("".join(["0" for _ in range(level)])): solution = hashlib.sha1(f"{data}{(nounce)}".encode()).hexdigest() nounce += 1 return nounce, solution the celery.py: import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project', broker='redis://localhost', backend='db+sqlite:///results.sqlite') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.retry = 360 app.conf.timeout = 300 # Load task modules from all registered Django apps. app.autodiscover_tasks() settings.py: CELERY_RESULT_BACKEND = 'django-db' I run celery using the command: celery -A project worker -l INFO then got : `[2023-09-30 19:29:13,461: INFO/MainProcess] Task puzzle.tasks.solve_puzzle[e1960235-801d-4bc4-8f5d-e7fb923830ba] received [2023-09-30 19:29:15,909: INFO/SpawnPoolWorker-21] child process 624 calling … -
Can we implement Airflow in a Django project for scheduling tasks?
I'm working on a Django rest project to create different API endpoints. I want to implement airflow that reads a text file and stores it in a Django Model daily. I have installed Apache airflow, created a DAG, and changed my dag location in the airflow.cfg file. But when I run the webserver and the scheduler I cannot see my dag in the DAG's list. Can somebody help me with the airflow django implementation? -
is this erroro comming due to problem in server or code error
where i made mistake in django code code error for loop and if else in django html code <!doctype html> <style> table, th, td{ border:1px solid black; padding-right: 2px; } </style> <title>divyanshu jha</title> </head> <body> <h1>this is heading 1</h1> <h2>{{title}}</h2> {%for n in a%} <div>{{forloop.counter}}{{n}}</div> {% endfor %} <table> <tr> <th>phone no</th> <th>name</th> <th>age</th> </tr> {% for i in user_detail%} <tr> <td style="width:400px">{{i.phone}}</td> <td>{{i.name}}</td> <td>{{i.age}}</td> </tr> {% endfor %} </table> {% if dj|length > 0 % } {% for ch in dj %} {% if ch > 12 %} <div>{{ch}}</div> {% endif %} {% endfor %} { % else %} no data found {% endif %} </body> django code from django.http import HttpResponse from django.shortcuts import render def aboutus(request): return HttpResponse("hello") def difficult(request,userid): return HttpResponse(userid) def homepage(request): x={ "title":"divyanshu jha", "a":['mumbai','dj','hello','meow'], "dj":[10,11,12,15,16,17,18,19], "user_detail":[ {'name':'divyanshu jha','phone':7977879695, 'age':16}, {'name':'dipti jha','phone':7977879695, 'age':40}, {'name':'ajun jha','phone':9322864840, 'age': 47,},] } return render(request,"index.html",x) -
Django and chroma with docker-compose error: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url
I am trying to build a REST api with django and chromadb, I built two containers: django for RESTApi, chroma for vector database. Two containers are running successfully, as shown: enter image description here Here is my docker-compose file: enter image description here Here is my Dockerfile: enter image description here I'm trying to establish the connection with chromadb from django, here is my code: enter image description here It gives me the error: enter image description here I did some research, it shows that this is the problem of port or host, but I do not have a clue how to fix it. I hope to get the help from the kind people in this community to fix it. -
use up.render to rerender a section in django using unpoly and alpinejs
I am building an ecommerce website using Django with Alpine and Unpoly, In home page i got a list of products so its making a lot of queries which means it takes time, long story short, I got a functionality for adding product to wishlist and removing it from wishlist, for the a tag that added/removed a product to/from wishlist I added up-follow to not refreshing the page. It works, but the problem is that it rerender the whole page(without refresh) which means its making the same queries again when instead I want to only rerender the AddToWishlist/RemoveFromWishlist part so the site wont be slow, this is how it looks: This is the code that renders the a tags: {% is_product_in_wishlist request product as is_in_wishlist %} {% if is_in_wishlist %} <a href="{% url 'products:remove-from-wishlist' product_id=product.id %}" id="id__{{product.id}}" class="absolute top-0 right-0 inline-block text-black transform duartion-200 rounded-full bg-white m-1 p-1 two" up-follow @click='removeFromWishlist'> <svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" fill="currentColor" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" aria-hidden="true" class=""><path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path></svg> </a> {% else %} <a href="{% url 'products:add-to-wishlist' product_id=product.id %}" id="id__{{product.id}}" class="absolute top-0 right-0 inline-block text-black transform duartion-200 rounded-full … -
Django how to filter products by multiple fields
I have a db containa products(name, origin place, price, img...) and I want to filter them by place or price or both when i chose from form. My models: class ProductFilter(models.Model): place = models.CharField(max_length=50) price = models.CharField(max_length=50) def __str__(self): return self.name My forms: class ProductFilterForm(forms.Form): place = forms.ChoiceField(choices=place_choices, widget=forms.Select()) price = forms.ChoiceField(choices=price_choices, widget=forms.Select()) class Meta: model = ProductFilter fields = ('place', 'price') with place_choices: place_choices = ( ("A","All"), ("C","Cellphones"), ("M","Media Mart"), ("N","Nguyễn Kim") ) price_choices: price_choices = ( ("", "All"), ("A", "Giá thấp > cao"), ("B", "Giá cao > thấp") ) My views right now: def show_db(request): place = ProductPlaceForm() newForm = ProductNameForm() filterForm = ProductFilterForm() product_list = Product.objects.all() ft_place = request.POST.get('place', None) ft_price = request.POST.get('price', None) print(ft_place) print(ft_price) return render(request, 'product_list.html', {'product_list' : product_list, 'form':newForm, 'place':place, 'filterForm':filterForm}) My template: {% block content %} {{filterForm}} <ul class="d-flex flex-row flex-wrap align-content-center justify-content-around align-items-center list-unstyled"> {% for p in product_list %} <li> <div class="card h-100 mt-2 border-dark mb-3" style="max-width: 18rem;"> <img src="{{p.img}}" class="card-img-top" style="height:17.813em;width:auto;" alt="product image"> <div class="card-body"> <h5 class="card-title">{{p.name}}</h5> <p class="card-text">{{p.current_price}}</p> <p class="card-text">Store: {{p.place}}</p> <p class="card-text">Add at {{p.date_add}}</p> <a href="{{p.url}}" target="_blank" class="btn btn-primary">Go to store</a> </div> </div> </li> {% endfor %} </ul> {% endblock %} I believe i have to redirect … -
Django : django.db.utils.OperationalError: no such table: Blog_username
django.db.utils.OperationalError: no such table: Blog_username i got this error,I have designed my model already and I wanted to add a new table to the model called username in my models.py using SQLite in my Django application called Blog. And after adding it to my model I then use the following command to add it to my database: python manage.py makemigrations python manage.py migrate And I didn't get any error while running this command. But later when i wanted to query the data in my database using the following command: python manage.py shell from Blog.models import Person Note: Person is the name of the class in my database Person.objects.all() After running the last command I then got an error saying django.db.utils.OperationalError: no such table: Blog_username and I have already makemigrations and also migrate and I got the error. Please I would really appreciate it if anyone could help me with this error and it really bothering me -
Saving Django form displayed on template like {{form.item}}
Django beginner here. I'm trying to understand something : In my template if I'm rendering my form like this {{form}} and click my button <button name="button" type="submit" onclick="">Save Form</button> The form is correctly saving. But if I change the way I'm displaying my form like : {{form.item1}} {{form.item2}} {{form.item3}} to be more flexible on my template, it doesn't save anymore. Is there a way to achieve this ? -
Changing color of a ul class wrapped within a specific hiearchy
<div class="one"> <nav id="sidebar" class="col-md-auto col-lg-2 d-md-inlineblock fontsize-5rem text-white sidebar"> <div class="position-sticky"> <ul class="nav flex-column"> <li class="nav-item"> <a href="{% url 'dashboard:dashboard' %}" class="nav-link active">Dashboard</a> </li> I am trying to figure out how to customize the background of wrapped within a specific hierarchy. I want to specifically change the color of nav-link active class here. How do I go about it? Is there any issue with any declaration here and the way it is framed? I confess that I do not know much about html except what I have gathered from Dash module in python. If possible, please also suggest me a way to go around managing the page structure of Django Dash wherein how do I configure the page setup if I am uploading Django dash set up directly in html template? Thank you! Color does not change. If other items on vertical tabs get selected, they change color but not the main first tab. -
Building Django app with Database server failure
I have Django app that is running on docker on serve and a database that running on another machine .My app has some API that doesn't need data base just call another service, So I want to be able to build my app even on database failure and it failure don't make my app exit. and users be able to use independent database API's. I try to catch connection failure by using try catch block in Django setting but it didn't work, Is it possible to do what I need? -
Django select_related() and prefetch_related() don't solve N+1 problem with nested objects
I'm trying to solve N+1 problem right now. I'm aware of select_related() and prefetch_related() methods but unfortunately the query I'm requesting to DB still not efficient enough. I have Comment model which has ForeignKey/M2M relations. class Comment(models.Model): profile = models.ForeignKey(Profile, related_name="comments", on_delete=CASCADE) post = models.ForeignKey(Post, related_name="comments", on_delete=CASCADE) parent = models.ForeignKey("self", related_name="children", blank=True, null=True, on_delete=models.CASCADE) reply_to = models.ForeignKey("self", related_name="replies", blank=True, null=True, on_delete=models.CASCADE) text = models.TextField(max_length=350) liked_by = models.ManyToManyField(Profile, related_name="comment_likes", blank=True) Comments system has just two-level layout (root comment and replies). But whenever I perform a query : comments = ( Comment.objects.filter(parent=None) .select_related("profile__specialization", "post", "parent", "reply_to") .prefetch_related("liked_by") .annotate(likes_count=Count("liked_by", distinct=True)) .order_by("-date_published") ) I'm still getting over 50 queries against DB to fetch profiles, posts etc. Even I remove select_related() and prefetch_related() at all I still get just 4-5 queries more. Serializers I use are just normal model.Serializer (requirements of a project pattern): class CommentDTOSerializer(serializers.Serializer): id = serializers.IntegerField(required=False, read_only=True) profile = ProfileBaseDTOSerializer(read_only=True) post = PostBaseDTOSerializer(read_only=True) parent = BaseCommentDTOSerializer(read_only=True) reply_to = BaseCommentDTOSerializer(read_only=True) children = BaseCommentDTOSerializer(many=True, read_only=True) text = serializers.CharField(read_only=True) liked_by = ProfileBaseDTOSerializer(many=True, read_only=True) likes_count = serializers.IntegerField(read_only=True) I can't get what is wrong with my prefetching and why all the nested models (profile, post, parent, reply_to) are not prefetched correctly and still require DB to perform … -
Why can i remove user from many to many relation in django
I am unable to remove current user from a many to many relation in django class User(AbstractUser): pass class Post(models.Model): content=models.CharField(max_length=1000) owner=models.ForeignKey(User,on_delete=models.CASCADE) liked_by=models.ManyToManyField(User,symmetrical=False,related_name="liked_by",blank=True) Given above are my models def like(request,id): x=Post.objects.get(id=id) x.liked_by.add(request.user) x.save() return JsonResponse({"status":"successfully liked"}) def unlike(request,id): if request.method=="GET": x=Post.objects.get(id=id) x.liked_by.remove(request.user) x.save() return JsonResponse({"status":"successfully unliked"}) the above functions are used to like and unlike a post . I am able like ie add a user to the many to many relation but unable to remove {% extends "network/layout.html" %} {% block body %} {%for post in posts%} <div>{{post.content}} <button class="like" value="{{post.id}}">{%if request.user in post.liked_by.all%}unlike{%else%}like{%endif%}</button> </div> {%endfor%} <script> let like=document.querySelectorAll('.like') like.forEach(Element=>{ Element.addEventListener('click',(event)=>{ const clickedbutton=event.target if(clickedbutton.innerHTML==='like'){ fetch('like/'+clickedbutton.value) clickedbutton.innerHTML='unlike' } else if(clickedbutton.innerHTML==='unlike'){ fetch('unlike/'+clickedbutton.value) clickedbutton.innerHTML='like' } }) }) </script> {% endblock %} this is html i tried . my objective is to remove current user for many to many relation on clicking unlike -
Django Signals File
How does django know where exactly to look for Signal functions? like which .py file to search for receiver functions? Does it search for every single file and execute the function if found? Tried reading docs but didnt help much, Please help me out here. Django signals -
Unable to test websockets by using django channels
I'm trying to test my websockets but i'm getting '404 not found error' I have no idea why im getting error..i checked my code many times but still no use. Please have a look. This is my settings.py INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' ] ASGI_APPLICATION = 'routing_pro.asgi.application' and this is my consumers.py from channels.consumer import SyncConsumer,AsyncConsumer class MySyncConsumer(SyncConsumer): def websocket_connect(self,event): print('Websocket connected...',event) def websocket_receive(self,event): print('Websocket Recived...',event) def websocket_disconnect(self,event): print('Websocket disconnected...',event) class MyASyncConsumer(AsyncConsumer): def websocket_connect(self,event): print('Websocket connected',event) def websocket_receive(self,event): print('Websocket Recived',event) def websocket_disconnect(self,event): print('Websocket disconnected',event) and this is my asgi.py file: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter import myapp.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'routing_pro.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': URLRouter( myapp.routing.websocket_urlpatterns. myapp.routing.websocket_urlpatterns ) }) and this is my routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/sc/',consumers.MySyncConsumer.as_asgi()), path('ws/ac/',consumers.MyASyncConsumer.as_asgi()), ] This is the error im getting : Could not connect to ws://127.0.0.1:8000/ws/sc/ 15:12:33 Error: Unexpected server response: 404 Handshake Details Request URL: http://127.0.0.1:8000/ws/sc/ Request Method: GET Status Code: 404 Not Found Request Headers Sec-WebSocket-Version: 13 Sec-WebSocket-Key: xO8WLEzNls1BeFdnyPJlbw== Connection: Upgrade Upgrade: websocket Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits Host: 127.0.0.1:8000 Response Headers Date: Sat, 30 Sep 2023 09:42:33 GMT Server: WSGIServer/0.2 CPython/3.10.11 Content-Type: … -
Trying to get the latest entry of a Django model
So I am trying to make a webpage that on the first page puts the three latest recipes that have been added. I know how to loop through all of the recipes, but I am having trouble finding out how to call only the latest, second-latest, and third-latest recipes. Here is my models: class Recipe(models.Model): """A recipe the user is learning about.""" text = models.CharField(max_length=200, blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True, blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): """Return a string representation of the model.""" return self.text Here is my view @login_required def recipes(request): """Show all recipes""" recipes = Recipe.objects.filter(owner=request.user).order_by("-date_added") context = {"recipes": recipes} return render(request, "recipe_book/recipes.xhtml", context) @login_required def recipe(request, recipe_id): """Show a single recipe and all its entries""" recipe = Recipe.objects.get(id=recipe_id) # Make sure the recipe belongs to the current user if recipe.owner != request.user: raise Http404 # Show all entries for this recipe ingredients = recipe.ingredient_set.order_by("-time_added") context = { "recipe": recipe, "ingredients": ingredients, } return render(request, "recipe_book/recipe.xhtml", context) My url app_name = "recipe_book" ... # Page that shows all recipes path("recipes/", views.recipes, name="recipes"), # Detail page for a single recipe path("recipes/<int:recipe_id>/", views.recipe, name="recipe"), My index I am trying to make buttons that link to those … -
Use phone number / sms token instead of username password in django
I'm new to django and I'm developing a website with django, but I want to have a custom flow for register/login instead of django's default, as described below: When a user want to login/register redirects to a form that only have one field "phone number" and a submit button in the next page if the phone is belongs to a registered user, user receive a token via SMS and enter it to complete login. and if the phone isn't found, redirects to a form to receive user's information such as first/last name and SMS token to complete registering user. I know I need custom forms and custom user model, but I don't know how to implement this. Do I need to subclass my custom user model from django's AbstractUser or AbstractBaseUser? Do I need to use any plugin? Should I write a custom authentication backend? what should I do, if i want to differ between staffs and customers. So staff should login with username/password and customers use system described. I browsed some topics and tutorial about django user system and official document of django, but I feel confused and can't find my way. -
Djanog statics are not loading
I'm trying to run my Django project on localhost server (with runserver command) but my css files are not loading with the error : Refused to apply style from 'http://127.0.0.1:8000/statics/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. I've setup STATIC_URL = 'static/' STATIC_ROOT= BASE_DIR / 'static' MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media' STATICFILES_DIRS = [ BASE_DIR / "statics/css/", ] in settings.py file and put my css files in BASE_DIR / statics/css/ but still I've got the error I also added these setting to the url pattern in urls.py file: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
i want to send mail to forget password in django
my views.py def ForgetPassword(request): try: if request.method=="POST": username=request.POST.get('username') if not User.objects.filter(username=username).first(): messages.success(request,'not user found with this username') return redirect('forget-password/') user_obj=User.objects.get(username=username) token=str(uuid.uuid4()) send_forget_password_mail(user_obj,token) messages.success(request,'An email is sent') return redirect('/forget-password/') except Exception as e: print(e) return render(request,'forget-password.html') helpers.py def send_forget_password_mail(email, token): subject="your forget password link" message=f'hi, click on the link to rest your password http://127.0.0.1:8000/change-password/{token}/' email_from=settings.EMAIL_HOST_USER recipient_list=[email] send_mail(subject,message, email_from, recipient_list) return True i have created a function which will send mail if anyone click on forget password but email is not sending. -
Django Email doesn't render HTML tags
I am trying to make an email notification system using Django, but there's a problem. The body of the email doesn't render html tags, and instead the body display the html tag and the message in a long line instead. Even when the message contains \n, it doesn't create a new line but the \n is not visible in the body of the email This is my email template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{subject}}</title> </head> <body> {{body}} </body> </html> This is my code to send the email from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags from django.conf import settings class SendNotification: @staticmethod def by_email(instance): subject = instance.subject to = list(instance.receivers.values_list("to", flat=True)) html_content = render_to_string("email.html", {'subject': subject, "body": instance.message}) text_content = strip_tags(html_content) try: email = EmailMultiAlternatives( subject, text_content, settings.EMAIL_HOST_USER, to, ) email.attach_alternative(html_content, 'text/html') email.send() instance.counter += 1 instance.save() instance.receivers.all().update(status=True) any idea why the html tag is not rendered properly? -
Simple Example of Multiple ManyToMany Model Relations in Django
I'm writing a workout app and have a number of models that need to link together. Specifically, I have an Exercise model that needs to track the name of each exercise as well as the primary and secondary muscle groups targeted by the exercise. I also need a muscle group model, and these all need to link together in a ManyToMany fashion, e.g. any muscle group be associated with the primary and/or secondary or multiple exercises and vice versa. How do I write the code to define the classes, as well as write a script to populate the database and test how to access various fields? Answered below as hopefully a useful super intro tutorial for others since I couldn't find something so easily online. -
Is Django_daraja currently missing some classes ? I can't get it to work
I've already installed django_daraja via pip on the environment and it's still invisible, to the project. Even on the setting file, I've included it and it's still fairing of poorly. I added all the necessary applications It's still being seen as an unsolved reference. -
How can I enter the time at 24:00 in timeFiled
I am booking a stadium at a specific time And everything is correct But when I enter the from_hour or to_hour to time(24:00) it prompts an error the erorr is (Cannot use None as a query value) class OpeningHours(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) pitche = models.ForeignKey(Pitche,on_delete=models.DO_NOTHING) made_on = models.DateField() from_hour = models.TimeField() to_hour = models.TimeField() timing = models.CharField(max_length=50,choices=timing) def clean(self): if self.from_hour == self.to_hour: raise ValidationError('Wrong Time') if self.made_on < datetime.date.today(): raise ValidationError('InVaild Date') if ( OpeningHours.objects.exclude(pk=self.pk) .filter( made_on=self.made_on, pitche_id=self.pitche_id, to_hour__gt=self.from_hour, from_hour__lt=self.to_hour, ) .exists() ): raise ValidationError( f'The booked time ({self.from_hour} to {self.to_hour}) is occupied.' ) return super().clean() -
How to Implement Two-Factor Authentication (2FA) in a Django Web Application?
I'm working on a Django web application and want to enhance security by adding Two-Factor Authentication (2FA) for user logins. I've looked into various libraries and approaches, but I'm not sure which one is the most reliable and secure for my project. Can someone provide guidance on how to implement 2FA in a Django application? What libraries or methods are recommended for this purpose? Thanks! -
Uploading multiple images no longer working after updating from django 3 to 4
I have a Django project I recently updated to version 4.2 I am experiencing an issue where a ClearableFileInput i had that allowed a user to upload multiple images no longer works throwing the error ValueError: ClearableFileInput doesn't support uploading multiple files. I have looked at the updated documentation and it seems multiple has changed to allow_multiple_selected however when i use this like 'images': forms.ClearableFileInput(attrs={'allow_multiple_selected ': True}), I am only able to upload only a single image. form: class PostImagesForm(ModelForm): class Meta: model = PostImages fields = ('images',) widgets = { 'images': forms.ClearableFileInput(attrs={'allow_multiple_selected ': True}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['images'].required = False view: @login_required def createPostView(request): postForm = PostForm() if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) postImages = PostImagesForm(request.POST, request.FILES) #has to be 21 as it includes the cover img if len(request.FILES.getlist('images')) >= 21: messages.error(request, 'More than 20 image gallery images uploaded') return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm}) for image in request.FILES.getlist('images'): if image.size > settings.MAX_UPLOAD_SIZE: messages.error(request, f'Image gallery image {image} is too large 10mb max per image') return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm}) else: if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() if len(request.FILES.getlist('images')) == 0: return redirect('post-detail', PostFormID.pk , PostFormID.slug) else: for f …