Questions & Answers about Django, page 2006

django create views use more models

hi everyone I have a doubt with the use of forms and models. I have to create a code that creates records in multiple tables and I don't know how to do it. my goal is to create a page …


I'm trying to get my Django project up and running but keep getting the error below when I run the code in the virtual environment. What could be the problem? Thanks! Traceback (most recent call last): File "D:\Studio\Python\REST\elections\", line …

How can I display the image to the desired product category? (if there are two separate models (Product and Image))

I can't figure out how to connect two models (product and images) in views and output images in html. At the moment, several images are loaded for a specific project (for example, photos of a 3D model) all this through …

Django Rest Framework: Register pure function-based views with router so it appears under API root

This is my class ChoicesViewSet(viewsets.ModelViewSet): queryset = SingleChoice.objects.all() serializer_class = SingleChoiceSerializer ... class AssessmentTakersViewSet(viewsets.ModelViewSet): queryset = AssessmentTaker.objects.all() serializer_class = AssessmentTakersSerializer ... @api_view(['POST']) @parser_classes((JSONParser,)) def studio_create_view(request, format=None): """" A view that accept POST request with JSON content and in turn …

i want to do something on value of a ModelForm before saving in database-django

I'm trying to do something on the value of a ModelForm in Django before saving that on the database. that "something" is changing the value of the DateTime field... I want to take Jalali DateTime from the user in the …

Is there any way to clear the session on a browser or tab close in Django as SESSION_EXPIRE_AT_BROWSER_CLOSE = True is not working at all?

When I close a tab or browser and then I run the application again opening the browser again, the previous session remains active. I tried SESSION_EXPIRE_AT_BROWSER_CLOSE = True in file in the project directory as per the Django documentation. …

Bidirectional one-to-may django

I would like to create a bidirectional one-to-many and many-to-one relationship in django like: class User(models.Model): device = dont_know_what_to_write() class Device(models.Model): user = models.ForeignKey( User, on_delete = models.CASCADE ) What should I do?

Django makemigrations does not create admin databases

I have a django project, this is the installed apps entry in INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crawler', ] when I run python migrate everything seems to be fine. But when I try …

in Visual Studio Code, how can i trigger intellisense in an html django template file to get parameters from a .py file under same app?

I'm learning Django and I would like to know if there's a way to trigger intellisense within an html django template file to get a parameter declared in a python class from another file under the same app, I'm trying …

jango filter by latest date in python

I have the following model class CoinsQuotes(models.Model): coinQuotesID = models.AutoField(primary_key=True) coinID = models.ForeignKey(Coins, on_delete=models.CASCADE) coinCurrency= models.CharField(max_length=10) coinPrice = models.DecimalField(decimal_places=8, max_digits=40) coinVolume24h = models.DecimalField(decimal_places=2, max_digits=30) coinPercentageChange1h = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange24h = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange7D = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange30D = models.DecimalField(decimal_places=2, max_digits=20) …

Concurrency Tests in Django

Just started Django last month. I needed help running concurrency tests in Django, so what I've done is tried to write code that will prevent issues that arise due to lack of concurrency but what I don't know is how …

Using Arabic letters in Django urls causes a 404 error

I want to use Arabic letters in my addresses, there is no problem in local mode, but it causes an error on the server. class Product(models.Model): title = models.CharField(max_length=40, verbose_name='عنوان محصول') slug = models.SlugField(max_length=100,unique=True,allow_unicode=True, verbose_name='آدرس') urlpatterns = …

how make django sleep

I have a project in which one client register a request and some other clients must answer if they want to work with him or not in real time the problem is that how can i sleep the consumer of …

Как совместить во views две models (Images и Products)?

Не могу понять, как связать две модели (продукт и картинки) во views и вывести картинки в html. В будущем это будет отдельной формой. Через админку заливаю по 3-4 фотографии к каждому проекту. Не знаю, как вывести одну к нужному проекту …

menu model design like uber eats menu maker with rules and pricing

I am trying to mimic uber eats menu maker. It has a concepts like modifier, modifier groups, ingredients, preparation time, rules for modifier groups and able to set conditional pricing. I am not quite confident but at least I have …

ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied

Please Help me to install Django on virtual enviroment My terminal throw this error ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/home/user/lib/python3.8/site-packages/sqlparse' Consider using the --user option or check the permissions.

serializer.is_valid returns false with an error that the field is required even though I am passing it

I am building a serializer so that if I post using the following command curl -d '{"food": "test", "portion": 12}' it will save to the db. However my problem is serializer.is_valid() returns false with an error that the field …

How to Update field of Django model based on another model with foreign key relation

I have two models Betslip and Bet,I want to update value of Betslip.settled_status to 'Lost', if Bet.settlement_status is 'half_lost' or 'lost', can anyone create a method for it ? class Betslip(models.Model): SETTLED_STATUS_CHOICE = ( ('InGame','InGame'), ('Won','Won'), ('Lost','Lost'), ('Refunded','Refunded') ) settled_status …

Obtaining unique set of related models

I'm attempting to get a unique set of Employees that are represented within a queryset of jobs. My models are as follows: class Employee(models.Model): name = models.CharField(max_length=100) class Job(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True) start_time = models.DateTimeField(null=True, blank=False) end_time = …

Add view count if video is played more than 3 seconds

I am building a Simple Video App. What i am trying to do :- I am trying to add a user's view count if video is played more than three seconds. What i have done :- I got the …


Константы Python: Улучшение управляемости вашего кода

Современный Python: начинаем проект с pyenv и poetry

Настройка проекта Python — виртуальные среды и управление пакетами

Использование requests в Python — тайм-ауты, повторы, хуки

Понимание декораторов в Python

ProcessPoolExecutor в Python: полное руководство

map() против submit() с ProcessPoolExecutor в Python

Понимание атрибутов, словарей и слотов в Python

Полное руководство по slice в Python

Выпуск Django 4.0

Безопасное развертывание приложения Django с помощью Gunicorn, Nginx и HTTPS

Автоматический повтор невыполненных задач Celery

Django REST Framework и Elasticsearch

Докеризация Django с помощью Postgres, Gunicorn и Nginx

Асинхронные задачи с Django и Celery

Релизы безопасности Django: 3.2.4, 3.1.12 и 2.2.24

Выпуски исправлений ошибок Django: 3.2.3, 3.1.11 и 2.2.23

Эффективное использование сериализаторов Django REST Framework

Выпуски безопасности Django: 3.2.2, 3.1.10 и 2.2.22

Выпущенные релизы безопасности Django: 3.2.1, 3.1.9 и 2.2.21

View all tutorials →