Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wanted to build a cloud service where a static file is accessible on every dynamically generated URL
I aim to access specific static files and HTML pages stored in either an S3 bucket or an Azure blob container using various URLs. The concept involves our server generating dynamic URLs in a specific format and then responding with a redirect to the client. Ultimately, I wanted to show the client the same content on the dynamic URL they are redirected to. I anticipate that an HTML page named "x" will be accessible via hundreds of URLs, such as https://base_url/x/1, https://base_url/x/2, https://base_url/x/3, and so forth, up to https://base_url/x/100. -
Cryptography Fernet Invalid Token
I am trying in Python Django to create a system for encrypting and decrypting messages. Does anyone know why I get an error every time I try to read a message: "The encrypted message is invalid and cannot be decrypted". Below is my code: `class MessageSerializer(serializers.ModelSerializer): created_by = BasicUserSerializer(read_only=True) class Meta: model = Message fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) load_dotenv() self.ENCRYPTION_KEY = "key_generated_by_fernet.generate_key()" self.fernet = Fernet(self.ENCRYPTION_KEY) def to_representation(self, instance): representation = super().to_representation(instance) representation['text'] = self.decrypt(instance.text) return representation def encrypt(self, message): encoded_message = message.encode() encrypted_message = self.fernet.encrypt(encoded_message) return encrypted_message def decrypt(self, encrypted_message): try: decrypted_message = self.fernet.decrypt(encrypted_message) decoded_message = decrypted_message.decode() return decoded_message except InvalidToken: raise ValueError("The encrypted message is invalid and cannot be decrypted.")` Has anyone ever had a similar problem and knows how to solve it? -
Trouble in setting up virtual environment for django in device
After running installation command , the output are as follows. please help me in setting up virtual env for django \Django>pip install virtualenv Requirement already satisfied: virtualenv in c:\python311\lib\site-packages (20.26.1) Requirement already satisfied: distlib<1,>=0.3.7 in c:\python311\lib\site-packages (from virtualenv) (0.3.8) Requirement already satisfied: filelock<4,>=3.12.2 in c:\python311\lib\site-packages (from virtualenv) (3.12.4) Requirement already satisfied: platformdirs<5,>=3.9.1 in c:\python311\lib\site-packages (from virtualenv) (4.2.1) D:\Django>virtualenv env 'virtualenv' is not recognized as an internal or external command, operable program or batch file. Please provide me with commands to write first django program in virtual environment. I have been trying the same from 2 days but unable to do so. please help me . And provide commands to run my first program in djano in VScode -
Django Test - How to work out why not redirecting
I have the following Django Test for a CreateView: def test_post_non_chargeable(self): self.client.force_login(self.user) form = EditStudyForm(data=self.non_chargeable_payload) self.assertTrue(form.is_valid()) response = self.client.post(self.url, self.non_chargeable_payload) self.assertRedirects(response, reverse("researcher_ui:console_study", kwargs={"pk": self.study.pk})) The first test, that the form is valid works. The second test doesn't work. The response is not redirecting but getting a 200 response. How do I work out why it isn't redirecting when the form is valid and it does when I use the application? -
How to fix the ImportError: cannot import name 'formatargspec' from 'inspect' (/usr/lib/python3.12/inspect.py). Did you mean: 'formatargvalues'?
I'm trying to run django app usind docker .. it gives me this error when i try to docker-compose up --build : water_maps | File "<frozen importlib._bootstrap>", line 1387, in _gcd_import water_maps | File "<frozen importlib._bootstrap>", line 1360, in _find_and_load water_maps | File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked water_maps | File "<frozen importlib._bootstrap>", line 935, in _load_unlocked water_maps | File "<frozen importlib._bootstrap_external>", line 995, in exec_module water_maps | File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed water_maps | File "/var/www/html/demo_app/water_maps/__init__.py", line 4, in <module> water_maps | from celery import Celery water_maps | File "/usr/local/lib/python3.12/dist-packages/celery/__init__.py", line 17, in <module> water_maps | from . import local # noqa water_maps | ^^^^^^^^^^^^^^^^^^^ water_maps | File "/usr/local/lib/python3.12/dist-packages/celery/local.py", line 17, in <module> water_maps | from .five import PY3, bytes_if_py2, items, string, string_t water_maps | File "/usr/local/lib/python3.12/dist-packages/celery/five.py", line 7, in <module> water_maps | import vine.five water_maps | File "/usr/local/lib/python3.12/dist-packages/vine/__init__.py", line 8, in <module> water_maps | from .abstract import Thenable water_maps | File "/usr/local/lib/python3.12/dist-packages/vine/abstract.py", line 6, in <module> water_maps | from .five import with_metaclass, Callable water_maps | File "/usr/local/lib/python3.12/dist-packages/vine/five.py", line 364, in <module> water_maps | from inspect import formatargspec, getargspec as _getargspec # noqa water_maps | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ water_maps | ImportError: cannot import name 'formatargspec' from 'inspect' (/usr/lib/python3.12/inspect.py). … -
Django serializer is not validating or saving data
I am trying to save data in the database, it works for most of my models but for few models I am not sure why but django is not serializing data. I hope someone can point out where I might be doing wrong. Here is my code Django Models class UserModel(AbstractUser): uuid = models.UUIDField(default=uuid.uuid4, editable=False) class UserWorkPresenceModel(models.Model): user = models.ForeignKey("UserModel", on_delete=models.CASCADE, related_name="workpresence") is_active = models.BooleanField(default=False) check_in = models.DateTimeField(blank=False) check_out = models.DateTimeField(blank=True, null=True) work_break = [] class UserWorkBreakModel(models.Model): work_presence = models.ForeignKey("UserWorkPresenceModel", on_delete=models.CASCADE, related_name="work_break") start_break = models.DateTimeField(blank=True) end_break = models.DateTimeField(blank=True, null=True) is_current_break = models.BooleanField(default=False) Serializer: class UserTakeBreakSerializer(serializers.Serializer): class Meta: model = UserWorkBreakModel # fields = ("start_break", "end_break") fields = '__all__' API View class UserStartWorkBreakView(APIView): def post(self, request, id): try: user = UserModel.objects.get(uuid=id) except: return Response({'message': 'User not found'}, status=HTTP_400_BAD_REQUEST) try: work_presence = UserWorkPresenceModel.objects.get(user=user, is_active=True) except UserWorkPresenceModel.DoesNotExist: return Response({'message': 'User work presence not found'}, status=HTTP_400_BAD_REQUEST) currently_onbreak = UserWorkBreakModel.objects.filter(work_presence=work_presence, is_current_break=True) if currently_onbreak.exists(): return Response({'message': 'User already working'}, status=HTTP_400_BAD_REQUEST) serializer = UserTakeBreakSerializer(data=request.data) print(serializer) if serializer.is_valid(): print(f'validated_data: {serializer.validated_data}') user.workpresence_status = UserWorkPresenceStatus.ON_BREAK serializer.validated_data['is_current_break'] = True serializer.save(work_presence=work_presence) user.save() print(f'serializer.data: {serializer.data}') return Response(serializer.data, status=HTTP_201_CREATED) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) I'm not getting any error just empty dictionary, here is result of my print commands: UserTakeBreakSerializer(data={'start_break': '2024-05-10 15:05:52.829867'}): validated_data: {} serializer.data: {} … -
django-ckeditor: html template doesn't render my ckeditor content properly although I am using {{ content | safe }}
I am using the django-ckeditor plugin to implement a ckeditor field in my django website. I have an updateView where you can edit the "notes" attribute of a model called Server. The ckeditor widget is working perfectly here in my server_update_form.html: <div class="flex flex-col items-center justify-center px-6 py-8 mx-auto md:h-screen lg:py-0"> <form class="w-full" action="" method="post"> {% csrf_token %} {{ form.media }} <table> <div class="relative z-0 w-full mb-5 group"> <form class="max-w-sm mx-auto"> <label for="notes" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">{{ form.notes.label_tag }}</label> {{ form.notes }} </form> </div> </table> <button type="submit" style="display:block" class="w-1/10 text-white bg-orange-600 hover:bg-orange-700 focus:ring-4 focus:outline-none focus:ring-orange-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center"> Submit </button> </form> </div> This is how it looks like I also have a DetailView where I would like to display the content inside server.notes without being able to edit it. My server_detail.html looks like this: {% if server %} <h1 class="mb-8 text-3xl font-bold">Server: {{ server.displayname }}</h1> </div> <div class="flex flex-col pt-3"> <dt class="mb-1 text-gray-500 md:text-sm dark:text-gray-40">Notes</dt> <dd class="text-md mb-5 p-2 border rounded-md"> <form>{{ server.notes |safe }} </dd> </div> </dl> But html doesn't render the notes properly: DetailView page model.py: class Server(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this server", editable=False) ip_address = models.CharField(max_length=30, help_text="Enter servers … -
Celery Command Not Found When Running from Docker Entrypoint Script
I am deploying a Django application using Docker onto ECS and encountering an issue where Celery commands specified in my entrypoint.sh script are not being recognized, resulting in errors. My Docker setup involves using Celery for asynchronous task processing, with separate containers for Celery workers and beat scheduled tasks. I get the following error messages when I create the ECS which includes the celery worker and beat as containers within the same task definition. Error Messages: /app/entrypoint.sh: line 28: exec: celery -A healthcare_project worker -l info: not found /app/entrypoint.sh: line 28: exec: celery -A healthcare_project beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler: not found Entrypoint Script (entrypoint.sh): #!/bin/bash # Exit script in case of error set -e # Apply database migrations echo "Applying database migrations..." python manage.py migrate --noinput # Collect static files echo "Collecting static files..." python manage.py collectstatic --noinput --clear # Debugging: List installed packages and show PATH echo "Installed Python packages:" pip freeze echo "Current PATH in Docker: $PATH" # Check if celery command is passed if [[ "$1" == "celery" ]]; then # Shift command line arguments left shift 1 # Execute the celery command with the passed arguments exec /usr/local/bin/celery -A healthcare_project "$@" else # Start command … -
Two instances of django project (same project) - sharing static?
I'd like to setup two (or more) instances of django project, with separate databases (so far it is easy). But, I think static files (that are massive - images, css, html ,js etc) - can be only in one place. No need to copy it multiple times, as they are not changing. Is it possible to setup it that way? Like some hardcoded path to static folder, outside of "project-instance" path? -
Django bulk upload takes 30 seconds to process 100 records
I have working on a travel insurance project, by which on my requirements is to allow agents to bulk upload travellers with pre-bought policies and packages. I have somehow managed to create this process, but unfortunately 100 rows of excel sheet takes 30 seconds to process. Its very bad in user experiences, most of the agents will be uploading 1000 travellers per month atleast. Please help on pointing out the issue and how this can be optimised further ? This is flow: Admin -> Creates Benefits ( For ex: Medical Expense, theft etc) Admin -> Create Policy -> Attach Package (one policy can many package) -> Choose Benefits and its limits -> Done (Note: Each benefit will have allocated amount stored in PackageBenefit table while creating Policy) Agents -> Upload Traveller via Excel Excel -> User -> Traveller -> PolicyHolder (traveller who bought policy) ->PolicyUsage (this is where i store Package details, Benefits and its allocated amount) These are the models User Traveller (1-1 with user) Policy Package (Foreign with Policy) Benefits PackageBenefit (Foreign with Policy, Package, this holds max_allocated money for the benefit in package) PolicyHolder (Stores all information when traveller buys/attaches to a policy, foreign with traveller, policy, … -
How do I manage the queue of hundreds of GET to be made in a given time with Django?
Good morning, I need to create a Django service that checks the status of hundreds of servers, the GET is routed to the healthcheck/ endpoint of hundreds of microservices, the user can enter the microservice to check and can enter the seconds before making another check: model class Target(models.Model): # ip address service_name = models.CharField( _("Service address"), max_lenght=90, blank=False, null=False ) # seconds (cron) check_every_seconds = models.IntegerField(_("Check every x seconds"), default=3600) is_active = models.BooleanField(_("Is Active")) What is the best approach to managing the queue? What is best for me to use? Celery? Thanks. -
"User matching query does not exist" When tried to follow a user
I am building a small social media website using Django, When I Click on follow button, I get this error saying: "User matching query does not exist." And showing the error here in the profile view function"user_object = User.objects.get(username=pk) this is the follow function in view.py file, def Follow(request): if request.method == "POST": follower_username = request.POST['follower'] user_username = request.POST['user'] # Get User model instances based on usernames follower_user = User.objects.get(username=follower_username) user_user = User.objects.get(username=user_username) if FollowersCount.objects.filter(follower=follower_user,user=user_user).first(): delete_follower = FollowersCount.objects.get(follower=follower_user,user=user_user) delete_follower.delete() else: add_follower = FollowersCount.objects.create(follower=follower_user,user=user_user) add_follower.save() return redirect('profile',username=follower_user) I tried to give try and except to the user_object, but it didn't work this is the profile view function, def Profile_view(request,pk): user_object = User.objects.get(username=pk) user_profile = Profile.objects.get(user=user_object) user_post = Post_Upload.objects.filter(user=user_object) following_count = FollowersCount.objects.filter(follower=user_object).count() followers_count = FollowersCount.objects.filter(user=user_object).count() post_count = user_post.count() context = { "user_profile":user_profile, "user_post":user_post, "post_count":post_count, "following_count":following_count, "followers_count":followers_count, } return render(request, 'profile.html',context) -
Gunicorn Running Django Project: nohup Instance Works Fine, systemd Service Instance Returns 400 Error
Problem Description: I'm encountering an issue with my Gunicorn setup while running a Django project. Specifically, I have two instances of Gunicorn running the same Django project: one using nohup and the other implemented as a systemd service. Surprisingly, the instance running with nohup works perfectly fine, while the one set up as a systemd service consistently returns a 400 error. Background Information: I'm running a Django project with Gunicorn as the WSGI server. Each instance of Gunicorn is configured identically. Both instances are using the same Django project and Gunicorn configuration. Steps Taken: nohup Instance: I'm starting the nohup instance using the following command: nohup /home/user/project_backend/venv/bin/gunicorn --workers 5 --bind 0.0.0.0:8000 backend.wsgi:application & It works perfectly fine! Run Gunicorn as a systemd service, create or open the config file:sudo nano /etc/systemd/system/gunicorn.service Following is gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=user Group=user WorkingDirectory=/home/user/project_backend ExecStart=/home/user/project_backend/venv/bin/gunicorn --workers 5 --bind 0.0.0.0:8000 ExecReload=/bin/kill -s HUP $MAINPID KillMode=mixed TimeoutStopSec=5 [Install] WantedBy=multi-user.target and thenrun sudo systemctl daemon-reload to apply the config change and sudo systemctl start gunicorn Attempted to send the same HTTP request to both instances: Request sent to nohup instance: success Request sent to systemd service instance: failure (returned 400 error) Has anyone encountered a … -
Django Infinite Scroll repeats the whole page, how do I solve this so it just repeats the content?
Making a django app, that lists off articles. Rather than pagenate manually with a page 2 button, I'd rather try and get infinite scroll working. Been trying some HTMX, Django native, and JS solutions but I'm not that experienced and I've struggled to get anything working. I found an HTMX solution that I got working, however because my view renders the whole page, rather than get the article segment, the infinite scroll just loads the entire webpage at the bottom again, header, navigation and all. I've tried to tweak some things, experiment with a view within a view but couldn't quite get it working. Below is my code. My view: @csrf_protect def Home(request,filtr): # Create a Session ID if one isn't already available for JS if not request.session.exists(request.session.session_key): request.session.create() session = request.session.session_key # ----- ----- f = filtr # filter for page view type p = 6 # page limit page = request.GET.get("page") # ----- ----- # Editors Pick curated = ContentQuery(3) # Filter View if f == 1: # Newest items = ContentQuery(f) elif f == 2: #Random items = ContentQuery(f) else: # Trending items = ContentQuery(f) paginator = Paginator(items,p) page_obj = paginator.get_page(page) try: content = paginator.page(page) except PageNotAnInteger: … -
Fetch all data with single query in Django
How to fetch all child related objects in a single query in Django? For example we have 3 models: class Parent(models.Model): ... class Child(models.Model): parent = models.ForeignKey(Parent) class SubChild(models.Model): parent = models.ForeignKey(Child) I want to fetch all the data in a single query like this: select * from parent p join child c on c.parent_id = p.id join subchild sc on sc.parent_id = c.id How I could perform this using Django ORM? What if I will have multiple child models? In SQL I just add more joins, but how I could do it in Django? Now I have few seconds delay when load everything recursively with multiple queries. The prefetch_related method does not help, I mean qs = Parent.objects.all().prefetch_related('child').prefetch_related('child__subchild') for parent in qs: # here I need to access parent.childs.all() and child.subchild.all() without new queries -
Django REST API Form Showing "Content" Only
In my REST API screen I'm seeing this view: Instead of the "Content" field I used to see a form where I could input data. Now my only option is to manually write in JSON. I'm not entirely sure when/how this change happened so I'm at a bit of a loss for where to look to change it back. I've tried changing the media type on this page but that has no effect. Does anyone know how this field is generated and how I can switch it back to the form data instead? Thanks, Mitchell -
How to Display a Modal on Click Event of a Polygon in a Django Class-Based View Using Folium Map?
I'm using Folium in a Django CBV to display a map with polygons. How can I trigger a modal to appear with more region details when a user clicks on a polygon? ` def get(self, request, *args, **kwargs): context = {} # Retrieve form and queryset data context['RegionalMalnutritionForm'] = RegionalMalnutritionForm() context['regional_levels'] = RegionalLevel.objects.all() context['national_levels'] = NationalLevel.objects.filter(age_category=1, year_record=1) #for Default map when open the pages - Regional is the default for malutrition module min_id = YearCategoryMalnutrition.objects.all().order_by('id').first().id age_category_min_id = AgeCategory.objects.all().order_by('id').first().id coodinate_locations = RegionalLevel.objects.filter(year_record=min_id,age_category=age_category_min_id) geo_data = {"type": "FeatureCollection", "features": []} for location in coodinate_locations: json_string = location.regional_level_coordinate.region_coordinate polygons_type = location.regional_level_coordinate.geo_type malnutrition_category = location.malnutrition_category percentage = location.percentage age_category = location.age_category color = location.color.hex_color region_name = location.region_name geo_data['features'].append(self.create_geojson_feature(json.loads(json_string,), polygons_type, percentage,age_category,malnutrition_category,color,region_name)) folium_map = self.create_map() # Add the feature to the map with the popup folium.GeoJson( geo_data, highlight_function=highlight_function, style_function=style_function, tooltip=folium.features.GeoJsonTooltip( fields=['Data'], aliases=[''], localize=True, style="background-color: rgba(0, 0, 0, 0.5); color: white; font-size: 16px; padding:8px;", ), ).add_to(folium_map) # Convert map to HTML representation context['folium_map'] = folium_map._repr_html_()` I tried adding an onclick event to the polygons in my Folium map within a Django class-based view, expecting a modal to be triggered on click. The modal should display detailed information about the clicked region. However, this doesn't work as expected and … -
Django Admin Import Error: NOT NULL Constraint Failed for ForeignKey Field in CSV Import
I'm experiencing a persistent issue with importing CSV data into my Django project using the django-import-export library in the admin panel. When trying to import records for a Copy model which has ForeignKey relations, I keep encountering a NOT NULL constraint failed error for the book_id field. AGAIN THIS ONLY OCCURS IN THE ADMIN PANEL, I have tested in shell and it works. I am sure there is no issue with the CSV and likely not even the resources/models files. It seems something is going wrong with the admin logic before the actual import. Error looks like this but for every single row. It occurs when hitting "submit". I never even get to "Confirm Import" button Line number: 1 - NOT NULL constraint failed: catalog_copy.book_id Line number: 2 - NOT NULL constraint failed: catalog_copy.book_id Line number: 3 - NOT NULL constraint failed: catalog_copy.book_id Line number: 4 - NOT NULL constraint failed: catalog_copy.book_id Line number: 5 - NOT NULL constraint failed: catalog_copy.book_id Line number: 6 - NOT NULL constraint failed: catalog_copy.book_id Line number: 7 - NOT NULL constraint failed: catalog_copy.book_id Line number: 8 - NOT NULL constraint failed: catalog_copy.book_id Line number: 9 - NOT NULL constraint failed: catalog_copy.book_id Line number: 10 … -
How to render right buttons (Like or Unlike) in a post based on user's choice using Javascript in a web app?
I'm working on a web app where a user has the option to like or unlike a post posted by another user. I created a button and wrote a Javascript function to change the text inside the button based on user's choice. If user clicks Like button it changes to Unlike and vice versa. Here's my code: models.py class Post(models.Model): """ Model representing a post. """ user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) no_of_likes = models.IntegerField(default=0) def __str__(self): return f"Post {self.id} by {self.user.username} on {self.timestamp}" class Like(models.Model): """ Model representing a like. """ user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user} likes {self.post}" urls.py path("", views.index, name="index"), path("like/<int:post_id>", views.like, name="like"), path("unlike/<int:post_id>", views.unlike, name="unlike"), views.py def index(request): """ Home page. """ posts = Post.objects.all().order_by('-timestamp') paginator = Paginator(posts, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) likes = Like.objects.all() # List of post ids. liked_posts = Like.objects.filter(user=request.user).values_list('post', flat=True) liked_posts = list(liked_posts) return render(request, "network/index.html", { "posts": posts, "page_obj": page_obj, "likes": likes, "liked_posts": liked_posts, }) @login_required def like(request, post_id): post = Post.objects.get(pk=post_id) user = User.objects.get(pk=request.user.id) like = Like.objects.create(user=user, post=post) like.save() post.no_of_likes = Like.objects.filter(post=post).count() post.save() return JsonResponse({"message": "successfully liked", "no_of_likes": post.no_of_likes}) @login_required def unlike(request, post_id): … -
Reverse lookup for fields with choices in django models
I have following model : class Role(models.Model) : class RoleTypes(models.TextChoices) : PAID = 'P', 'Paid' UNPAID = 'U', 'Unpaid' COLLABORATION = 'C', 'Collaboration' role_type = models.CharField(max_length=5, choices=RoleTypes.choices, default=RoleTypes.PAID) role_count = models.IntegerField(default = 1, validators=[MinValueValidator(1), MaxValueValidator(10)]) And following serializer : class RoleSerializer(serializers.ModelSerializer): class Meta : model = Role fields = '__all__' Now Role resource is created by passing following data in post request : {'role_type':'P', 'role_count':2} Is it possible that data sent in post request sets role_type = 'Paid' instead of 'P' -
Django + NextJs
How can I integrate django backend with NextJs frontend? Is it possible if yes can anyone please define me the steps... I saw some lectures on youtube and they were about react+django but not next+django Need guidance regarding this I am using Django Rest Framework at backend and NextJs at frontend. -
chat_message doesn't work in consumsers.py, when channel_name value is changed
I'm building a synchronous chat AI bot, there are 7 different models of them each serve for different purpose, therefore I assign a different channel_name during connection(connect). However, when I assign a new channel_name, my chat_message doesn't work at all, but the rest functions(receive, connect, disconnect) doing fine. import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer from .models import Message from .contants import SendType class ChatConsumer(WebsocketConsumer): def connect(self): self.group_name = str(self.scope["user"].pk) module_name = self.scope['url_route']['kwargs']['module'] self.channel_name = module_name #self.channel_name = "something" # print(self.scope) # print("-------") print(self.scope['url_route']) print(self.channel_name) self.user = self.scope["user"] async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.group_name, self.channel_name ) def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] event = { 'type':"chat.message", "message":message } print(message) print(self.channel_name) print(self.scope['user']) if len(message) > 0: async_to_sync(self.channel_layer.group_send)( self.group_name, event ) def chat_message(self, event): message = event["message"] print("CHECKING\n") message_obj = Message(text=message, user=self.user, sender_type=1) message_obj.save() self.send(text_data=json.dumps({"message": f"{self.user.username}: {message}"})) consumers.py from django.urls import re_path, path from . import consumers websocket_urlpatterns = [ path("ws/chat/", consumers.ChatConsumer .as_asgi()), #re_path(r'ws/chat/(?P<module>\w+)/$', consumers.ChatConsumer.as_asgi()), ] routes.py <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <textarea id="chat-log" cols="100" rows="20"></textarea><br> <input id="chat-message-input" type="text" size="100"><br> <input id="chat-message-submit" type="button" value="Send"> <script> console.log("Script started."); const chatSocket = new WebSocket( 'ws://' + window.location.host + … -
is there a way of solving; TypeError: 'module' object is not iterable in django?
I am a beginner learning django. while doing my project, I encountered an error and now am stack. while running 'python manage.py makemigrations', the error below occured: TypeError: 'module' object is not iterable I need help where I can start to solve the problem as soon as possible. this is my code myapp/views.py from django.shortcuts import render, redirect from .models import Book, UserBook from django.contrib.auth.decorators import login_required # Create your views here. def home(request): books = Book.objects.all() return render(request, 'home.html', {'books': books}) def library(request): user_books = UserBook.objects.filter(user=request.user) return render(request, 'library.html', {'user_books': user_books}) def add_book(request, book_id): book = Book.objects.get(id=book_id) user_book = UserBook.objects.create(user=request.user, book=book) return redirect('library') myapp/urls.py '''Defines the urls for the library application''' from django.urls import path from . import views app_name = 'library' urlpatterns = [ #homepage path('', views.index, name='home'), path('library/', views.library, name='library'), path('add_book/<int:book_id>/', views.add_book, name='add_book'), ] traceback Traceback (most recent call last): File "/Users/in/.local/share/virtualenvs/ArenaStudy-g4tNO7nf/lib/python3.10/site-packages/django/urls/resolvers.py", line 740, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/in/Desktop/ArenaStudy/manage.py", line 22, in <module> main() File "/Users/in/Desktop/ArenaStudy/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/in/.local/share/virtualenvs/ArenaStudy-g4tNO7nf/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/in/.local/share/virtualenvs/ArenaStudy-g4tNO7nf/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
My custom templatetag is not working. The output is empty
Here's the folder structure: homepage (this is the Django app) | |templatetags | __init__.py | shamsi_tags.py The content of shamsi_tags.py: from datetime import datetime from django import template from jdatetime import datetime as jdatetime register = template.Library() @register.simple_tag def shamsi_date(): """ This template tag returns the current date in Shamsi format. """ now = datetime.now() shamsi_date = jdatetime.fromgregorian(now.year, now.month, now.day) return shamsi_date.strftime('%Y/%m/%d') The index.html: {% load shamsi_tags %} ... <div>{{ shamsi_date }}</div> ... And nothing displays. I check the page source and it shows <div></div>. The rest of the page is displaying correctly so I guess there's nothing wrong with the URL or view. Obviously jdatetime is installed. It is Django 5.0.6 on Windows. I'm sure this is something easy but I can't figure it out. -
Validation of old standard Brazilian and Mercosur vehicle license plates in Django
I'm trying to validate Brazilian boards in Django (Python) for both the old ABC2546 standard and the Mercosul ABC1A35 standard. But when I type the Mercosur standard on the invalid plate. def validate_placa(placa): """ Valida se a placa do veículo está no formato correto. Args: placa (str): A placa do veículo a ser validada. Returns: None se a placa for válida, uma mensagem de erro se não for. """ placa_regex = r'^[A-Z]{3}-[0-9]{4}$|^([0-9]{3})-([0-9]{3})([A-Z]{1})$' # Formato: ABC-1234 validator = RegexValidator(regex=placa_regex, message='Placa inválida.') try: validator(placa) except ValidationError as error: return error.message class ClienteForm(forms.ModelForm): class Meta: model = Cliente fields = '__all__' veiculo_placa = forms.CharField( validators=[validate_placa], max_length=8, error_messages={'required': 'Placa é obrigatória.'} ) def validate_data(self, data): cleaned_data = super().validate_data(data) veiculo_placas = self.data.getlist('veiculo_placa') for placa in veiculo_placas: error_message = validate_placa(placa) if error_message: self.add_error('veiculo_placa', error_message) return cleaned_data I need to validate both standards