Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Recover Bulk Deleted items in django framework
Is it possible to recover multiple deleted files in one go using django framework. If so, what are the ways? I tried latest file recovery, it worked. but not sure on multiple files recovery . I am using IDE as pycharm and django admin view. -
Timezone conversion failed due to winter hour change pytz
in my code I am trying to convert a date with pytz timezone, but due to the change to winter hour at 3 am, my code crash. I have two questions : one, why does changing hours makes the timezone conversion crash ? Two, how to avoid this bug ? Here is my code : purchase_date = make_aware( datetime.strptime( sale.findtext('n:purchasedate', namespaces={'n': ns}), '%d/%m/%Y-%H:%M' ), timezone('Europe/Paris') ) Error returned : Traceback (most recent call last): File "/app/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ purchase_date = make_aware( ^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/timezone.py", line 287, in make_aware return timezone.localize(value, is_dst=is_dst) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/pytz/tzinfo.py", line 366, in localize raise AmbiguousTimeError(dt) pytz.exceptions.AmbiguousTimeError: 2023-10-29 02:08:00 Knowing that my code was executed at 3:02 am and the change of hour happened at 3:00 am. Thanks in advance for any response ! -
Assert when ObjectDoesNotExitst is raise
I have this function which raises the ObjectDoesNotExist def is_user_login(self,id): try: u = m.CustomUser.objects.get(id=id) except ObjectDoesNotExist as e: raise e Now I am writing the test script. try: CommonFunc.is_user_login(4) except Exception as e: print(e) self.assertEqual(ObjectDoesNotExist,e) It doesn't work. It shows error like this below , AssertionError: <class 'django.core.exceptions.ObjectDoesNotExist'> != DoesNotExist('CustomUser matching query does not exist.') How can I assert for ObjectDoesNotEqual? -
Django models: have foreign keys in a class return different things
I have following in my django models file : class Category(models.Model): name = models.CharField(max_length=200) image = models.ImageField(upload_to='uploads/cats', null=True, blank=True) def __str__(self): return self.name and I want to have foreign key to its name and its image separately like this : class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) category_image = models.ForeignKey(Category.image, on_delete=models.CASCADE, blank=True, null=True) how should I achieve this ? -
unable to access object's property despite it being present
My serializer: class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = "__all__" def create(self, validated_data): try: print(validated_data) print(validated_data.author) task = Task.objects.create(**validated_data) return task except BaseException as e: print(e) raise HTTP_400_BAD_REQUEST my view: class TaskCreateApiView(generics.CreateAPIView): serializer_class = TaskSerializer my model: from django.db import models from django.contrib.auth.models import User class Task(models.Model): content = models.CharField( default="", max_length=255, ) author = models.ForeignKey( User, on_delete=models.CASCADE, null=True, ) category = models.CharField( default="", max_length=255, ) def __str__(self): return str(self.id) + self.content My log from serializer: {'content': 'test2', 'category': 'test', 'author': <User: zaq1>} 'dict' object has no attribute 'author' print(validated_data.author) ^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'dict' object has no attribute 'author' How can I access author? I see it exists as <User:zaq1> but can't seem to access it -
Modifying DJANGO_SETTINGS_MODULE in environment variables
I've come across a very dumb yet irritating problem when running my Django server. When running the server it says: ModuleNotFoundError: No module named 'apolo_client.setting' I don't know where in hell I've set this variable to apolo_client.setting. Obviously it's supposed to be "settings" with as s at the end. I tried manually setting the variable in windows and even in python itself, but it doesn't work. I tried retrieving the variable in init.py file in django's conf folder and it says apolo_client.setting! However running os.environ anywhere else in windows gives the current output. Is there a way I could reset the value or maybe search for the bit where it's being set the wrong valule? -
Failure to display the output despite entering the codes
Despite entering the codes, no output is displayed in this field. What is the reason? in views.py: def category(request, category_id): category = get_object_or_404(Category, pk=category_id) products = category.product_set.all() return render(request, 'category.html', {'category': category, 'products': products}) in urls.py: path("category<int:category_id>", views.category, name="category") in category.html: {% extends "auctions/layout.html" %} {% block body %} <h2>{{ category.name }}</h2> <ul> {% for product in products %} <li>{{ product.category }}</li> {% endfor %} </ul> {% endblock %} in layout.html: <li class="nav-item"> {% for category in categories %} <a class="nav-link" href="{% url 'category' category.id %}">Category</a> {% endfor %} </li> -
Failure to register comments without login
Comments are registered on the desired page, and for people who aren't logged in, if they want to leave a comment, it says to enter the site first, but later the comments are registered under the name AnonymousUser. I don't want this registration to happen. Which part and how should be edited? in views.py: comments = Comment.objects.filter(product=product) if request.method == 'POST': # comment if 'comment' in request.POST: author = request.user content = request.POST.get('content') comment = Comment(product=product, author=author, content=content) comment.save() context = { 'comments': comments, } return render(request, 'auctions/product_detail.html', context) in product_detail.html: <h3 id="h3">Comments</h3> {% if user.is_authenticated %} <ul> {% for comment in comments %} <li><a>{{ comment.author }} : {{comment.content}}</a></li> {% endfor %} </ul> {% else %} Not signed in. {% endif %} ` Thanks in advance for your help -
how to store checkboxes in database?
i want to make a website which can save the seats of the plane for a user but i am facing trouble storing these checkboxes in database and have no idea how to make it so that the checkboxes remain when i revisit the webpage with logged used this is my models.py from django.db import models # Create your models here. class Logs(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=200) email=models.EmailField(max_length=200,unique=True) password=models.CharField(max_length=200) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) def get_special_combination_value(self): return '{}{}'.format(self.name,self.password) this is my views.py from django.db import models # Create your models here. class Logs(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=200) email=models.EmailField(max_length=200,unique=True) password=models.CharField(max_length=200) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) def get_special_combination_value(self): return '{}{}'.format(self.name,self.password) this is my plane.html(shortened version) <!DOCTYPE html> <html> <head> <style> .container { display: flex; justify-content: center; align-items: center; height: 100vh; } .a, .b { transform: scale(2.5); } .b { margin-left: 200px; /* Add margin between the two divs */ } /* Additional CSS to adjust the layout */ .a, .b { display: inline-block; } #sub { margin-bottom: -200px; } </style> </head> <body> <div class="container"> <form method="POST" action=""> {% csrf_token %} <div class="a"> <table> <tr> <td> <input type="checkbox" name="seat"> </td> <td> <input type="checkbox" name="seat"> </td> <td> <input type="checkbox" name="seat"> </td> </tr> <tr> <td> <input type="checkbox" name="seat"> </td> <td> <input type="checkbox" name="seat"> </td> <td> … -
How to get the "overall" counter of an object in a group in a Django template?
I'm using Django's regroup template tag to group a series of objects. Let's say these are the objects: cities = [ {"name": "Mumbai", "population": "19,000,000", "country": "India"}, {"name": "Calcutta", "population": "15,000,000", "country": "India"}, {"name": "New York", "population": "20,000,000", "country": "USA"}, {"name": "Chicago", "population": "7,000,000", "country": "USA"}, {"name": "Tokyo", "population": "33,000,000", "country": "Japan"}, ] In my template, I'm grouping them like this: {% regroup cities by country as country_list %} <ul> {% for country in country_list %} <li>{{ country.grouper }} <ul> {% for city in country.list %} <li>{{ city.name }}: {{ city.population }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> Which results in India Mumbai: 19,000,000 Calcutta: 15,000,000 USA New York: 20,000,000 Chicago: 7,000,000 Japan Tokyo: 33,000,000 I would like to show an "overall" index for each object, so that it looks like this: India 1: Mumbai: 19,000,000 2: Calcutta: 15,000,000 USA 3: New York: 20,000,000 4: Chicago: 7,000,000 Japan 5: Tokyo: 33,000,000 I'm not asking for an HTML solution; my use case is a series of grouped questions and I would like to add a question counter. Is there a way to do this in the template, or should I write the necessary code in my view? -
IntegrityError at /todo NOT NULL constraint failed: todo_todo.name i don't have a Foreign key only a name charfield
models.py from django.db import models # Create your models here. class ToDo(models.Model): name = models.CharField(max_length=200, default=" ") views.py from django.shortcuts import render, HttpResponse from .models import ToDo # Create your views here. def home(request): # temp = ToDo.objects.all() # context = {'temp':temp} data = request.POST.get('name') print(data) context = {'data':data} return render(request, "todo/home.html", context) def todo(request): # temp = ToDo.objects.all() # context = {'temp':temp} name = request.POST.get('name') todo = ToDo(name=name) todo.save() context = {'names' : todo} return render(request, "todo/todo.html", context) todo.html <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <h1>TO DO LIST</h1> <form method="post" action="/todo"> {% csrf_token %} <label for="name"> </label> <input type="text" name="name" id="name"> <br> <button type="submit">Add Task</button> </form> {% for x in names %} <h4>{{ x.name }}</h4> {% endfor %} </body> </html> I have tried changing name's and id's everything that was there in youtube but no solution I don't know where the error is occuring in the error page it shows todo.save() has the error but i don't know where the error is occuring at please help :( -
Django ORM, How to join a dropped table, with multiple conditions
class Post(Common): author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() class Comment(Common): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField() class Test(Common): post = models.ForeignKey(Post, on_delete=models.CASCADE) tester = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category) class Category(Common): pass I want to find a query (Inner JOIN test ON Test.post _id = Comment.post _id AND Test.tester_id = Comment.author_id) to specify two conditions for the join syntax when executing the query based on the following Comment table, but I leave a question because it is hard to find. -
How to solve jquery datatables repeated search and pagination rows?
I am using HTMX (for Ajax requests) and JQuery Datables in a django project, but I am experiencing a weird issue. Indeed the datatables work fine, but repeat search and pagination rows when I navigate history using the browser forward or back buttons. I assume it has to do with htmx given that when issuing Ajax requests the new content will replace the old one and the tables will probably be reinitialized with no page refresh I'd be happy if you could help. Thanks -
Django - Running pip as the 'root' user can result in broken permissions
I'm deploying my Django backend utilizing the AWS app runner service. The contents of my files are as follows. apprunner.yaml version: 1.0 runtime: python3 build: commands: build: - pip install -r requirements.txt run: runtime-version: 3.8.16 command: sh startup.sh network: port: 8000 requirements.txt asttokens==2.2.1 backcall==0.2.0 category-encoders==2.6.0 certifi==2023.7.22 charset-normalizer==3.3.0 colorama>=0.2.5, <0.4.5 comm==0.1.3 contourpy==1.0.7 cycler==0.11.0 debugpy==1.6.7 decorator==5.1.1 distlib==0.3.7 executing==1.2.0 filelock==3.13.0 fonttools==4.40.0 gunicorn==20.1.0 idna==3.4 ipykernel==6.23.2 ipython>=7.0.0, <8.0.0 jedi==0.18.2 joblib==1.2.0 jupyter_client==8.2.0 jupyter_core==5.3.0 kiwisolver==1.4.4 matplotlib==3.7.1 matplotlib-inline==0.1.6 nest-asyncio==1.5.6 numpy==1.24.2 opencv-python==4.7.0.68 packaging==23.0 pandas==1.5.3 parso==0.8.3 patsy==0.5.3 pickleshare==0.7.5 Pillow==9.5.0 pipenv==2023.10.24 platformdirs==3.11.0 prompt-toolkit==3.0.38 psutil==5.9.5 pure-eval==0.2.2 pycodestyle==2.10.0 pygame==2.1.3 Pygments==2.15.1 pyparsing==3.0.9 python-dateutil==2.8.2 pytz==2022.7.1 pyzmq==25.1.0 scikit-learn==1.2.1 scipy==1.10.0 seaborn==0.12.2 six==1.16.0 stack-data==0.6.2 statsmodels==0.13.5 threadpoolctl==3.1.0 tornado==6.3.2 traitlets==5.9.0 urllib3>=1.25.4, <1.27 virtualenv==20.24.6 wcwidth==0.2.6 whitenoise==6.4.0 startup.sh #!/bin/bash python manage.py collectstatic && gunicorn --workers 2 backend.wsgi By the way all the packages are installed successfully in the AWS app runner, finally it gives 10-29-2023 02:39:34 AM [Build] [91mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv 10-29-2023 02:39:34 AM [Build] [0mRemoving intermediate container 4a0110123b9d 10-29-2023 02:39:34 AM [Build] ---> fca9ca934529 10-29-2023 02:39:34 AM [Build] Step 5/5 : EXPOSE 8000 10-29-2023 02:39:34 AM [Build] ---> Running in c8a4669398b0 10-29-2023 02:39:34 AM … -
Python Django OAuth toolkit postman works fine but unsupported_grant_type using expo with axios
So this is a little strange of a problem. I'm using Python Django 4.2.5 as my back-end while my front-end is React Native with Expo and Axios 1.6 for all HTTP requests. For authentication, I'm using django-oauth-toolkit version 2.3.0. Now the problem is that Postman does fine with the /o/token/ request to fetch an OAuth2 token, however I keep getting the unsupported_grant_type error with Axios. Here is my configurations on Postman (disclaimer: I know this password looks somewhat realistic. I do not use this for anything else. I'm only using a somewhat complex one in a dev environment because Django Admin is smart about minimum password complexity): What the response to this Postman request is, is this: I try the same thing in Axios: axios .post(DEV_DOMAIN, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br' }, client_id: CLIENT_ID, client_secret: CLIENT_SECRET grant_type: 'password', username: username, password: password }) , but I get this: (I redacted the host, client ID and client secret, I quadruple-checked and they're the same as in Postman) {"message":"Request failed with status code 400","name":"AxiosError","stack":"AxiosError: Request failed with status code 400\n at settle (http://192.168.1.222:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&lazy=true:147573:37)\n at onloadend (http://192.168.1.222:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&lazy=true:147469:29)\n at call (native)\n at dispatchEvent (http://192.168.1.222:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&lazy=true:31756:31)\n at setReadyState (http://192.168.1.222:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&lazy=true:30386:29)\n at … -
Use of django-modeltranslation with django-filter
I'm constructing Django-based 4-language website for a real estate agency. I'm using django-modeltranslation for translation and django-filter package to filter property objects by certain parameters, such as type (house, apartment, etc.), city and some others. The 'type' of a property is a foreign key of the related model 'Type'. It uses ModelChoiceFilter to select all available types from the database, and render them as a select element with options, which is and is displayed as a drop list with options, which is good so far. class SalePropertyFilter(FilterSet): ... type = ModelChoiceFilter( queryset=Type.objects.all(), empty_label=_("Any type"), label="", widget=forms.Select(attrs={'class': 'form-control'}), ) However, the drop-down list looks ugly, since the field label is not translated, and the options are displayed as slug names of the related model. What I want is that options are displayed as common names of types (which are in the field 'name') instead of slug names, and they should be translated. That means, in the English version of the site options should be rendered from the field 'name_en', in the Spanish version - from 'name_es', etc. There should be a proper way to do it. Please, help, I'm stuck! -
django.db.utils.OperationalError: no such table: auth_user; but works with django admin
i am beginner to django and learn how to create custom user model using abstractuser in my accounts app. But while creating registration system I got this issue: django.db.utils.OperationalError: no such table: auth_user Request URL: http://localhost:8000/accounts/register/ Django Version: 4.2.6 Python Version: 3.11.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig'] Installed 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'] Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above exception (no such table: auth_user) was the direct cause of the following exception: File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/views/generic/base.py", line 143, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/home/qrkeeper/accounts/views.py", line 55, in post user.save() ^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/contrib/auth/base_user.py", line 76, in save super().save(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 814, in save self.save_base( ^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 877, in save_base updated = self._save_table( File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 1020, in _save_table results = self._do_insert( File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 1061, in _do_insert return manager._insert( File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/manager.py", line 87, in … -
Django profile update comes out as an error
I have been developing a blog and facing the same issue again and again. "" p_form = ProfileUpdateForm(instance=request.user.profile) "" This part of the code is showing an error and I have no idea what to do. I have tried everything. The error is ""Exception Value: User has no profile."" I tried manually creating a profile. No use. Please help -
How can I add my python code to my django web app?
So I'm building a website using django and what it's supposed to do is detect emotions in real time, like there should be a button to start and stop detecting and it will use the device's webcam. I've already built both the django project and app and written the python code to do that but i wrote them separately. The problem comes when I'm trying to add the python code to my web app views.py and template(html). This is my code, could someone help me out? #mood detection python code import cv2 import numpy as np from deepface import DeepFace def detect_emotions(): face_cascade_name = cv2.data.haarcascades + 'haarcascade_frontalface_alt.xml' face_cascade = cv2.CascadeClassifier() if not face_cascade.load(cv2.samples.findFile(face_cascade_name)): print("Error loading xml file") cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() resized_frame = cv2.resize(frame, (48, 48), interpolation=cv2.INTER_AREA) gray_frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2GRAY) img = gray_frame.astype('float32') / 255.0 img = np.expand_dims(img, axis=-1) img = np.expand_dims(img, axis=0) analyze = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False) cv2.rectangle(frame, (0, 0), (200, 30), (0, 0, 0), -1) first_data = analyze[0] dominant_emotion = first_data['dominant_emotion'] text = str(dominant_emotion) cv2.putText(frame, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) cv2.imshow('Real-time Emotion Detection', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() if __name__ == "__main__": detect_emotions() … -
How to display a non-default value in django-admin?
I have the Model: class Question(models.Model): type = models.CharField( choices=[["text", "Text"], ["choice", "Choice"]], max_length=6, ) structure = models.JSONField( default=dict, ) def get_default_structure(self) -> dict: if self.type == "text": return {"maxLength": None} if self.type == "choice": return {"variants": []} return dict() @receiver(post_init, sender=Question) def set_default_structure(sender: Type[Question], **kwargs): instance = kwargs["instance"] if not instance.structure: instance.structure = instance.get_default_structure() Also there is Form and ModelAdmin: class QuestionForm(ModelForm): class Meta: model = Question fields = "__all__" @admin.register(Question) class QuestionAdmin(admin.ModelAdmin): form = QuestionForm By logic, after initializing an empty Question, the structure field should be overwritten, and it is. But still the admin form for some reason displays the {} value gotten from default=dict. Why does this happen and how can I make the structure widget display not the {} value, but the value taken from the get_default_structure method? -
Static files not loaded when deploy a django web page in vercel(with whitenoise)
when the project is deployed shows this error here is my settings.py: import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-^30@=wx2m&2q6l48hxb*y6c%0negga@@eixcj5%-rn^3yzo#^k' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'me', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', "whitenoise.runserver_nostatic", 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", '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', ] ROOT_URLCONF = 'Matheus.urls' 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', ], }, }, ] WSGI_APPLICATION = 'Matheus.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT … -
Django Q() for filtering returns the same objects multiple times
I am making a tutoring dashboard in Django. The tools used are htmx,jquery, bootstrap. In the tutors.html page, there is a searchbar. When an user types something, it will send a request to the server and it would call the view search_tutor. The following is the code: <form method="POST"> {% csrf_token %} <div class="form-floating mb-3"> <input class="form-control" id="search-input" hx-get="{% url 'search_tutor' %}" hx-target="#tutors" hx-trigger="keyup changed" name="q" placeholder="Search Tutor" data-sb-validations="required"> <label class="text-muted" for="q"> Search Tutor</label> </div> </form> <div id="tutors" style="transition:1s"> {% include "templates/partials/tutors.html" %} </div> The Tutor Model is the following: class Account(models.Model): token = models.CharField(max_length=50, unique=True) user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to=upload_prof_pic, blank=True, null=True) school = models.ForeignKey(School, on_delete=models.CASCADE , null=True) country = models.ForeignKey(Country, on_delete=models.DO_NOTHING, related_name='account_country', null=True) phone = models.CharField(max_length=20, blank=False) added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) stripe_account = models.CharField(max_length=300, blank=True) stripe_client = models.CharField(max_length=300, blank=True) is_tutor = models.BooleanField(default=False) description = models.TextField(max_length=600, blank=False) tutor_subject = models.ManyToManyField(Subject, blank=True, null=True ) def __str__(self): return str(self.user) def get_phone(self, *args, **kwargs): if self.country != None: return f"+{self.country.phone_extension} ({self.phone1})-{self.phone2}-{self.phone3}" else: return "NONE" def rating_score (self, *args, **kwargs): total = 0 amount = 0 r = Rating.objects.filter(user=self.user) if r.count() == 0 : return 0 else: for i in r.all(): total += i.rating amount +=1 return total/amount def … -
How can i save cart in session if user logout?
I store users carts in sessions, but when they log out their accounts, they are deleted. I decided to save the keys when they logout of their account in the database, and restore them in the sessions when they login. Is this method reliable and secure today, and are there any other methods? class UserLoginView(View): def post(self, request): email = request.POST.get('username') password = request.POST.get('password') if email and password: user = auth.authenticate(email=email, password=password, request=request) if user is not None and user.is_active: login(request, user) if SessionKey.objects.filter(user=request.user).exists(): session_key = SessionKey.objects.get(user=request.user) if session_key.key: cart = json.loads(session_key.key) request.session[settings.CART_SESSION_ID] = cart return JsonResponse({'status': 200}) return JsonResponse({'status': 400}) return JsonResponse({'status': 400}) def logout(request): cart = request.session.get(settings.CART_SESSION_ID, None) session_key, created = SessionKey.objects.get_or_create(user=request.user) auth.logout(request) if cart: session_key.key = json.dumps(cart) session_key.save() return HttpResponseRedirect(reverse('home')) -
What is the most secure way to store sessions with Django?
What Django session storage should I use for enhanced security? -
You cannot call this from an async context - use a thread or sync_to_async. Django ORM
I wrote the following code: class BookmakerA: def __init__(self) -> None: self.bookmaker = None async def _init(self): self.bookmaker, _ = await Bookmaker.objects.aget_or_create(name="BookmakerA", defaults={"name": "BookmakerA"}) I call this class from a Celery task which looks as follows: @shared_task def get_bookmaker_matches(): start = time.time() bookmakera = BookmakerA() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(bookmakera._init()) This however results in the following error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Why does this happen and how do I resolve this. Using Django 4.2.6 which supports async ORM (acreate_or_create, aget, so on)