Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django annotate query to return datetime values in localtime like `Extract` can
settings.py: TIME_ZONE = 'UTC' USE_TZ = True I understand that Django returns values in model queries in UTC. If I want to show the values of time-aware datetime objects to users in there localtime I can do so in templates etc via timezone.activate or timezone.override. I have the need to return all datetime values in a specific timezone before it is rendered in any template. With timezone.activate or timezone.override, I notice `DateTimeField extracts do something close to what I want: import zoneinfo from datetime import datetime from django.utils import timezone class Experiment(models.Model): created_at = models.DateTimeField() created_at = datetime(2015, 6, 15, 23, 30, 1, tzinfo=timezone.utc) Experiment.objects.create(created_at = created_at) tz = zoneinfo.ZoneInfo('Australia/Melbourne') with timezone.override(tz): qs = Trade.objects.annotate(hour=ExtractHour('created_at')).values('created_at', 'hour') print(qs.query) print(qs) Output SELECT "experiment"."created_at", EXTRACT('hour' FROM "app_trade"."created_at" AT TIME ZONE 'Australia/Melbourne') AS "hour" FROM "experiment" <QuerySet [{'created_at': datetime.datetime(2015, 6, 15, 23, 30, 1, tzinfo=<UTC>), 'hour': 9}]> Notice the hour 'Australia/Melbourne' and created_at is UTC. What I want is I want all my timestamps to comeback in specified zone. Is there a Django-native or elegant way to do this? Hopefully integrated with any timezone.override. Something like: tz = zoneinfo.ZoneInfo('Australia/Melbourne') with timezone.override(tz): qs = Trade.objects.annotate(local_created_at=LocalTimeZone('created_at')).values('created_at') Related How can I cast a DateField() + TimeField() to … -
Sum aggregation over a JsonField using Django Orm
I have a model in my django project with the following structure: class Portfolio(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) entered_usdt = models.DecimalField(max_digits=22, decimal_places=2, default=0) detail = models.JSONField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I would like to have a Sum aggregate function over non-zero value keys of detail field of records this model in database. This field may be empty or have different keys for earch record in database for example I capture a section of database to better explain what I mean: For this purpose, I wrote the below code snippet with pure Python, which first extracts their keys for records whose details are not empty, and then calculates the sum of all those keys in all those records. import json from bestbuy.models import Portfolio from django.db.models import Q def calculate_sum_of_all_basket_coins(): non_zero_portfolios_details = list(Portfolio.objects.filter(~Q(detail={})).values('detail')) detail_list = list() result = {} for detail in non_zero_portfolios_details: detail_list.append(json.loads(portfolio)) for d in detail_list: for k in d.keys(): if k in result: result[k] += d.get(k, 0.0) else: result[k] = d.get(k, 0.0) return result I know this method is not good at all because as the database records increase, this function takes more and more time to perform this calculation. I also read the below … -
How I do save stars in Movie model?
Wha I want to achive. I want to save stars in Movie model when def average_stars() is used. I want to put a number in stars and save it when the movie function is called like the code below. What should I do? class Movie(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_movie.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars -
AuthCanceled at /oauth/complete/github/ (Authentication process canceled)
I'm working with a Django app and when I try to login with Github, this error occurs: AuthCanceled at /oauth/complete/github/ Authentication process canceled Request Method: GET Request URL: https://my-site.com/oauth/complete/github/?code=xxxxxxxxxxxxxx&state=xxxxxxxxxxxxxx Django Version: 3.0.5 Exception Type: AuthCanceled Exception Value: Authentication process canceled Exception Location: /usr/local/lib/python3.7/site-packages/social_core/utils.py in wrapper, line 254 Python Executable: /usr/local/bin/python Python Version: 3.7.2 Python Path: ['/code', '/usr/local/bin', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages'] I have set (correctly, I think) SOCIAL_AUTH_GITHUB_KEY and SOCIAL_AUTH_GITHUB_SECRET on my settings.py (adding https://my-site.com/oauth/ as Authorization callback URL on https://github.com/settings/applications/XXXXX). Any idea of where is the problem? -
Strings from default locale missing from Django JavaScript catalog
Problem The problem I am having is that the JavaScript catalog doesn't include fallback strings in certain scenarios. In other words: when string "A" is not translated in es_MX but it is translated in es, the JavaScript catalog contains the default or untranslated "A" string. I set up an app that demonstrates this problem: https://github.com/cmermingas/i18n_test Setup LOCALE_PATHS set to PROJECT_ROOT/locale. Translations for all apps stored under LOCALE_PATHS. JavaScriptCatalog configured without packages: path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog') es_MX and es translations that demonstrate the problem: The string "es - Not translated" is translated in the es locale. The string "es_MX - Not translated" is translated in the es_MX locale. Workaround This works if I pass packages to JavaScriptCatalog: path( 'jsi18n/', JavaScriptCatalog.as_view(packages=["testapp"]), name='javascript-catalog' ) But this is not required, is it? I tried this answer, which suggests adding domain="django", but it didn't work for me. What am I doing wrong or is this an issue? -
Why am I seeing "No module named '_tkinter" when I deploy django to heroku?
django works well on my local machine. But, when I deploy it to heroku, I see "ModuleNotFoundError" "No module named '_tkinter'". Though, I never imported "_tkinter" or "tkinter" in my code. Your help will be appreciated. Thank you. ModuleNotFoundError at / No module named '_tkinter' Request Method: GET Request URL: https://howididit.herokuapp.com/ Django Version: 4.0.6 Exception Type: ModuleNotFoundError Exception Value: No module named '_tkinter' Exception Location: /app/.heroku/python/lib/python3.10/tkinter/init.py, line 37, in Python Executable: /app/.heroku/python/bin/python Python Version: 3.10.5 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python310.zip', '/app/.heroku/python/lib/python3.10', '/app/.heroku/python/lib/python3.10/lib-dynload', '/app/.heroku/python/lib/python3.10/site-packages'] -
Django with social auth: Direct assignment to the forward side of a many-to-many set is prohibited
When trying to authenticate (create) a user in Django, I get the following error: Direct assignment to the forward side of a many-to-many set is prohibited. Use gave_mangoes.set() instead. Code: models.py ... from waters.models import Water class User(AbstractUser): id = models.AutoField(primary_key=True) posts = models.ManyToManyField(Water) # MANY TO MANY FIELD CAUSING ERROR ... oauth.py from social_core.backends.oauth import BaseOAuth2 class <name>Oauth2(BaseOAuth2): name = "<name>" AUTHORIZATION_URL = "<url>" ACCESS_TOKEN_URL = "<url>" ACCESS_TOKEN_METHOD = "POST" EXTRA_DATA = [("refresh_token", "refresh_token", True), ("expires_in", "expires")] def get_scope(self): return ["read"] def get_user_details(self, response): profile = self.get_json("<url>", params={"access_token": response["access_token"]}) return { "id": profile["id"], "username": profile["username"], ... } def get_user_id(self, details, response): return details["id"] I read this answer that deals with the same error: You need to save the cart before you can add items to the many-to-many field. However, since I'm using Python Social Auth, it creates the user in the backend, so I'm not able to save it and modify the field later. How can I fix this error? -
why is CSS align-items not centering my text
.top-part { position: relative; display: flex; background: rgba(51, 102, 255,0.7); width: 100%; height: 8cm; background-position: center; background-size: cover; } .not-content { display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; font-family:'Consolas','Courier New','Trebuchet MS'; color: white; line-height: .5cm; flex-wrap: wrap; } <section class="top-part"> <div class="not-content"> <h1><strong>BIG TEXT</strong></h1> <h4>TEXT</h4> </div> </section> i don't know what error I've made, the "align-items: center;" is not working as it should be, it's not centering my text horizontally -
Send Email: user.email_user vs send_mail
_Hi, gentlemans and ladies.) I want to send you email (some spam), but I couldn't. Can you help me? If I use 'email_user' it sends the email. current_site = get_current_site(request) subject = 'Activate Your Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') But when I want to use send_mail instead of email_user, it's not working. I want to understand what I do wrong. send_mail(subject, message, email_from, recipient_list, fail_silently=False) My settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = get_secret('EMAIL_HOST_USER') EMAIL_HOST = get_secret('EMAIL_HOST') EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = get_secret('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = get_secret('EMAIL_HOST_PASSWORD') # Custom setting. To email RECIPIENT_ADDRESS = ['None'] -
comment model not attached to ticket model
Creating a separate comments app for ticket app. My issue is that when I create and submit my comment on a particle ticket, it creates its own new page of tickets instead of being attached to original ticket. I think the issue has to do with my urls.py file and I feel like i'm close to solving this but i’m not sure how to proceed. Here is my comment models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from tickets.models import Ticket class Comment(models.Model): ticket = models.ForeignKey(Ticket, related_name='comments', on_delete=models.CASCADE, null=True) title = models.CharField(max_length=20) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('tickets:ticket-detail', kwargs={'pk': self.pk}) Here is my ticket models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from users.models import Profile class Ticket(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) assignee = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True) status = models.BooleanField(choices=MARKED, default=True) priority = models.TextField(choices=PRIORITIES, default='None', max_length=10) label = models.CharField(choices=TYPES, default='Misc', max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse('ticket-detail', kwargs={'pk': self.pk}) Here is the main urls.py from django.conf import settings … -
How can i automatically fill fields for new users that register django?
i have got a problem with automatically filling fields for new users that register in django. I don't know how can i get some informations. so this is my Profile Model class Profile(models.Model): user = models.ForeignKey(MyUser, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=45) last_name = models.CharField(max_length=60) profile_picture = models.ImageField(default='profile_pics/Default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.first_name} {self.user.last_name}' this is the function that automatically creates Profile. @receiver(post_save, sender=MyUser) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) and this is MyUser model that i use. class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name, mobile, **extra_fields): if not email: raise ValueError("Email must be provided") if not password: raise ValueError("Password is not provided") user = self.model( email= self.normalize_email(email), first_name = first_name, last_name = last_name, mobile = mobile, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password,first_name, last_name, mobile, **extra_fields) def create_superuser(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', True) return self._create_user(email, password, first_name, last_name, mobile, **extra_fields) class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) first_name = models.CharField(max_length=240) last_name = models.CharField(max_length=240) mobile = models.CharField(max_length=50) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects= CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', … -
How to change a django venv (coded on windows) in the way to get it running on linux server?
Iam trying to get my windows django project working on a linux server. I realised that the venv causing trouble to get it running on a linux server. Is there an easy way to convert the venv to linux without booting a linux dist and setup the whole project on linux? Thanks for helping. -
create a django-queryset with all objects but not all related many to many fields by a condition
class Post(models.Model): text = models.TextField() class Project(models.Model): name = models.CharField(max_length=60) description = models.CharField(max_length=500) class Tag(models.Model): name = models.CharField(max_length=60) project = models.ForeignKey(Project, on_delete=models.CASCADE) class TaggedPost(models.Model): org_post = models.ForeignKey(Post, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag) Assumed I have defined above models. There exist multiple projects which all have multiple tags. Eg: Project1 -> Tag1, Tag2 Project2 -> Tag3 Not every Post do have a TaggedPost object. Eg. Post1 -> no tags Post2 ->TaggedPost -> Tag1 Post3 ->TaggedPost -> Tag2 Post4 ->TaggedPost -> Tag2, Tag3 (Here are tags of multiple Projects) What I now want to do is a queryset which contains all Posts (also the untagged posts) but only tags of a defined project. qs.include_tags_of_project(Project1) results in: Post1 -> no tags Post2 -> Tag1 Post3 -> Tag2 Post4 -> Tag2 qs.include_tags_of_project(Project2) results in: Post1 -> no tags Post2 -> no tags Post3 -> no tags Post4 -> Tag3 any sugestions how to handle that? Thx -
AWS RDS postgres runing locally but not on EC2
i set a DB on AWS postgres and its connected locally, but when i push them same app on EC2 server, it give following error django.db.utils.OperationalError: connection to server at "portfolio-db.cco9tqdwh3aa.us-east-1.rds.amazonaws.com" (172.00.69.176), port 5432 failed: Connection timed out Is the server running on that host and accepting TCP/IP connections? Here is the security group of server Security group of DB -
Images are uploaded into S3 but URL within django application is not displaying correctly
Problem I am able to upload images into S3, however the structure of the URL within my django app is not structured properly. The URL appears like this: http://localhost:8000/plants/https://'%s.s3.amazonaws.com'%AWS_STORAGE_BUCKET_NAME/media/plant_images/image.jpeg However, I want it to appear as https://opensprouts-dev-media.s3.amazonaws.com/media/plant_images/images.jpeg Context I have a model that allows me to upload multiple images. I think I need to rewrite the way I call for the image within my template, or within my model. After reading through Django documentation and other stackoverflow questions, I'm not sure how to resolve this issue. settings.py/base.py # MEDIA # ------------------------------------------------------------------------------ USE_S3 = os.getenv('USE_S3') == 'TRUE' AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_QUERYSTRING_AUTH = config('AWS_QUERYSTRING_AUTH') AWS_S3_CUSTOM_DOMAIN = config('AWS_S3_CUSTOM_DOMAIN') AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = config('AWS_LOCATION') PUBLIC_MEDIA_LOCATION = 'media' AWS_QUERYSTRING_AUTH = False MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATIN) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') The section of my template that is calling for the URL {{ image.images.url }} {% for image in plant.plant_images.all %} {% if forloop.first %} <div class="carousel-item active"> {% else %} <div class="carousel-item"> {% endif %} <img src="{{ image.images.url }}" alt="{{ plant.name }}"> </div> {% endfor %} </div> models.py import datetime from django.conf import settings from django.db import models from django.utils import … -
Chain filtering with OR operator in the filterset - Django Rest Framework
I want to use multiple filter fields together in the filterset class which I can populate in the browsable api and make queries with OR condition. For example: SELECT name FROM Person WHERE age > 17 OR address LIKE ‘%New%’ I wonder how to implement something like this as HTML controls in the browsable API : f = Q(name__contains='Ja') | Q(age>500000) qs = qs.filter(f) -
Django channels for personal chat and keep websocket connected
I've been successful to create Websocket to connect and also able to personalize chats with route by doing something like path(r'chat/<str:user_id>/<str:other_user_id>/', ChatConsumer.as_asgi()) This works great with creating room/group with user_id and other_user_id on Django channels consumer. However scaling it with flutter and keeping the user connected to WebSocket in the background. To simplify I can't send connect request to the above mentioned endpoint to keep the user connected in the background on a flutter application. How do I create a room to have personal chats function on Django Channels? Create room/group specifically for two users when messages is sent to a user. -
Is the output of Next.js SSG build, SEO friendly?
I would like to know if the output generated by nextjs SSG build is SEO friendly, the same way as using nextjs with SSR. The reason I am asking is, because I would like to build a full stack app with React frontend (Django/DRF backend for what is worth), and SEO is really important. Also I would prefer to not have a separate nodejs instance serving the frontend separately. tl:dr I would like to serve only static files for the frontend while also being SEO friendly. Thanks very much in advance. -
Conditional processing of CreateView Django
i Have the following view in django : class CompraCreateView(CreateView): model = Compra fields = ['edicion'] def get_form(self, *args, **kwargs): form = super(CompraCreateView, self).get_form(*args, **kwargs) queryset = Edicion.objects.filter(promocion__fecha_de_finalizacion__gte = timezone.now()) form.fields['edicion'].queryset = queryset return form and its template: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}nueva compra{% endblock title%} {% block content%} <h1>Nueva Compra</h1> <form action="" method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-success ml-2" type="submit">Comprar</button> </form> {% endblock content %} What I'm trying to do is to force a conditional behavior of the view so it displays an error message in case the queryset of the field 'edicion' is empty. Thank you for your help. Sorry for my bad english -
How to delete data from database with a button using only DJANGO python, java script, and HTML?
I am working on a django project where my database gets populated from a post call, and for quality of life, I want to be able to clear the database at the click of a button. If it's possible, I'd like to only use python, javascript, and HTML. I've done some searching on here and haven't found any question like this so far with an answer. Here's a link to a similar question with no answer. There is a question that is similar to mine, but OP is using PHP, jquery, and SQL, which isn't ideal for me. I haven't attempted any code because I don't know where to start. If anyone has knowledge about this kind of thing, it would be much appreciated if you gave me a starting place. -
How do I retrieve file from server with graphene and Django?
How do I retrieve file from server with graphene and Django? I found graphene-file-upload, but it seems to take care of only uploading client's files to the server -
createsuperuser gives KeyError after implementing custom user
Hey I'm fairly new to Django and I'm trying to setup a pretty basic rest API. I am using djoser to handle authentication. However I want to use a custom user model. Where 1. the unique field is the email (instead of username) and 2. it is has one extra field. I tried to follow these two guides, https://testdriven.io/blog/django-custom-user-model/ (To use email instead of username) https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#abstractuser (To extend the usermodel) I create the model like so, class MyUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) DIET_CHOICES = ( ('vegan', 'Vegan'), ('vegetarian', 'Vegetarian'), ('meat', 'Meat') ) diet = models.CharField(max_length=10, choices=DIET_CHOICES) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [diet] objects = CustomUserManager() def __str__(self): return self.email Using the CustomUserManager() as shown in https://testdriven.io/blog/django-custom-user-model/. I have also registered the user in AUTH_USER_MODEL. Looking at the migration file I get what I expect. But after migrating when I then try to run createsuperuser, it instantly results in the following error Traceback (most recent call last): File "/home/frederik/Documents/andet/madklubTests/2madklubDjango/venv/lib/python3.9/site-packages/django/db/models/options.py", line 672, in get_field return self.fields_map[field_name] KeyError: <django.db.models.fields.CharField: diet> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/frederik/Documents/andet/madklubTests/2madklubDjango/manage.py", line 22, in <module> main() File "/home/frederik/Documents/andet/madklubTests/2madklubDjango/manage.py", line 18, in main execute_from_command_line(sys.argv) File … -
everytime i do some activity on my website i get this error :- Wallpaper.models.Wallpaper.DoesNotExist: Wallpaper matching query does not exist
Views.py def home(request): WAllPAPER_PER_PAGE = 4 WALL = Wallpaper.objects.all() from django.core.paginator import EmptyPage, Paginator from django.db.models import Q qd = request.GET.copy() qd.pop('page', None) querystring = qd.urlencode() #link formatting for ordering ordering =request.GET.get('ordering', "") #link formatting for sorting search = request.GET.get('search', "") if search: wallpapers = Wallpaper.objects.filter(Q(name__icontains=search) | Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search)).distinct() WALL = None else: wallpapers = Wallpaper.objects.all() if ordering: wallpapers = wallpapers.order_by(ordering) page = request.GET.get('page', 1) wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE) try: wallpapers = wallpaper_paginator.page(page) except EmptyPage: wallpapers = wallpaper_paginator.page(wallpaper_paginator.num_pages) except: wallpapers = wallpaper_paginator.page(WAllPAPER_PER_PAGE) context = {'querystring': querystring, "wallpapers": wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator, 'WALL': WALL} return render(request, "Wallpaper/Home.html", context) def All_category(request): Cat = Category.objects.all() context = {'Cat': Cat } return render(request, "Wallpaper/ALL_Category.html", context ) def category(request, Category_name): cat = Category.objects.get(category_name=Category_name) wallpapers = Wallpaper.objects.filter(category__category_name=Category_name) context = {'cat':cat, 'wallpapers': wallpapers} return render(request,'Wallpaper/Category.html', context) def download(request, wallpaper_name): wallpaper = Wallpaper.objects.get(name=wallpaper_name) similar_wallpapers = wallpaper.tags.similar_objects() context = {'wallpaper': wallpaper, 'similar_wallpapers': similar_wallpapers} return render(request, 'Wallpaper/download.html', context) error C:\Users\Atharva thaware\Desktop\aman\projects\Ongoing\WallpaperTown\WallpaperTown\Wallpaper\views.py:30: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'Wallpaper.models. Wallpaper'> QuerySet. wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE) [19/Jul/2022 22:29:39] "GET / HTTP/1.1" 200 10744 [19/Jul/2022 22:29:39] "GET /media/Wallpaper/Images/wp4589844-inosuke-hashibira-wallpapers.jpg HTTP/1.1" 304 0 [19/Jul/2022 22:29:39] "GET /media/Wallpaper/Images/wp2162463-shoto-todoroki-wallpapers.png HTTP/1.1" 304 0 [19/Jul/2022 22:29:39] "GET /media/Wallpaper/Images/wp2490700-haikyu-2018-wallpapers.jpg HTTP/1.1" 304 … -
ValueError in django project
I am getting the following error when running my code: ValueError at /company/3 The view company.views.dynamic_company_number didn't return an HttpResponse object. It download my project -
Django @property and setter for models field
I'm trying to create a field that should be updated by time and use getter and setter for it. Below is my code that should work but something went wrong, could you help me, what have I missed? How to add this field to the admin pannel (the result of setter)? _status = models.CharField(max_length=15, choices=status_choice, default=COMING_SOON) time_start = models.DateTimeField() time_end = models.DateTimeField() @property def status(self): return self._status @status.setter def status(self, value): if value == Lessons.COMING_SOON and self.time_end > datetime.now() > self.time_start: self._status = Lessons.IN_PROGRESS elif value == Lessons.IN_PROGRESS and self.time_end < datetime.now(): self._status = Lessons.DONE I have tried to check if it works by the manual changing value in ./manage.py shell but haven't result. Seems like @property doesn't work.