Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializing Django simple history items the same way as the main model
I am trying to work with Django rest framework in conjunction with Django simple history. This answer has gotten me pretty far with understanding how to serialize the history items of a model. This works well for simple cases, but my model has a calculated field ("store" in the example below). The problem is that the the serialization of the history field doesn't seem to capture these. How to I serialize the history in the same way as the main model? Is it possible to do this in the to_representation method of the HistoricalRecordField? class MyModel(models.Model): ... history = HistoricalRecords() @property def store(self): return {} class HistoricalRecordField(serializers.ListField): child = serializers.DictField() def to_representation(self, data): return super().to_representation(data.values()) class MySerializer(serializers.ModelSerializer): ... store = serializers.DictField(child=serializers.CharField(), read_only=True) history = HistoricalRecordField(read_only=True) class Meta: model = MyModel -
You're accessing the development server over HTTPS, but it only supports
enter image description here enter image description here -
AttributeError: 'WSGIRequest' object has no attribute 'app'
I'm building a dashboard with these commands on a local machine and then copy it to the remote server: cd ~/repos/fork/saleor-dashboard git checkout 2.11.1 npm14 --verbose install export API_URI="https://api.mydomain.com/graphql/" export GTM_ID="GTM-K9ZZ3R8" npm14 run build ls build/dashboard/ scp -i ~/Documents/webserver-key-pair.pem -r build/dashboard ec2-user@3.1.16.71:/srv/www/mydomain/ The dashboard is available online. But when I log in with a valid user/pass, the Saleor API throws these errors, visible by sudo journalctl -xe: File "/home/ec2-user/repos/fork/saleor/saleor/graphql/utils/__init__.py", line 128, in get_user_or_app_from_context return context.app or context.user graphql.error.located_error.GraphQLLocatedError: 'WSGIRequest' object has no attribute 'app' ERROR saleor.graphql.errors.unhandled A query failed unexpectedly [PID:8388:Thread-108] ... File "/home/ec2-user/repos/fork/saleor/saleor/graphql/utils/__init__.py", line 128, in get_user_or_app_from_context return context.app or context.user AttributeError: 'WSGIRequest' object has no attribute 'app' ... File "/home/ec2-user/repos/fork/saleor/saleor/graphql/utils/__init__.py", line 128, in get_user_or_app_from_context return context.app or context.user AttributeError: 'WSGIRequest' object has no attribute 'app' What could be the cause? Thanks! =) -
Nginx problem when i enabled the file by linking to the sites-enabled dir
my gorgeous friends on the internet. I was doing something about Nginx for deploying my app made by Django, Postgresql, Gunicorn, Nginx, and DigitalOcean. First of all, The project name in the Github gist is btre_project, but my app's project name is pfc_calc. Considering the name dif, I created project folder by coping and pasting the line on the gist. sudo nano /etc/nginx/sites-available/pfc_calc And, copy the code and paste it into the file I just made. server { listen 80; server_name 104.248.152.6; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/djangoadmin/pyapps/pfc_calc; } location /media/ { root /home/djangoadmin/pyapps/pfc_calc; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } BUT, here is where I made a mistake and got an error I was so foolish that I forgot to change btre_project to pfc_calc sudo ln -s /etc/nginx/sites-available/btre_project /etc/nginx/sites-enabled Because I noticed that mistake, I typed this line again. sudo ln -s /etc/nginx/sites-available/pfc_calc /etc/nginx/sites-enabled I thought it would be ok and my mistake was under the bridge, but it wouldn't. When I typed this line sudo nginx -t this error below showed up. nginx: [emerg] open() "/etc/nginx/sites-enabled/btre_project" failed (2: No such file or directory) in /etc/nginx/nginx.conf:62 nginx: configuration … -
How to improve tests for models with multiple foreign keys (Django)
I have a MVP for my testing suite, but my current style will be a beast to maintain. I am running into trouble efficiently writing tests for my model which has two Foreign Keys. I include my model.py file and my test.py file below: models.py class Category(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=100) class ProductCategoryValue(models.Model): value = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="categories") product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="products") class Meta: unique_together = [['category', 'product']] (The idea behind this model structure is that there can be a list of products and a list of categories, with the ProductCategoryValue to serve as the glue between the two lists. The list of categories may change later on in the project and I would like to easily modify the values of each product text with respect to that category. I am open to suggestions to improve this model structure as well!) test.py #... def setUp(self): p = Product(name="Touchscreen") p.save() Product.objects.create(name="Dancer") c = Category(name="Use Case", selection_type="bullets") c.save() Category.objects.create(name="Video Conferencincg", selection_type="text") Category.objects.create(name="Multisite", selection_type="Boolean") ProductCategoryValue.objects.create(value="foobar", product=p, category=c) Is this the canonical way of writing tests for models which have multiple foreign keys? I'm hoping that there is a more efficient way so that my testing … -
Django rest framework large file upload
Is there an easy way to upload large files from the client side to a django rest framework endpoint. In my application, users will be uploading very large files (>4gb). Browsers have a upload limit, here's the chart. My current idea is to upload the file in chunks from the client side and receive the chunks from the rest endpoint. But how will I do that? I saw some libraries like - resumable.js, tus.js, flow.js etc. But how will I handle the chunks in the backend? Is there any library that is actively maintained for a problem like this? Please help me. -
How to use detailview pk in createview
# models.py class NewBlank(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=50) description = models.CharField(max_length=100, blank=True) blank_on_off = models.BooleanField(default=False) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) class BlankContent(models.Model): refer = models.TextField() memo = models.TextField() new_blank = models.ForeignKey('NewBlank', on_delete=models.CASCADE, related_name='blankcontent') # views.py class BlankDetail(LoginRequiredMixin, DetailView): model = NewBlank template_name = 'blank_app/blank_detail.html' context_object_name = 'blank' class BlankContentCreate(CreateView): model = BlankContent fields = "__all__" template_name = 'blank_app/new_blank_content_create.html' def get_success_url(self): return reverse_lazy('blank_detail', kwargs={'pk': self.object.new_blank.pk}) # urls.py urlpatterns = [ path('blank/<int:pk>/', BlankDetail.as_view(), name='blank_detail'), path('new-blank-content/', BlankContentCreate.as_view(), name='blank_content_create'), ] There is a creativeview in the detail view and I want to create a model in the detailview when I press it. So even if I don't specify the new_blank part, I want it to be filled automatically according to the pk in the detailview, what should I do? -
Django request + variable issues when Debug = True
I am getting a 500 error on all my pages except admin when I set debug to False in Django. (When Debug is True, everything works just fine.) When I look at my error log, I get a huge litany of errors, starting with the following: [20/Jul/2021 00:10:22] DEBUG [django.template:869] Exception while resolving variable 'self' in template '404.html'. I also get a number of "VariableDoesNotExist" errors for variables that are not even associated with the template in question. -
Django form is not valid in class based view
I'm currently working on a blog project where I have created a custom user model in which I intend on creating a Registration Form from this custom user model. I have my registration form that inherits from the UserCreationForm in Django. The form rendered properly in my template as it should but whenever I try registering a user the form is not valid. I'm not sure what I'm doing wrong. I'm looking forward to get some help from you brilliant people! :-) See the related usages below: models.py from django.contrib.auth import get_user_model from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=255, null=True, blank=True) last_name = models.CharField(max_length=255, null=True, blank=True) username = models.CharField(max_length=200, unique=True) email = models.EmailField(_('email address'), max_length=150, unique=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] class Meta: ordering = ['-date_joined', 'username', 'email'] verbose_name = 'User' verbose_name_plural = 'Users' def __str__(self): return self.username.title() forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model class RegistrationForm(UserCreationForm): # confirm_password = forms.CharField(widget=forms.PasswordInput(attrs=registration_form_fields['confirm_password'])) class Meta: model = get_user_model() fields = ['first_name', … -
Sending a .zip file in Django?
I've been trying to send a .zip file via a POST request in Django but can't seem to work it out, here's what I've tried: def test_1(self): z = zipfile.ZipFile("test.zip") file = (io.BytesIO(b"abcdef"), z) res = self.client.post("/upload/", {"zip":file}, content_type="multipart/form-data") self.assertEqual(res.status_code, 200) def test_1(self): file = (io.BytesIO(b"abcdef"), "test.zip") res = self.client.post("/upload/", {"zip":file}, content_type="multipart/form-data") self.assertEqual(res.status_code, 200) def test_1(self): z = zipfile.ZipFile("test.zip") res = self.client.post("/upload/", {"zip":z}, content_type="multipart/form-data") self.assertEqual(res.status_code, 200) Every time I try to run the test it gets a status code of 400. Any ideas why? Here is the view: def upload(request): z = zipfile.ZipFile(request.FILES['zip']) for fi in z.namelist(): dirname = os.path.splitext(fi)[0] os.mkdir(dirname) content = io.BytesIO(z.read(fi)) zip_file = zipfile.ZipFile(content) for i in zip_file.namelist(): zip_file.extract(i, dirname) sum = os.path.getsize(dirname) shutil.rmtree(dirname) return HttpResponse(f"Success") The program works fine when running it normally, just not when being tested which makes me think I'm not sending the .zip file correctly. Here's the HTML that works: <form method="post" action="/upload/" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="zip"> <button type="submit">Upload</button> </form> -
How to get days from queryset using expressionwrapper
gap_condition = Attribute.objects.filter(Q(register_date__gte='2021-01-01')) \ .annotate(register_gap=ExpressionWrapper(F('create_date') - Cast(F('register_date'), DateTimeField()), output_field=DurationField())).values('register_gap') I Changed 'create_date' field from 'datetime' type to 'date' type to get the date difference between two fields. The result is output as a queryset.<QuerySet [{'register_gap': datetime.timedelta(days=1)}, {'register_gap': datetime.timedelta(days=1)}, {'register_gap': datetime.timedelta( 0)}, {'register_gap': datetime.timedelta(days=7)}, ...]> In this queryset, I want to extract only the days value, but if I use the .days syntax, an error is displayed saying that days cannot be extracted using expressionwrapper . Is there any other way? -
I am trying to create a login view that works for Customuser. Presently,the Loginform just redirects even when the fields are empty /incorrect input
I have allauth installed to handle the login yet, I don't seem to find a breakthrough with having a proper login as the redirect just takes everyone to the destination page without any authentication.. The signup works fine as I can see created users in the admin. Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'useraccount', 'crispy_forms', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', Views.py from django.contrib.auth import logout , login, authenticate from django.shortcuts import render,redirect from .forms import RegisterForm,LoginForm from django.urls import reverse_lazy from django.views.generic.edit import CreateView from django.http import request , HttpResponseRedirect def login_request(request): if request.method == 'POST': form = LoginForm(data=request.POST) email = request.POST.get('email') password = request.POST.get('password') if form.is_valid (): user = form.get_user () user = authenticate ( email=email , password=password ) login ( request , user ) return HttpResponseRedirect(reverse_lazy('dashboard')) else: form = LoginForm () return render ( request=request , template_name="useraccount/login.html" , context={"form": form} )' Urls.py from django.contrib import admin from django.urls import path , include from useraccount import views as c from useraccount import views as m from useraccount import views as a from django.contrib.auth import views as auth_views app_name = 'useraccount' urlpatterns = [ path ( 'admin/' , admin.site.urls ) , path ( '' , … -
Wagtail/Django - How to find the template name of wagtail root home page?
I have a root home page made using the default model that comes out of the box with Wagtail. I'm currently trying to create a navbar header that maps out children pages in the following manner: {% for menu_page in home_page.get_children.live.in_menu %} The problem here is, I'm using the wrong tag. Above I use home_page, but that does not seem to work. I am able to use: {% for menu_page in page.get_children.live.in_menu %} Which then lists out the menu_pages, but this does not work for a navbar because it won't always select children pages from the root, due to the general page tag. Any ideas on how I can locate the actual template or page name before adding the: page.get_children.live.in_menu . To re-iterate, I am using the out of the box home page model: from wagtail.core.models import Page class HomePage(Page): pass The title of the root page is called Home and the type is Home Page Thanks for any possible help. -
Should i have multiple update methods or just one
I am writing an update method to a Book model in python-django. I was wondering which way to write code is "best". I would like all the updates go through this "controller" class and not update the model directly. class Book(object): id: UUID name: str price: float quantity: int ... I can either have 1 update method that takes in **kwargs and updates the fields in the model class BookController: def update(self, **kwargs): for field, value in kwargs.items(): self.field = value self.save() I can have multiple methods that each updates a particular set of fields, based on usecase class BookController: def update_price(self, price) def update_quantity(self, quantity) def update_price_quantity(self, price, quantity) ... The first option obfuscates things, and makes it difficult to understand which fields are being updated. It can be used as a one-size fits all, but may lead to bugs as anyone can add any field in the caller. The second grows exponentially with more fields being added (the only constraint being the use cases needed) and also kinda ugly to look at. Is there a guideline or preferred way to structure this type of code ? -
Nested serializers doesn't return the correct data Django Rest
I have an Order app, with two models, order and order unit. Now the idea is that I need to make a nested serializer to take in both of them and then a nested view to display them. When I create an order, I can also put in how many units I want to order, so basically when product X is selected, I need the code to get the price for the product X so the user doesn't have to enter it. Thats the main issue here. Here's the models: class Order(models.Model): code = models.IntegerField(unique=True) code_year = models.IntegerField(null=True) date_registered = models.DateTimeField(default=timezone.now) customer = models.ForeignKey(Customer, related_name='customer_orders', null=True, on_delete=models.CASCADE) creator = models.ForeignKey(User, related_name='orders', null=True, on_delete=models.CASCADE) class Order_unit(models.Model): order = models.ForeignKey(Order, related_name='orderunits_orders', null=True, on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='orderunits_products', null=True, on_delete=models.CASCADE) amount = models.IntegerField price = models.IntegerField This is the serializer that I set up: class OrderUnitSerializer(serializers.ModelSerializer): class Meta: model = Order_unit fields = ['order', 'product', 'amount', 'price'] class OrderSerializer(serializers.ModelSerializer): orderunits_orders = OrderUnitSerializer(many=True) class Meta: model = Order fields = [ 'id', 'code', 'code_year', 'date_registered', 'customer', 'creator', 'orderunits_orders' ] This is the view: class OrderListCreateAPIView(ListCreateAPIView): queryset = Order.objects.all() serializer_class = OrderSerializer permission_classes = [AllowAny] def unit_detail_view(request): obj=Order_unit.objects.all() obj1=Product.objects.all() context={ 'order': obj.order, 'product': obj.product, 'amount': … -
Opening sweet alert.js on button click
I have the following button: <a class="btn btn-success" href="">Accept</a> I want to display a javascript sweet alert when it is clicked on For example, when the user clicks on it, I call swal("Hello world!"); How would I do this? -
using signals to create a model?
I have instructor and club models. I want when an instructor who is a supervisor is created, he/she will be assigned to a club that is equal to his/her department. I'm new to signals and not sure how to achieve it? models.py class Instructor(models.Model): dep_choice = ( (0, 'ISOM'), (1, 'Accounting'), (2, 'PA'), (3, 'Finance'), (4, 'Management & Marketing'), (5, 'Economics'), ) instructor_user = models.OneToOneField(MyUser, on_delete=models.CASCADE) department = models.IntegerField(choices=dep_choice, default=0) supervisor = models.BooleanField(default=False) def __str__(self): return str(self.instructor_user) class Club(models.Model): ISOM = 0 Accounting = 1 PA = 2 Finance = 3 ManagementandMarketing = 4 Economics = 5 club_name = ( (ISOM, 'ISOM'), (Accounting, 'Accounting'), (PA, 'PA'), (Finance, 'Finance'), (ManagementandMarketing, 'Management & Marketing'), (Economics, 'Economics'), ) instructor = models.OneToOneField(Instructor, on_delete=models.CASCADE) name = models.IntegerField(choices=club_name, default=0) def __str__(self): return self.get_name_display() signals.py from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from .models import Instructor, Student, Adminstrator, MyUser, Club @receiver(post_save, sender=Instructor) def post_save_create_instructor(sender, instance, created, **kwargs): if created: if instance.supervisor == True: Club.objects.create(instructor=instance) -
django null value in column violates not-null constraint postgres
I am attempting to have a form that a user can upload multiple images on their blog. When the user submits the form I get the error null value in column "post_id" of relation "blog_postimages" violates not-null constraint The form has a foreign key to the blogpost. What confuses me is that the value is not null and I am using it else where (pk). I am running a postgres db view def DetailPostView(request, pk): model = Post post = Post.objects.get(pk=pk) if request.method == 'POST': test = PostImagesForm(request.POST, request.FILES) files = request.FILES.getlist('images') if test.is_valid(): for f in files: test.save(commit=False) test.post = Post.objects.get(pk=pk) test.save() else: print(PostImagesForm.errors) context = { 'post':post, 'PostImagesForm':PostImagesForm, } return render(request, 'blog/post_detail.html', context) models class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(default='default.jpg', upload_to='hero_car_image') content = RichTextUploadingField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class PostImages(models.Model): post = models.ForeignKey('Post', on_delete=models.CASCADE) images = models.ImageField(upload_to='post_images') date_posted = models.DateTimeField(default=timezone.now) I do not have any unapplied migrations and I am positive I am calling it properly. Even if I hard code in a number it still errors out. -
VaulueError: too many values to unpack (expected 2) Django 3.2.5
I have an orders model that displays the order status as a dropdown in the Django admin panel. class Orders(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for Delivery', 'Out for Delivery'), ('Delivered', 'Delivered'), ) customers = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) products = models.ForeignKey(Products, on_delete=models.SET_NULL, null=True) status = models.CharField(max_length=50, null=True, choices=STATUS) date_created = models.DateTimeField(auto_now_add=True, null=True) And I am rendering the models in the dashboard view def dashboard_view(request): customers = Customer.objects.all() orders = Orders.objects.all() total_customers = customers.count() total_orders = orders.count() delivered = orders.filter('Delivered').count() pending = orders.filter('Pending').count() context = {'customers': customers, 'orders': orders,'total_orders': total_orders, 'delivered': delivered, 'pending': pending} return render(request, "account/dashboard.html", context) while filtering the string 'Delivered' from class Orders, Django throws me a ValueError saying that 'too many values to unpack (expected 2)' This is my first Django implementation, any help is appreciated. Thank you! -
How to change ViewSet retrieve to filter data in Django?
I'm a neewbie building an API integrating a MongoDB with Django. My situation is that I want to retrieve the data of db A filtered against a parameter of db B, but I can't figure out how to properly edit the views(ViewSet). For instance, in db A there are collections of documents containing the fields: _id = ObjectId('some_id'), date = some_date and link = link_of_something, and in db B there are collections of documents containing: date = some_date and ids = list_of_some_ObjectId(str)_from_db_A. So, I want to retrieve just the db A links for which the ObjectId(str) are present in the ids list of db B, how can I do that? Thanks in advance, cheers -
I am building a webapplication using Django. I have created 3 models in models.py and want to connect the models using templates
I am building a web application for my college project.I am referring to the Django beginner book where they have built a blog post. I am using this as a reference to build a construction management application. I currently have 3 models as in the image. This is a screenshot of my models.py with this I have created class based views and the URLS for them. I want to start a new project from the client details page but i am not able to configure the url properly. I get the error TypeError at /client/1/update/ 'str' object is not a mapping I am stuck and not sure how to proceed further. Please let me know i can share more screenshots for the community. This is a screenshot of my models.py and this is my URLs -
Django / PostGreSQL: Create queryset grouped by 'date' when each row has a different timezone
Let's say I have two models: from django.db import model class Company(model.Model): name = models.TextField() timezone = models.TextField() class Sale(models.Model): amount = models.IntegerField() company = models.ForeignKey('Company') time = models.DateTimeField() I want to create a queryset grouped by date and company, where date refers to the calendar date of the sale at the timezone specified on the Company object. This query: result = Sale.objects.values( 'company', 'time__date' ).aggregate( models.Sum('amount') ) This returns the data in a format that works for me. However, the sales are grouped by UTC day. I want them grouped by the timezone on the Company objects. What is the cleanest, quickest way to do this? I know I could dump the entire set of values into Python, like this: result = Order.objects.values( 'amount', 'company__timezone', 'time' ).order_by( 'company_timezone' ) for r in result: r.date = r.time.astimezone(pytz.timezone(r.company_timezone)).date() and then groupby, but is there a better way? -
Django Celery Redis Auth
I'm trying to add Celery to django to schedule tasks. I use Redis backend, and connect via unix socket. Setup was working until I have tried using password auth to redis.conf: My settings.py: CELERY_BROKER_URL = 'redis+socket:///home/username/domain/redis.sock?password=mypasswd' CELERY_RESULT_BACKEND = 'redis+socket:///home/username/domain/redis.sock?password=mypasswd' celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'public_python.settings') # celery settings for the demo_project app = Celery('public_python') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() Result: [2021-07-19 21:22:14,003: ERROR/MainProcess] consumer: Cannot connect to redis+socket:///home/username/domain/redis.sock: Authentication required.. I have already tried adding: CELERY_REDIS_PASSWORD='mypasswd' (any any concievable combination of similar words), with no luck. -
Django template tags all() and count() don't work what should I do
I am very new to Django so bare with me. I have a model called Posts that looks like this: class Post(models.Model): author = models.ForeignKey(User,on_delete=CASCADE, related_name='posts') content = models.TextField(max_length=127) date = models.DateField(auto_now=True) objects = PostManager() def __str__(self): return f"{self.author} : {self.content} -- ({self.date})" And a model of Likes that looks like this: class Like(models.Model): post = models.ForeignKey(Post, on_delete=CASCADE, related_name='likes') user = models.ForeignKey(User, on_delete= CASCADE, related_name='liked') class Meta: unique_together = ('post', 'user') From the Like model I have a foreign key that points to my Post model. If I want to access the amount of likes a post has I write this in the shell: post1 = Post.objects.get(id =1) post1.likes.all().count() This is my view for rendering posts @require_GET def getposts(request): posts = Post.objects.order_by('-date').all() p = Paginator(posts, 10) someposts = p.page(int(request.GET.get('page', 1))) rendered_posts = render_to_string('network/posts.html', context={'page':someposts}) return JsonResponse({'posts': rendered_posts}) This is how post.html looks like {% for post in page.object_list%} <div class="post"> <ul class="post__head"> <li class="author">{{post.author.username}}</li> <li class="date">{{post.date}}</li> </ul> <p class="content">{{post.content}}</p> <div class="post__actions"> <span class="like__button"></span> <p class="like__amount">{{post.likes.all().count()}}</p> </div> </div> {% endfor %} Now this line is what's giving me trouble: <p class="like__amount">{{post.likes.all().count()}}</p> I get an error that I can't use all() and count() in my template I was wondering if there's a … -
'DiscordUser' object is not iterable
I'm trying to do login() with Discord OAuth2 and a custom authentication backend but I get an error. When a user logs in for the first time this error pops up, but if they log out and then log in again, it will work. The error is originating from discord_user_auth = list(discord_user_auth).pop() def discord_login_redirect(request, *args, **kwargs): code = request.GET.get("code") exchange_user = exchange_code(code) discord_user_auth = DiscordAuthenticationBackend.authenticate(request=request, user=exchange_user) discord_user_auth = list(discord_user_auth).pop() login(request, discord_user_auth) return redirect("/app") def exchange_code(code: str): data = { "client_id": client_id, "client_secret": "secret", "grant_type": "authorization_code", "code": code, "redirect_uri": "http://localhost:8000/app/oauth2/login/redirect", "scope": "identify guilds" } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } validate_token = requests.post("https://discord.com/api/oauth2/token", data=data, headers=headers) credentials = validate_token.json() access_token = credentials['access_token'] get_user_info = requests.get('https://discord.com/api/v9/users/@me', headers={ 'Authorization': 'Bearer %s' % access_token }) get_guilds = requests.get('https://discord.com/api/v9/users/@me/guilds', headers={ 'Authorization': 'Bearer %s' % access_token }) global guilds guilds = get_guilds.json() global user user = get_user_info.json() return user Full Traceback: Traceback (most recent call last): File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Internet\Desktop\Programming\Discord\exo_website\website\exo_dashboard\dashboard\home\views.py", line 186, in discord_login_redirect discord_user_auth = list(discord_user_auth).pop() TypeError: 'DiscordUser' object is not iterable