Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I let the user add a new field in a Django-form dynamically, instead of letting them append the entire form at every addition?
In forms.py: class BillGateway(forms.Form): from_date=forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='From ', label_suffix=' - ') to_date=forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='To ', label_suffix=' - ') billing_date=forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='Date of Billing ', label_suffix=' - ') rt_cash_amount_desc=forms.CharField(label='RT Cash Amount Description', label_suffix=' - ', required=False) rt_cash_amount=forms.DecimalField(label='RT Cash Amount', label_suffix=' - ', required=False) other_desc=forms.CharField(label='Other Head', label_suffix=' - ', required=False) other_amount=forms.DecimalField(label="Other Head's Amount", label_suffix=' - ', required=False) In views.py: def bill_gateway_view(request): if request.method=='POST': fro=request.POST.get('from_date') to=request.POST.get('to_date') bill_date=request.POST.get('billing_date') rt_cash_desc=request.POST.get('rt_cash_amount_desc') rt_cash_amount=request.POST.get('rt_cash_amount') other_desc=request.POST.get('other_desc') other_amount=request.POST.get('other_amount') request.session['fro']=fro request.session['to']=to request.session['bill_date']=bill_date request.session['rt_cash_desc']=rt_cash_desc request.session['rt_cash_amount']=rt_cash_amount return HttpResponseRedirect('/provisional_bill/') else: form=BillGateway() return render(request, 'account/bill_gateway.html', {'form':form}) In templates: <form action="" method="post" novalidate> {% csrf_token %} {{form.as_p}} <button type="submit" id="savebtn">Proceed</button> </form> Now, what I want to achieve is to let the user extend the other fields, both, the other_desc and other_amount if he/she needs to fill in more details in the bills. I'm fairly new to this concept. I have seen some tutorials in which the tutors mainly used htmx to achieve such things and seemed pretty cool and easy but what they did was adding the whole form again upon clicking the add button. I just want the user to be able to add these two fields only and not the entire form. How can I achieve this? I have spent my whole day looking … -
What will happen if I push changes from one branch to another?
I have two branches in my project. main and test_deploy It's incorrect to push changes without any tests to the main branch, but never mind. I use the main branch to make some changes locally and the test_deploy where I have other changes in settings.py (for example DEBUG=False, use a cloud for storing my model images and so on) and files for deployment(Procfile, runtime.txt and so on). For example, I'm going to add a new app and push it to the main branch and to the test_deploy branch too(to get the newest version of my project) I have a question. What will happen if I commit these changes to the main branch, push it to this branch AND also push it to the test_deploy branch? Will I have conflicts that I'll have to fix manually? Or I have firstly pull all files from the test_deploy branch and then push it?(I don't wanna pull files from the test_deploy branch. That's why I asked this question) Summary So, generally, I wanna push changes from the main branch to test_deploy, but without pulling separate files from the test_deploy branch, because they are superfluous on the main branch which I use locally. -
How to keep track of attendance in django project
I have a project in which two different models have cyclic many-to-many relation. Models are "Training" and "Student", where a student can enroll to many trainings and vice-versa, so i want to keep track of attendance of each student for each training. How can i achieve this in django? -
How do you create next and previous buttons for django lists?
I want to basically create a previous and next button so that the dates of a list would change on the same page (next means next day, and previous means previous day). Here is the generic list view I am using: class LessonList(generic.ListView): model = Lesson template_name = 'lesson_list.html' context_object_name = "lessons" def get_queryset(self): today = datetime.datetime.today() queryset = Lesson.objects.filter(date=today) return queryset Here is my html: {% for lesson in lessons %} <h1> {{lesson}} </h1> {% endfor %} And here is my model: Lesson(models.Model): name = models.CharField(max_length=100) date = models.DateField(null=True, blank=True) I did not mention it in the above code, but this list view already takes a primary key through the url, so I need another way of transferring the date value of the list to the next page when I click either the next or previous button. Is there any way I can do this? I would appreciate it if you guys could write the full code based on the code I have given in this question. If you have any questions, please leave a message. -
share media between multiple django(VMs) servers
we have deployed a django server (nginx/gunicorn/django) but to scale the server there are multiple instances of same django application running. here is the diagram (architecture) each blue rectangle is a Virtual Machine. HAProxy sends all request to example.com/admin to Server 3.other requests are divided between Server 1 and Server 2.(load balance) Old Problem: each machine has a media folder and when admin Uploads something the uploaded media is only on Server 3.( normal users can't upload anything ) we solved this by sending all requests to example.com/media/* to Server 3 and nginx from Server3 serves all static files and media. Problem right now we are also using sorl-thumbnail. when a requests comes for example.com/,sorl-thumbnail tries to access the media file but it doesn't exist on this machine because it's on Server3. so now all requests to that machine(server 1 or 2) get 404 for that media file. one solution that comes to mind is to make a shared partition between all 3 machines and use it as media. another solution is to sync all media folders after each upload but this solution has problem and that is we have almost 2000 requests per second and sometimes sync might not … -
Display Todo under its category [Django]
I'm not sure how to ask this question but I'll give it a shot. I am writing a Todo application and want to display each todo under its respective category in the template. For example Display each category {% for category in categories %} <h2>{{ category.name }}</h2> Now show each todo that falls under the above category {% for todo in todos %} <p>{{ todo.description }}</p> {% endfor %} {% endfor %} How do I create a queryset that will give my this type of structure? Or is there are different way to achieve this? If something is unclear or require more info let me know and I'll add it to the post Any help is appreciated, thank you. Models class Category(models.Model): name = models.CharField(max_length=20) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Todo(models.Model): # Priority choices PRIORITY_CHOICES = ( ("bg-danger", "High"), ("bg-info", "Normal"), ("bg-warning", "Low"), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) description = models.CharField(max_length=255) priority = models.CharField(max_length=200, choices=PRIORITY_CHOICES, null=True) completed = models.BooleanField(default=False) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) category = models.ManyToManyField(Category) def __str__(self): return self.description View def todo_listview(request): template_name = "todos/listview.html" context = { "todos": get_users_todos(user=request.user), "categories": Category.objects.all(), } return render(request, template_name, context) -
trying to plot d3.js heatmap django backend
Trying to plot heatmap from data, group variable and value, in inspect element the data shows fine data example : data = [ {group: 'HIV-1 protease', variable:'None', value: 30 }, {group: 'HIV-1 protease', variable:'ZINC03915219', value: 0.37 }, {group: 'HIV-1 protease', variable:'ZINC27425989', value: 0.38 }] views.py def search_result(request): if request.method == "POST": ChemSearched = request.POST.get('ChemSearched') tarname = BINDLL.objects.filter(targetnameassignedbycuratorordatasource__contains=ChemSearched).exclude(ki_nm="") return render(request, 'Search/search_result.html', {'ChemSearched':ChemSearched, 'tarname':tarname}) else: return render(request, 'Search/search_result.html',{}) <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <!-- Load d3.js --> <script src="https://d3js.org/d3.v4.js"></script> <!-- Create a div where the graph will take place --> <div id="my_dataviz"></div> <!-- Load color palettes --> <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script> <title>Search_results</title> </head> <body> {% if ChemSearched %} <script> data = [{% for Bindll in tarname %} {group: '{{ Bindll.targetnameassignedbycuratorordatasource }}', variable:'{{ Bindll.zincidofligand}}', value: {{Bindll.ki_nm}} }, {% endfor %}]; function(data) { var myGroups = d3.map(data, function(d){return d.group;}).keys() var myVars = d3.map(data, function(d){return d.variable;}).keys() // Build X scales and axis: var x = d3.scaleBand() .range([ 0, width ]) .domain(myGroups) .padding(0.05); svg.append("g") .style("font-size", 15) .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x).tickSize(0)) .select(".domain").remove() // Build Y scales and axis: var y = d3.scaleBand() .range([ height, 0 ]) .domain(myVars) .padding(0.05); svg.append("g") .style("font-size", 15) .call(d3.axisLeft(y).tickSize(0)) .select(".domain").remove() // Build color scale var myColor … -
How to use Django + Cloudinary for images + Heroku?
I have some models with the ImageField. If I load an image for a new Django model, it disappears after 1-2 hours. I suppose it's because Heroku doesn't save images. How can I connect my django project, cloudinary and heroku together? -
how to design front-end of blog page with tailwind which renders data of a ckeditor django form which contains images, code snippets and text
{{blog_obj.content|safe}} //this is the rendered part of the blog which contains the main contents of the blog. But the image sometimes has a large width which is destructuring the whole page. Is there a way to fix this? -
How To Use Child Loop value as a key in Parent Loop in Django template?
I am trying to read a dynamic uploaded CSV file and want to show it on HTML Page. Backend Code using to read CSV file = request.FILES.get('file') decoded_file = file.read().decode('utf-8').splitlines() records = csv.DictReader(decoded_file) headers = records.fieldnames rows = [] for row in list(records): rows.append(dict(row)) main_data = { 'headers':headers, 'records':rows } Am passing this main_data passing to the front end as context. And then on the template, I am using below code <thead class="table-dark"> <tr> {% for header in headers %} <th scope="col">{{header}}</th> {% endfor %} </tr> </thead> <tbody> {% for row in records %} <tr> {% for header in headers %} <td> {{row.header}} This is coming blank {{header}} # This is properly printing the header name </td> {% endfor %} </tr> {% endfor %} </tbody> I want to use this header value as a key. If anyone can please tell me how can I achieve it? -
probleme when trying to login in Django Admin
hello i have a legacy database wiche use unix time and I have override an absractbaseuser here is my model from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager from django.contrib.auth.signals import user_logged_in from .helper import get_current_unix_timestamp class MyUserManager(BaseUserManager): def create_user(self, username,password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not username: raise ValueError('user must have a username') user = self.model( username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( username, password=password, ) user.is_admin = True user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class Account(AbstractBaseUser): id = models.AutoField(primary_key=True,verbose_name='ID',) username = models.CharField(max_length=50, blank=True, null=True,unique=True) password = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) ip = models.CharField(max_length=255,null=True,blank=True) date_registered = models.IntegerField(default=get_current_unix_timestamp()) last_login = models.IntegerField(null=True,blank=True) member_group_id = models.IntegerField(blank=True, null=True) credits = models.FloatField(blank=True, null=True) notes = models.TextField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) reseller_dns = models.TextField(blank=True, null=True) owner_id = models.IntegerField(blank=True, null=True) override_packages = models.TextField(blank=True, null=True) hue = models.CharField(max_length=50, blank=True, null=True) theme = models.IntegerField(blank=True, null=True) timezone = models.CharField(max_length=255, blank=True, null=True) api_key = models.CharField(max_length=64, blank=True, null=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = … -
How do I save share data with two separate models that is linked by a foreignkey
I have a Post model that has a separate image model and i want to have functionality for group users being able to share data to their walls, but i have been challenge in saving the data since the foreignkey of the groupimage mismatch the original data from the post. How do i get the original image id to much the post for it to save ?Here what i have than so far! def share_post(request, pk): original_img = GroupImage.objects.prefetch_related('groupimage_set').get(pk=pk) original_post = Post.objects.prefetch_related('groupimage_set').get(pk=pk) form = ShareForm(request.POST, request.FILES) if form.is_valid(): new_post = Post( shared_body = request.POST.get('description'), description = original_post.description, username = original_post.username, date_posted = original_post.date_posted, group = original_post.group, shared_on = datetime.now(), shared_user = request.user) new_post.save() for f in original_img.images: data = GroupImage(post=original_img,group=original_post.group.pk,image=f) data.save() return redirect('group:main',original_post.group.pk) else: form = ShareForm(request.POST, request.FILES) ctx = {'form':form, 'original_post':original_post} return render(request,'group/share_form.html', ctx) -
How to get max score of answers to a question by each user
I have these 2 models: class Question(models.Model): title = models.CharField(max_length=200) # other fields class Answer(models.Model): user = models.ForeignKey(User) question = models.ForeignKey(Question) score = models.IntegerField() each user can answer a question multiple times. Imagine I have these answers: { "user": 1, "question": 1, "score": 50 }, { "user": 1, "question": 1, "score": 100 }, { "user": 2, "question": 1, "score": 100 }, { "user": 2, "question": 1, "score": 200 }, { "user": 2, "question": 2, "score": 100 }, { "user": 2, "question": 2, "score": 200 } I want a query to give me this result: { "user": 1, "question": 1, "max_score": 100 }, { "user": 2, "question": 1, "max_score": 200 }, { "user": 2, "question": 2, "max_score": 200 } I want all of the max scores of each user to each answer. -
Django DRF Custom user model field "updated" (last login) is not being updated upon login
I have a problem with the user fields "created" and "updated". First of all, there's a "Last login" field (I assume this represents "updated") in admin which is always empty. There's no field for "created" it seems. Secondly, Created and updated do get initiated with the account creation datetime, however it is not updated upon login. I'm using Django 4.0 RegisterSerializer class RegisterSerializer(UserSerializer): password = serializers.CharField(max_length=128, min_length=8, write_only=True, required=True) email = serializers.EmailField(required=True, write_only=True, max_length=128) class Meta: model = User fields = ['id', 'username', 'email', 'password', 'is_active', 'created', 'updated', 'testfield'] def create(self, validated_data): try: user = User.objects.get(email=validated_data['email']) except ObjectDoesNotExist: user = User.objects.create_user(**validated_data) return user User model class User(AbstractBaseUser, PermissionsMixin): id = models.AutoField(primary_key=True) username = models.CharField(db_index=True, max_length=255, unique=True, blank=True) email = models.EmailField(db_index=True, unique=True, null=True, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) testfield = models.CharField(max_length=255, blank=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return f"{self.email}" UserSerializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'is_active', 'created', 'updated'] read_only_field = ['is_active', 'created', 'updated'] I followed this guide for the user setup https://dev.to/koladev/build-a-crud-application-using-django-and-react-5389 -
How to migrate all the data of an sqlite database to cockroachdb (for a django project)
I created a Django application and deployed it for testing purposes. I now have data which i would not like to lose, but i want to use cockroachDB for storing the web-app data. The SQLite database is the one django creates automatically while applying migrations. Is there a way to move all that data to my cockroachDB cluster? I will be using cockroachDB for my database. Thank you for your time -
Can you connect Django and React JS to the servers and SQL databases?
I have been recently working on my note-taking app. I wanted to build it in Django and React JS. Backend and front end. The question is can I connect all of this to the SQL databases and connect it to servers where will be stored data of the users? -
How to reduce for loops in html in Django?
I tried the following for loops and if statements in django html, but it takes so long to load one page. First, here is the html: {% for time in TIME_CHOICES %} <h1>{{time}}</h1> {% for each_date in dates_in_month %} {% if each_date not in weekends %} {% for class in classes %} {% if class.date == each_date and class.time == time %} <h1>{{class}}</h1> {% endif %} {% endfor %} {% else %} <h1>weekday</h1> {% endif %} {% endfor %} {% endfor %} I think this is because I have too many for loops and if statements happening in my html. Is there anyway I can increase the speed? Or is there any way I can do the same thing in django views(I am using generic list view, so I need some code for the get_context_data)? Thank you, and please leave any questions you might have. -
Django: Best way to render model instances based on authorization
I want to ask you about a recommendation how to solve this issue I'm struggling right now. My objective is to have a simple page which renders my model instances one after another, but based on the user it should skip certain instances. models.py class Item(models.Model): creator= models.ForeignKey(User,null=True, on_delete=SET_NULL) title = models.CharField(max_length=200) private = models.BooleanField(null=False, blank=True, default=False) views.py def topics(request): items=Item.objects.all() context={'items' : items} return render(request, 'items.html', context) main.html {% for item in items %} <div> <p>{{item.title}}</p> </div> {% endfor %} Question: If 'private' is true I want to skip that item if the user is not staff. This way I can separate the items based on this boolean. What is the recommended/best way to do that? I don't want a if/else statement in html and then repeat the code. It's getting a messy as the project grows. Thanks in advance! -
Why Django's OneToOneField returns 500 if relation aready exists
In a Django REST Framework POST view, is there any way to avoid an HTTP 500 if the OneToOneField relation already exists? Instead, it would be great to get an HTTP 400. Thanks. -
How to solve PUT method is not allowed in drf?
I've a model: class ListingPrice(Timestamps): price = models.ForeignKey("Price", on_delete=models.CASCADE) location = models.ForeignKey("location", on_delete=models.CASCADE) class Meta: unique_together = ["price", "location"] class Price(Timestamps): package = models.ForeignKey("products.Package", on_delete=models.CASCADE) locations = models.ManyToManyField("location", through="ListingPrice") price = models.DecimalField(max_digits=11, decimal_places=3) with a serializer: class LocationSerializer(serializers.ModelSerializer): name = LocalizedField() class Meta: model = location fields = ['id', 'name'] class PriceSerializer(serializers.ModelSerializer): locations = LocationSerializer(many=True, read_only=True) class Meta: model = Price fields = ['package', 'locations', 'price'] def create(self, validated_data): print("validated_data, validated_data) and viewset: class PriceViewSet(ModelViewSet): queryset = Price.objects.all() serializer_class = PriceSerializer ordering = ['id'] permissions = { "GET": ["view_minimum_listing_price", ], "POST": ["add_minimum_listing_price", ], 'PUT': ['update_minimum_listing_price', ], 'DELETE': ['delete_minimum_listing_price', ], } In testing I'mm using the following: data = { "price": 15, } response = self.client.put(path=self.url, data=data, format='json', args=[1]) I'm trying to update the price in the instance with id 1, but neither put or update is not allowed? How to overcome this and update it? edit: urls.py router = SimpleRouter() router.register('listing_price', PriceViewSet, basename='listing_price') -
Page not found (404) The current path, register/register, didn’t match any of these
on running server browser show I am trying to save the the data into database on submitting the form the browser show page not found error and and same wrong address. http://127.0.0.1:8000/register/register while i am rendering the homepage on submitting the form. views.py file from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth.models import User def homePage(request): return render(request,"index.html") def register(request): if request.method=='POST': firstname = request.POST.get('fname') lastname = request.POST.get('lname') email = request.POST.get('email') password = request.POST.get('password') username = request.POST.get('uname') user = User(first_name=firstname,last_name=lastname,email=email,password=password,username=username) user.save() return redirect('/') return render(request,"register.html") def course(request): return HttpResponse("welcome to my 2nd page") def courseDetail(request,courseid): return HttpResponse(courseid) urls.py file from django.urls import include, path from django.contrib import admin from django.urls import path from name import views import name urlpatterns = [ path('admin/', admin.site.urls), path('',views.homePage), path('register/',views.register), path('course/',views.course), path('course/<courseid>',views.courseDetail), ] -
I want to link 2 models like a field abc linked to abcd model is in mymodel and a field in mod linked to mymodel is in abcd django
I want to link 2 models like a field abc linked to abcd model is in mymodel and a field in mod linked to mymodel is in abcd but shows mymodel isn't define because it is written after abcd model but if I replace the place of both model mymodel written above and abcd written after then mymodel shows that abcd isn't define... -
Django GraphQL subscriptions using websockets within the dockerized API works fine locally but fails in production
I have a Django GraphQL API and an Angular 12 UI that uses Apollo to interface with GraphQL. The Django app is dockerized and uses NGINX. These are my files:- settings.py (only relevant sections pasted below) INSTALLED_APPS = [ 'channels', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # This is for altering the domain name in the migration 'app', 'graphene_django', 'graphql_jwt.refresh_token.apps.RefreshTokenConfig', 'graphql_auth', 'rest_framework', 'django_filters', ] GRAPHENE = { 'SCHEMA': 'project.schema.schema', 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware', ], "SUBSCRIPTION_PATH": "/ws/graphql" } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'common.utils.UpdateLastActivityMiddleware' ] AUTHENTICATION_BACKENDS = [ 'graphql_auth.backends.GraphQLAuthBackend', 'django.contrib.auth.backends.ModelBackend', ] GRAPHQL_AUTH = { "ALLOW_LOGIN_NOT_VERIFIED": False } GRAPHQL_JWT = { "JWT_ALLOW_ANY_CLASSES": [ "graphql_auth.mutations.Register", "graphql_auth.mutations.VerifyAccount", "graphql_auth.mutations.ResendActivationEmail", "graphql_auth.mutations.SendPasswordResetEmail", "graphql_auth.mutations.PasswordReset", "graphql_auth.mutations.ObtainJSONWebToken", "graphql_auth.mutations.VerifyToken", "graphql_auth.mutations.RefreshToken", "graphql_auth.mutations.RevokeToken", ], 'JWT_PAYLOAD_HANDLER': 'common.utils.jwt_payload', "JWT_VERIFY_EXPIRATION": True, "JWT_LONG_RUNNING_REFRESH_TOKEN": True, 'JWT_REUSE_REFRESH_TOKENS': True, # Eliminates creation of new db records every time refreshtoken is requested. 'JWT_EXPIRATION_DELTA': timedelta(minutes=60), # Expiry time of token 'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=7), # Expiry time of refreshToken } ROOT_URLCONF = 'project.urls' WSGI_APPLICATION = 'project.wsgi.application' ASGI_APPLICATION = 'project.router.application' REDIS_URL = env('REDIS_URL') hosts = [REDIS_URL] if DEBUG: hosts = [('redis', 6379)] CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": hosts, }, }, } router.py @database_sync_to_async def get_user(token_key): try: decodedPayload = jwt.decode( token_key, key=SECRET_KEY, … -
Getting NoReverseMatch___ Reverse for 'for_user' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['/(?P<username>[-\\w]+)/$']
I'm sorry if I'm repeating an already answered question. I have tried to look this up but can't seem to get a way around this bug. NoReverseMatch at /groups/ Reverse for 'for_user' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['posts/by/(?P[-\w]+)/$'] models.py ''' enter code here from groups.models import Group # Create your models here. from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User,related_name='posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable='False') group = models.ForeignKey(Group,related_name='posts', null=True,blank=True,on_delete=models.CASCADE) def __str__(self): return self.message def save(self,*args,**kwargs): self.message_html = misaka.html(self.message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse( 'posts:single', kwargs={'username':self.user.username, 'pk':self.pk}) class Meta: ordering = ['-created_at'] unique_together = ['user','message'] ''' Views.py ''' enter code here class PostList(SelectRelatedMixin,generic.ListView): model = models.Post select_related = ('user','group') class UserPosts(generic.ListView): model = models.Post template_name = "posts/user_post_list.html" def get_queryset(self): try: self.post_user = User.objects.prefetch_related("posts").get( username__iexact=self.kwargs.get("username") ) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["post_user"] = self.post_user return context class PostDetail(SelectRelatedMixin,generic.DetailView): model = models.Post select_related = ('user','group') def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user__username__iexact=self.kwargs.get('username')) class CreatePost(LoginRequiredMixin,SelectRelatedMixin,generic.CreateView): fields = ('message','group') model = models.Post def form_valid(self,form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class DeletePost(LoginRequiredMixin,SelectRelatedMixin,generic.DeleteView): model = models.Post select_related = ('user','group') success_url = … -
Django get a value for annotated field based on condition?
I have a couple simple models and want to annotate query with field which value based on condition. class Book(models.Model): price = models.DecimalField('Price', null=True, default=None, max_digits=32, decimal_places=2) ... class Config(models.Model): city_prices = models.JSONField(default={"Paris": 10, "London": 15}, null=True) ... I've try to query this model like that: from django.db.models import F, When, Case, Subquery config = Config.objects.first() Book.objects.annotate(custom_price=Case( When(price__isnull=False, then=F('price')), When(price__isnull=True, then=Subquery(config.city_prices.get(F('city')))) ) the first "When" works good but the second one gets me an error. AttributeError: 'NoneType' object has no attribute 'all' I've tried to get rid of "F()" on second "When" and hardcore city name, but gets another error. When(price__isnull=True, then=Subquery(config.city_prices.get('London'))) AttributeError: 'int' object has no attribute 'all' This error shows that I get a value of "London" but Subquery try to query it. So I made a conclusion that when in previous query I've tried to use "F('city')" it got back None, and I think this because of F('city') refer to Config model rather than the Book. I've tried different approach but it's unsuccessful either. >>>from django.db.models.expressions import RawSQL >>>Books.objects.annotate(custom_price=RawSQL('SELECT d.city_prices ->> %s FROM CONFIG_CONFIG d WHERE d.id = 1', (F('price'),))) ProgrammingError: can't adapt type 'F' I read somewhere here that F() can't collaborate with RawSQL. Think the …