Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + Cloud Firestore CRED not working - FileNotFoundError: [Errno 2] No such file or directory // NameError: name 'database' is not defined
Anyone familiar with Django and Firestore? I would highly appreciate help. I'm troubleshooting an Error for hours and I guess I'm not able to fix it. It somehow can't find my cred Certificate altough its 100% located at the given path. XXX = censored firebase=pyrebase.initialize_app(config) authe = firebase.auth() cred = credentials.Certificate("G:\Python Programme\Keys\XXX.json") firebase_admin.initialize_app(cred, {"https://XXX-default-rtdb.europe-west1.firebasedatabase.app"}) database = firestore.client() Now the Error is: FileNotFoundError: [Errno 2] No such file or directory: 'G:\Python Programme\Keys\XXX.json' Now, the weird thing is if I create a try except to see the actual error it works without an Error but I do get a Problem when actually writing into the db: try: cred = credentials.Certificate("G:\Python Programme\Keys\XXX.json") firebase_admin.initialize_app(cred, {"https://XXX-default-rtdb.europe-west1.firebasedatabase.app"}) database = firestore.client() except BaseException as e: print("Error ist: ") print(e) NameError: name 'database' is not defined Django View: def postSignUp(request): name = request.POST.get('name') email = request.POST.get('email') passw = request.POST.get('pass') try: user=authe.create_user_with_email_and_password(email,passw) except: message="User exists already - please sign in." return render(request, "signUp.html", {"messg":message}) isBusinessClient=False uid = user['localId'] data = {"name":name, "email":email, "isBusinessClient": isBusinessClient,} #database.child("users").child(uid).child("details").set(data) alter Code doc_ref=database.collection('User').document() doc_ref.set(data) return render(request, "welcome.html", {"e":email}) I was expecting an Error when using try except. I was expecting the view to acutally write into the firestore cloud. -
Unable to open the remote html file in JetBrains client
I'm using JetBrains Client 2023.3 RC. I have django html templates in my project. When I try to open them, the JetBrains client displays the message "Unable to open the remote file". Other files open without problems. enter image description here I have to open these html files in other editors, but sometimes I need to debug them. I don’t know if this is important or not, but for remote development I use WSL, which has Ubuntu 22.04 installed. -
how to solve this page isnt working now in django
i am doing a project in django,and im half way there with login page. and when i run my server and route to logout/ page, the pageenter image description here isnt working[enterenter image description here image description here](https://i.stack.imgur.com/zRQ7z.png) im stuck here for a day with this -
why tests.py Task matching query does not exist?
ERROR: test_task_check_success (tasks.tests.TaskCheckTestCase.test_task_check_success) Traceback (most recent call last): File "C:\Users\gns03\OneDrive\바탕 화면\사전과제\tasks\tests.py", line 119, in test_task_check_success response = self.client.get(self.url, params=self.data1, **header, format='json') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 289, in get response = super().get(path, data=data, **extra) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 206, in get return self.generic('GET', path, **r) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 234, in generic return super().generic( ^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\test\client.py", line 609, in generic return self.request(**r) ^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 286, in request return super().request(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 238, in request request = super().request(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\test\client.py", line 891, in request self.check_exception(response) File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\test\client.py", line 738, in check_exception raise exc_value File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\OneDrive\바탕 화면\사전과제\tasks\views.py", line 69, in get task_instance = Task.objects.get(id=request.data.get('task')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File … -
Firebase settings match fcm-django and android app
I try implement push notifications from drf. I did everything with fcm-djabgo documentations and add firebase settings to my project, call test notification from django admin, but still got fell sending: A message failed to send. 1 device was marked as inactive. Is android token enough? Or I have to add some firebase settings to add permissions for notifications to android app? I could not find any information -
Connect multiple Django web applications to a single MySQL database
In order to save costs (I have limited funds at the moment), I hope to connect multiple Django web applications (or one or two with Flask) up to a single MySQL database online. Is this possible? Will it cause problems with the "sessions" tables? Will I need to add additional code to distinguish different applications? -
Django ArrayAgg is returning values in sorted order don't want reordering
So I'm using Django's ArrayAgg, to get array of. Consider below example: Likes = Posts.objects.all().annotate(like_id = ArrayAgg('like__id', distinct=True), like_name = ArrayAgg('like__name', distinct=True) Now, because it is sorting ArrayAgg, hence when I'm trying to match like_id with like_name, its mismatching because both like_id and like_name are returned as sorted by Django. How to tell Django to not sort them. Please help! -
Django operational error. Server gone away
I had been facing this error that prompted, "Operational Error: Server gone away", in my djago project. This happended when I submitted the django user creation form. I used the connection.close method from django.db and the problem got resolved. I rewrote the registerview class as follows. class registerView(CreateView): form_class = UserCreationForm template_name = 'register.html' def get(self, request: HttpRequest, *args: str, **kwargs: Any) -> HttpResponse: if (self.request.user.is_authenticated): return redirect('home') return super().get(request, *args, **kwargs) def get_success_url(self) -> str: return '/login' def post(self, request: HttpRequest, *args: str, **kwargs: Any) -> HttpResponse: try: connection.connection.ping() return super().post(request, *args, **kwargs) except Exception: connection.close() return super().post(request, *args, **kwargs) The problem is solved but I don't understand why this is happening. The connection.close() method is meant to close the connection. -
Best place to control permissions logic in app using django and postgresql
I am building an app which allows users to create tables and set permissions for other users on each column (if required). The tables need to be auditable so that users can interrogate: who made changes; when; and what they were - this is to support a diffing feature. Users will also be able to add columns to tables, and I am hoping to be able to automate all of this: creation of the table, permissions for columns, altering table to add new columns, creating triggers etc. I am in the process of setting up the audit table automation with trigger functions. I started writing the permissions logic into the trigger functions but stopped when my approach started to get hacky: using hstore to loop over column headers (https://dbfiddle.uk/sRJf7ZBm); storing inserts in a string (https://dbfiddle.uk/gE5bqKWe) to be added if the user has permission for every column - I'm also concerned what impact this will have on types (I have other types besides text); I couldn't work out how to use transactions to commit or rollback if an error occurred, apparently this is only possible in procedures? I know that postgres has the ability to set user permissions for tables by … -
Filter based off of user specific variable in order to do a stats page per tracked object
So, I am trying to filter based on 3 conditions. While I can filter on the two known quantities (the user logged in and if the outcome is a win), I have difficulty filtering on the last condition, which is user-specific information. I know it has to be a simple fix. It's something that probably has to do with the deck's object number, but I can't figure out how to reference those. Image of what I would like to be shown but with the correct numbers views.py def stats(request): deck_list = Deck.objects.filter(user=request.user) total_games = Game.objects.filter(user=request.user) total_wins = Game.objects.filter(user=request.user, outcome='Win') # WHERE I AM ATTEMPTING TO GET THE DATA deck_wins = Game.objects.filter(user=request.user, outcome='Win', ) user = User.objects.get(username=request.user) context = {'deck_list': deck_list, 'user': user, 'total_wins': total_wins, 'total_games': total_games, 'deck_wins': deck_wins, } return render(request, 'gametracker_app/stats.html', context=context) models.py class Deck(models.Model): deck = models.CharField(max_length=150) is_cedh = models.BooleanField(default=False) user = models.ForeignKey(User, max_length=10, on_delete=models.CASCADE, null=True) def __str__(self): return self.deck class Game(models.Model): user = models.ForeignKey(User, max_length=10, on_delete=models.CASCADE, null=True) deck = models.ForeignKey(Deck, on_delete=models.CASCADE, null=True) wincon = models.ForeignKey(Wincon, on_delete=models.CASCADE, null=True, blank=True) tournament = models.BooleanField(default=False) num_players = models.IntegerField(choices=NUM_PLAYERS_CHOICE, default=4) start_pos = models.CharField(max_length=20, choices=START_POS_CHOICE, default=1) mull = models.CharField(max_length=20, choices=MULL_CHOICE, default='1st 7') outcome = models.CharField(max_length=10, choices=OUTCOME_CHOICE, default='Win') medium = models.CharField(max_length=10, choices=MEDIUM_CHOICE, default='Paper') date … -
How can I make a "post" method in Python using the marshmallow?
I am working on a small project and have started using the marshmallow library for serialization. I want to write a post request to create a new object in the database, but during my development, I came across the fact that when executing the request, my object is not added to the database. Moreover, I have another error: response should return the id of new object. serializer.py class ObjectSerializer(Schema): operatorId = fields.String(required=True) operator = fields.String(required=True) inaction = fields.String(required=False) id = fields.Integer(required=False) def create(self, data: dict) -> dict: try: data = super().dump(data) except ValidationError as err: data = {'errors': err.messages} return data controller.py def post(self, params: dict) -> Tuple[dict, int]: logger.info('Adding new object for params: %s', str(params)) data = ObjectSerializer().create(params) if 'errors' in data: logger.error('Error deserializing params: %s', str(data['errors'])) return data, HTTPStatus.BAD_REQUEST.value return ( data, HTTPStatus.OK.value ) views.py def post(self, request: Request, *args, **kwargs) -> Response: query_data = request.data payload, status = self.controller.post(query_data) return Response(data=payload, status=status) usecase.py def create(self, operatorId: str, operator: str) -> ObjectEntity: return self.lead_repo.create(operatorId, operator) entities.py @dataclass() class ObjectEntity: id: int operatorId: str = None createdAt: date = None operator: str = None inaction: int = 1 @staticmethod def to_string(operatory: 'ObjectEntity') -> str: operatorId = f" ({operatory.operatorId}):" if … -
How can Gunicorn launch me the Django application if the index file is well inside directories?
Gunicorn: #!/bin/bash NAME="estate" DIR=/usr/share/nginx/myweb.com/alvar USER=boardsalvaro GROUP=boardsalvaro WORKERS=13 BIND=unix:/usr/share/nginx/myweb.com/run/gunicorn.sock DJANGO_SETTINGS_MODULE=estate.settings DJANGO_WSGI_MODULE=estate.wsgi LOG_LEVEL=error The whole Django app was cloned into the alvar directory. But, as you know, the index file in Django is well inside, you have to go through several directories project/app/templates/index.html and I know that you don't need to write the whole path, somehow gunicorn knows, but it doesn't work for me. So I created a 2 lines fake index.hmtl and put it in the alvar directory. Gunicorn found it but that is not the index I want. Nginx conf is: server { listen 80; listen [::]:80; server_name myweb.com; root /usr/share/nginx/myweb.com/alvar; } Supervisor is running but I don't know if I managed to connect it to gunicorn. I read supervisor is not necessary, others say it is, ... At the button of supervisord.conf file: [progam:boards] command=/usr/share/nginx/myweb.com autostart=true autorestart=true redirect_stedrr=true stdout_logfile=/usr/share/nginx/myweb.com/logs/gunicorn.log This is extremely annoying because there isn't a single serious reliable tutorial for centos/redhat/fedora system that explains everything and has everything needed. Can anyone knowledgeable put things in order from what I have included? -
DELETE button on Django Python API
I would like to have the DELETE button work right away on the table (add.stock_html template), instead of opening up another URL (page). I don't want to send to delete_stock.html URL. I've tried many ways, it seems that the problem might be on the delete_stock.html template. Any clues on how to solve it?! I have attached the images. add_stock.html template {% extends 'base.html' %} {% block content %} <div class="card-body"> <div class="table-responsive"> <table class="table align-middle table-hover table-bordered " id="example" style="text-align: center"> <thead class="table-dark thead-default" style="align-items: center"> <tr> <th scope="col">Symbol</th> <th scope="col">Previous Close</th> <th scope="col">Price</th> <th scope="col">Change $</th> <th scope="col">Change %</th> <th scope="col">52Wk Low</th> <th scope="col">52Wk High</th> <th scope="col">YTD %</th> <th scope="col">Market Cap</th> <th scope="col"> </th> <th scope="col">Company Name</th> </tr> </thead> <tbody> {% if ticker %} {% for list_item in output %} <tr> <th>{{ list_item.companyName }}</th> <td>{{ list_item.symbol }}</td> <td>$ {{ list_item.previousClose }}</td> <td>$ {{ list_item.latestPrice }}</td> <td>$ {{ list_item.change }}</td> <td>{{ list_item.changePercentage }} %</td> <td>$ {{ list_item.week52Low }}</td> <td>$ {{ list_item.week52High }}</td> <td>{{ list_item.ytdChange }} %</td> <td>$ {{ list_item.marketCap }}</td> <td><a class="btn btn-danger" href="{% url 'delete_stock' %}"><i class="fa-regular fa-trash-can" aria-hidden="true"></i></a></td> </tr> {% endfor %} {% endif %} </tbody> </table> </div> </div> {% endblock %} delete_stock.html template {% extends 'base.html' %} … -
{{Peoples}} django template is not rendering my backend data in html page
enter image description hereenter image description here (https://i.stack.imgur.com/dXn0b.png) in my views.py I have written function with dictionary in it u can see in image which is in my html page I have written code of html and pass the variable of django with {{peoples}} but it is not rendering in my live server and I have attached all of my code images -
Includes HTML template, not rendering Django content
I have created a special offers page which is meant to form as a carousel. I have created this HTML file in my products/templates/products/includes/special_offers.html folder. I have then added {% include products/includes/special_offers.html %} on the appropriate page. When I vew that page, everything before my for loop is appearing. I cannot get content within the for loop to appear and I have no idea why. I'm using a similar for loop on my products page already and it's working fine. I must be missing some piece of the puzzle. I've tried remove most of the HTML and just render a product image but no joy. Anyone able to spot anything? I've tested quite a bit to no avail. What would cause code that works on 1 page, but not on the other page? HTML {% load static %} {% block content %} <section class="container"> <hr> <h2 class="sub-title">Special Offers</h2> <div class="container my-5"> <div class="row"> <div class="col-12 m-auto"> <div class="owl-carousel owl-theme"> {% for product in products %} <p>HELLO</p> <div class="card card-owl h-100 border-0"> {% if product.image %} <a href="{% url 'product_detail' product.id %}"> <img class="card-img-top img-fluid w-75 product-img" src="{{ product.image.url }}" alt="{{ product.name }} Image"> </a> {% else %} <a href="{% url … -
__init__() got an unexpected keyword argument 'id'
It's my first time asking question here :) I'm a beginner with Django and I've been stuck on my edit_booking method for days, I don't even know what I'm doing wrong anymore... I'm making a booking system and I'm getting a "TypeError at /edit-booking/6 __init__() got an unexpected keyword argument 'id'". I've been trying a lot of things to make editing the exact booking possible, but they only cause more errors... Views: class EditBooking(DetailView): def __init__(self): template_name = 'edit-profile.html' initial = {} @login_required def edit_booking(request, id): booking = get_object_or_404(Booking, id=id) if request.method == 'POST': form = BookingForm(request.POST, instance=booking) customer_data = UserProfile.objects.all() if form.is_valid(): instance = form.save(commit=False) instance.customer_data = customer_data instance.save() messages.success(request, 'Thank you! Your booking has been updated!') else: return messages.error(request, form.errors) else: form = BookingForm(initial={ 'booking_date': booking.booking_date, 'booking_time': booking.booking_time, 'table_size': booking.table_size, 'additional_info': booking.additional_info, }) return render(request, template_name, {'form': form}) Templates: profile.html button triggering edit page: <a href="{% url 'editbooking' id=booking.id %}" aria-label="edit booking"> <button type="button" class="btn btn-secondary btn-brown px-5">Edit</button> </a> edit_booking.html: <form method="POST" action="{% url 'editbooking' id=booking.id %}" class="col-6"> {% csrf_token %} {% crispy form %} </form> Urls: path('edit-booking/<int:id>', views.EditBooking, name='editbooking'), Models: class Booking(models.Model): booking_customer = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True) booking_date = models.DateField(default=datetime.date.today) booking_time = models.CharField(choices=TIME_SLOTS, default='8:00 - 8:30', max_length=50) … -
Troubleshooting ReactJS Display Issue with MediaPipe-Django API Integration for Exercise Rep Calculation Web App
I'm currently developing a web application that utilizes MediaPipe for calculating exercise repetitions. The backend is implemented using Django, which communicates with the frontend written in ReactJS via an API. However, I've encountered an issue where ReactJS seems unable to process the frames being sent by Django through the API. As a result, the exercise interface isn't displaying anything at all, making it impossible to view or interact with the exercise calculation functionality. How can I troubleshoot and resolve this problem to ensure that ReactJS properly handles the frames received from Django via the API, allowing the exercise interface to display as intended? In attempting to resolve the issue of ReactJS not processing frames sent by Django through the API, I initially checked for any potential errors in the data transfer between the backend and frontend. I reviewed the API endpoints, the data format being sent, and ensured that the communication between Django and ReactJS was properly established. -
Gunicorn file for Django project gunicorn.service keep getting Permission denied
Hello I am currently practicing Linux and Django project using Gunicorn and Nginx on CentOS. I'm testing my server on AWS Lightsail and here's some info of what I'm using for this practice. CS9-20230110 Python 3.9 Django 4.0.2 Nginx 1.22.1 Gunicorn 21.2.0 The test of opening the server by opening a gunicorn socket and port 8000 with Gunicorn was successful. I had no trouble in here. gunicorn --bind 0:8000 mysite.wsgi:application gunicorn --bind unix:/home/ec2-user/Django/venv/gunicorn.sock config.wsgi:application (I put sock file into my venv directory, thinking this could've be the problem (sadly it wasn't)) But when I try to start Gunicorn service on systemd. The system send permission denied message on gunicorn file. So I set every single files UID and GID to my user account and group and set 775 authorization on most files. It didn't work at all. I have no clue what I'm missing now. Just thinking that I made a mistake and the mess is everywhere now. Please someone tell me what's going on here. Directory Tree # /home/ec2-user/Django Django ├── Django_Project │ ├── db.sqlite3 │ ├── manage.py │ ├── mysite │ │ ├── asgi.py │ │ ├── db.sqlite3 │ │ ├── __init__.py │ │ ├── __pycache__ │ │ … -
Trying to send Emails in models.py to members in django 4.2
I'm trying to send an email to people when 3 or fewer days are remain, I'm using Django, this is the models.py in my main app, I want to automatically send emails when 3 days or less remain I'm using 4.2 from django.db import models from django.contrib.auth.models import User import uuid from django.urls import reverse from datetime import date from django.conf import settings from django.core.mail import send_mail # Create your models here. class sub(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key = True, editable = False) provider = models.CharField(max_length=70) tier = models.CharField(max_length=40) date_started = models.DateField(auto_now=False, auto_now_add=False) date_end = models.DateField(auto_now=False, auto_now_add=False, ) author = models.ForeignKey(User, on_delete=models.CASCADE) def remain(self): today = date.today() remaining_days = (self.date_end - today).days return(remaining_days) def get_absolute_url(self):` return reverse('sub-detail', kwargs={'pk':self.id}) trying to send emails to people -
fcm-django push notifications to mobile app messages is falling
I'm new with Firebase. The problem is that the sending of messages is falling. I suspect this is due to lack of Firebase authentication. So, what I did: I created new Firebase project and turn on an Anonymous authentication on project settings. On the backend side I installed fcm-django, add settings, and make migrations. Settings: # Firebase app certificate = json.loads(config('FIREBASE_CREDENTIALS', default='')) cred = credentials.Certificate(certificate) FIREBASE_APP = firebase_admin.initialize_app(cred) FCM_DJANGO_SETTINGS = { "DEFAULT_FIREBASE_APP": FIREBASE_APP, "APP_VERBOSE_NAME": ("FCM Brokers CRM notifications"), "ONE_DEVICE_PER_USER": False, "DELETE_INACTIVE_DEVICES": False, } Add standard route from this library: router = DefaultRouter() router.register('devices', FCMDeviceAuthorizedViewSet) path('', include(router.urls)), I call post device/ endpoint with my drf auth user, and send only registration_id (firebase token). Is it enough? So I see in database id of user from AUTH_USER_MODEL: I have simple test endpoint with code: from firebase_admin.messaging import Message, Notification ... devices = FCMDevice.objects.filter(user=request.user) from device in devices: device.send_message(Message( notification=Notification(title="title", body="text"), topic="Optional topic parameter: Whatever you want", )) And I call it from my android app. But its fall with error: I really desperate and don't know what to do. Do I have to somehow add another user and connect it to the endpoint call? Or I have to match the android app … -
Django Template not displaying model objects
` class BookView(CreateView): model = Booking fields = 'all' success_url = "/customer/" template_name = 'book.html' class CustomerBook(View): template_name = 'customer_booking.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request, *args, **kwargs): first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') guest_number = request.POST.get('guest_number') comment = request.POST.get('comment') booking_data = get_object_or_404(Booking, first_name=first_name, last_name=last_name, guest_number=guest_number, comment=comment ) print(booking_data) #context = {"bookers": booking_data} return render(request, self.template_name , {"bookers": booking_data}) class Booking(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) guest_number = models.IntegerField() comment = models.CharField(max_length=1000) def __str__(self): return self.first_name + ' ' + self.last_name class Menu(models.Model): name = models.CharField(max_length=200) price = models.IntegerField() discription = models.TextField(max_length=1000, default='') def __str__(self): return self.name` urlpatterns = [ path('book/', BookView.as_view(), name="book"), path('customer/', CustomerBook.as_view(), name="customer"),] urlpatterns = [ path('book/', BookView.as_view(), name="book"), path('customer/', CustomerBook.as_view(), name="customer"),] I have tried making the model objects display with different code but to no avail. I want to return customer's booking details on the browser after booking. -
Django custom middleware get Anonymous user even after sending authenticated request
I have implemented the custom middleware in which I wanted to have logged in user. But I'm getting AnonymousUser in request.user For authentication method, I have implemented JWT Authentication using django-rest-framework-simplejwt library. Settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } 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', 'core.middleware.ReverseProxyMiddleware', ] custom_middleware.py class ReverseProxyMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def process_request(self, request): print(request.user.is_authenticated) for each_path in settings.BY_PASS_URLS: if each_path in request.path: response = self.get_response(request) return response if self.check_permission(request): response = self.get_response(request) return response else: return HttpResponseForbidden("Permission denied") def check_permission(self, request): perm = APICheckPermission() return perm.has_permission(request) logs 2023-12-09 17:43:34 False AnonymousUser 2023-12-09 17:43:34 Forbidden: /some_url 2023-12-09 17:43:34 [09/Dec/2023 17:43:34] "GET /some_url HTTP/1.1" 403 17 Response Permission denied -
How to fix No ":" found in value with Django core signing
I have a django rest framework api where a i create a token using the django.core.signing module. The signing and unsigning of object works fine when using an API Clinet (E.g) Postman. But when i try to connect with my Next Js frontend using axios it get. No ":" found in value for the token eyJlbWFpbCI6InJhbW9ucmFzaDJAZ21haWwuY29tIiwiZmlyc3RfbmFtZSI6IlJhc2hlZWQiLCJsYXN0X25hbWUiOiJSYW1vbiIsInBhc3N3b3JkIjoiTmluaW9sYTEyIiwiYWN0aXZhdGlvbl9jb2RlIjoiNzk3ODY5In0%3A1rBvFl%3Ato5l_EAmsHy76eJt0sHDcO_eqlk0k4fho78czQeNVx4. But the acutal token is eyJlbWFpbCI6InJhbW9ucmFzaDJAZ21haWwuY29tIiwiZmlyc3RfbmFtZSI6IlJhc2hlZWQiLCJsYXN0X25hbWUiOiJSYW1vbiIsInBhc3N3b3JkIjoiTmluaW9sYTEyIiwiYWN0aXZhdGlvbl9jb2RlIjoiNzk3ODY5In0:1rBvFl:to5l_EAmsHy76eJt0sHDcO_eqlk0k4fho78czQeNVx4 This is the API Code def create(self, request, *args, **kwargs): activation_token = request.data.get("activation_token") activation_code = request.data.get("activation_code") print(activation_token) try: data = signer.unsign_object( activation_token, max_age=timedelta(minutes=10)) except Exception as e: print(e) return Response({"message": "OTP has expired! Try registering again."}, status=status.HTTP_400_BAD_REQUEST) if data["activation_code"] == activation_code: user = User.objects.create_user( email=data["email"], password=data["password"], first_name=data["first_name"], last_name=data["last_name"]) serializer = UserSerializer(user, many=False) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response({"message": "Invalid OTP"}, status=status.HTTP_400_BAD_REQUEST) And The Axios Code const response = await axios.post( `${BASEURL}auth/users/activate/`, JSON.stringify({ activation_code: values.otp, activation_token: token, }), { headers: { Accept: "*/*", "Content-Type": "application/json", }, } ); -
line 158, in get_app_config return self.app_configs[app_label] KeyError: 'account'
I am developing a django project, the main directory/project name is django-basic-ecommerce. One of the apps name is accounts (note that it has the final "s"). as I run python manage.py makemigrations I get Traceback (most recent call last): File "/my/path/basic-django-ecommerce/venv/lib/python3.10/site-packages/django/apps/registry.py", line 158, in get_app_config return self.app_configs[app_label] KeyError: 'account' During handling of the above exception, another exception occurred: [...] /my/path/basic-django-ecommerce/venv/lib/python3.10/site-packages/django/apps/registry.py", line 165, in get_app_config raise LookupError(message) LookupError: No installed app with label 'account'. During handling of the above exception, another exception occurred: [...] /my/path/basic-django-ecommerce/venv/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 176, in get_user_model raise ImproperlyConfigured(django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'account.User' that has not been installed The last message makes me think that I missed some configurations for account.User, however, it is correctly installed in mainapp_ecommerce/settings.py INSTALLED_APPS = [ ... 'accounts', ... 'django.contrib.auth', ... ] AUTH_USER_MODEL = 'account.User' # it changes the builtin model user to User custom defined model and about that AUTH_USER_MODEL , it refers to the account.User modeldefined in accounts/models.py as class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) # full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) # is h* allowed to login? staff = models.BooleanField(default=False) # staff user, not superuser admin = models.BooleanField(default=False) # superuser timestamp = models.DateTimeField(auto_now_add=True) # superuser USERNAME_FIELD = 'username' … -
Difficulty Sending List of Working Hours as Multipart Data Using Swagger in Django DRF
I'm currently facing an issue when attempting to send data in the correct format using Swagger in Django Rest Framework (DRF). The specific challenge is with sending a list of working hours as multipart data. Below is a simplified version of my code: # models.py class Facility(models.Model): name = models.CharField(max_length=255) # ... other fields class WorkingHours(models.Model): linkedFacility = models.ForeignKey(Facility, on_delete=models.CASCADE, related_name='workingHours') dayOfWeek = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(7)]) startTime = models.TimeField() endTime = models.TimeField() # serializers.py class WorkingHoursSerializer(serializers.ModelSerializer): class Meta: model = WorkingHours fields = ('dayOfWeek', 'startTime', 'endTime') class FacilitySerializer(serializers.ModelSerializer): workingHours = WorkingHoursSerializer(many=True, read_only=True) class Meta: model = Facility fields = ('id', 'name', 'workingHours') curl -X 'POST' \ 'http://127.0.0.1:8000/api/v1/facilities/' \ -H 'accept: application/json' \ -H 'Content-Type: multipart/form-data' \ -H 'X-CSRFTOKEN: ot91cIAOrwhjDMU0LtAFhAce1vVxODO5JVQqTRrFumPjyHImS6e0dHqDqseqMbVI' \ -F 'name=first' \ -F 'price=300' \ -F 'phoneNumber=+3821312231213' \ -F 'coordinates=POINT(44.7866 20.4489)' \ -F 'uploadImages=@1.jpeg;type=image/jpeg' \ -F 'uploadSearchImage=@2.jpeg;type=image/jpeg' \ -F 'workingHours={ "dayOfWeek": 7, "startTime": "string", "endTime": "string" },{ "dayOfWeek": 6, "startTime": "string", "endTime": "string" }' In Swagger (I'm using drf-spectacular), when attempting to send a POST request to create a new Facility along with a list of related WorkingHours, the format of the request data appears to be causing issues. Specifically, the Swagger interface is struggling to handle the correct format …