Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
On the timeweb server, django-ckeditor does not work in the admin panel
on server: Python == 3.6.9 Django == 3.2.23 django-ckeditor == 5.9.0 the editor was installed according to the instructions https://django-ckeditor.readthedocs.io/en/latest/#section-9 there is no point in rewriting my files: models.py from ckeditor.fields import RichTextField ... education = RichTextField(verbose_name='Education') ... settings.py INSTALLED_APPS = [ ... 'ckeditor', 'ckeditor_uploader' ] STATIC_ROOT = '/home/.../public_html/static/' STATIC_URL = '/static/' # change STATICFILES_DIRS = [ BASE_DIR/'staticfiles' ] if DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ### CKEDITOR_BASEPATH = "/home/.../public_html/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'height': 300, 'width': 300, }, } after changing the code I started getting an error VM1137 ckeditor.js:260 Uncaught TypeError: Cannot set properties of undefined (setting 'dir') at Object.d (VM1137 ckeditor.js:260:54) at w (VM1137 ckeditor.js:261:181) at Array.y (VM1137 ckeditor.js:261:336) at z (VM1137 ckeditor.js:261:420) at A.CKEDITOR.env.ie.f.$.onerror (VM1137 ckeditor.js:262:429) how can this be solved? I tried changing the paths and reinstalling the application, to no avail. -
Djang/websocket not sending messages
i'm using django and daphne and websocket to make a chat room by following a tutorial on youtube..everything worked fine , but when i send the message it does'nt show the message in the screen....it does not show any errors in the server side ..but shows 2 warniings and one error in the browser console im intermediate in django but completely new to web sockets Here's my script tag: {% endblock %} {% block scripts %} {{ room.slug|json_script:"json-roomname" }} {{ request.user.username|json_script:"json-username"}} <script> const roomName = JSON.parse( document.getElementById("json-roomname").textContent ); const usrName = JSON.parse( document.getElementById("json-username").textContent ); const chatSocket = new WebSocket( "ws://" + window.location.host + "/ws/" + roomName + "/" ); chatSocket.onmessage = function (e) { console.log("onemssage"); const data = JSON.parse(e.data); if (data.message) { let html = '<div class="p-4 bg-gray-200 rounded-xl">'; html += '<p class="font-semibold">' + data.username + "</p>"; html += "<p>" + data.message + "</p></div>"; document.querySelector("#chat-messages").innerHTML += html; } else { alert("The message was empty!"); } }; chatSocket.onclose = function (e) { console.log("onclose", e); }; document .querySelector("#chat-message-submit") .addEventListener("click", function (e) { e.preventDefault(); const messageInputDom = document.querySelector("#chat-message-input"); const message = messageInputDom.value; chatSocket.send( JSON.stringify({ message: message, username: usrName, room: roomName, }) ); messageInputDom.value = ""; return false; }); </script> here's my python file: … -
migration the database and django
(venv) C:\Users\LENOVO\PycharmProjects\Projectpython\mysite>python manage.py makemigrations No changes detected Traceback (most recent call last): File "C:\Users\LENOVO\PycharmProjects\Projectpython\mysite\manage.py", line 22, in main() File "C:\Users\LENOVO\PycharmProjects\Projectpython\mysite\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\core\management_init_.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\core\management_init_.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\core\management\base.py", line 415, in run_from_argv connections.close_all() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\utils\connection.py", line 85, in close_all conn.close() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\db\backends\base\base.py", line 358, in close self._close() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\djongo\base.py", line 208, in _close if self.connection: File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\pymongo\database.py", line 1337, in bool raise NotImplementedError( NotImplementedError: Database objects do not implement truth value testing or bool(). Please compare with None instead: database is not None (venv) C:\Users\LENOVO\PycharmProjects\Projectpython\mysite>python manage.py makemigrations No changes detected Traceback (most recent call last): File "C:\Users\LENOVO\PycharmProjects\Projectpython\mysite\manage.py", line 22, in main() File "C:\Users\LENOVO\PycharmProjects\Projectpython\mysite\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\core\management_init_.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\core\management_init_.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\core\management\base.py", line 415, in run_from_argv connections.close_all() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\utils\connection.py", line 85, in close_all conn.close() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\django\db\backends\base\base.py", line 358, in close self._close() File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\djongo\base.py", line 208, in _close if self.connection: File "C:\Users\LENOVO\PycharmProjects\Projectpython\venv\Lib\site-packages\pymongo\database.py", line 1337, in bool raise NotImplementedError( NotImplementedError: Database objects do not implement truth value … -
Getting a 500 Internal Server Error when Booking a Hotel with Amadeus API
I'm working on integrating the Amadeus API into my application to allow users to book hotels. However, I'm encountering a 500 Internal Server Error when attempting to book a hotel using the provided offer ID. Here's a simplified version of my Python code: @app.post("/book_hotel") async def book_hotel( offer_id: str = Query(..., description="Offer ID") ): try: # Confirm availability of a given offer offer_availability = amadeus.shopping.hotel_offer_search(offer_id).get() if offer_availability.status_code == 200: guests = [ { 'id': 1, 'name': {'title': 'MR', 'firstName': 'BOB', 'lastName': 'SMITH'}, 'contact': {'phone': '+33679278416', 'email': 'bob.smith@email.com'} } ] payments = { 'id': 1, 'method': 'creditCard', 'card': { 'vendorCode': 'VI', 'cardNumber': '4151289722471370', 'expiryDate': '2023-08' } } booking = amadeus.booking.hotel_bookings.post(offer_id, guests, payments).data else: return {"response": 'The room is not available'} except ResponseError as error: raise HTTPException(status_code=500, detail=str(error.response.body)) return { "id": booking[0]['id'], "providerConfirmationId": booking[0]['providerConfirmationId'] } I'm providing a valid offer ID, '8ANZ20L7F2', but I'm consistently getting a 500 error. I've checked my API credentials, and they seem to be correct. What could be causing this 500 Internal Server Error when trying to book a hotel with the Amadeus API? Are there any common issues or troubleshooting steps I should consider? The other endpoints for fetching data and so work as expected, only … -
Django Weasyprint PDF output into Postgres Database
I am trying to stick a WeasyPrint html PDF into the Model. Using Django. I can generate the PDF file fine. pdf_file = HTML(string=html,base_url=base_url).write_pdf(stylesheets, [css_path],font_config=font_config) Now what is best way to convert the pdf_file output to a format I can use for the database? class Reports(models.Model): pdf = models.FileField( upload_to='media/pdfs/', max_length=254, ) created = models.DateField(auto_now=False, auto_now_add=True) If I do something like this it creates the file automatically before the Model. fs = FileSystemStorage() report = fs.save(f'pdfs/{uuid}.pdf', File(BytesIO(pdf_file)) ) And gives the table a 'pdf/...' in the database. What is most efficent way to convert the Wesasy HTML into a format the Model can use and let the model save the file? Thanks. -
Using Django_tenants and django_tenant_users for a multi tenancy SAAS
I am creating a SAAS project, what I want is that I will have clients, and each client can have sub clients/departments. So I came across django_tenants and using it, also django_tenant_users. But I am little stuck with, how can I manage a multi level tenancy, where each tenant has multiple tenants. Can I do that ? -
How to manage iterative django migrations when working on same branch with other people
I am working on a django project and many times i will iterate on a new model creating new migration files along the way.The migration file names are different but change parts of the same model. These migration files are also shared with other developers.What is the correct order of operations to execute in order to synchronize the changes with other developers working on the same branch and applying the migrations? I understand that reinitializing the db is a solution but arguably not a very clean one. I have tried this sequence after deleting the last migration in the receiving end but it does not work as expected python manage.py migrate app_name XX #returns to the previous migration python manage.py makemigrations python manage.py migrate # this creates issue because the relations-columns already exist The next logical thing to do is python manage.py migrate --fake However, this does not solve the issue because the updated changes are not reflected. Lastly, I have also tried python manage.py makemigrations --merge but this does not find something to merge. -
Django admin outputs ul for foreignkey instead of dropdown list
that is, instead of a drop-down list, the ul-li tag appears class EpApplicationAdmin(admin.ModelAdmin): list_display = ('id', 'application_status', 'f_iin', 'f_phone', 's_iin', 's_phone', 'entity_bin', 'entity_grnz') list_per_page = 20 search_fields = ["id__id", "f_iin", "s_iin", "f_phone", "s_phone"] list_filter = ('application_status__description', ) -
DJango - different auth models and urls
To Modesl: Customers Agents I've got custom auth for Customers with URL: /customers/ /customers/login.html /customers/logout.html with added middleware auth script in settings.py MIDDLEWARE = [ ... 'main.backends.check_user_customer', ... ] Now i wanna add new sections for new Model: Agent with new URL: /agent/ /agent/login.html /agent/logout.html My goal: to make different login/logout pages, auth backends and custom redirects if each section (eq login_required) also how to prevent open another section when user authenticated NON AUTH /agent/ -> /agent/login.html /customer/ -> /customer/login.html AUTHENTICATED AS AGENT /agent/ -> OK /customer/ -> /customer/login.html AUTHENTICATED AS CUSTOMER /agent/ -> /agent/login.html /customer/ -> OK So the question is: how to make it correct? -
Django-tenants: Tenant App specific URLs throw 404 error, but when included in Shared App works perfectly
I have a Django-tenant based application. In the Shared App I have a 'publicApp' and in Tenant Apps I have 'AHIDev' & 'ahi'. Now this ahi is my django project starting point, meaning ahi folder includes settings.py, wsgi.py, etc. When I try the urls included in publicApp everything is working as expected. But problem arises when I try the urls included in 'ahi' or 'AHIDev'. Everytime Django throws 404 error. Now if I include the tenant urls in publicApp it is again working. My settings.py file: SHARED_APPS = [ 'django_tenants', ... 'publicApp', ] TENANT_APPS = [ #Project related apps 'ahi', 'ahiDev', ] INSTALLED_APPS = SHARED_APPS + [app for app in TENANT_APPS if app not in SHARED_APPS] I cannot find the problem. Can someone help? i'm new to Django-tenants. Thank you. ahi/urls.py: urlpatterns = [ #For standard user logins path('AHIDev/',include('ahiDev.urls')), ] ahidev/urls.py urlpatterns = [ path('test_get/', views.test_get, name="test_get"), .... ] -
How do i collect static files in a django application deployed in digital ocean and store this in a staticfiles folder in AmazonS3 bucket?
I have a dockerized app deployed in digital ocean. However it fails to collect static files to be used in production. I have a static folder (static) containing the app's static files in django. I want to save the static files from the local static directory in a staticfiles folder in digital ocean.How can i solve this? Attached is my settings.py in Django for storage settings. AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME") AWS_S3_ENDPOINT_URL = os.getenv("AWS_S3_ENDPOINT_URL") AWS_S3_OBJECT_PARAMETERS = { "CacheControl": "max-age=86400", } AWS_LOCATION = "static" AWS_S3_SIGNATURE_VERSION = "s3v4" STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") # STATICFILES_DIRS = [ # os.path.join(BASE_DIR, "static"), # ] STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" # Media files MEDIA_URL = "https://%s/%s/" % ( AWS_S3_ENDPOINT_URL, "media", ) # Change this to a different path # DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" # Configuring Django to use DigitalOcean Spaces for media files DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" Here is my Dockerfile: FROM python:3.10 ENV PYTHONUNBUFFERED=1 WORKDIR /code # Install build dependencies RUN apt-get update && apt-get install -y tzdata libpython3-dev gcc # Upgrade pip and setuptools RUN pip install --upgrade pip setuptools # Copy requirements and install dependencies COPY requirements.txt . # RUN pip install poetry # RUN pip install django_cleanup # RUN … -
User authorization in django and the ways to achieve it if the default User model is extended to create custom User model
I am working on building a movie ticket booking website. I am told to implement authorization in the project so that only superuser can do certain actions on mongodb database(like adding movies and theatres). Please help me in understanding this process and the ways to achieve this. And also I am getting an error when creating superuser. I am attaching the code for the reference. models.py --> from .userManage import UserManager class User(AbstractBaseUser): id=models.AutoField(primary_key=True,null=False) name=models.CharField(max_length=100) email=models.CharField(max_length=60) password=models.CharField(max_length=16) username=models.CharField(max_length=20,unique=True) mobileNumber=models.IntegerField() USERNAME_FIELD = 'username' objects=UserManager() usermanage.py - this python file is in same directory path from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self,username,password,**extra_fields): if not username: return ValueError("Username should be provided") user=self.model(username=username,**extra_fields) user.set_password(password) user.save() return user def create_superuser(self,username,password,**extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) return self.create_user(username,password,**extra_fields) The error in creating superuser when I entered username and password: User() got unexpected keyword arguments: 'is_staff', 'is_superuser'. Please help! -
Django Python: AttributeError: 'NoneType' object has no attribute 'startswith'
I bumped into the error when running python3 manage.py runserver. I have mydb.py in the project's root directory (same as manage.py), in order to connect to MySQL and create a database (if it does not exist). mydb.py and settings.py share same database configuration which is loaded from environment variables in .env. .env: ENV=DEV SECRET_KEY='django-insecure-9#1j%osjd33e' DB_NAME=todolist DB_USER=user DB_PASSWORD=12345 DB_HOST=localhost DB_PORT=3306 settings.py: import os from os.path import join, dirname from dotenv import load_dotenv, find_dotenv # (1) ENV = os.environ.get('ENV') if ENV == 'PROD': env_filename = '.env.prod' elif ENV == 'TEST': env_filename = '.env.test' # elif ENV == 'DEV': # env_filename = '.env.dev' else: env_filename = '.env' dotenv_path = join(dirname(__file__), env_filename) load_dotenv(dotenv_path) ... # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), } } ... mydb.py: import mysql.connector import os from os.path import join, dirname from dotenv import load_dotenv, find_dotenv ENV = os.environ.get('ENV') if ENV == 'PROD': env_filename = '.env.prod' elif ENV == 'TEST': env_filename = '.env.test' # elif ENV == 'DEV': # env_filename = '.env.dev' else: env_filename = '.env' dotenv_path = join(dirname(__file__), env_filename) load_dotenv(dotenv_path) dataBase = mysql.connector.connect( host = os.environ.get('DB_HOST'), user = os.environ.get('DB_USER'), passwd = os.environ.get('DB_PASSWORD'), ) dataBase = mysql.connector.connect() ... Problem: … -
In Django, how do I generate a queryset containing the results of a many-to-many relationship in reverse direction?
I have the following model layout class Group(models.Model): group_name = models.CharField(max_length=100, default="New Group") group_created_date = models.DateField(default=date.today) class GroupMember(models.Model): groups_joined = models.ManyToManyField(Group) email = models.EmailField(max_length=100) name = models.CharField(max_length=100) I'm trying, in a class based view, to return a queryset of all group members for a given group. My attempt so far: def get_queryset(self): groupid = self.kwargs['groupid'] qs = Group.objects.filter(groupmember__groups_joined__id=groupid).order_by('-id') return qs However, this gives an error. Related Field got invalid lookup: groups_joined groups_joined is the column that has a relationship to the Group table, and I seem to be accessing it the right way using double underscores as I have. I want to return only group members that have en entry in groups_joined matching the current group with the ID matching groupid. What is the correct way to format a query that will accomplish this? -
Django built-in authentication form is not rendering inside the Bulma modal
I've created the template file "templates/registration/login.html." This file will be {%include '../registration/login.html' %} in the header of my navbar-menu in the header.html file. login.html <div x-data="{ modalopen: false }"> <a class="navbar-item " x-cloak href="" @click.stop.prevent="modalopen = !modalopen"> Login </a> <div class="modal" x-bind:class="modalopen ? 'is-active' : ''" > <div class="modal-background" ></div> <div class="modal-content has-background-white py-5 px-5" @click.stop.outside="modalopen = false"> <form method="post" action="/"> {% csrf_token %} {{ form.as_p }} <button class="button is-success" type="submit">Login</button> </form> <button class="modal-close is-large" aria-label="close" @click.stop="modalopen = false"></button> </div> </div> </div> In the future, I will use HTMX, but I need to address the form rendering problem first. The urls.py has path("accounts/", include("django.contrib.auth.urls")), and the forms and views are from the Django built-in authentication system. Without the modal, the login form appears. The modal closes (with the button and outside click), so Alpine.js is not the problem. The button is styled, so Bulma is working as well. However, the modal appears without the forms. "I don't think it's important, but this is the header.html file." <header> <nav x-data="{ open: false }" x-cloak class="navbar is-light" role="navigation" aria-label="main navigation"> <div class="navbar-brand"> <a class="navbar-item brand-text is-size-4 has-text-dark" href="/"> SITE </a> <div class="navbar-item"> <div class="control"> <input class="input is-rounded is-fullwidth" type="text" placeholder="Search..."> </div> </div> … -
Django Microsoft Authentication: Page not found (404)
I am developing a Django app and attempting to integrate Microsoft authentication using the django_microsoft_auth library by following the steps outlined in the documentation here. However, I'm encountering a "Page not found (404)" error when trying to access /microsoft/authenticate/. Here's the error message: Page not found (404) Request Method: GET Request URL: https://127.0.0.1:8000/microsoft/authenticate/?next=/validate/ I have added the necessary configurations in my settings.py: INSTALLED_APPS = [ # ... other apps ... 'django.contrib.sites', 'microsoft_auth', 'sslserver', ] SITE_ID = 2 # the id matches the record in the django_site table with the corporate email domain. # ... other settings ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'microsoft_auth.context_processors.microsoft', ], }, }, ] AUTHENTICATION_BACKENDS = [ 'microsoft_auth.backends.MicrosoftAuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ] LOGIN_URL = '/microsoft/authenticate/' # Using Microsoft authentication LOGIN_REDIRECT_URL = '/dashboard/' LOGOUT_REDIRECT_URL = '/' MICROSOFT_AUTH_CLIENT_ID = 'your_client_id' MICROSOFT_AUTH_TENANT_ID = 'your_tenant_id' MICROSOFT_AUTH_CLIENT_SECRET = 'your_client_secret' MICROSOFT_AUTH_LOGIN_TYPE = 'ma' MICROSOFT_AUTH_LOGIN_REDIRECT = '/microsoft/auth-callback/' And my urls.py looks like this: from django.urls import path from . import views from django.contrib.auth import views as auth_views from django.conf.urls import include urlpatterns = [ # ... other paths ... path('microsoft/', include('microsoft_auth.urls', namespace='microsoft')), ] Additionally, I have registered my Django app in … -
Understanding TemplateResponseMixin class in django.views.generic.base module
Let's say we inherit TemplateView and till now we are not defining any methods. So the child class will somewhat look like this: class ChildClass(TemplateView): """ A default context mixin that passes the keyword arguments received by get_context_data() as the template context. """ extra_context = None def get_context_data(self, **kwargs): kwargs.setdefault("view", self) if self.extra_context is not None: kwargs.update(self.extra_context) return kwargs """ Intentionally simple parent class for all views. Only implements dispatch-by-method and simple sanity checking. """ http_method_names = [ "get", "post", "put", "patch", "delete", "head", "options", "trace", ] def __init__(self, **kwargs): """ Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things. """ # Go through keyword arguments, and either save their values to our # instance, or raise an error. for key, value in kwargs.items(): setattr(self, key, value) @classproperty def view_is_async(cls): handlers = [ getattr(cls, method) for method in cls.http_method_names if (method != "options" and hasattr(cls, method)) ] if not handlers: return False is_async = iscoroutinefunction(handlers[0]) if not all(iscoroutinefunction(h) == is_async for h in handlers[1:]): raise ImproperlyConfigured( f"{cls.__qualname__} HTTP handlers must either be all sync or all " "async." ) return is_async @classonlymethod def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" for key in … -
CSRF token not being set in Django leading to 403 on client-side
When making a POST request with axios from an endpoint in django, the CSRF token cookie seems to not be set, because of this it gives me a 403 status code. which i couldn't fix even after days trying to BACKEND: i've used cors-headers in django to set up in settings the CSRF_TRUSTED_ORIGINS,CSRF_COOKIE_DOMAIN and the CORS_ALLOWED_ORIGINS to all match the origin frontend's url but still didn't work. i also set CORS_ALLOW_CREDENTIALS = True, for context the middlewares config are on point too though. in the endpoint view i have already tried ensure_csrf_cookie with no success, because it is a class-based-view i have tried method_decorator too without success FRONTEND: i have defined default names for csrf header and token name in order for me to include them in my axios.post call and get the actual value of the csrftoken cookie with a getCookie function but it always returns null, which probably means the server-side isn't setting this csrf cookie at all :( : axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN'; axios.defaults.xsrfCookieName = 'csrftoken';) the function is the getCookie(code at the end) that takes the defined name of the cookie as a param: const csrftoken = getCookie('csrftoken') for that to be later included into my axios … -
TypeError "Field 'id' expected a number but got <built-in function id>."
I am working on an auction application in Django. When I try to create a new listing I get a Type Error saying, Type Error at/create> "Field 'id' expected a number but got <built-in function id>". It also highlights views.py, line 81: "viewListing = Listing.objects.get.(pk=id)". What input should I pass to make this work properly? I expected to be redirected to the index view which would include the newly created listing. Here is the relevant view from views.py: @login_required def create(request): if request.method == "GET": categories = Category.objects.all() return render(request, "auctions/create.html", { "categories": categories }) else: title = request.POST\["title"\] description = request.POST\["description"\] image = request.POST\["image"\] price = request.POST\["price"\] category = request.POST\["category"\] categories = Category.objects.get(categoryType=category) sessionUser = request.user viewListing = Listing.objects.get(pk=id) viewListing.watchlist.add(sessionUser) bid = Bid(bid=float(price), user=sessionUser) bid.save() listing = Listing( title=title, description=description, image=image, price=bid, category=categories, owner=sessionUser ) listing.save() return HttpResponseRedirect(reverse(index)) Here is urls.py: from django.urls import path from . import views urlpatterns = \[ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create", views.create, name="create"), path("categories/", views.categories, name="categories"), path("filter/\<int:category_id\>", views.filter, name="filter"), path("listing/\<int:id\>", views.listing, name="listing"), path("remove/\<int:id\>", views.remove, name="remove"), path("add/\<int:id\>", views.add, name="add"), path("watchlist", views.watchlist, name="watchlist"), path("comment/\<int:id\>", views.comment, name="comment"), path("bid/\<int:id\>", views.bid, name="bid"), path("close/\<int:id\>", views.close, name="close") \] And just in case, … -
Angular v17 Error Forbidden (CSRF cookie not set.):
¿Alguien sabe como solucionar este problema Angular v17 Error Forbidden (CSRF cookie not set.):? Hola, hace muy poco me he comenzado a aventurar en Angular creando una web donde se use Angular como FrontEnd y Django como Backend, bueno resulta que quiero crear un formulario para registrarse y enviar los datos ingresados a Django, el problema es que cuando hago el POST sale el siguiente error, les dejo parte de la consola para que se vea donde se cae exactamente: Entrando a función get token [16/Jan/2024 21:47:49] "GET /obt_csrf_token/ HTTP/1.1" 200 82 Forbidden (CSRF cookie not set.): /procesar_registrarse/ [16/Jan/2024 21:47:51] "POST /procesar_registrarse/ HTTP/1.1" 403 2869 views.py from django.shortcuts import render from django.http import JsonResponse from django.middleware.csrf import get_token from django.views.decorators.csrf import csrf_protect # Create your views here. def inicio(request): return render(request, 'inicio/index.html') def obt_csrf_token(request): csrf_token = get_token(request) print("Entrando a función get token") return JsonResponse({'csrf_token': csrf_token}) @csrf_protect def procesar_registrarse(request): print("Entrando a función registrarseeeeeeee") if request.method == 'POST': print("Procesar registrarse") print(request) data = request.POST.get(request) print(data) return JsonResponse({'success': True}) else: print("ERROOOOOOOOOOOR") return JsonResponse({'mensaje': 'Metodo no permitido'}, status=405) settings.py from pathlib import Path import os DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'DjangoBackApp', 'corsheaders' ] MIDDLEWARE … -
Next JS 14 cookie management for Login with Django
So, I am using nextjs 14 with Django as my backend and so far, things have been quite difficult to get working but I like the combination. Now, I have to authenticate users and so far, I have a client form that has a function handler which calls a server action. I tried passing the server action directly, but I am not sure how to pass errors and show them in the form. I am using redux and rtk query for client-side requests as per the redux recommendations. My previous workflow before using nextjs was to send a request to the Django Api and if the credentials are valid the response would include necessary data like the access token and a http only cookie containing the refresh token. The access token would be put in the state and if it expires the refreshtoken api would be called to refresh both tokens. This approach works and you can tell me if its secure (all over https ofc). But, for experimentation now I have the form use a server-side action and inside it calls the login Api but now the refresh token is included in the response. When the action receives the … -
How to set up django-defender to work with django-two-factor-auth (django-otp)
I created a django app utilizing the django-two-factor-auth to enable two factor authorization using google authenticator. I also configured django-defender to protect my site from brute force attacks. It works correctly for the default django.contrib.auth. However it doesn't do anything for the custom otp authorization page. From my research I suppose the custom login method should be decorated with @watch_login from defender.decorators. But I have no clue which method should that be (possibly one from django-otp?) nor how to override this method with the decorator in my code. By the way - the django-two-factor-auth is already utilizing some kind of preventing brute force attacks - the screen where you submit google authorization code is correctly locking out after a few tries. However the first 'standard' login page does not utilize that feature. If django-defender is not the right method to do this I am open to any other suggestions. -
using django rest framework not able to save multiple items
I'm creating models and serializers for placing an order from a menu. The Order can have multiple MenuItem's: class MenuItem(models.Model): name = models.CharField(max_length=40) price = models.FloatField(default=0.0) class Order(models.Model): customer = models.CharField(max_length=50) order_time = models.DateTimeField(auto_now_add=True) items = models.ManyToManyField(MenuItem, through='OrderItem') class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class MenuItemSerializer(serializers.ModelSerializer): class Meta: model = MenuItem fields = "__all__" class OrderItemSerializer(serializers.ModelSerializer): menu_item = MenuItemSerializer() class Meta: model = OrderItem fields = "__all__" class OrderSerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True, read_only=True) class Meta: model = Order fields = "__all__" When I drop into the django shell and test the serialiser: order_data = {'customer': 'John Doe', 'items': [{'menu_item': 5, 'quantity': 2}, {'menu_item': 8, 'quantity':3}]} order_serializer = OrderSerializer(data=order_data) order_serializer.is_valid() # TRUE order_serializer.save() It's not saving the items: {'id': 5, 'items': [], 'customer': 'John Doe', 'order_time': '2024-01-16T22:09:55.800262Z'} There is nothing being created in OrderItem. OrderItem.objects.all() gives an empty QuerySet. -
django-contact-form: using super().save(...) to save a an object field not working
I'm using django-contact-form package and it works well for what I need. But, with my use of super().save(fail_silently=fail_silently, *args, **kwargs), it does not appear to be saving the info from the form as a Contact object field. I had thought this was the way go about it but it doesn't appear to be working. I'd like to save the object in the form.save() method since we're directly using the package's ContactFormView defined in our urls.py path definition for /contact and don't require any customization there. My code: # model: class Contact(models.Model): name = models.CharField(max_length=100, default="") subject = models.CharField(max_length=255, default="") email = models.EmailField() body = models.TextField() def __str__(self): return self.subject[:100] class Meta: ordering = ("-created",) # form: class CustomContactForm(ContactForm): template_name = "core/django_contact_form/contact_form.txt" subject_template_name = "core/django_contact_form/contact_form_subject.txt" name = forms.CharField(label="Full Name") subject = forms.CharField(max_length=255, label="Subject") email = forms.EmailField(label="Email") recipient_list = ['admin@localhost',] class Meta: model = Contact fields = ["name", "subject", "email", "body"] def save(self, fail_silently=False, *args, **kwargs): try: super().save(fail_silently=fail_silently, *args, **kwargs) except Exception as e: print(f"Error saving Contact object: {str(e)}") send_mail(fail_silently=fail_silently, **self.get_message_dict()) There are no exception errors shown, so it looks like I am missing something that would get this to work as intended. What … -
In Django, how do I obtain a queryset of fields in a relate table, and return it along with context data from a class based view?
I have the following model layout class Group(models.Model): group_name = models.CharField(max_length=100, default="New Group") group_created_date = models.DateField(default=date.today) class GroupMember(models.Model): groups_joined = models.ManyToManyField(Group) email = models.EmailField(max_length=100) name = models.CharField(max_length=100) I'm trying, in a class based view, to return a queryset of all group members for a given group. I want to return this queryset, along with context data via a class based view. My attempt so far: class viewgroup(LoginRequiredMixin, SingleTableView): def get_queryset(self): groupid = self.kwargs['groupid'] qs = Group.objects.filter(groupmember__groups_joined__id=groupid).order_by('-id') return qs def get_context_data(self, **kwargs): groupid = self.kwargs['groupid'] group = Group.objects.get(id=groupid) context = { 'group': group, } return context def get_template_names(self): return ['myapp/viewgroup.html'] def get_table_class(self): return GroupTable If I have def_context_data there, I get an error in my template (which mainly just calls render table from django-tables2) that a queryset, not a string was expected. Somehow, the context data gets passed to render_table instead of the queryset. Without trying to pass context data, I get an error because of my query: Related Field got invalid lookup: groups_joined What is the correct way to construct a query to retrieve rows via a relationship, and to pass it as a queryset along with context data from a class based view?