Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve sender mail and receiver same issues in Django?
I want, when a user will submit the contact form then I'll get a mail from the user mail. Everything is okay here, but the issue is I get the mail from my own mail when a user submits the form. Mean, sender mail and receiver mail is the same. That's why I can't see from which mail the mail cam Where is the problem?😢. Help me to resolve the issues. views.py: def ContactME(request): if request.method == "POST": MessageSenderName = request.POST.get('name') SenderMessage = request.POST.get('message') SenderEmail = request.POST.get('email') Contact.objects.create( Name = MessageSenderName, Email = SenderEmail, Message = SenderMessage, ) send_mail( '(Portfolio)' + MessageSenderName, SenderMessage, SenderEmail, ['mossaddak15-2413@diu.edu.bd'], ) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) settings.py: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'demo@gmail.com' EMAIL_HOST_PASSWORD = 'vkqhtdnqhzfrcuhs' EMAIL_USE_TLS = True -
Django & mongoDB integration failing
i'm trying to connect my django project with MongoDB by using djongo. every time i run the python manage.py migrate, the migration runs but it throws an error after this Applying App.0007_alter_order_customer_alter_orderitem_customer_and_more...Not implemented alter command for SQL ALTER TABLE "App_order" ALTER COLUMN "customer_id" TYPE int how to fix this??? i'm using two database in one cluster btw, hopefully that's not an issue #settings.py """ Django settings for amazon_clone project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-su&kse9ph!^@6x@r^vbb6396okv7u5mf#$cy()n(vl90y&kbe@' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['https://amazon-clone69.herokuapp.com','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'App', 'corsheaders', 'rest_framework_simplejwt.token_blacklist', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=90), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, … -
Get django date from subtracted timezone now
I am subtracting django's model datetimefield from timezone.now() and its resturning 17 days ,20:33:09.233443 as output , how to get date format? datetimefield = django_model.created_date date_i_want = timezone.now() - datetimefield print(date_i_want) output: 17 days, 20:33:09.233443 -
Call Celery Inspect from Django fails on every 2 requests with a "not enough values to unpack (expected 2, got 1)"
I am calling the following code from a django view (taken from https://docs.celeryq.dev/en/latest/userguide/workers.html#inspecting-workers): inspect_report = celery_app.control.inspect() tasks_active = inspect_report.active() It works correctly the first time but when I refresh the page i get a ValueError: not enough values to unpack (expected 2, got 1) Stacktrace: File "/venv_path/python3.9/site-packages/asgiref/sync.py", line 458, in thread_handler raise exc_info[1] File "/venv_path/python3.9/site-packages/django/core/handlers/exception.py", line 38, in inner response = await get_response(request) File "/venv_path/python3.9/site-packages/django/core/handlers/base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "/venv_path/python3.9/site-packages/asgiref/sync.py", line 423, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/home/benjamin/.pyenv/versions/3.9.6/lib/python3.9/asyncio/tasks.py", line 442, in wait_for return await fut File "/venv_path/python3.9/site-packages/asgiref/current_thread_executor.py", line 22, in run result = self.fn(*self.args, **self.kwargs) File "/venv_path/python3.9/site-packages/asgiref/sync.py", line 462, in thread_handler return func(*args, **kwargs) File "/venv_path/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/venv_path/python3.9/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/benjamin/project/administration/views.py", line 357, in dashboard tasks_active = inspect_report.active() File "/venv_path/python3.9/site-packages/celery/app/control.py", line 149, in active return self._request('active', safe=safe) File "/venv_path/python3.9/site-packages/celery/app/control.py", line 106, in _request return self._prepare(self.app.control.broadcast( File "/venv_path/python3.9/site-packages/celery/app/control.py", line 741, in broadcast return self.mailbox(conn)._broadcast( File "/venv_path/python3.9/site-packages/kombu/pidbox.py", line 344, in _broadcast return self._collect(reply_ticket, limit=limit, File "/venv_path/python3.9/site-packages/kombu/pidbox.py", line 386, in _collect self.connection.drain_events(timeout=timeout) File "/venv_path/python3.9/site-packages/kombu/connection.py", line 317, in drain_events return self.transport.drain_events(self.connection, **kwargs) File "/venv_path/python3.9/site-packages/kombu/transport/virtual/base.py", line 969, in drain_events … -
Redis-RQ not executing jobs
I have a question but it turns out I have similar problems to other Github threads that haven't been resolved yet, might as well ask it here. I am running Django and is using redis-rq to execute background jobs. Unfortunately, it doesn't execute jobs from the default queue. I have already tried to rename it but no progress so far. Have you guys had this similar event before, and how did you resolve it? Thanks! -
Proper directory structure for app versioning (Django)
I am currently starting work on a existing Django Project, and I need to make changes to the existing APIs. However, I can't change the existing code since old apps and sites have been using it, which might take a lot of time to change the structure, and might break current dependencies for those. So, for now, as asked, I need to maintain separate directories to change/review the existing code and achieve a versioning-like structure for Django apps. What might be the best way/structure to achieve this? The current structure is simple as given by django-admin startproject project_dir |___project_name_dir |___settings.py ... |___app_1_dir |___ __init__.py |___ views.py, serializers.py ... |___app_2_dir ... So, I need to like create versioning type structure for app_1 here. What might be the best approach to do that? -
Django Rest Framework custom throttling classes not working
I am having issues with setting up custom throttling using the django-restframework for django. I made the following views.py class which contains a view with this custom throttle: from .custom_throttles import * @api_view(('GET',)) @throttle_classes([LowLevelThrottle]) def home_stats(request): token = request.data['token'] if token == os.environ['api_token']: content = { 'users' : len(Profile.objects.all()), 'posts' : len(Post.objects.all()), 'reactions' : len(PostReaction.objects.all()) } return Response(json.dumps(content), status=status.HTTP_200_OK) else: content = { 'error' : 'invalid token' } return Response(json.dumps(content), status=status.HTTP_401_UNAUTHORIZED) This custom throttle is imported from custom_throttles.py which looks as following: from rest_framework import throttling class LowLevelThrottle(throttling.AnonRateThrottle): scope = 'll' def allow_request(self, request, view): if request.method == "GET": return True return super().allow_request(request, view) And last but not least, this is how I have some settings in my settings.py file setup: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'django_project.custom_throttles.LowLevelThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'll': '1/second', } } I also have the following logs I can provide clearly showing how multiple requests were made within this 1 second time frame. [24/Aug/2022 07:43:14] "GET /homestats HTTP/1.1" 200 51 [24/Aug/2022 07:43:23] "GET /homestats HTTP/1.1" 200 51 [24/Aug/2022 07:43:23] "GET /homestats HTTP/1.1" 200 51 [24/Aug/2022 07:43:23] "GET /homestats HTTP/1.1" 200 51 [24/Aug/2022 07:43:24] "GET /homestats … -
How to use Django with a legacy mysql 5.7 database (troubles with mysqlclient version)
I started a new Django project, but it supposed to be working with a legacy MySQL 5.7 database. For now, I have Django project, with specified database in settings.py and mysqlclient installed. First thing i tried was python manage.py inspectdb --database dbname but I git this error: MySQLdb.OperationalError: (1043, 'Bad handshake') I already realized that this is because I have mysqlconnector for version 8.0, and it's not compatible with mysql 5.7. I also found out that when installing mysqlconnector, its version depends on what i have in mysql_config. If I type mysql_config --version I get 8.0.30 And I cannot understand why, because if I run sudo dpkg-reconfigure mysql-apt-config It says that I have currently selected mysql-5.7. What actually is mysql_config and why it's configured to a different version? How can I switch it to 5.7 and have right version of mysqlclient installed? Or are there any other ways to make mysql 5.7 and my Django project work together? -
model creation in django
"here is the code i entered" class Projects(models.Model): title = models.CharField(max_length = 200) description = models.TextField(null = True, blank = True) demo_link = models.CharField(max_length = 2000, null = True, blank = True) source_link = models.CharField(max_Length = 2000, null = True, blank = True) created = models.DateTimeField(auto_now_add = True) id = models.UUIDField(default = uuid.uuid4, unique = True, primary_key = True, editable = False) code -
DRF - Request unique identifier [closed]
Is there any unique identifier like uuid in request object? from rest_framework.decorators import api_view from rest_framework.responses import Response @api_view(['GET]) def index_view(request): return Response() If there is not where to add it? Into request.META? -
How to Manage/Add Multiple User in Django Rest Framework
Scenario The are two roles in the system; LIBRARIAN and MEMBER As a User I can signup either as LIBRARIAN and MEMBER using username and password I can login using username/password and get JWT access token As a Librarian I can add, update, and remove Books from the system I can add, update, view, and remove Member from the system As a Member I can view, borrow, and return available Books Once a book is borrowed, its status will change to BORROWED Once a book is returned, its status will change to AVAILABLE I can delete my own account As i'm a newbie. Please help in how can I create the models of these. Thank you -
serializer.data and serializer.validated_data is blank when a serializer is initialized by dictionary
I am building an app using django and drf. While testing a serializer, I found the serializer could not save data to database because of null constraints. Below is the test code, serializer and model. location_serializer_data: LocationDict = { 'address': 'address', 'latitude': 11.1, 'longitude': 22.2, } @pytest.mark.django_db def test_deserializing(self): serializer = LocationSerializer(data=location_serializer_data) serializer.is_valid() new_location = serializer.save() # < where the test explodes Here is the error message django.db.utils.IntegrityError: NOT NULL constraint failed: locations_location.latitude I found that serializer.initial_data gets the data appropriately, but after serializer.is_valid(), two of serializer.data, serializer.validated_data become blank dict. I searched a bit but I found no clue of what was causing this. -
How to solve AttributeError of rest_framework_simplejwt/token_blacklist migration error?
After running python manage.py runserver I got a migration suggestion You have 9 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): token_blacklist. Run 'python manage.py migrate' to apply them. So I ran the migration command: python manage.py migrate Then I got this AttributeError. Part of the stack trace: File "{myproject_folder}/env/lib/python3.8/site-packages/rest_framework_simplejwt/token_blacklist/migrations/0003_auto_20171017_2007.py", line 11, in populate_jti_hex token.jti_hex = token.jti.hex AttributeError: 'str' object has no attribute 'hex'. System & Python Information: OS: Ubuntu 22.04.1 LTS x86_64 Kernel: 5.15.0-46-generic python: python3.8.10 I am using pyenv for multiple python installations and venv for the virtual environments. -
Difference between Django normal and Async views
async def index(request): return HttpResponse("Hello, async Django!") and def index(request): return HttpResponse("Hello, Django!") -
Django: typehinting backward / related_name / ForeignKey relationships
Let's say we have the following django models: class Foo(models.Model): pass class Bar(models.Model): foo = models.ForeignKey(Foo) And if I use this somewhere in some other class: bar = self.foo.bar Then mypy complains: Foo has no attribute "bar" How can I make mypy happy here? -
How can I update my {% for x in list %} table with setInterval() in Django?
[NOTE] I'm really new in web development. Please consider this I can make mistakes and I can ask stupid questions. Sorry about everything. Hello, I'm trying to make a student table with Django + Ajax. But there's a problem which I really can't understand how can I implement my ajax code for each row in the table. Now, I'm taking first index of every field in my ajax code. And ajax refresh this field in tables every second. But I want to update every cell and row in every second. Also I tried to add new cell with append(). It doesn't worked because of {% for students in object_list %} I didn't understand how to add a new append() row in {% for students in object_list %} In my html, this is the table body and ajax code. infoindex.html <table class="table table-light" id="studentstable"> <thead> <tr> <th scope ="col">Numara</th> <th scope ="col">Adı</th> <th scope ="col">Soyadı</th> <th scope ="col">Yaşı</th> <th scope ="col">Cinsiyet</th> </tr> <tbody id="tbodyid"> {% for students in object_list %} <tr> <td id="num">{{students.num}}</td> <td id="first_name">{{students.first_name}}</td> <td id="last_name">{{students.last_name}}</td> <td id="age">{{students.age}}</td> <td id="gender">{{students.gender}}</td> </tr> {% endfor %} </tbody> </table> <script> setInterval(function (){ $.ajax({ url : "http://127.0.0.1:8000/studentsapi", dataType: "json", success : function (data) { … -
Django send profile picture with django channels
I am doing a chat app and I want to show the profile picture of a user every time he sends something in the chat. Here is the code: Models.py class Chat(models.Model): room_name = models.CharField(max_length=200,null=True) message = models.CharField(max_length=200,null=True) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) username = models.CharField(max_length=200,blank=False,null=True,unique=True) profpic = models.ImageField(upload_to='profpics/',blank=True,null=True) Consumers.py # chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from .models import * from main.models import * class ChatConsumer(AsyncWebsocketConsumer): @sync_to_async def get_profile(self): return self.scope['user'].profile async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] room = text_data_json['room'] profile = await self.get_profile() profile_pic = profile.profpic profpic = json.dumps(str(profile_pic)) print(profpic) username = text_data_json['username'] await self.save_message(message, room,username) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username':username, 'profpic':profpic } ) # Receive message from room group async def chat_message(self, event): message = event['message'] username = event['username'] profpic = event['profpic'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username':username, 'profpic':profpic })) chat.html .... chatS.onmessage = function(e){ const data … -
Is it possible to get the payload data of a JavaScript socket io and print it using Django?
I have this JavaScript project that uses socket io and console the data. const = generateMockData(deviceId); console.log(payload) io.of("/").emit("data", JSON.stringify(payload)); And this is the generated mock data function generateMockData(deviceId) { const contaminants = [ { id: 9, ave: chance.floating({ min: 5, max: 5.5, fixed: 7 }), ave_reduction: chance.floating({ min: 0, max: 1, fixed: 1 }), }, { id: 10, ave: chance.floating({ min: 5, max: 5.5, fixed: 7 }), ave_reduction: chance.floating({ min: 0, max: 1, fixed: 1 }), }, { id: 14, ave: chance.floating({ min: 5, max: 5.5, fixed: 7 }), ave_reduction: chance.floating({ min: 0, max: 1, fixed: 1 }), }, { id: 15, ave: chance.floating({ min: 5, max: 5.5, fixed: 7 }), ave_reduction: chance.floating({ min: 0, max: 1, fixed: 1 }), }, ]; in my console it looks like this contaminants: [ { id: 9, ave: 5.4897571, ave_reduction: 0.5 }, { id: 10, ave: 5.4942647, ave_reduction: 0.7 }, { id: 14, ave: 5.316183, ave_reduction: 0.5 }, { id: 15, ave: 5.0806739, ave_reduction: 0.9 } ], is it possible to pass this payload data (console data) to Django? I tried using httpresponse in Django but it's not getting the data I want. The javascript and the django are in different projects. from … -
how to deploy django app on AWS windows server instance
thanks in advance. I want to deploy django app on aws having windows instance, gone through many doc and video but all are showing with ubuntu and linux machine. please provide any suggestion or right approach for doing this, your suggestion is vital.. Thank You -
Forbidden (CSRF cookie not set.): /api/signinUser
The error occurs in this react code const headers = new Headers({ "X-CSRFToken": Cookies.get('csrftoken') }); const response = await fetch("api/signinUser", { method: "POST", headers: headers, body: formData }); Trying to access this Django Api @ensure_csrf_cookie def signin(request): if request.method == 'POST': auth = False username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) print("Authenticating User", user) if user is not None: auth = True login(request, user) # Does this return anything? ret = { "auth": auth } print("RET", ret) return JsonResponse(ret) I have django.middleware.csrf.CsrfViewMiddleware in my MIDDLEWARE variable I'm running my Django server in an AWS EC2 instance that I access with http://<my public ip>:8000/ -
Vue, How to control HTML attr by Vue Js
I made a web page through Django and Bootstrap. And now I'm using vue to change the code. However, I'm having a hard time controlling the attribute value, so please let me know if there is a good way. I'd appreciate it if you could give me an answer. in Django <button type="submit" data-bs-target="#carouselCaptions" data-bs-slide-to="{{forloop.counter0}}" aria-label="Slide {{forloop.counter}}" {% if forloop.first %} class="active" aria-current="true" {% endif%}> </button> vue?? <button v-else type="submit" data-bs-target="#carouselCaptions" :data-bs-slide-to="Slide [[idx]]":aria-label="[[idx+1]]" :class=""> </button> How do I code to operate in the same format as Django? And :data="[x]" works fine, but :data="Slide [[x]]" is a problem that causes errors. How do I fix it? -
Django formsets not saving all forms to the database
I have a formset to render multiple forms at once. By default only two forms are rendered. Using JavaScript, I'm adding another two forms to the formset, so the total number of forms is now four. When I sent POST request, my view saves only first two objects to the database. The data from forms, added using JavaScript, is not saved. What am I doing wrong? My code: This is my forms.py file, where i define my formset. class AddAnswerForm(ModelForm): class Meta: model = Answer exclude = ['question'] widgets = { 'answer_text': forms.TextInput(attrs={'class': 'input'}), } AnswerFormSet = modelformset_factory(Answer, form=AddAnswerForm, extra=2, max_num=4) This is JS code, which I'm using to add new forms to the page (it's not mine code, but it works). <script> let answerForm = document.querySelectorAll(".answer-form") let container = document.querySelector("#question-form") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_form-TOTAL_FORMS") let formNum = answerForm.length-1 addButton.addEventListener('click', addForm) function addForm(e){ e.preventDefault() let newForm = answerForm[0].cloneNode(true) let formRegex = RegExp(`form-(\\d){1}-`, 'g') formNum++ newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form=${formNum}-`) container.insertBefore(newForm, addButton) totalForms.setAttribute('value', `${formNum+1}`) } </script> And here is my view. class QuestionAddView(View): form_class = NewQuestionForm form_class_for_answers = AnswerFormSet template_name = 'questions/question_add.html' def get(self, request, *args, **kwargs): form = self.form_class() answers_form = self.form_class_for_answers(queryset=Answer.objects.none()) return render(request, self.template_name, {'form': form, … -
What is running behind when creating Django project with one line command
a fresh question about Django. It maybe silly...I wonder what is running behind the scene when I create a Django project with one line command. Well, I have done with couples of Django projects, the framework is really powerful. So this question is just jumping into my mind. who created the directory structure. Is it a script in some installed Django folder? where can I find it? Thanks. -
How to merge two models inherited from Django into one serializer
In Django, is there a way to combine two models that inherit the same class into one serializer? from django.db.models import Model class A(Model): a = IntegerField(...) class B(A): # There may or may not be such a thing as class C. class C(A): # There may or may not be such a thing as class B. I have code like above. Could it be possible to create a serializer based on the class A model? I tried to create a view table in SQL, but gave up due to performance issues. Any good ideas please. It's so painful...😥 -
Time Zones and Filters in Django Rest Framework
We have a game where we keep track of daily, weekly and monthly leaderboards. Most of the users are in the US, so we're trying to have the daily/weekly/monthly charts update around a US timezone. So the setup we have is pretty straight forward. # models.py class PackGameSavedPack(auto_prefetch.Model): date = models.DateTimeField(null=True, blank=True) user_name = models.CharField(max_length=120, null=True) pack_score = models.IntegerField(null=True) # save_pack.py def pack_game_save_pack(user_id, user_name, pack_score=None): pack = PackGameSavedPack.objects.create( user_id=user_id, date=timezone.now(), user_name=user_name, pack_score=pack_score, ) #views.py class PackGameFilter(django_filters.FilterSet): user_id = CharInFilter(field_name='user_id', lookup_expr='in') date_range = DateRangeFilter(field_name='date') For the most part, this works great - except its saving all of the dates in the UTC (O offset) format. We set the USE_TZ and TIME_ZONE parameters in the settings.py file, however, this didn't seem t change anything. USE_TZ = True TIME_ZONE = "America/Los_Angeles"` I know I can adjust the dates/times at the serializer level, however, that doesn't help with the DateRangeFilter as it is using the UTC (0 offset) timezone. How can I get the DateRangeFilter using the TIME_ZONE or whats a better way to approach this?