Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check password that has been hashed and salted?
In my register method, I've created a user after hashing and salting their password. And in the login method, I need to check if the user has entered the correct password. The check_password() doesn't seem to accept a salt, and when I use the default authenticate(), I get an error saying: AttributeError: 'Manager' object has no attribute 'get_by_natural_key' I'm guessing this is probably because I created a custom User model by extending AbstractBaseUser. Is there some way I can verify the password by using an existing method? Or will I have to get the salt, hash and salt the password the user just entered, and then compare with the password in the DB? My user model: class User(AbstractBaseUser): name = models.CharField(max_length=128, blank=False) created_at = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(blank=True,default=False, verbose_name="Is admin") designation = models.CharField(max_length=90, blank=True) email = models.EmailField(max_length=160, blank=False, unique=True) USERNAME_FIELD = "email" def __str__(self): return self.name + " " + self.email Method for creating user: def register_user(self, request, **kwargs): serializer = UserSerializer(data=request.data) # handle invalid request if not serializer.is_valid(): for key, values in serializer.errors.items(): errorMsg = key + ": " + values[0].title() return Response( {"message": errorMsg}, status=status.HTTP_400_BAD_REQUEST ) name = serializer.data.get("name") email = serializer.data.get("email") password = serializer.data.get("password") user = User.objects.filter(email=email).first() … -
Why the User has no attribute 'objects'
user = User.objects.filter(email=email).first() AttributeError: type object 'User' has no attribute 'objects' views.py class PasswordReset(generics.GenericAPIView): serializer_class = serializers.EmailSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.data["email"] user = User.objects.filter(email=email).first() if user: encoded_pk = urlsafe_base64_encode(force_bytes(user.pk)) token = PasswordResetTokenGenerator().make_token(user) reset_url = reverse("reset-password", kwargs={"encoded_pk": encoded_pk, "token": token}) rest_url = f"localhost:8000{reset_url}" return Response( { "message": f"Your password reset link: {rest_url}" }, status=status.HTTP_200_OK, ) else: Response( { "message": "User doesn't exists" }, status=status.HTTP_400_BAD_REQUEST, ) serializers.py class EmailSerializer(serializers.Serializer): email = serializers.EmailField() class Meta: field = ("email",) -
How make scrollable dropdown in foreignkey field Django
I need to make the city field scrollable, how can i do this? models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import RegexValidator from django.dispatch import receiver from django.db.models.signals import post_save from cities_light.models import City # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField(validators=[RegexValidator(r'^\d{1,10}$')], blank=True, null=True) image = models.ImageField(upload_to='profile/') city = models.ForeignKey(City, on_delete=models.CASCADE, blank=True, null=True) def __str__(self) -> str: return str(self.user) forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' exclude = ('user',) edit_profile.html <form method='POST' enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form userForm %} {% bootstrap_form profileForm %} {% buttons %} <button href="{% url 'accounts:profile' %}" type="submit" class='boxed-btn3 w-100'>Save</button> {% endbuttons %} </form> there any argument should add in Forignkey field or the html file should edit? -
Telegram login widget with django TypeError: Cannot read properties of null (reading 'postMessage') with some browsers
I'm trying to implement Telegram login widget in my Django website. I'm using django-allauth and the login did work indeed for my test with Firefox browser but it failed to work on mobile devices and Chrome desktop. Authorization dialog just disappear after entering my phone number and confirming the login in Telegram messenger. I was able to run a debugger for the quickly disappearing popup window and caught this error: TypeError: Cannot read properties of null (reading 'postMessage') Login page is: <html> <body> <div> <script async src="https://telegram.org/js/telegram-widget.js?21" data-telegram-login="NameOfTelegrambot" data-size="medium" data-userpic="false" data-auth-url="https://example.com/accounts/telegram/login/"></script> </div> </body> </html> Login works with Firefox browser and I can see: Successfully signed in as TelegramUserName. And user name is shown in the upper right corner as singed in to "django-classified" But that doesn't happen in Chrome or in some popular Mobile browsers that I've tested. There is docker compose file to test the setup that can work locally after providing some Telegram Bot token in the .env file. -
Why i am getting ValueError at /login The given username must be set in Request Method POST- DJANGO
ValueError at /login The given username must be set Request Method: POST Below is the code for views.py and signup.html views.py def login(request): if request.method == 'POST': email = request.POST['email'] name = request.POST.get('fname') passw = request.POST['pass'] my_user = User.objects.create_user(username=name,email=email,password=passw) my_user.save() if not email: messages.error("Please Fill Correct Credentials.{0} is missing".format(email)) if not name: messages.error("Please Fill Correct Credentials.{0} is missing".format(name)) if not passw: messages.error("Please Fill Correct Credentials.{0} is missing".format(passw)) return render(request,'signup.html') signup.html {% load static %} <html lang="en"> <head> <title>Login V1</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--===============================================================================================--> <link rel="icon" type="image/png" href="{% static 'images/icons/favicon.ico' %}"/> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'fonts/font-awesome-4.7.0/css/font-awesome.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'vendor/animate/animate.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'vendor/css-hamburgers/hamburgers.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'vendor/select2/select2.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'css/util.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <!--===============================================================================================--> </head> <body> <div class="limiter"> <div class="container-login100"> <div class="wrap-login100"> <div class="login100-pic js-tilt" data-tilt> <img src="{% static 'img/img-01.png' %}" alt="IMG"> </div> <form class="login100-form validate-form" method="POST"> <span class="login100-form-title"> Signup </span> {% csrf_token %} <div class="wrap-input100 validate-input" data-validate = "Username is required"> <input class="input100" type="text" name="fname" placeholder="Username" required> <span class="focus-input100"></span> <span class="symbol-input100"> <i class="fa fa-envelope" … -
What is the reason for getting HTTP 504 while trying to make HTTP call-back to retrieve further information from caller API in Django?
The above is the very high-level sequence diagram for two APIs trying to communicate with each other. The frontend does only communicate with AppOne. AppOne calls AppTwo to store some data in AppTwo's DB but before saving the data, AppTwo calls AppOne to retrieve some further information. Once AppTwo receive further information from AppOne, if everything goes as intended, AppTwo will return OK response to AppOne, finally that response will be shown to user. This works just OK on my local machine, however after deploying to Azure. The call R1 just hangs. So I added logs to monitor whats happening. I found call (a) was initiated and after line executions, call (c) is also initiated from AppTwo to AppOne. AppOne also did some thing to prepare response for the call (c) and I can see the validated response for call (c) is being printed however the response (e) does not reach AppTwo, rather I am getting HTTP 504 after some waiting time and also getting 2006 error for MySQL too. Both these apps use MySQL as backend (different databases on a single server). Additionally, in the waiting time the AppOne does not facilitate any other requests. Can anyone explain why … -
FirebaseError: Messaging: We are unable to register the default service worker. Django Rest + Reactjs App
My web app has a django rest framework backend and reactjs frontend. I want to add firebase push notification service to my web app. According to the tutorials I added the firebase-messaging-sw.js in the public folder of the react app which is the frontend. The contents in the firebase-messaging-sw.js is as below: firebase-messaging-sw.js/public importScripts( "https://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js" ); importScripts( "https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-compat.js" ); const firebaseConfig = { ... }; firebase.initializeApp(firebaseConfig); const messaging = firebase.messaging(); messaging.onBackgroundMessage((payload) => { const notificationTitle = payload.notification.title; const notificationOptions = { body: payload.notification.body, icon: payload.notification.icon, }; console.log(notificationOptions, notificationTitle); self.registration.showNotification(notificationTitle, notificationOptions); }); }); firebase.js/src import { initializeApp } from "firebase/app"; import { getMessaging } from "firebase/messaging"; const firebaseConfig = { ... }; export const app = initializeApp(firebaseConfig); export const messaging = getMessaging(app); file where I generate the token for fcm const requestPermission = async () => { if (Notification.permission === "default") { if (user.regd_as === "TCH") { NotificationBar( `Please click allow for notification accesss so that you can receive notifications when students send you a request.`, `info` ); } else { NotificationBar( `Please click allow for notification accesss so that you can receive notifications when teacher accept your request.`, `info` ); } } try { const permission = await Notification.requestPermission(); if … -
Crf_exempt for class based views
class ErrorReportView(View): def get(self, request, *args, **kwargs): return HttpResponse('Hello, World!') @method_decorator(csrf_exempt) def post(self, request, *args, **kwargs): return HttpResponse('Hello, World!') I use Postman, but I get <p>CSRF verification failed. Request aborted.</p> Documentation: https://docs.djangoproject.com/en/4.1/topics/class-based-views/intro/#decorating-the-class Could you help me? -
How to implement Django Admin and Super Admin? Is super admin and Super user are same in Django?
I am a beginner in Django.. i am trying to work with, admin,super admin,user in Django. What is the difference between admin and super admin in Django? how can i implement super admin & Django admin? How can i give separate permission to Django admin and super admin and Django user? Is super user and super admin are same? Is there any need to use inheritance to create super admin? Is there any tutorial or notes available.. Please share.. @admin.register(User) class UserAdmin(admin.ModelAdmin): def get_list_display(self, request): return [a.name for a in self.model._meta.concrete_fields] -
crispy forms creating fields with id of other form
I am trying to add some JS to my password field, so I need its ID. I am getting error: It makes sense if I look into HTML with inspect. There are 2 identical password fields, but in my forms, I am adding ID to only one of them. Forms: class CustomUserSignUpForm(UserCreationForm): email = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Enter email'})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'placeholder': 'Enter password', 'id': 'password-input'})) class CustomUserLogInForm(forms.Form): email = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Enter email'})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'placeholder': 'Enter password'})) HTML: <!-- LOG IN FORM --> <div class="form-group log-in-form" id="log-in-form"> <button type="button" class="btn-close" id="close-log-in" aria-label="Close"></button> <form method="POST" action=""> {% csrf_token %} <h1>Log in</h1> {{ form.email|as_crispy_field }} {{ form.password1|as_crispy_field }} <input type="checkbox" name="remember">Remember me<br> <button type="submit" class="btn log-in-btn" id="log-in-btn">Log in</button> <p>Forgot password? <a href="#">Reset</a></p> </form> <a href="{% url 'sign_up' %}" class="btn sign-up-btn">Sign up</a> </div> {% block content %} {% endblock %} Other HTML (diffrent view, but I am inheriting template): {% block content %} <div class="form-group sign-up-form container-fluid"> <form method="POST" action=""> {% csrf_token %} <h1>Sign up</h1> {{ form.email|as_crispy_field }} {{ form.password1|as_crispy_field }} <input type="checkbox" id="show-password">Show Password<br> {{ form.nick|as_crispy_field }} <p id="sign-up-requirements">Password too short</p> <button type="submit" class="btn log-in-btn">Sign up</button> * required field </form> </div> {% endblock %} Now I am getting around the problem … -
Django makemigrations
I set two apps,when i migrate the first one, it's done perfectly,but when i migrate the second one ,there is something makes me confuse, the second database has the first app's table data,i just want to have the second app's data in the second database,how can i do? I set two apps,when i migrate the first one, it's done perfectly,but when i migrate the second one ,there is something makes me confuse, the second database has the first app's data,i just want to have the second app's data in the second database,how can i do? -
efficient way on excluding values from a database query based on timestamp
I'd like to select all instances of Link for Monitors which last_change affect a Shop. Condition: if there is a Shop linked, it cannot have a Customer linked and the other way around. Also each Monitor can only occur once with every theme. class Link(models.Model): customers = models.ManyToManyField(Customer, related_name = "%(class)s_name", related_query_name = "customer_link_qs", blank = True) shop = models.ForeignKey(Shop, on_delete = models.CASCADE, null = True, blank = True) theme = models.PositiveIntegerField("theme", default = 0, choices = [(0, 0), (1, 1)]) monitor = models.ForeignKey(Monitor, on_delete = models.CASCADE) last_change = models.DateTimeField("last change", auto_now = True) class Meta: unique_together = ["monitor", "theme"] My approach: from collections import defaultdict monitors_dict = defaultdict(list) for link in Link.objects.all() if link.monitor.store == "mystore": monitors_dict[link.monitor].append(link) last_links = [] for monitor in monitors_dict: monitor_links = monitor[1] ## list of all links for a monitor last_link = monitor_links.sort(key = lambda x: x.last_change)[-1] ## sort by last_change and take last one if last_link.shop != None: last_links.append(last_link) It feels "hacky" and I am looking for suggestions on how to make it smoother. -
How to separate user login session and admin login session in django
I have created small ecommerce website. User can register and login also created custom admin panel for admin which can product add, update and delete. User and Admin both URLS is different. problem is that when user login into website after I'm hit admin URLS is directly redirect to admin dashboard that I want to prevent. ** Here my panel app which can handle admin site link admin can add and update the product** def Login_Page(request): if request.user.is_authenticated: return redirect('dashboard') if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username = username) except: messages.error(request,'User Does Not Exist !') try: vendor_authe = User_login.objects.get(user_auth=user, is_vendor_user='y',is_customer_user='n') user = authenticate(request, username= username, password = password) if user is not None: login(request, user) return redirect('dashboard') else: messages.error(request,'Username and Password Does Not Match. !') except: messages.error(request,'User not Found !') else: pass context = { } return render(request,'panel/login.html',context) Here my base app view.py which can handle user side login # Create your views here. def User_Login_Page(request): if request.user.is_authenticated: return redirect('home') if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username = username) except: messages.error(request,'User Does Not Exist !') try: user_authe = User_login.objects.get(user_auth=user, is_vendor_user='n',is_customer_user='y') user = authenticate(request, username= username, password … -
efficient way on excluding values from a database query based on timestamp
I am monitoring campaigns on monitors and I try to select my linked pictures on the monitor based on the information if the last_change was made for a customer or a shop (can only be one or the other). class Link(models.Models): customer = ManyToManyField(Customer, related_name = "%(class)s_name", related_query_name = "customer_link_qs", blank = True) shop = models.ForeignKey(Shop, on_delete = models.CASCADE, null = True, blank = True) theme = PositiveIntegerField("theme", default = 0, choices = [(0, 0), (1, 1)]) last_change = models.DateTimeField("last_change", auto_now = True) monitor = models.ForeignKey(Monitor, on_delete = models.CASCADE) class Meta: default_permissions = () unique_together = ["monitor", "significance"] class Campaign(models.Model): store = models.ForeignKey(Store, on_delete = models.CASCADE) active = models.BooleanField("active", default = True) name = models.CharField("campaign name", max_length = 32) only_shops = models.BooleanField("only shops", default = False) only_customers = models.BooleanField("only customers", default = False) I have done it like this and it feels "hacky": from collections import defaultdict for CAMPAIGN in Campaign.objects.filter(active = True): MONITORS = Monitor.objects.filter(store = Campaign.store) MONITORS_DICT = defaultdict(list) for LINK in Link.objects.all(): if LINK.monitor in MONITORS: MONITORS_DICT [LINK.monitor].append(LINK) LAST_LINKS = [] for MONITOR in MONITORS_DICT: MONITOR_LINKS = MONITOR[1] ## contains a list of all links for this monitor LAST_LINK = MONITOR_LINKS.sort(key = lambda x: x.last_change)[-1] ## sorted … -
root - ERROR - post - 46 - Record creation failed: (1062, "Duplicate entry '23SNS0002' for key '' ")
from django.db import models from django.utils import timezone import datetime class Employee(models.Model): emp_id = models.CharField(editable=False,unique=True,max_length=10,default=None) def save(self,*args, **kwargs): if not self.emp_id: prefix2 = format(timezone.now().strftime('%y'))+'SNS' prev_instances = self.__class__.objects.filter(emp_id__contains=prefix2) if prev_instances.exists(): last_instance_id = prev_instances.last().emp_id[-4:] self.emp_id = prefix2+'{0:04d}'.format(int(last_instance_id)+1) self.email_id else: self.emp_id =prefix2+'{0:04d}'.format(1) self.emp_id super(Employee, self).save(*args, **kwargs) Performing system checks... System check identified no issues (0 silenced). March 04, 2023 - 12:37:39 Django version 4.1, using settings 'CRMSolutions.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [04/Mar/2023 12:37:45] "POST /employee/emp/ HTTP/1.1" 201 418 [04/Mar/2023 12:38:06] "POST /employee/emp/ HTTP/1.1" 201 416 2023-03-04 12:38:20,500 - root - ERROR - post - 46 - employee Record creation failed: (1062, "Duplicate entry '23SNS0002' for key 'employee_employee .emp_id'") Internal Server Error: /employee/emp/ 2023-03-04 12:38:20,500 - django.request - ERROR - log_response - 241 - Internal Server Error: /employee/emp/ [04/Mar/2023 12:38:20] "POST /employee/emp/ HTTP/1.1" 500 73 i want to generate employee id example: 23SNS0001,23SNSNS0002,23SNS0003.... and so on... as unique and should not form duplicate...emp_id. above shown my models create duplicate .... even if i set unique = True. i think i have to change my code in save function that i have used...can help with problem to solve -
How can I render Svelte output in a Django template?
I'm trying to render app.svelte in index.html. // app.svelte <script> let name = 'World'; </script> <h1>Hello {name}!</h1> <!-- Django template: base.html --> <!doctype html> <html lang='ko'> {% include 'partials/head.html' %} <body> {% block webpack_content %} {% endblock webpack_content %} </body> </html> <!-- Django template: index.html --> {% extends "base.html" %} {% load static %} {% load render_bundle from webpack_loader %} {% block webpack_content %} {% render_bundle "main" %} {% endblock %} My Django backend is serving index.html, but the page my web browser rendering is <body> <script src="/static/bundle/bundle.js"></script> </body> rather than <!-- my expectation --> <body> <h1>Hello World!</h1> </body> What am I missing in using webpack_loader in Django template? -
403 when post request is sent
Code: class ErrorReportView(View): def get(self, request, *args, **kwargs): return HttpResponse('Hello, World!') @csrf_exempt def post(self, request, *args, **kwargs): return HttpResponse('Hello, World!') **Error: ** The request will be sent from another site. The site is known. If I use a GET-request, it reqches the view. But if I use a POST-request, it returns 403. This is about error mistakes reports, so, the data will be saved to the database. So, POST is highly desirable here. Could you help me -
Django unions and temporary fields in serializers
I have a DjangoRest view that finds several QuerySets of a Model (Item), calculates a "rank" for each item, and then passes the final list to a serializer. My "rank" field is a temporary field added by the serializer. When I try something like the this: q_a = Item.objects.filter(some filter) q_b = Item.objects.filter(some other filter) q_c = Item.objects.filter(some other filter) for item in q_a: item['rank'] = 5 #fixed rank for item in q_b: item['rank'] = calulcateRank(type_b) #my function for item in q_c: item['rank'] = calculateRank(type_c) #my function final_q = q_a | q_b | q_c serializer = ItemSertializer(final_q, many=True) My rank field is lost by the serializer. However, if I do this: q_a = Item.objects.filter(some filter) q_b = Item.objects.filter(some other filter) q_c = Item.objects.filter(some other filter) final_q = q_a | q_b | q_c for item in final_q: item['rank'] = calulcateRank() # with type logic inside now serializer = ItemSertializer(final_q, many=True) It works fine. The second version is cleaner code and probably superior but I don't really understand what the issue is and would like to know. -
Not able to map Dictionary key to values in Django Jinja2
I am unable to map the dictionary key value to the value in the jinja template. below is the block where I was trying to map. so the variable(maji.u_priority) value is a numeric value and I want it to be displayed as P1, P2, etc. Pri = dict([ ("1", "P1"), ("2", "P2"), ("3", "P3"), ("0", "Code Red") ]) <td style="border: 1px solid #ddd; padding: 8px;">{{ maji.u_brandprodsvc_affected }}</td> <td style="border: 1px solid #ddd; padding: 8px;">{{ maji.u_technical_info|striptags }}</td> <td style="border: 1px solid #ddd; padding: 8px;">{{ maji.u_notification_status }}</td> <td style="border: 1px solid #ddd; padding: 8px;">{{ maji.u_priority }}</td> I was able to achieve same thing in Flask jinja template by doing {% for maji in maji %} <tr> <td style="border: 1px solid #ddd; padding: 8px;">{{ maji['u_incident_number.number']}}</td> <td style="border: 1px solid #ddd; padding: 8px;">{{ maji['u_notification_status'] }}-</td> <td style="border: 1px solid #ddd; padding: 8px;">{{ priority[maji['u_priority']] }}</td> <td style="border: 1px solid #ddd; padding: 8px;">{{ maji['u_restoration_info']|striptags }}</td> </tr> {% endfor %} -
Model in admin panels works, but not rendering on HTML page
I have already created a model for friend requests, but the page isn't rendering any requests. I manually added in a request in the admin panel but it's not showing up on my html page. Could anyone please tell me where my code is wrong? I originally had (receiver=current_profile) but kept running into the error 'Cannot query "admin": Must be "User" instance.' so i added .user to the end of it. Views.py def MyRequestsView(request): current_profile = FriendList.objects.get(user=request.user) my_requests = FriendRequest.objects.filter(receiver=current_profile.user) return render(request,'myrequests.html',{'my_requests':my_requests}) When I print(my_requests) & print(currentprofile), I get <QuerySet [<FriendRequest: Test2>]> & admin so my views.py works properly. Models.py """ Friend Request model """ class FriendRequest(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') def __str__(self): return self.sender.username Here's my script for my HTML page (i've tried multiple variations and nothing shows up) {% for request in my_requests %} <li>{{ request.sender.user }}</li> <li>{{ request.sender }}</li> {% endfor %} -
WebSocket closes without opening, error 1006
I'm working on a Django realtime chat app but for some reason I can not get my WebSocket to connect on chrome nor Firefox. I get the error message : room.js:43 WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/%22default%22/' failed: room.js:52 WebSocket ERROR room.js:57 connection closed. 1006 room.js:59 Reconnecting... my websocket: function connect(){ chatSocket = new WebSocket("ws://" + window.location.host + "/ws/chat/" + roomName + "/"); chatSocket.onopen = (event) => { console.log("SOCKET CONNECTED!!!!"); } chatSocket.onerror = (err) => { console.log("WebSocket ERROR"); //chatSocket.close(); } chatSocket.onclose = (event) => { console.log(" connection closed.", event.reason, event.code); setTimeout(() => { console.log("Reconnecting..."); connect(); }, 2000); }; chatSocket.onmessage = (event) => { const data = JSON.parse(event.data); console.log(data); if (data.type === "chat_message") { chatLog.value += data.message + "\n"; } else{ console.log("Wrong message type!"); } // scroll 'chatLog' to the bottom chatLog.scrollTop = chatLog.scrollHeight; }; console.log(chatSocket) } I had a similar problem with a different chat app earlier, script.js: const chatSocket = new WebSocket("ws://" + window.location.host + "/"); chatSocket.onopen = (e) => console.log("user connected successfully",e) chatSocket.onclose = (e) => console.log("user ejected from room", e) document.querySelector("#id_message_send_input").focus() document.querySelector("#id_message_send_input").onkeyup = (event) =>{ if (event.keycode == "13"){ document.querySelector("#id_message_send_button").click(); } } document.querySelector("#id_message_send_button").onclick = (event) =>{ const messageInput = document.querySelector("#id_message_send_input").value chatSocket.send(JSON.stringify({message: messageInput, username : request.user.username})) } chatSocket.onmessage = (event) … -
Django filter Two Models for ID
I am working on a Django Application where registered users can be added Deposit by staff users, and I want to know whether a user has been added Deposit in the current month. And also check in HTML on a Button url whether the user has a deposit or Not then decide how whether to display the Button. I have tried with the below but here is the error I am getting: Cannot use QuerySet for "Account": Use a QuerySet for "Profile". Here is my Models: class Account(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True) account_number = models.CharField(max_length=10, null=True) date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return f' {self.customer} - Account No: {self.account_number}' class Deposit(models.Model): customer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) transID = models.CharField(max_length=12, null=True) acct = models.CharField(max_length=6, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' Here is my View function: def create_account(request): customer = Account.objects.all() deposited_this_month = Deposit.objects.filter(customer__profile=customer, date__year=now.year, date__month=now.month).aggregate(deposited_this_month=Sum('deposit_amount')).get('deposited_this_month') or 0 context = { 'deposited_this_month ':deposited_this_month , } return render(request, 'dashboard/customers.html', context) In my HTML below is my code: {% if deposited_this_month %} <a class="btn btn-success btn-sm" href="{% url 'account-statement' customer.id %}">Statement</a> {% else %} … -
rant_category() got an unexpected keyword argument 'slug'
Running into an rant_category() got an unexpected keyword argument 'slug' on my django project. Basically, I just need to get the slug of the #category in my app to show it in the url. Here's my code: views.py class RantListView(ListView): model = Rant context_object_name = "rants" template_name = "rants/rant_list.html" class RantDetailView(DetailView): model = Rant template_name = "rants/rant_detail.html" models.py class Category(models.Model): title = models.CharField(max_length=50) slug = AutoSlugField(populate_from="title", slugify_function=to_slugify) class Meta: get_latest_by = "-date_added" verbose_name = _("Category") verbose_name_plural = _("Categories") def get_absolute_url(self): return reverse("rants:rant-category", kwargs={"slug": self.slug}) def __str__(self): return self.slug class Rant(BaseModel, models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.TextField(blank=False) slug = AutoSlugField(populate_from="post", slugify_function=to_slugify) categories = models.ManyToManyField(Category, related_name="rants") class Meta: get_latest_by = "-date_added" verbose_name = _("rant") verbose_name_plural = _("rants") def get_absolute_url(self): return reverse("rants:rant-detail", kwargs={"slug": self.slug}) def __str__(self): return self.slug html code {% for rant in rants %} {{ rant.post }} {% for category in rant.categories.all %} <a href="{% url 'rants:rant-category' category.slug %}">#{{ category.title }}</a> {% endfor %} {% endfor %} I'm getting an: TypeError at /rants/category/category 1/ rant_category() got an unexpected keyword argument 'slug' haven't coded in awhile so I based everything on my old tutorial https://github.com/reyesvicente/cookiecutter-blog-tutorial-learnetto but it seems to not be working Any help is appreciated -
When logging in to django server getting Forbidden (CSRF cookie not set.): /admin/login/
The website is live and its hosted on remote server(aws ec2) but when I try to login to the django admin its giving error. Error while login to django admin I have gone through previous SO post but they didn't help me to fix: https://stackoverflow.com/questions/29573163/django-admin-login-suddenly-demanding-csrf-token Django admin login returns Forbidden 403 CSRF verification failed. Request aborted settings.py IP_ADDRESS = "HERE_WILL_BE_THE_IP_ADDRESS" ALLOWED_HOSTS = [IP_ADDRESS, f"{IP_ADDRESS}:8000"] CSRF_TRUSTED_ORIGINS = [f"http://{IP_ADDRESS}:8000/", f"http://{IP_ADDRESS}/", "http://127.0.0.1/", "http://127.0.0.1:8000/", "http://*.127.0.0.1/"] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "users", "django.contrib.sites", "allauth", "allauth.account", "allauth.socialaccount", "allauth.socialaccount.providers.google", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "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", ] SECURE_REFERRER_POLICY = "no-referrer-when-downgrade" CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' # SMTP CONFIGURATION EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = PRO_SETTINGS["email_address"] EMAIL_HOST_PASSWORD = PRO_SETTINGS["email_pass"] LOGIN_URL = 'login' AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend' ] SOCIALACCOUNT_LOGIN_ON_GET = True SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', }, 'OAUTH_PKCE_ENABLED': True, } } The login to admin works totally fine in local machine but shows error when its on the deployed server. The website is live I can view the website but can't login to the django admin … -
'ChatForm' object has no attribute 'img'
I'm trying create image form field, but it gives an error and is not creating image form field. maybe I'm doing something wrong. It gets message. With messages I have no troubles. models.py from django.db import models def upload_to(instance, filename): return '{filename}'.format(filename=filename) class Chat(models.Model): username = models.CharField(max_length=255, blank=True, null=True) message = models.TextField() img = models.ImageField(upload_to=upload_to, null=True, blank=True) created_time = models.DateTimeField(auto_now_add=True) forms.py from django import forms from .models import Chat class ChatForm(forms.ModelForm): message = forms.CharField(widget=forms.TextInput(attrs={ 'class' : 'form-control', 'autofocus' : True })) img = forms.ImageField() class Meta: model = Chat fields = ['message', 'img'] views.py @login_required(login_url='/authentication/login/') def index(request): forms = ChatForm() if request.method == 'GET': chats = Chat.objects.all().order_by('-created_time') if request.user.groups.all()[0].name != 'superadmin': user = 'user' else : user = 'admin' context = { 'chats': chats, 'forms': forms, 'user' : user, } return render(request, 'chat/index.html', context) forms = ChatForm(request.POST) print(forms.img) if forms.is_valid(): message = forms.save(commit=False) message.username = request.user.username message.save() return redirect('chat:index') It must work, but doesn't create img field. template <form action="" method="post"> {% csrf_token %} <div> {{ forms.message.label }}: {{ forms.message }} </div> <div> {{ forms.img.label }}: {{ forms.img }} </div> <div class="d-flex justify-content-end mt-2"> <button class="btn btn-success" type="submit">Send</button> </div> </form>