Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I only query paginated data in django?
I have successfully paginated when returning all the objects but however, when I query the return for the searched result, it initially gets the correct pagination number of page. But clicking on any of the paginated searched result will immediately return the pagination of all the objects. My HTML pagination <ul class="pagination center" id="pagination" hx-swap-oob="true"> {% if data.has_previous %} <li class="waves-effect"> <a href="?page={{ data.previous_page_number }}"><i class="material-icons"><</i></a> </li> {% endif %} {% for page in data.paginator.page_range %} {% if page == data.number %} <li class="active purple lighten-2"><a href="?page={{ page }}">{{page}}</a></li> {% else %} <li class="waves-effect"><a href="?page={{ page }}">{{page}}</a></li> {% endif %} {% endfor %} {% if data.has_next %} <li class="waves-effect"> <a href="?page={{data.next_page_number}}"><i class="material-icons">></i></a> </li> {% endif %} </ul> paginate function and views.py, when i use AI, it shows me to change the html code, but i cannot understand it and i've spent hours to find something that mentions this very well and haven't found one def paginate(data, request): paginator = Paginator(data, 10) page_number = request.GET.get('page') data = paginator.get_page(page_number) return data def submission_portal(request): data = DataEntry.objects.all() data = paginate(data=data, request=request) text_count = DataEntry.objects.filter(category='text').count() image_url_count = DataEntry.objects.filter(category='image_url').count() context = { 'data': data, 'text_count': text_count, 'image_url_count': image_url_count } return render(request, 'submission_portal/submission_page.html', context=context) # Read … -
Django - Dictionary value set to returned as `None` in template but returns value in console
In my console I have this print: r_distance in context: {13: 7905.59} In my template, I get the following returned {13: None} , using: r_distance: {{ r_distance}} I dont understand what would turn the value to None in the my logic. views.py: for r in rps: if r.model_field: ref_v = rewardprogram.model_field if ref_v.latitude and ref_v.longitude and user_lat and user_lon: v_distance = distance.distance((user_lat, user_lon), (ref_v.latitude, ref_v.longitude)).km v_distance = round(v_distance, 2) r_distance[model.id] = v_distance # prints: {13: 7905.59} else: r_distance[model.id] = None context = { ... "r_distance": r_distance} } In my template: {% for r in rps%} <p>r_distance: {{ r_distance}}</p> # prints: {13: None} {% endfor %} Question: Considering r_distance is recognised in the template, it cannot be that the dictionaryy is not being passed to the template. The model object id is correct (13), why would the value not getting passed? -
It would be helpful if you explained the reason for using action in the search case?
Straightly, it works even if you don't give action to submit data on the login and registration pages. It would be helpful if you explained the reason for using action in the search case?? {% extends "base/index.html" %} {% load static %} {% block body %} <h1 class="display-4 text-center my-5">All Quizzes</h1> <div class="container"> <div class="d-flex"> <a href="{% url 'all_quizzes_view' %}" class="btn btn-light me-2">All Quiz</a> {% comment %} <a href="./all-quiz.html" class="btn btn-light me-2">English</a> {% endcomment %} {% for category in categories %} <a href="{% url 'cat_search' category.name %}" class="btn btn-sm btn-light m-1">{{category.name}}</a> {% endfor %} </div> </div> {% comment %} <form class="container d-flex my-4" role="search" method="get" action="{% url 'search' %}"> <input value="{{ query }}" name="q" class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button type="submit" class="btn btn-primary ms-2">Search</button> </form> {% endcomment %} <form class="container d-flex my-4" role="search" method="get"> <input type="search" name="q" class="form-control me-2" placeholder="Search quizzes..." value=" " aria-label="Search"> <button type="submit" class="btn btn-primary ms-2">Search</button> </form> <div class="container"> <div class="row row-cols-1 row-cols-sm-1 row-cols-md-2 row-cols-lg-3 g-3"> {% if quizzes|length > 0 %} {% comment %} {{ quizzes|length }}, here quizzes object all properties will be counted {% endcomment %} {% for quiz in quizzes %} <div class="col"> <div class="card shadow-sm"> <div class="card-body"> <h4> {{quiz.title}} </h4> <p class="card-text">Total … -
Auth.jsx:38 POST http://127.0.0.1:8000/api/register/ 404 (Not Found) - Django / React
I'm trying to implement an authentication system and stack on the register part When I submit the form data I get back this error: POST http://127.0.0.1:8000/api/register/ 404 (Not Found) Here is some of my code url.py from django.urls import path from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView from .views import RegisterView, LoginView, RefreshTokenView urlpatterns = [ path("api/register/", RegisterView.as_view(), name="register"), path("api/login/", LoginView.as_view(), name="login"), path("api/token/refresh/", RefreshTokenView.as_view(), name="token_refresh"), ] view.py class RegisterView(APIView): permissions_classes = [AllowAny] def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() return Response({"message": "User registered succefully"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) On the client side; I have a utility that creates the baseURl import axios from "axios"; const API = axios.create({ baseURL: "http://127.0.0.1:8000/api/", headers: { "Content-Type": "application/json", } }); export default API; And my handleSubmit function looks like this; const handleSubmit = async (e) => { e.preventDefault(); setError(""); // Clear previous errors try { const endpoint = isSignup ? "register/" : "login/"; const response = await API.post(endpoint, formData); if (isSignup) { alert("Registration successful!"); setIsSignup(false); // Switch to login form } else { // Store JWT tokens localStorage.setItem("accessToken", response.data.access); localStorage.setItem("refreshToken", response.data.refresh); localStorage.setItem("role", response.data.role); console.log("Login successful:", response.data); alert("Login successful!"); const roleRedirects = { "admin": "/admin-dashboard", "student": "/student-dashboard", "lecturer": "/lecturer-dashboard", "academic_registrar": "/registrar-dashboard" }; window.location.href … -
Django: "Product matching query does not exist" After Stripe Payment
I am building a Django e-commerce website where users: Add products to the cart (stored in session) Complete Stripe payment Place an order Problem: After the payment, Django throws this error: An error occurred: Product matching query does not exist. The error happens when retrieving the Product model from the cart session data. ** My Session Data (Before Payment)** I print the session data before payment, and it looks like this: { 'cart_data_obj': { '71_32': { # Key format: productID_size 'title': 'Iphone 16 Black', 'qty': 1, 'price': '160000.00', 'image': '/media/user_1/iphone_4.jpg', 'pid': '71', # Product ID 'size': '32', 'old_price': '240000.00' } }, 'total_cart_items': 1, '_auth_user_id': '1' } Here, pid correctly exists in the session. ** My Cart View (Where Users See Their Cart)** View Code: def cart_view(request): cart_total_amount = 0 sub_category = SubCategory.objects.all() categories = Category.objects.prefetch_related('subcategories').order_by('?')[:4] wishlist = wishlist_model.objects.filter(user=request.user) if request.user.is_authenticated else None nav_category = Category.objects.filter(special_category=True).prefetch_related('subcategories').order_by('?')[:4] if 'cart_data_obj' in request.session: print(" Cart Data:", request.session['cart_data_obj']) # Debugging for p_id, item in request.session['cart_data_obj'].items(): try: item_price = float(item['price']) except (ValueError, TypeError): item_price = 0 item_quantity = int(item['qty']) cart_total_amount += item_quantity * item_price print(" Total Amount Before Discount:", cart_total_amount) return render(request, "core/cart.html", { "data": request.session['cart_data_obj'], "cart_total_amount": cart_total_amount, "sub_category": sub_category, "categories": categories, "w": wishlist, "nav_category": nav_category, … -
How can users modify cart prices using Burp Suite, and why is this a security risk in Django?
I recently discovered a serious security issue in Django e-commerce websites where users can modify product prices before adding items to the cart. Many developers allow users to send price data from the frontend, which can be easily tampered with using Burp Suite or browser developer tools. Example of the Issue: Consider a simple Django view that adds items to the cart: def add_item(request): product_id = request.GET.get('product_id') price = request.GET.get('price') # User-controlled value (security risk) qty = int(request.GET.get('qty', 1)) cart_item = { 'product_id': product_id, 'qty': qty, 'price': price, # This price comes from the user, not the database! } request.session['cart'] = request.session.get('cart', {}) request.session['cart'][product_id] = cart_item request.session.modified = True return JsonResponse({'message': 'Added to cart'}) How an Attacker Can Exploit This: A product costs $500 in the database. The user clicks "Add to Cart". Instead of sending the original price, the attacker intercepts the request using Burp Suite. The price field is changed to $1, and the request is forwarded. The cart now stores the manipulated price, and the user can proceed to checkout with the wrong amount. Why Is This a Security Risk? The backend trusts data from the frontend, which can be easily manipulated. The session stores the wrong … -
Django - ValueError at /selected-events/ Cannot assign ... must be a "Profile" instance
I have a Django project that consists of, essentially, 3 datasets: auth User (plus a Profile dataset), mem_ev and Events such that User --< mem_ev >-- Event, ie a classic many to many relationship such that members can go to many events and an event can be visited by many members. I want to update the mem_ev dataset with the 'events to be attended' selected by a member, but it's not working. my models.py file is: from django.db import models from django.utils.text import slugify from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Delete profile when user is deleted event_count = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' #show how we want it to be displayed class Event(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50,default="", null=False) description = models.TextField() cost = models.DecimalField(max_digits = 5, decimal_places = 2, default = 0.0) event_date = models.DateTimeField(null=True,blank=True) attendees = models.IntegerField(default=0) class Meta: ordering = ['event_date'] def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Event, self).save(*args, **kwargs) class Meta: ordering = ['event_date'] def __str__(self): return self.title class mem_ev(models.Model): member_id = models.ForeignKey("Profile",on_delete=models.CASCADE) event_id = models.ForeignKey("Event",on_delete=models.CASCADE) is_attending = models.BooleanField(default=False) amt_paid = models.DecimalField(max_digits = 5, decimal_places = 2, default = 0.0) date_paid = models.DateTimeField(null=True,blank=True) The relevant part of my … -
Django's SQL query has repeated subquery when using filters with annotations and subqueries
I have Camp Model that stores dates as an array of strings in a Json field. I'm trying to optimize a database query to retrieve Camp objects with future dates. class Camp(models.Model): dates = models.JSONField(default=None, blank=True, null=True, validators= [datesListValidator]) I'm using annotations and subqueries to filter out instances of that model where none of the dates are equal to or greater than the current date (basically I only want camps that have a date in the future). I'm using annotations and Subqueries to get the "max_date" from the dates for each camp and then filtering the camps based on the "max_date" I'm trying to optimize this filtering process, as getting all the camps and then filtering it in Python is too slow for my use case and as more time goes on the number of Camps that have to be filtered out would just keep increasing. The solution i came up with gives me the results I need, but the generated SQL query has multiple runs of the same subquery which I don't need. I'd like to avoid doing this using RawSQL and would like to find a way to achieve my desired result using the django ORM functions. I'm … -
How do I fix django.db.utils.OperationalError: no such table: when migrations don’t work?
Good day everyone, I’m a new intern and I’m trying to learn Django. I was tasked with looking over this new branch of the project that was recently updated. I downloaded a zip file from the github and I used this command python manage.py runserver then I got this error message django.db.utils.OperationalError: no such table: streaming_data_streaminginfo I tried using this command python manage.py makemigrations streaming_data but I’m still getting the same error. I tried python manage.py showmigrations and got the exact same error. Another possible solution is to delete and recreate the database but I don’t want to mess with the database. My supervisor told me to make a super user and connect on the admin page with my login credentials and go look at the tables. When I used python manage.py createsuperuser I got the django.db.utils.OperationalError: no such table: streaming_data_streaminginfo error again. So, I went to an older branch and opened the admin page, but I didn’t see the tables. Here's the complete error message PS C:\Users\OneDrive\Documents\music_data-map> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\OneDrive\Documents\music_data-map\venv\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^ File … -
Getting 401 when attempting to signup or login in django allauth react-spa example
I am very new to using to Django-allauth, I'm wanting to integrate it with my Django backend. I was trying to use the react-spa example outlined in the docs https://react.demo.allauth.org/, but I 401 error when sending either a signup or login request. Why is this happening? The response looks like: { "status": 401, "data": { "flows": [ { "id": "login" }, { "id": "login_by_code" }, { "id": "signup" }, { "id": "provider_redirect", "providers": [ "dummy" ] }, { "id": "provider_token", "providers": [ "dummy" ] }, { "id": "mfa_login_webauthn" }, { "id": "verify_email", "is_pending": true } ] }, "meta": { "is_authenticated": false } } I understand that the flows array indicates those are the methods to authenticate. But how can I authenticate if the login / signup method preventing me from doing so? Steps to repro: I ran this example locally, cloned it here https://codeberg.org/allauth/django-allauth/src/branch/main/examples/react-spa Ran docker compose up Visit localhost:10000, when to signup - entered email and password + password confirmation. Request was successful and I was redirected to the enter email confirmation code screen I didn't input the code in step 3. Instead, went back to signup page to enter my actual email to get the code and input … -
Run EXE software using App in Windows IIS
I hosted my Django app on Windows IIS in Windows Server 2022 Standard But my application has a feature that opens software (.exe) and run specific user tasks provided in the request of the site. For example, a user provides some input from my site, and then it processes it with my app by opening software using python code in views.py script_path = "C:\inetpub\wwwroot\webapp\script\runthescript.py" subprocess.run(["C:/Program Files/My Soft/Soft.exe", "-runScriptFile", script_path]) MY PROBLEM When I tested my application locally using python manage.py runserver it was working due to admin privileges and session 1 access, but the same when I tried after hosting with IIS then everything working except software to start. WHAT I TRIED: I tried providing my AppPool Identity as (IIS APPPOOL\webapp) Administrator privileges. Tried using Task Scheduler, but it works with the background process but not with the GUI app. ISSUE When I googled it, I found that it is due to privileges and session 0 access. IIS has only session 0 isolation so that it is unable to access GUI. Your small help, idea or suggestion definitely be helpful for me. :) -
Pass value from one Django template to other
I want to build a Django template hierarchy like so: root.html |_ root-dashboard.html |_ root-regular.html root.html shall have an if statement: {% if style == "dashboard" %} {# render some elements in a certain way #} {% else %} {# render those elements in a different way #} {% endif %} And root-dashboard.html and root-regular.html should individually extend root.html by setting style: # root-dashboard.html {% extend 'root.html' with style='dashboard'%} # root-regular.html {% extend 'root.html' with style='regular'%} (with above is not an actual valid syntax, its just something similar I want) And a view can use either root-dashboard.html or root-regular.html to show the content in one style or the other. How do I achieve this without the view having to set the style context? -
How to handle authentication and AUTH_USER_MODEL in Django multi-tenant with separate databases?
I’m developing a multi-tenant SaaS application using Django, where each tenant has its own separate database with its own schema and relationships. However, I'm struggling with how to properly manage authentication and define AUTH_USER_MODEL in this environment. 📌 System Requirements Global superadmins that manage the system and are stored in the public database (public). Tenant users, who exist in their respective tenant database and have relationships with other tables inside their own database. Separate authentication: Superadmins should authenticate in the public database. Tenant users should authenticate within their specific tenant database. The main problem is that Django allows only one AUTH_USER_MODEL, but I need to manage users separately for each tenant while maintaining the ability to associate them with other tables within their respective databases. ❌ Current Issue If I define a single user model in AUTH_USER_MODEL, I cannot differentiate between global superadmins and tenant users, nor can I correctly manage relationships within each database. I tried defining two different user models, but Django does not allow multiple AUTH_USER_MODEL, which complicates authentication. ✅ Possible Solution I thought of defining a base model BaseUser that extends AbstractUser, and then creating two inherited models. But I am not sure which is the … -
I am trying to run uwsg-emporer vassal and it can't find my python
When I create a uwsgi vassal ini file, the server throws this error when I hit the site: --- no python application found, check your startup logs for errors --- The virtualenv is correct and if I do python manage.py check I do not have errors and python manage.py runserver runs a dev version fine. I first source in my venv so I know python is installed in the Virtual Envelope at this path: /var/www/webapps/lhhs/env this is my .ini file [uwsgi] uid = www-data socket = /var/www/webapps/lhhs/lhhs.sock chown-socket = %(uid):www-data chmod-socket = 660 chdir = /var/www/webapps/lhhs/ virtualenv = /var/www/webapps/lhhs/env binary-path = /var/www/webapps/lhhs/env/bin/uwsgi modue = lhhs.wsgi:application wsgi-file = lhhs/wsgi.py env = DJANGO_SETTINGS_MODULE=lhhs.settings.dev module = django.core.handlers.wsgi:WSGIHandler() stats = 127.0.0.1:9191 vacuum = true processes = 1 threads = 1 plugins = python3,logfile logger = file:/var/www/webapps/lhhs/log/uwsgi.log -
request.method == POST equaling true in next function causing it to run prematurely
so i am running this code def login_or_join(request): if request.method == "POST": option = request.POST.get("option") print('post request recieved') if option == "1": return login_screen(request) if option == '2': return in_game(request) return render(request,"login_or_join.html") and def login_screen() looks like this def login_screen(request): if request.method == "POST": username = request.POST.get("username") password = request.POSt.get("password") print(username) print(password) user = authenticate(request, username=username, password=password) print(user) if user is not None: return redirect('join_lobby') else: return render('login_page.html', {'error': 'Invalid login credentials' }) return render(request, 'login_page.html') Whenever I click "option 1" it runs login_screen but in a way I don't want it to. it seems to just follow that request.method == "POST" and prints username and password immediately, meaning it is setting username and password immediately making any log in attempt wrong. But I don't want it to set those (or print them) until I've pressed the button on the next page. Further more when I hit "enter" or "log in" it doesn't reshow the page with the error message, it just goes back login_or_join(). I feel like I am taking crazy pills as I've been working on this website for a while and this is the first time I'm having this kind of issue. I've tried messing with it … -
Django syntax highlighting/intellisense not working for undefined class methods
I'm working in a python/django repo and I'm having an issue where unknown methods are not being highlighted by VSCode with a red error squiggly line. As you can see from the screenshot, I have it setup to show python errors, but the non-existent method on the test_email class doesn't throw any errors or warnings. I have Black Formatter, isort, Pylance, Python, Pylint, Python Debugger extensions installed. The correct python interpreter + environment are setup and the python language server is also running. I'm happy to include any other information, but didn't want to dump unneeded info. Any insight, help or guidance is greatly appreciated! -
I am confused....whether Mern is better or django....and which is more in use in companies? [closed]
please tell me which one is better MERN or Django and what is more prefferd in companies these days? -
Raspberry Pi based POS: what do you think?
I have finished a simple but hopefully complete and useful Order Management and POS System built on a RaspBerry Pi based on Django and a Apache web server. I know it is perhaps too ambitious to call it "POS", given its simplicity. Anyhow, please feel free to take a look and provide your feedbacks: https://github.com/simOrderS/simOrder -
Account creation and authentication using Django
I'm hitting a wall with this code. I am able to create a user and store the data. I can see the user in django admin panel. When I try logging into that user, I get a failure message. Ive tried changing the password in the django-admin panel. That did not work either. Here is my code. login.html {% extends "users/base.html" %} {% block title %} Login Page {% endblock title %} {% block content %} <div class="container"> <div class="row justify-content-center align-items-center" style="min-height: 100vh;"> <div class="col-lg-5"> <div class="card shadow-lg border-0 rounded-lg"> <div class="card-body"> <h3 class="font-weight-light my-1 text-center">Sign In</h3> {% if form.errors %} <div class="alert alert-danger alert-dismissible" role="alert"> <div id="form_errors"> {% for key, value in form.errors.items %} <strong>{{ value }}</strong> {% endfor %} </div> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endif %} <form method="POST"> {% csrf_token %} <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group"> <label class="small mb-1">Username</label> {{ form.username }} </div> </div> </div> <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group"> <label class="small mb-1">Password</label> {{ form.password }} </div> </div> </div> <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group"> {{ form.remember_me }} <label> Remember me</label> </div> </div> </div> <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group mt-0 mb-1"> <button name="login" class="col-md-12 … -
How to Enable Web Push Notification Permissions on iOS for a Django Web App?
I am building a Django web app for status checking and need real-time background updates using the Web Push API. The web app will be accessed on both Android and iOS devices. To enable push notifications, I am using the Notification API to request user permission. The implementation works on Windows, Linux, Android, and Mac, but it does not work on iOS. However, I do not want to convert my web app into a Progressive Web App (PWA). I need guidance on how to request notification permissions on iOS and ensure web push notifications function correctly. Can someone help me find a solution to complete my project? Current Implementation I am using the following JavaScript code to request notification permissions from users: document.getElementById('grant-permission').addEventListener('click', ()=> { Notification.requestPermission().then(permission => { console.log("permission:", permission); if (permission === "granted") { console.log("Notifications allowed!"); } else { console.log("Notifications denied!"); } }); }); Issue This code works as expected on Windows, Linux, Android, and Mac. However, on iOS (Safari), it does not work. The permission prompt does not appear, and notifications are not allowed. What I Have Tried Tested on different browsers (Safari, Chrome) on iOS. Confirmed that Web Push API only works for installed PWAs on iOS. … -
I've been working on buildings a password reset system on my django site
I intend on also using a similar system for account creation confirmation but i am unable to test the system at the moment as i am having issues with my mailgun account def password_reset_request(request): if request.method == 'POST': email = request.POST.get('email') try: user = get_user_model().objects.get(email=email) # Generate reset token and expiry profile, created = UserProfile.objects.get_or_create(user=user) profile.generate_reset_token() # Prepare the email context with the reset token context = { 'user': user, 'reset_token': profile.reset_token, # Send the reset token in the email } # Render email templates email_html = render_to_string('password_reset_email.html', context) email_plain = strip_tags(email_html) # Mailgun API setup mailgun_url = f"https://api.mailgun.net/v4/{MAILGUN_DOMAIN_NAME}/messages" mailgun_auth = ("api", MAILGUN_API_KEY) mailgun_data = { "from":DEFAULT_FROM_EMAIL, "to": user.email, "subject": "Password Reset Request", "text": email_plain, "html": email_html } # Send email via Mailgun API try: response = requests.post(mailgun_url, auth=mailgun_auth, data=mailgun_data, verify=False) if response.status_code == 200: messages.success(request, "A password reset token has been sent to your email.") else: messages.warning(request, "Password reset requested, but there was an issue sending the email.") except requests.exceptions.RequestException as e: messages.warning(request, f"Password reset requested, but we couldn't send the email: {str(e)}") return redirect('password_reset_verify') except get_user_model().DoesNotExist: messages.error(request, "Email address not found.") return render(request, 'password_reset_request.html') def password_reset_verify(request): if request.method == 'POST': token = request.POST.get('token') # Assuming the user inputs … -
Error: { "detail": "Authentication credentials were not provided." }
Hello community enter image description here I have a problem: When i want to get into information in postman, This sends me the next error: "detail": "Authentication credentials were not provided." Attach: The code in Django Settings.py in (A) that shows the REST_FRAMEWORK REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'authentication.customJWTAuthentication.CustomJWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } Views.py in (B1 and B2) that indicates the code POST from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework import status from roles.models import Role from roles.serializers import RoleSerializer from users.models import User, UserHasRoles from users.serializers import UserSerializer import bcrypt from rest_framework_simplejwt.tokens import RefreshToken from rest_framework.permissions import AllowAny from django.conf import settings` Create your views here. GET -> OBTENER POST -> CREAR PUT -> ACTUALIZAR DELETE -> BORRAR 200 RESPUESTAS EXITOSAS 400 O 500 ERRORES` @api_view(['POST']) @permission_classes([AllowAny]) def register(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() client_role = get_object_or_404(Role, id='CLIENT') UserHasRoles.objects.create(id_user=user, id_rol=client_role) roles = Role.objects.filter(userhasroles__id_user=user) roles_serializer = RoleSerializer(roles, many=True) response_data = { **serializer.data, 'roles': roles_serializer.data } return Response(response_data, status=status.HTTP_201_CREATED) error_messages = [] for field, errors in serializer.errors.items(): for error in errors: error_messages.append(f"{field}: {error}") error_response = { "message": error_messages, "statusCode": status.HTTP_400_BAD_REQUEST } return Response(error_response, status=status.HTTP_400_BAD_REQUEST) def getCustomTokenForUser(user): refresh_token = … -
Django ignores urlpatterns
I have created a very basic urlpattern but it is ignored. def hallo(request): return JsonResponse("Hallo", safe=False) urlpatterns = [ # path('admin/', admin.site.urls), # path('admin/', JsonResponse("Hallo", safe=False) ), path("", hallo), path("hallo/", hallo) ] It will always be shown the "standard" page instead of "hallo", and even the admin page. And the page hallo cannot be found. I stopped the server and run it with different ports but there is always the same behaviour. -
I keep getting this issue Invalid block tag on line 5: 'static', expected 'endblock'. Did you forget to register or load this tag?
<!-- about.html --> 1 {% extends 'book/base.html' %} 2 3 {% block title %} About {% endblock %} 4 {% block extra_head %} 5 <link rel="stylesheet" href="{% static 'css/style.css' %}"> 6 {% endblock %} 7 {% block header %} 8 <h1> About Me </h1> 9 {% endblock %} 10 {% block main %} 11 <article> 12 <section> <p>My name is Uyiosasere Idemudia Oduware</p> 13 </section> 14 </article> 15 {% endblock %} base.html {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %} Uyi's Page {% endblock %}</title> {% block extra_head %} {% endblock %} </head> <body> <header> {% block header %} {% endblock %} </header> <main> {% block main %} {% endblock %} </main> <footer> {% block footer %} {% endblock %} </footer> </body> </html> my css file is inside LearnSphere/book/static/css/style.css the base.html and about.html file is inside Learnsphere/book/templates/book/base.html about.html -
django mongo db conection - All auth - Social account extra field error
raise ValueError( ValueError: Cannot alter field socialaccount.SocialAccount.extra_data into socialaccount.SocialAccount.extra_data - they do not properly define db_type (are you using a badly-written custom field?) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) address = models.CharField(max_length=255) profile_picture = models.ImageField(upload_to='account/profilepicture/', blank=True, null=True) mobile_number = models.CharField(max_length=15, blank=True, null=True) def __str__(self): return f"{self.user.username}'s Profile"