Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access django model using JS?
I'm trying to create a e-commerce app and I'm trying to block users not to request more items than in stock. Therefore, I wanted to add some JS to control user. However, although I tried to use answers from other posts, I failed. In my HTML file, I'm sending products and I'm displaying properties of each product using for loop: HTML source code: <main class="pt-5"> <div class="row g-3"> <div class="col-md-5 col-lg-5 order-md-first bg-light"> <div class="mainImage"> <img class="img-fluid mx-auto d-block" alt="Responsive image" src="{{ product.image.url }}"> </div> <ul class="thumb"> <li> <a href="{{ product.image.url }}" target="mainImage"><img src="{{ product.image.url }}" alt="Product Image"></a> {% for im in product_gallery %} <a href="{{ im.image.url }}" target="mainImage"><img src="{{ im.image.url }}" alt="Product Image"></a> {% endfor %} </li> </ul> </div> <div class=" col-md-7 col-lg-7 ps-md-3 ps-lg-5"> <h1 class="mb-0 h4"> {{ product.title }} </h1> <strong> {{ product.brand }} </strong> <hr> <br> <p> {{ product.description }} </p> <div class="border"> <div class="col border-bottom"> <div class="row p-3"> <div class="col-6"> Price </div> <div class="col-6 text-end"><span class="h4 fw-bold">$ {{ product.price }} </span></div> </div> </div> {% if product.stock_qty >= 1%} <div class="col"> <div class="row p-3"> <div class="col-6"> <button type="button" id="qty-decrease-button" class="btn btn-primary btn-sm"> - </button> &nbsp; <label id = "qty-show" for="select" value="{{ product.id }}">1</label> &nbsp; <button type="button" … -
What is the difference between CsrfViewMiddleware and enforce_csrf?
I am trying to apply CSRF token in Django. I am applying csrf token using middleware and custom authentication. But I think I'm doing the same process twice. Because the value of csrf_token from cookie and response is different. Is it okay to apply+check csrf token by middleware only? MiddleWare settings.py CSRF_COOKIE_SECURE = True # CSRF cookie enabled only Https server CSRF_COOKIE_HTTPONLY = True # CSRF stored in http only cookie CSRF_TESTED_ORIGINS = [ "http://localhost:8000" ] CSRF_COOKIE_SAMESITE = "Lax" # Samesite "Lax" - Protection against csrf attacks MIDDLEWARE = [ ... 'django.middleware.csrf.CsrfViewMiddleware' ] enforce csrf during authentication authenticate.py (I have set CustomAuthentication as DEFAULT_AUTHENTICATION_CLASSES) from rest_framework_simplejwt import authentication as jwt_authentication from django.conf import settings from rest_framework import authentication, exceptions as rest_exceptions def enforce_csrf(request): check = authentication.CSRFCheck(request) reason = check.process_view(request, None, (), {}) print(check, reason) print(request.META) if reason: raise rest_exceptions.PermissionDenied('CSRF Failed: %s' % reason) class CustomAuthentication(jwt_authentication.JWTAuthentication): def authenticate(self, request): header = self.get_header(request) if header is None: raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE']) or None else: raw_token = self.get_raw_token(header) if raw_token is None: return None validated_token = self.get_validated_token(raw_token) enforce_csrf(request) return self.get_user(validated_token), validated_token loginView response["X-CSRFToken"] = request.COOKIES.get("csrftoken") You can check the django csrf documentation here. django documentation -
What is Indentation in Python Programming?
Indentation In Python I want to know how Indentation works? And I want to know how to write code using right indentation. -
Django: sending a POST request with Javascript, but then displaying an updated page rather than the old one
I have an input that fires a onclick calling a javascript function in my main template: <div class="removeTagElementChildDiv"> {% csrf_token %} <input type="image" name="deleteTagImage" class="deleteTagImage" src="{% static 'images/deleteTag.png' %}" width = "10" height = "10" onclick="return removeTag(this.parentElement)"> </div> This calls this method: function removeTag(removeSymbolDivForTagToRemove) { tagElement = removeSymbolDivForTagToRemove.parentElement tagValue = tagElement.querySelector('button[name="tagInTagsMenu"]').value console.log(tagValue) if (window.confirm(`Are you sure you want to delete the, ${tagValue}, tag`)) { return test(tagValue) } } Where the test method makes a POST request to one of my specified urls in urls.py: function test(tagValue) { var csrftoken = getCookie('csrftoken') fetch('deleteTag', { method: 'POST', action: 'deleteTag', headers: { "X-Requested-With": "XMLHttpRequest", "X-CSRFToken": csrftoken, }, body: tagValue }) } This method deletes the specific tag from the post request, and redirects to the main page: def deleteTag(request): tagName = request.body.decode('utf-8') Tag.objects.filter(name=tagName).delete() tagsFromModel = Tag.objects.all() for tag in tags: if util.findTagByTagName(tag.name,tagsFromModel) == None: #if the tag from the original list is not in the model, it has been deleted tags.remove(tag) loadTagsFromModel() print("end of delete tag method") return(redirect("/")) def main(request): now = datetime.now() time = now.strftime("%H:%M:%S") loadTagsFromModel() context = {'myTags':tags,'time':time} print("tags in main",len(tags)) #problemet er, at den stadig displayer den gamle index.html når man sletter et tag return render(request, 'index.html',context) All this works … -
Getting HttpResponseNotFound in Django test get method
I am building a test case for an endpoint. Visiting the endpoint in the local development using the browser works fine -- I get the expected response. However, during the test, I get an HttpResponseNotFound in which the endpoint is not found on the server. #views.py class ExampleView(APIView): permission_classes = (permissions.AllowAny,) def get(self, request): print('GOT HERE') qs = Example.objects.last() if self.request.user.is_authenticated: if self.request.user.is_subscribed: message = { 'info': 'User can download template.', 'template': qs.file.url } return Response(message, status.HTTP_200_OK) message = { 'info': 'User cannot download template.', 'template': None } return Response(message, status.HTTP_400_BAD_REQUEST) In my urls.py #urls.py urlpatterns = [ path('admin/', admin.site.urls), path('request/download_template', ExampleView.as_view()), ] My test build class TestExample(APITestCase): fixtures = ['fixtures/initial', 'fixtures/auth', 'fixtures/example'] def test_forecast_template_authenticated(self): response = self.client.get( '/request/download_template/') print('result', response) self.assertEqual(response.status_code, status.HTTP_200_OK) The response <HttpResponseNotFound status_code=404, "text/html; charset=utf-8"> I am trying to debug but I do not even reach the print statement I have in my view. I have been figuring out where could be my mistake but its been hours. Why am I getting that response? Where could be my mistake? -
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 %}