Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make easy to share offline django projects
I have completed a Django project. It runs well on the development server on my machine. However, it can't be shared and run on other devices easily. How can I package it so that it can easily be shared and run on local server, offline on individual machines? What I do: I use xampp to serve it from Apache then manually copy the necessary files. However this has too many setting up steps, copy paste files and not user friendly at all. Is there a better way? -
django.db.utils.DatabaseError with MongoDB as Backend Database
i was using MongoDB as my Backend Database which was working perfectly today until now!. i didn't make any changes, yet suddenly every time i runserver, i get this error. can't even debug what's the issue here. i really haven't made any change in Django yet this is happening. please help me figure this out! #my models.py from django.db import models from django.contrib.auth.models import User class Room(models.Model): name = models.CharField(max_length=100,unique=True,blank=True,null=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,default=User.objects.get(id=1).id) rooms = models.ManyToManyField(Room) def __str__(self): return self.user.username class Message(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,blank=False,null=True) message = models.TextField(max_length=500,blank=False,null=True) name = models.CharField(max_length=100,blank=True,null=True) room = models.ForeignKey(Room,on_delete=models.CASCADE,null=True) time = models.DateTimeField(auto_now_add=True) received = models.BooleanField(default=False,null=True) terminal response Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 808, in __iter__ yield from iter(self._query) File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 166, in __iter__ for doc in cursor: File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\cursor.py", line 1238, in next if len(self.__data) or self._refresh(): File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\cursor.py", line 1130, in _refresh self.__session = self.__collection.database.client._ensure_session() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1935, in _ensure_session return self.__start_session(True, causal_consistency=False) File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1883, in __start_session server_session = self._get_server_session() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1921, in _get_server_session return self._topology.get_server_session() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\topology.py", line 520, in get_server_session session_timeout = self._check_session_support() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\topology.py", line 504, in _check_session_support self._select_servers_loop( File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\topology.py", line … -
corsheaders.E013 error in django cors headers
I try to open port for using django backend as API at 'http://localhost:3000' here is my implement CORS_ALLOWED_ORIGINS = ( 'http://localhost:3000' ) INSTALLED_APPS = [ * 'corsheaders', ] MIDDLEWARE = [ * "corsheaders.middleware.CorsMiddleware",# new "django.middleware.common.CommonMiddleware", # new * ] but I keep getting the error message like this django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E013) Origin '/' in CORS_ALLOWED_ORIGINS is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '/' in CORS_ALLOWED_ORIGINS is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ALLOWED_ORIGINS is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ALLOWED_ORIGINS is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). . . . . . . System check identified 21 issues (0 silenced). PS. python version 3.10.6 django version 4.0.6 django-cors-headers version 3.13.0 -
Django 4.1 can't connect to MSSQL
I have two servers, both running Ubuntu 22.04. The application server is running Django 4.1, and the database server is running a fresh install of SQL Server installed following these instructions. I followed these instructions in order to install the ODBC driver. And then per THESE instructions, set up my Django setttings.py file as follows: default_db_settings = { 'ENGINE': 'mssql', 'NAME': '***', 'USER': '***', 'PASSWORD':'***', 'HOST':'***', 'PORT':'5432', 'OPTIONS':{'driver':'ODBC Driver 18 for SQL Server'} } Trying to visit my site, I get: django.core.exceptions.ImproperlyConfigured: 'mssql' isn't an available database backend or couldn't be imported. just for some sanity checking: sudo apt-get install msodbcsql18 [sudo] password for ***: Reading package lists... Done Building dependency tree... Done Reading state information... Done msodbcsql18 is already the newest version (18.1.1.1-1). 0 upgraded, 0 newly installed, 0 to remove and 18 not upgraded. sudo apt-get install mssql-tools18 Reading package lists... Done Building dependency tree... Done Reading state information... Done mssql-tools18 is already the newest version (18.1.1.1-1). 0 upgraded, 0 newly installed, 0 to remove and 18 not upgraded. sudo apt-get install unixodbc-dev Reading package lists... Done Building dependency tree... Done Reading state information... Done unixodbc-dev is already the newest version (2.3.9-5). 0 upgraded, 0 newly installed, 0 … -
OSError at /register/
OSError at /register/ cannot write mode RGBA as JPEG cant get rid of this error. tried to find solution on stackoverflow cant seem to get one models.py from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default = "default.jpg", upload_to = "profile_pics") def __str__(self): return f"{self.user.username} Profile " def save(self, *args, **kwargs): #helps to resize the image super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width >300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) def save_profile(sender, instance, **kwargs): instance.profile.save() -
How to lazy load javascript libraries after a htmx request?
Im creating a webapp dashboard (django + htmx) and I want to only load the plugins that the user needs and not load every single plugin immediately because it would slow down the site. Example: User clicks a button and the whole html body gets replaced with a wysiwyg editor. Whats the best way to dynamically load a JS library after an htmx request? Thanks in advance -
How to add fields from other (non-page) models in Wagtail Page admin?
I am looking for a way to include other model's fields in the Page editor of Wagtail. The scenario is a digital marketplace, which we want to deploy for multiple clients. Each client has their own specifications for the marketplace participants and therefore needs different fields in addition to the basic fields (title, address etc.) that we define beforehand. I am looking for a solution for the marketplace admin (which won't be us) to be able to add these extra fields, e.g. via Wagtail snippets. They could create a new Custom Field Snippet and define some options for it. The page admin for marketplace participants then needs to display these extra fields in its form (either in a custom tab or just below all the basic fields in the content panel). Is there a way for me to achieve this? I have managed to get the custom fields into the page form but without any kind of Wagtail styling. I am aware of the similar question here but unfortunately the answers there did not help and the scenario is slightly different here. In the question linked the extra field is in Python code in the model definition, something we want … -
What is the best way to create the following model in Django Rest Framework
I am currently in the process of creating a new model. The current model looks like this, DIET_OPTIONS = ( ('vegan', 'Vegan'), ('vegetarian', 'Vegetarian'), ('meat', 'Meat') ) class Madklub(models.Model): owner = models.ForeignKey(MyUser, related_name="owner", on_delete=models.CASCADE) dish = models.CharField(max_length=100) date = models.DateField() guests = models.PositiveIntegerField() active = models.BooleanField(default=True) participants = models.ManyToManyField(MyUser, related_name="participants") diet = ArrayField( models.CharField(choices=DIET_OPTIONS, max_length=10, default="vegetarian") ) Now the model should be quite simple, the most important fields are the two user relationships and the diet field. The idea is that one Madklub has an owner (a owner can have multiple Madklub). Each Madklub has a list of participants, whenever a Madklub is created it should start out with having only one participant, the owner itself. Now this is the first question, how would I go about doing that automatically, should I simply handle that in the view? Side note, the guests field is a field keeping track of how many non-user guests are invited/participates in the Madklub. Would there be a way to bind this to a user, somehow? Now another question is, as can be seen I currently have the diet field as an ArrayField this of course only works with a Postgres database. As I see it, … -
Heroku deployed app returns 500 error - how to further investigate this issue?
So I have an app deployed at https://cherry-app-fr4mk.ondigitalocean.app/. This returns a error 500 page even though I have DEBUG=TRUE. How to further debug this issue and why it doesn't show Django styled errors? DEBUG: Variables: -
Using sourcedefender with Django
I have a python Django code that I wish to encrypt and can still run the django server from the encrypted folder. I read the PyPi specifically under Integrating encrypted code with Django and I could not get it to work. My python Django project structure is as follows: -- backend ---- config directory (where the settings.py file, wsgi.py are) ---- services directory (contains multiple directories of which all are encrypted, service1, service2, service3 which contains the Django rest framework APIs and code logic) ---- manage.py -- requirements.txt For me, it is not important the config directory, manage.py, and requirements.txt to be encrypted. What is important is that the services directory is encrypted. So how can I achieve that? Here is what I have tried. cd backend sourcedefender --remove encrypt --password 1234abcd --salt dcba4321 services In the manage.py, and wsgi.py I add import sourcedefender to the very top and then run python3 -m sourcedefender manage.py runserver and I get ImportError: manage Any help is appreciated. -
How to Post line items in Django REST API
This GET Response data [ { "id": "055444eb-5c4d-445b-99cc-a01be17deeb7", "transaction_line_items": [ { "id": "5b0ea944-a032-4b8e-a29a-3f52e0863040", "title": "Sambar Powder", "description": "Sambar Powder 100g", "price": "10", "quantity": 1, "created_at": "2022-08-17T14:01:39.387406Z", "updated_at": "2022-08-17T14:01:39.387406Z" }, { "id": "ace1546b-12e4-4a6d-991e-b867cf64515a", "title": "Tomato", "description": "Tomato 10kg", "price": "20", "quantity": 10, "created_at": "2022-08-17T14:01:05.194278Z", "updated_at": "2022-08-17T14:01:05.194278Z" } ], "transaction_no": "6aa623a3", "cgst_per": 8, "igst_per": 8, "sgst_per": 0, "created_at": "2022-08-17T14:01:58.694463Z", "updated_at": "2022-08-17T14:01:58.694463Z", "account": "0b68e37e-ba15-4427-8a45-d48b152a42d5", "main_biiling_account": "edc9d792-ffdb-4122-8589-d499f05e4f7b" } ] This POST Request data { "transaction_line_items":[ { "title":"Tomato", "description":"2 kg Tomato", "price":"10", "quantity":2 }, { "title":"Fish", "description":"2 kg Fish", "price":"500", "quantity":2 } ], "cgst_per":"8", "igst_per":"8", "sgst_per":"0", "account":"edc9d792-ffdb-4122-8589-d499f05e4f7b", "main_biiling_account":"edc9d792-ffdb-4122-8589-d499f05e4f7b" } This POST Response data { "id": "dc2ed349-2e3b-42a3-9ce8-1ecd6f11a225", "transaction_line_items": [], "transaction_no": "6aa623a3", "cgst_per": 8, "igst_per": 8, "sgst_per": 0, "created_at": "2022-08-17T14:08:02.995195Z", "updated_at": "2022-08-17T14:08:02.995195Z", "account": "edc9d792-ffdb-4122-8589-d499f05e4f7b", "main_biiling_account": "edc9d792-ffdb-4122-8589-d499f05e4f7b" } View Code @api_view(['GET','POST']) @permission_classes([IsAuthenticated]) def apiTransactions(request,account_id): if request.method == 'GET': transactions = Transaction.objects.filter(account=account_id,account__user=request.user) serializer = TransactionSerializer(transactions, many=True) return Response(serializer.data) elif request.method == 'POST': data = request.data if (data["account"]==account_id): serializer = TransactionSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'meassage': 'Account ID not match'}, status=status.HTTP_400_BAD_REQUEST) Above I gave codes and JSON data. Why my line items aren't saved? When I enter data using the admin page it's working properly. When I use API it isn't saved properly. How … -
Django and Flutter wth http Plugin
I've created a REST API with Django and I want to use it in Fluter. I've created the endpoints and tested them; they work fine, I've also created the models in flutter. I've done the get all endpoint. I'm now struggling with how to decode the details endpoint and use it in Flutter. Anyone's thoughts ? -
how to apply bubble sort in django queryset
*how to sort object using bubble sort in django.TypeError: '<' not supported between instances of 'Product' and 'Product' -
What is the advantage of binding to a socket instead of an IP?
I'm following this guide to deploy a flask application to production using gunicorn I get to this line gunicorn --bind 0.0.0.0:5000 wsgi:app and it works perfectly After that the author recommends this instead gunicorn --workers 3 --bind unix:/home/movieapp/app.sock -m 777 wsgi:app So my (dumb) question: what is the advantage of binding to a socket instead of an IP? Thank you for your help! -
DRF: Serializer for different queryset
I have following serializer class VoteBaseSerializer(serializers.Serializer): likes = serializers.IntegerField() dislikes = serializers.IntegerField() is_voted = serializers.SerializerMethodField() def get_is_voted(self, obj): user = self.context.get('request').user vote = None if user.id: try: vote = Vote.objects.get(pk=obj.pk, user_id=user.id).choice except Vote.DoesNotExist: pass return vote My problem that i want yo use this serializer for different views. I have view that return article with prefetch_relted comments, then i annotate likes, dislikes and is_voted I have view that update vote object. And i want to return new condition. The problem in SerializerMethodField, when i trying get vote object In 1 case i'm working with post object and comment, then with reverse relation i get votes In 2 case i'm update vote by comment_id and there different lookups models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(blank=True) body = models.TextField() tags = TaggableManager(blank=True) pub_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-pub_date'] class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.TextField(max_length=500) pub_date = models.DateTimeField(auto_now=True) parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE, related_name='children') class Meta: ordering = ['-pub_date'] class Vote(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name='votes') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) choice = models.BooleanField(null=True) views.py class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer permission_classes = [IsOwnerOrAdminOrReadOnly] pagination_class = PostPagination lookup_field … -
how to create a API for user model in Django?
I am Trying To create a API for my custom user model to register a user and get details about current user that is logged in . I tried to Follow a tutorial but I faced 2 problems, 1.The confirmation password is not being hashed when creating a user, 2. The Get method didn't work. I hope any one can help me. This is my models.py: from django.db import models from django import forms # Create your models here. from django.db import models from django.contrib.auth.models import ( AbstractUser, BaseUserManager, AbstractBaseUser ) from django.forms import Widget from django.urls import reverse class CustomUserManager(BaseUserManager): def create_user(self,email,password=None,is_active=True,is_staff=False,is_admin=False): if not email: raise ValueError('User Must Have Email') if not password: raise ValueError('User Must Have Password') user_obj = self.model( email = self.normalize_email(email) ) user_obj.set_password(password)#change user password user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,password=None): user = self.create_user( email, password = password, is_staff = True ) return user def create_superuser(self,email,password=None): user = self.create_user( email, password = password, is_staff = True, is_admin = True, ) return user class CustomUser(AbstractBaseUser): username = models.CharField(max_length= 200) first_name = models.CharField(max_length = 300) last_name = models.CharField(max_length = 300) email = models.EmailField(max_length=255,unique=True) password = models.CharField(max_length=100,) password_2 = models.CharField(max_length=100,) sub_to_newsletter … -
How to change type in Django_filter input?
I have Django_filters form: class ContainerFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super(ContainerFilter, self).__init__(*args, **kwargs) self.filters['title'].label = 'Продукт' self.filters['status'].label = ' Первый Статус' self.filters['status1'].label = 'Второй Статус' start_date = DateFilter(label='Создан от', field_name='created', lookup_expr='gte') end_date = DateFilter(label='Создан до', field_name='created', lookup_expr='lte',) class Meta: model = Container fields = ('title', 'status', 'status1', 'warehouse', 'start_date', 'end_date') And I want to change the start_date input type from text to date. I add widgedts in Meta but it's give error also i did widgets to input but it still don't work. -
Why I'm Not Getting Lable Tag Even After Loading It On The Templates?
Here Is The Template Image :- templates.html I'm Facing Problem While Rendering Template ,The Issue Is That The {{field.lable_tag}} Is Not Working I'm supposed To Get Field Lable which Is Wrapped In HTML Here Is My HTML code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Index</title> </head> <body> <form action="" method="POST" novalidate> {%csrf_token%} {{form.non_field_error}} {% for field in form %} <div> {{field.lable_tag}} {{field}} {{field.errors|striptags}} </div> {%endfor%} <input type="submit" value="Submit"> </form> </body> </html> -
psycopg2.OperationalError: SSL SYSCALL error: EOF detected django Qcluster
Hi I'm trying to run a function as a background job from Django Qcluster and that jobs run for more than an hour based on the response of that job I update my Postgres table but when I get a response from Qcluster and try to update the table it gives me this error. How can I fix this error? psycopg2.OperationalError: SSL SYSCALL error: EOF detected. Qcluster setting: { "name": "sampleapp", "workers": 8, "recycle": 500, "compress": true, "save_limit": 250, "queue_limit": 500, "cpu_affinity": 1, "label": "Django Q", "max_attempts": 1, "attempt_count": 1, "catch_up": false, "redis": { "host": "127.0.0.1", "port": 6379, "db": 0 } } Django==3.1.7 django-q==1.3.9 Here is the complete stack trace: SSL SYSCALL error: EOF detected 15:36:35 [Q] ERROR Failed [kentucky-montana-west-alaska] - connection already closed : Traceback (most recent call last): File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/venv/lib/python3.9/site- packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.OperationalError: SSL SYSCALL error: EOF detected The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/connector/sync_utils.py", line 1361, in run_data_sync if not table_pipeline_json.count(): File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/venv/lib/python3.9/site- packages/django/db/models/query.py", line 411, in count return self.query.get_count(using=self.db) File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/venv/lib/python3.9/site- packages/django/db/models/sql/query.py", line 515, in get_count number = obj.get_aggregation(using, ['__count'])['__count'] File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/venv/lib/python3.9/site- packages/django/db/models/sql/query.py", line 500, in get_aggregation result = … -
How to filter queryset based on MethodSerializerField value?
I have serializers with SerializerMethodField field class EmployeeSerializer(serializers.Serializer): id = serializers.IntegerField() name = serializers.CharField() group_ids = serializers.SerializerMethodField() def get_group_ids(self): /* this method returns array of group_ids employee can me member of */ there is view: class EmployeeViewSet(GenericViewSet): serializer_class = EmployeeSerializer def get_queryset(self): return Employee.objects.all() If I want to list all employees I call this url and get the next resutl: http://localhost:8080/employees/ [ { "id": 1, "name": "Ann", "group_ids": [ 90, 100 ] }, { "id": 2, "name": "Tom", "group_ids": [ 90, 102 ] } ] I want to filter result by group_id. To have something like this: http://localhost:8080/employees/?group_id=102 and as a result I'll recieve only: [ { "id": 2, "name": "Tom", "group_ids": [ 90, 102 ] } ] Is there any options to filter queryset based on calculated value such as SerializerMethodField value? Thanks in advance -
Django ManytoMany field remains empty after .add() method called
Hi all so I'm using django to create a sign up platform where students can sign up to weekly classes. Each class is a django model called ClassCards with a User manytomany field called signed_up_student that represents all the users signed up for that class as seen below ''' class ClassCards(models.Model): content = models.CharField(max_length=100, default = '') date = models.DateField(blank=True, null = True) time = models.TimeField(blank=True,null=True) signed_up_students = models.ManyToManyField(User,blank=True) full = models.BooleanField(default = False) max_students = models.IntegerField(default=4) teacher = models.CharField(max_length=100, default='Adi') ''' I would like to add a subscription option that will autamatically sign up subscribed students to this weeks class. Here is my subscription model: ''' class Subscriptions(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null =True) day = models.CharField(max_length=100, choices=day_choices, null=True) time = models.TimeField(blank=True, null=True) num_of_times_used = models.IntegerField(default=0) cap = models.IntegerField(default=52) active = models.BooleanField(default= True) expirey_date = models.DateField() date_created = models.DateField(default = timezone.now) ''' To accomplish this I have created a post_save signal: ''' @receiver(post_save,sender=ClassCards) def apply_subsciptions(sender,instance,created, **kwargs): if created: subs = Subscriptions.objects.filter(day=instance.date.strftime("%A"), time=instance.time) for s in subs: instance.signed_up_students.add(s.user) print(instance.signed_up_students.get()) ''' The code runs properly when a ClassCard is saved without throwing any errors and the print statement prints the relevant User. However when i look on the admin page i … -
Heroku deploys app but can't serve it - ModuleNotFoundError: No module named 'django_app'
I'm trying to deploy an app via Digitalocean/Heroku which works for both the build and deployment. However, once I visit the successfully deployed site I get this: I already tried this without success. This is the full traceback: [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [1] [INFO] Starting gunicorn 20.1.0 [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [1] [INFO] Using worker: sync [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [17] [INFO] Booting worker with pid: 17 [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [17] [ERROR] Exception in worker process [cherry] [2022-08-17 13:43:20] Traceback (most recent call last): [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker [cherry] [2022-08-17 13:43:20] worker.init_process() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process [cherry] [2022-08-17 13:43:20] self.load_wsgi() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi [cherry] [2022-08-17 13:43:20] self.wsgi = self.app.wsgi() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi [cherry] [2022-08-17 13:43:20] self.callable = self.load() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load [cherry] [2022-08-17 13:43:20] return self.load_wsgiapp() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp [cherry] [2022-08-17 13:43:20] return util.import_app(self.app_uri) [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app [cherry] [2022-08-17 … -
Issue with Datetime from database and Django
I'm trying to generate some basic chart data, but I cannot, yet anyways. Whenever I retrieve datetime values from Django models, it gives me this output: [print(i) for i in UserAnalyticsMeta.objects.all().values('created_at')[:3]] {'created_at': datetime.datetime(2022, 8, 15, 22, 43, 23, 88381, tzinfo=datetime.timezone.utc)} {'created_at': datetime.datetime(2022, 8, 15, 22, 48, 43, 944993, tzinfo=datetime.timezone.utc)} {'created_at': datetime.datetime(2022, 8, 15, 22, 48, 49, 95255, tzinfo=datetime.timezone.utc)} Which translates to: 2022-08-15 22:43:23.088381+00:00 2022-08-15 22:48:43.944993+00:00 2022-08-15 22:48:49.095255+00:00 However, when I try to print out the date, this is the output I get: [print(i) for i in UserAnalyticsMeta.objects.all().values('created_at__date')[:3]] {'created_at__date': None} {'created_at__date': None} {'created_at__date': None} While I expect: 2022-08-15 2022-08-15 2022-08-15 What I've also noticed is that an old function I used also doesn't work anymore, and I feel like it has something to do with this. select_data = {"date_created": """strftime('%%m/%%d/%%Y', created_at)"""} qs = self.extra(select=select_data).values('date_created').annotate(models.Sum("page_visits")) return qs Now gives me the error: OperationalError at /admin/app_name/model_name/ (1305, 'FUNCTION app_name.strftime does not exist') Any help would be appreciated! Thank you. -
Django: assigning employees to the hotel rooms and manage dates overlaping and intersection
Task: Imagine we are a company and we want to send our employees on different work trips. Amount of employees for each trip can vary. Also, we are booking hotel rooms for each trip. The room type and max amount of employees per room can be one of these: [{"type": "single", "max_persons": 1}, {"type": "double", "max_persons": 2}, {"type": "triple", "max_persons": 3}, {"type": "quad", "max_persons": 4}] Employees can split the room if room is double, triple or quad Also, employees can live only few days in a row and then next employee could take this room. The task is to get list of dates when room is completely free (no employees lives there) and list of dates when room is partly free (there are 1-3 free beds) Image with visual task explanation The Django models.py is: class Hotels(models.Model): """ Model to store all hotels """ name = models.CharField(max_length=255) phone = PhoneNumberField(blank=True) address = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=255, blank=True) country = CountryField(blank=True) zip = models.CharField(max_length=255, blank=True) REQUIRED_FIELDS = ["name", "address", "city", "country"] def __str__(self) -> str: return self.name class Meta: ordering = ["name"] verbose_name = "Hotel" verbose_name_plural = "Hotels" class RoomTypes(models.Model): """ Model to store all room types """ type = … -
Django Model While User Login
Iam new in programming. I need to make a model/table in django where details of a User has to save. If the User login It will goes to registration page if he is not completed the registration, else if he already completed the registration it will goes to home page. What should I do? models.py class UserReg(models.Model): Name=models.CharField(max_length=200) Date_of_Birth=models.DateField() Age=models.IntegerField() Gender=models.CharField(max_length=200, choices=GenderChoice) Phone_no=models.IntegerField() Mail=models.EmailField(unique=True) Address=models.TextField(max_length=700) District=models.ForeignKey(District,on_delete=models.CASCADE) Branch=models.ForeignKey(Branch,on_delete=models.CASCADE) Account_Type=models.CharField(max_length=200,choices=AccType) Materials=models.ManyToManyField(Materials) views.py def reg(request): form = Userform() if request.method == 'POST': form=Userform(request.POST) if form.is_valid(): Name=request.POST.get('Name') Date_of_Birth = request.POST.get('Date_of_Birth') Age = request.POST.get('Age') Gender = request.POST.get('Gender') Phone_no = request.POST.get('Phone_no') Mail = request.POST.get('Mail') Address = request.POST.get('Address') District = request.POST.get('District') Branch = request.POST.get('Branch') Account_Type = request.POST.get('Account_Type') Materials = request.POST.get('Materials') obj=UserReg(Name=Name,Date_of_Birth=Date_of_Birth,Age=Age,Gender=Gender,Phone_no=Phone_no,Mail=Mail,Address=Address,District=District,Branch=Branch,Account_Type=Account_Type,Materials=Materials) obj.save() return redirect('/') return render(request,'registration.html',{'form':form,})