Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS ElasticBeanstalk container_commands: Commands trigger errors even if they were correct
I have a django project that I want to deploy with ElasticBeanstalk, I defined a [xxxx.config] file in .ebextensions, the content of the file is: xxxx.config container_commands: acvenv: command: "source /var/app/venv/*/bin/activate" migrate: command: "python /var/app/current/manage.py migrate" But the project doesn't deploy unless I remove xxxx.config. I follow the documentation: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html What am I doing wrong? -
Django UpdateView not Updating
I have created a Django app that allows users to enter their stock trades, as a journaling tool. When a user clicks on an individual journal entry from the index page, they will be taken to a detail page showing all the information on that individual entry (single_entry.html). This page is handled by an UpdateView. From this page, a user can edit/update any info, as well as DELETE that specific entry. There are two buttons on the form, one for 'Delete' and another for 'Update'. The deleting works fine. The updating used to work, but now is not for some reason! Nothing updates in the Entry. Also I can't figure out why the 'messages' middleware is not being output to the screen. Same with all my print() statements, nothing is coming out on the console. Thanks for your help! Here's my views.py: from django.forms.models import BaseModelForm from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from django.views import View from django.contrib import messages from django.urls import reverse_lazy from .forms import EntryForm from .models import Entry from django.views.generic.edit import UpdateView, DeletionMixin from django.views.generic import DeleteView # Create your views here. class EntryView(View): def get(self, request): entries = Entry.objects.all().order_by("entered_date") form = … -
Data is not being returned to Django Template, Data Does Exist
I am having an issue not getting data to return to a template, but this is not happening with other models in the same template. I can properly submit data on another page to this data model (TechnicianLabor) via a form, but the data will not publish from my calls in the html, what am I missing?: models.py class TicketList(models.Model): identifier = models.AutoField(primary_key=True) name = models.CharField(max_length=150, null=True, blank=True) description = RichTextField(default="Add description for Ticket: ", null=True, blank=True) client = models.ForeignKey('ClientCompany', blank=True, null=True, on_delete=models.CASCADE) assignment = models.ManyToManyField(TechnicianUser, null=True, blank=True) create_date = models.DateField(auto_now_add=True) end_date = models.DateField(null=True, blank=True) due_date = models.DateField(null=True) class TechnicianLabor(models.Model): ticket = models.ForeignKey(TicketList, on_delete=models.CASCADE) minutes = models.BigIntegerField(default=0) is_tracked = models.BooleanField(default=False) created_by = models.ForeignKey(TechnicianUser, on_delete=models.DO_NOTHING) created_at = models.DateTimeField() views.py def apps_tickets_details_view(request, pk): tickets = TicketList.objects.get(pk=pk) projects = ProjectList.objects.filter(pk=tickets.project_id) labors = TechnicianLabor.objects.all() comments = TicketComment.objects.filter(ticket_id=tickets) comment_count = comments.count() technicians = TechnicianUser.objects.all() replies = TicketCommentReplies.objects.filter(ticket_id=tickets) context = {"tickets":tickets,"comments":comments,"projects":projects, "replies":replies, "technicians":technicians, "labors":labors, "comment_count":comment_count} if request.method == "POST": form = TicketListAddForm(request.POST or None,request.FILES or None, instance=tickets) if form.is_valid(): print(comments) form.save() messages.success(request,"Ticket Updates Successfully!") #return redirect("apps:tickets.list") return redirect(reverse("apps:tickets.details", kwargs={'pk':tickets.pk})) else: print(form.errors) messages.error(request,"Something went wrong!") return redirect("apps:tickets.list") #return redirect(reverse("apps:tickets.list", kwargs={'pk':tickets.pk})) return render(request,'apps/support-tickets/apps-tickets-details.html',context) html <h6 class="card-title mb-4 pb-2">Time Entries</h6> <div class="table-responsive table-card"> <table class="table align-middle mb-0"> <thead class="table-light … -
Deploying Django in PAAS (Clever-Cloud) / can't find my app
I am trying to deploy my django (5.0.3) in Clever cloud It can't locate my app on the server, although it works fine locally Here is my tree structure Here is my settings.py Here are my env variables in cleveer-cloud Here is the error : 2024-03-09T14:55:49+01:00 ModuleNotFoundError: No module named 'photos' What could be the root cause ? -
Django: The static tag not loading on extended html when linking an image but works for CSS style sheet?
I have a layout.html file as follows: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link href="{% static 'app/styles.css' %}" rel="stylesheet"> </head> <body> {% block body %} {% endblock %} </body> </html> and a extended.html as follows: {% extends "layout.html" %} {% block body %} <div class="maincontainer"> <h1>Extended</h1> <img src="{% static 'app/images/image.svg' %}" alt="image"> </div> {% endblock %} When I load the exnteded.html I get the follwoing error: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 13: 'static', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I have tested a few scenarios out: If I remove the <img src="{% static 'app/images/image.svg' %}" alt="image"> from the extended.html the CSS style sheet loads perfectly. If I add {% load static %} to the extended.html the image and CSS style sheet both load. I have had a look at the Django docs and have ensured that the settings.py file does have django.contrib.staticfiles in INSTALLED_APPS and STATIC_URL = "static/". Am I missing something here? -
django-celery-beat loading task but celery worker not receiving it
I've been having these issues on my celery beat and worker where my celery beat creates task, but celery worker does not receive it . I am using elasticmq as the broker My celery beat logs docker exec -it app-1 celery -A app beat --loglevel info celery beat v5.3.6 (emerald-rush) is starting. __ - ... __ - _ LocalTime -> 2024-03-09 16:25:41 Configuration -> . broker -> sqs://user:**@sqs:9324// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2024-03-09 16:25:41,744: INFO/MainProcess] beat: Starting... [2024-03-09 16:25:41,821: INFO/MainProcess] Scheduler: Sending due task beat_task (app.tasks.beat_task) [2024-03-09 16:25:51,782: INFO/MainProcess] Scheduler: Sending due task beat_task (app.tasks.beat_task) My celery worker log docker exec -it kole-app-api-app-1 celery -A app worker --loglevel info/usr/local/lib/python3.11/site-packages/celery/platforms.py:829: SecurityWarning: You're running the worker with superuser privileges: this isabsolutely not recommended! Please specify a different user using the --uid option. User information: uid=0 euid=0 gid=0 egid=0 warnings.warn(SecurityWarning(ROOT_DISCOURAGED.format( -------------- celery@b4d9d70aafdc v5.3.6 (emerald-rush)--- ***** ------- ******* ---- Linux-5.10.16.3-microsoft-standard-WSL2-x86_64-with 2024-03-09 16:26:10 *** --- * --- ** ---------- [config] ** ---------- .> app: app:0x7fd2fe122f90 ** ---------- .> transport: sqs://user:**@sqs:9324// ** ---------- .> results: disabled:// *** --- * --- .> concurrency: 6 (prefork)-- ******* ---- .> task … -
send data from javascript to django without sending request, post, get
I have a project is about web game, if the player end the game #e.g. bool state == false then it will send the score back to the django backend, but i don't want the player have to press the submit button, is there any ways to do that? i have no any complete idea, i just found some solution is about ajax, fetch api..., but i don't really know if those work or not. my post can't pass the quality standard, is that means my post's word too less? -
how to use django validation with bootstrap tab list
I am trying to use bootstraps tab list with django, Basically i have grouped my fields under several fieldsets in the modelform. in the html template i generate bs nav-pills and tab-control to show the fields. it renders fine. below is the code. However whenever the user leaves a required field empty in a tab which is not active and clicks submit, django cannot put the focus on the required field. the same form works fine without bs tabs. So is there a way for me to be able to use django validation or do I need to write my own js to loop through all required fields and set focus? ========= the model form ================ class PostSellTutorForm(forms.ModelForm): class Meta: model = SellTutor exclude = default_exclude + ['post'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fieldsets = [ ['Basics', {'comment': 'about the tutor', 'fields': ['english', 'languages', 'years_of_experience', 'primary_occupation', 'message']}], ['Cost', {'comment': 'tutor cost', 'fields': ['hourly_rate', 'free_trial', 'free_trial_hours']}], ] def get_fieldsets(self): return self.fieldsets ============ the render function =============== def render_post_form(request, template, form, title, post_id, post_type, partial_save): context = {} # context['fieldsets'] = form.Fieldsets.value context['form'] = PostSellTutorForm context['page_title'] = title return render(request, template, context) =========== the template ======================= {% load static %} <!-- … -
Django ModuleNotFoundError on Heroku Release
Similar to many previously stated issues yet unresolved in my case, I get a ModuleNotFoundError when deploying my Django project for release on Heroku, which works fine locally. I use Django 4.0 and Python 3.10.13. Heroku release log: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 454, in execute self.check() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 486, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/compatibility/django_4_0.py", line 9, in check_csrf_trusted_origins for origin in settings.CSRF_TRUSTED_ORIGINS: File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 89, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 76, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'opportunities.settings.heroku_staging' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 426, in run_from_argv connections.close_all() File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/connection.py", line … -
Django i18n failing to catch strings in JS render functions
I'm using i18n to translate a Django project into various languages. Everything is nicely translated depending on locale, except for certain strings in JavaScript render functions. For example, if I run django-admin makemessages --all and django-admin makemessages -d djangojs --all, "Launch this app" and "App under review" from an HTML template don't show up in any of the django.po or djangojs.po files, despite being tagged with gettext(): <script> const renderStatus = () => { let launchApp = gettext("Launch this app"); document.getElementById("component-appLauncher").innerHTML = ` <span class="u-flex-grow-1" style="vertical-align: middle;">` + launchApp + `</span> <a href="#launch_this_app-modal"> <button style="btn--sm"> <i class="u-center fa-wrapper fa fa-solid fa-arrow-right-long"></i> </button> </a> `; let appReview = gettext("App under review"); document.getElementById("component-appStatus").style.color = "red"; document.getElementById("component-appStatus").innerHTML = appReview; } </script> Sometimes (though not consistently, and I can't reproduce this at will), one or the other .po file will have these lines (example from the Spanish translation), with no reference to the HTML template source file or line numbers: #~ msgid "Launch this app" #~ msgstr "Lanzar esta app" #~ msgid "App under review" #~ msgstr "App en estudio" This seems to be related to the cache because, after a lot of tab refreshes, the translation will suddenly appear (even though the mapping … -
How to add css_class to django ModelForm using crispy_forms
I have a ModelForm in django and I want to add desired classes to its fields using crispy_forms. this is my form: class ProductInventoryForm(ModelForm): class Meta: model = Product fields = ["sku", "regular_price", "sale_price", "stock_quantity"] def __init__(self, *args, **kwargs): super(ProductInventoryForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Field("sku", css_class="your-class"), Field("regular_price", css_class="another-class"), Field("sale_price", css_class="another-class"), Field("stock_quantity", css_class="another-class"), ) As you see I used init method and crispy helper and Layout, but it doesn't affect and no classes added to my form. -
Django FileField: File not uploading in media folder or sql database
I'm doing a e-learning portal using Django. The user 'teacher' should be able to upload files under any course. However, the files are not being upload in media/course_materials folder. When i check the sql database, there is no instance of the id being created when a file is upload (i tried both an image file and a word document file, both of very less storage). This is the debugging comment i get from views : " <MultiValueDict: {'course_materials': [<InMemoryUploadedFile: filematerial.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document)>]}>" models: class Course(models.Model): name = models.CharField(max_length=100) description = models.TextField(default ="Description of Course") course_materials = models.ManyToManyField('CourseMaterial', blank=True) def __str__(self): return self.name class CourseMaterial(models.Model): name = models.CharField(max_length=255) file = models.FileField(upload_to='course_materials/') def __str__(self): return self.name views: def edit_course(request, course_id): course = get_object_or_404(Course, id=course_id) if request.method == 'POST': form = CourseForm(request.POST, request.FILES.get, instance=course) if form.is_valid(): print(request.FILES) course = form.save(commit=False) course.save() form.save_m2m() # Save many-to-many relationships return redirect('teacher') # Redirect to teacher dashboard after editing the course else: form = CourseForm(instance=course) context = { 'form': form, 'course': course, } return render(request, 'elearn/edit_course.html', context) forms.py: class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['name', 'description', 'course_materials'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['course_materials'].queryset = CourseMaterial.objects.none() html: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> … -
Vue3 is fetching data from Django graphql but does not display the component on webpage?
While using Vue3 to fetch data from Django graphql backend, chrome console shows the fetched data as array: (3) [{…}, {…}, {…}] 0 : {__typename: 'PostType', title: 'That Bum.', subtitle: '', publishDate: '2023-12-14T19:23:09+00:00', published: false, …} 1 : {__typename: 'PostType', title: '"Fight Like a Girl!"', subtitle: '', publishDate: '2023-12-07T19:27:26+00:00', published: false, …} 2 : {__typename: 'PostType', title: 'Sunday Sermon', subtitle: '', publishDate: null, published: false, …} length : 3 but the component (AllPosts.vue) is not displayed on the webpage. Can you suggest a solution with description of the error and the solution? -
Nonexistent custom ModuleNotFound error for Django deployment on Apache24
The Problem I have a Django deployment with Apache24 that was working as expected previously, with the django project name being "API_Materials". However, when I tried to make new migrations with python manage.py makemigrations, a command that never had any problem before, I got the following stacktrace: (venv) C:\API\BD_API_Materials>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\core\management\base.py", line 453, in execute self.check() File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\core\checks\urls.py", line 36, in check_url_namespaces_unique if not getattr(settings, "ROOT_URLCONF", None): File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'MaterialsAPI' The module that the project tried to use is … -
OperationalError at /register/ no such table: CustomUser
models.py from django.db import models class CustomUser(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(unique=True) password = models.CharField(max_length=100) address = models.CharField(max_length=255) adharcard = models.CharField(max_length=12, unique=True) age = models.PositiveIntegerField() phone = models.CharField(max_length=15) class Meta: db_table = 'CustomUser' def __str__(self): return self.email views.py from django.contrib.auth import authenticate, login from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.contrib.auth.hashers import make_password from django.views import View from django.urls import reverse from django.contrib.auth.decorators import login_required from .models import CustomUser def home(request): return render(request, 'app/login.html') def register(request): if request.method == 'POST': first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') password = request.POST.get('password') address = request.POST.get('address') adharcard = request.POST.get('adharcard') phone = request.POST.get('phone') age = request.POST.get('age') hashed_password = make_password(password) user = CustomUser.objects.create( first_name=first_name, last_name=last_name, email=email, password=hashed_password, address=address, adharcard=adharcard, phone=phone, age=age ) user.save() return redirect('app/login.html') return render(request, 'app/register.html') class LoginView(View): """ Login view for the user. Returns: Response: indicating the result of the login attempt. - If successful, redirects to the dashboard. - If the user is not found, renders the login page with an error message. - If the password is incorrect, renders the login page with an error message. """ def get(self, request): return render(request, 'app/login.html') def post(self, request, *args, **kwargs): email = request.POST.get('email') … -
Imgur error 429: Only when trying to access image from Django application
So basically I have an active Django project where in a module I am uploading images to the Imgur server and retrieving them as a background image for generating a PDF using the direct link for the images (https://i.imgur.com/<hash>.png) The issue is that when trying to retrieve any image from the django server which is running on the local network IP (since the Imgur server blocks localhost) the server responds with a bizzare 429 error code. The bizzare thing is I can upload images to my application without any problem, and also access the direct image links from postman API / browser, but as soon as I try to read the image direct link from my Django server imgur responds with a status code of 429. Rate Limit data for my application: { "data": { "UserLimit": 500, "UserRemaining": 499, "UserReset": 1709980963, "ClientLimit": 12500, "ClientRemaining": 12495 }, "success": true, "status": 200 } Request code: import requests id = '<hash>' res = requests.get(f'https://i.imgur.com/{id}.png') # print(res.json()) #! Throws JSONDecodeError print({ "Headers": res.headers, "status_code": res.status_code, "reason": res.reason, "content": res.text, "url": res.url, }) Response Headers and content I have retrieved from debugging because the res.json() method is failing { "Headers": { "Connection": "close", "Content-Length": "0", … -
Reversed foreign key on an unmanaged model doesn't work
I've recentrly ran into a following problem. I have a couple of unmanaged models class A(models.Model): # some fields class Meta: app_label = "app" db_table = "table_a" managed = False class B(models.Model): # some fields a_fk = models.ForeignKey(A, on_delete=models.RESTRICT, related_name="b_objects") class Meta: app_label = "app" db_table = "table_b" managed = False so, as you can see, I've added related_name="b_objects" which I need to access objects B from objects A via django ORM. I need to get a count of B objects for each A object in my view, so what I do is: class InventoryLocationsCollectionView(ListAPIView): queryset = A.objects.prefetch_related("b_objects").annotate(total=Count("b_objects")) however what I get is an error that there's no such field 'b_objects' in A model. I also tried to use queryset = A.objects.raw("my query") however it didn't work as it calls .all() somewhere under the hood and raw querysets do not have .all() method. Also the difficulty is that I'm gonna need to add some filters and pagination raw queryset do not seem to support either. Are there any workarounds to make reversed foreign key work in unmanaged models? -
Django Rest Framework session authentication default view JSON Parse
I'm making a user session auth via DRF, React and Axios. I also use Postman for testing my endpoints. So the question is how to make default login view from rest_framework.urls work with JSON format. When I send user data (username and password) via form-data radio button inside Postman everything is working as intended. But when I use JSON format inside both Postman and Axios the DRF endpoint returns such html page: settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', ] } urls.py urlpatterns = [ path('drf-auth/', include('rest_framework.urls')), ] My JSON data {"username": "admin", "password": "admin"} -
Users may not be connecting to the same websocket - django channels
I’m developing a chat feature using django channels. when a message is sent, It gets created on the server side and I think it’s being broadcasted. in my consumer I'm adding both the sender and receiver to the same group. on the client side I’m using javascript to get the sender and receiver IDs and connect them to the websocket. but when user A sends a message to user B. even though the message object is created and sent, it doesn’t appear for User B. I've verified that both users are connected to the websocket and there are no errors. but i think the issue might be that they are not connecting to the same websocket but I’m not sure why this is happening. also I'm new to django channels and javascript. Javascript let senderId = null; let receiverId = null; document.addEventListener('DOMContentLoaded', function () { const chatLog = document.querySelector('#chat-conversation-content'); const messageInput = document.querySelector('#chat-message-input'); const chatMessageSubmit = document.querySelector('#chat-message-submit'); const activeChat = document.querySelector('.fade.tab-pane.show'); let chatSocket = null; function connectToChat(sender_id, receiver_id) { const wsURL = 'ws://' + window.location.host + '/ws/messenger/' + sender_id + '/' + receiver_id + '/'; try { chatSocket = new WebSocket(wsURL); chatSocket.onopen = function (e) { console.log('WebSocket connection established.'); }; … -
'Settings' object has no attribute 'PASSWORD_RESET_CONFIRM_URL'
A strange error 'Settings' object has no attribute 'PASSWORD_RESET_CONFIRM_URL', although Djoser settings have this field. the error occurs when trying to reset the password for an activated account. In addition, Djoser does not send an e-mail for activation of the account for some reason, but it does not display any errors. DJOSER = { 'USER_MODEL': 'users.Users', 'LOGIN_FIELD': 'email', "PASSWORD_RESET_CONFIRM_URL": '{}/password/reset/{uid}/{token}', 'ACTIVATION_URL': '#/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SEND_CONFIRM_EMAIL': False, 'USER_AUTHENTICATION_RULES': \['djoser.auth.authentication.UserAuthentication'\], 'SERIALIZERS': {'user_create': 'users.serializers.UserSerializer',} }``` the error occurs when trying to reset the password for an activated account. -
Swagger Documentation Issue: Incorrect Field Definition for SerializerMethodField in Django REST Framework
Problem Description I'm encountering an issue with generating Swagger documentation for a Django REST Framework project. Specifically, I'm using a SerializerMethodField named info in my serializer. However, in the generated Swagger documentation, it's incorrectly defined as a string, whereas info is derived from a related model and is not a string. Example In the Swagger documentation, info is incorrectly represented as a string: { "count": 0, "next": "http://example.com", "previous": "http://example.com", "results": [ { ... "info": "string", ... } ] } Relevant Serializer Code Here's a snippet of the serializer where the issue arises: class ProductSerializer(serializers.ModelSerializer): ... @staticmethod def get_info(obj): info = ProductInfo.objects.filter(product=obj.id) return ProductInfoSerializer(info, many=True).data ... I tried using swagger_serializer_method, but it doesn't seem to have any effect. Here's what I attempted: from drf_yasg.utils import swagger_serializer_method class ProductSerializer(serializers.ModelSerializer): ... @staticmethod @swagger_serializer_method(serializer_or_field=ProductInfoSerializer().fields) def get_info(obj): info = ProductInfo.objects.filter(product=obj.id) return ProductInfoSerializer(info, many=True).data ... However, this didn't resolve the issue. The problem applies to several fields, not just info. I'm seeking guidance on how to correctly represent info and other similar fields in the Swagger documentation. Any help or suggestions would be greatly appreciated. -
I created a filter function for my website but the javascript is not working
I created a filter option to filter the products by brand So, In my index.html <select id="brandFilter"> {% for v in vendors %} <option value="">All Brands</option> <option value="brand1" data-filter="vendor" class="filter-checkbox" type="checkbox" name="checkbox" value="{{v.id}}">{{v.title}}</option> <!-- Add more options as needed --> {% endfor %} </select> And I make a script for this So, In my function.js $(document).ready(function(){ $(".filter-checkbox").on("click" , function(){ console.log("Clicked"); }) }) And I also connected the template with the js file <script src="{% static 'assets/js/function.js' %}"></script> by this code. I am sure that the js file is connected with template but the filter function is not working. And also In my context-processor.py def default(request): categories=Category.objects.all() vendors=Vendor.objects.all() try: address=Address.objects.get(user=request.user) except: address=None return { 'categories':categories, 'address':address, 'vendors':vendors, } Please help me out with this!!! -
Getting whitenoise.storage.MissingFileError: The file 'vendor/bootswatch/default/bootstrap.min.css.map' could not be found
When I am using whitenoise to host my static files, after entering the python manage.py collecstatic command I am getting this error: whitenoise.storage.MissingFileError: The file 'vendor/bootswatch/default/bootstrap.min.css.map' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x0000029983D66570>. but when I remove all the whitenoise configurations it works collects all the static files successfully. Below are white noise and static files config in my settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR /'static'] STATIC_ROOT = "static_root" STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" and MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
Method not allowed DRF 405
I have API that should retrieve data about some country based on their names. But instead I'm getting error Method not allowed. How do I fix it? I am not using models for the countries. def get_country_info(country): country_info = { "Germany": [ _("Germany is a country with a rich history and culture, located in Central Europe. It is home to world-famous cities such as Berlin, Munich, Hamburg and Cologne. Germany is famous for its architecture, museums, beer and sausages."), ['img1', 'img2'], ], "USA": _( "The USA is the largest country in the world by area and population. It is located in North America and is a leading global economic and cultural center. The USA is known for its skyscrapers, Hollywood, Disneyland and Niagara Falls." ), "UK": _( "The United Kingdom is an island nation located in the North Atlantic. It comprises England, Scotland, Wales and Northern Ireland. The UK is the birthplace of the English language, Parliament, Big Ben and Queen Elizabeth II." ), "Turkey": _( "Turkey is a country located at the crossroads of Europe and Asia. It is known for its beaches, ancient ruins, mosques and bazaars. Turkey is a popular tourist destination for lovers of history, culture … -
Model fields not being displayed in django admin
actually i am beginner learning django and i wanted to create my own project. so i started with making models and fields of all required apps then i also registered in admin.py but still the fields are not being shown in the django admin panel. So this is models.py of one of my django app from django.db import models from authentication.models import User from course_management.models import Course # Create your models here. class Attendance(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) course=models.ForeignKey(Course,on_delete=models.CASCADE) date=models.DateField() status=models.CharField(max_length=250) and i have registered it in admin.py as well, but still the fields are not shown in django admin. this is happening w all the other django apps as well from django.contrib import admin from .models import Attendance # Register your models here. class AttendanceAdmin(admin.ModelAdmin): list_display=('user','course','date','status') admin.site.register(Attendance,AttendanceAdmin)```