Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic Serialization for related fields
I have the following models: class Country(models.Model): """ Country model """ # With name and isoCode (charfield) ... class State(models.Model): """ State model """ # With name and isoCode (charfield) country = models.ForeignKey(Country, on_delete=models.CASCADE) ... class City(models.Model): """ City model """ name = models.CharField(max_length=32) state = models.ForeignKey(State, on_delete=models.CASCADE) country = models.ForeignKey(Country, on_delete=models.CASCADE) ... And UserLocation referenced by: class Location(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="location") country = models.ForeignKey(Country, on_delete=models.CASCADE) state = models.ForeignKey(State, on_delete=models.CASCADE) city = models.ForeignKey(City, on_delete=models.CASCADE) How do I build a serializer that creates UserLocation, as well as return the info in JSON? I have tried class LocationSerializer(serializers.ModelSerializer): country = serializers.SlugRelatedField(slug_field="isoCode", queryset=Country.objects.all()) state = serializers.SlugRelatedField(slug_field="isoCode", queryset=State.objects.filter(country__isoCode=country)) city = serializers.SlugRelatedField(slug_field="name", queryset=City.objects.all()) class Meta: model = Location fields = ["user", "country", "state", "city"] But it does not work, it gives the error {"state":["Object with isoCode=BC does not exist."],... How does one create a dynamic linked serializer? Or how does one work around this? -
Django: unsupported operand type(s) for +: 'int' and 'method' when creating function in Django
i am writing a function in my model to get the cart total, but i keep getting this error and i don't seem to know exactly what is going wrong - unsupported operand type(s) for +: 'int' and 'method'. class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) transaction_id = models.CharField(max_length=1000, null=True, blank=True) completed = models.BooleanField(default=False) active = models.BooleanField(default=True) date_ordered = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.customer.user.username} - {self.transaction_id}" @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = int(sum([item.quantity for item in orderitems])) return total -
How to combine values from 2 queryset
I do have two queryset both having common field 'month' i want to combine both query set using field 'month' six_months_ago = date.today() + relativedelta(months=-6) ###### Geting number of New Patient registration by month (for last six month) patient_per_month = patientprofile.objects.filter(pat_Registration_Date__gte=six_months_ago)\ .annotate( month=Trunc('pat_Registration_Date', 'month') ) \ .order_by('month') \ .values('month') \ .annotate(patient=Count('month')) print(patient_per_month) ###### Geting number of visit by month (for last six month) visits_per_month = visits.objects.filter(visit_date__gte=six_months_ago)\ .annotate( month=Trunc('visit_date', 'month') ) \ .order_by('month') \ .values('month') \ .annotate(visits=Count('month')) print(visits_per_month) Both printing ad below: <QuerySet [{'month': datetime.date(2022, 2, 1), 'patient': 1}, {'month': datetime.date(2022, 3, 1), 'patient': 1}, {'month': datetime.date(2022, 4, 1), 'patient': 1}, {'month': datetime.date(2022, 5, 1), 'patient': 2}, {'month': datetime.date(2022, 6, 1), 'patient': 2}, {'month': datetime.date(2022, 7, 1), 'patient': 18}]> <QuerySet [{'month': datetime.date(2022, 5, 1), 'visits': 6}, {'month': datetime.date(2022, 6, 1), 'visits': 7}, {'month': datetime.date(2022, 7, 1), 'visits': 12}]> I want combine both of these query set as one by 'month' field something like below. <QuerySet [{'month': datetime.date(2022, 2, 1), 'patient': 1, 'visits': 0}, {'month': datetime.date(2022, 3, 1), 'patient': 1, 'visits': 0}, {'month': datetime.date(2022, 4, 1), 'patient': 1, 'visits': 0}, {'month': datetime.date(2022, 5, 1), 'patient': 2, 'visits': 6}, {'month': datetime.date(2022, 6, 1), 'patient': 2, 'visits': 7}, {'month': datetime.date(2022, 7, 1), 'patient': 18'visits': … -
Django Queryset Design: Filtering out soft-deleted users?
I have a soft-delete user model in Django, where we set is_active to False. But one problem I'm running into is needing to filter out is_active users on every type of content: Item.objects.filter(user__is_active=False, ...) Comment.objects.filter(user__is_active=False, ...) User.objects.filter(is_active=False, ...) And so-on. Is there some type of Django / Pythonic design pattern I can use here to avoid needing to manually filter out all users every time I query something made by a user, or a current list of users? -
How to remove "Currently" tag and link in django filefield
Basically, on the website it says currently: and then its the name of the file that was uploaded and im wondering how to remove the "currently" and the name of the file that was uploaded. ps: sorry if i didn't explain well im not the best at it pfp_url = models.FileField() bg_pfp = models.FileField() Heres a more indepth image -
ModuleNotFoundError: No module named 'django_apscheduler' when I migrate my file with heroku
I want to update my heroku site with this command heroku run python manage.py migrate, but the error appeared: » Warning: heroku update available from 7.53.0 to 7.60.2. Running python manage.py migrate on ⬢ mighty-harbor-18334... up, run.5980 (Free) Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/app/.heroku/python/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/config.py", line 223, in create import_module(entry) File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_apscheduler' I installed django_apscheduler with pip install django_apscheduler for sure. My python version is 3.10.2, and in my settings.py, the app module is in INSTALLED_APPS such: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' 'django_apscheduler', ] I am not sure why the ModuleNotFoundError would occured, any help will be appreciated. -
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