Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting values from django database
I'm just learning python and django. I am writing a thing that reads the values in the xlsx file, and if the values are similar to those in the database, then the value in the adjacent column in the xlsx file changes to the one I specify models.py class imgUpload(models.Model): title = models.CharField(max_length=100) img = models.ImageField(upload_to='img') def __str__(self): return self.title views.py def upload_xlsx(request): if request.method == 'POST': form = xlsxForm(request.POST, request.FILES) if form.is_valid(): form.save() fileName = xlsxUpload.objects.last() fileNameStr = str(fileName.file) book = load_workbook(fileNameStr) sheet: worksheet = book.worksheets[0] for row in range(2, sheet.max_row + 1): a = sheet[row][0].value fileNameImg = imgUpload.objects.all() fileNameImgStr = fileNameImg.filter(title=a) if a == fileNameImgStr: sheet[row][1].value = str(fileNameImgStr) book.save(fileNameStr) book.close() return redirect('xlsx_list') else: form = xlsxForm() return render(request, 'img/upload_xlsx.html', { 'form': form }) I have achieved that it takes all the values, but does not compare them -
How do I get rid of labels in django Form?
I have dealt with only ModelForm previously, so it is my first time using Form. I'd like to get rid of labels from my form, however, how I get rid of labels in ModelForm does not seem to work with Form. Here is my code: forms.py class UserLoginForm(forms.Form): email = forms.CharField(max_length=255) password = forms.CharField(max_length=255) labels = { 'email': '', 'password': '' } widgets = { 'email': forms.TextInput(attrs={'class': 'login_input', 'placeholder': 'Email'}), 'password': forms.PasswordInput(attrs={'class': 'login_input', 'placeholder': 'Password'}) } It seemed like a simple problem but it turned out I could not get what I wanted from the official django document or Google. I'd be really appreciated if you could help me solving it. Thank you. -
Django Unit Test login
I am trying to do a Unit-Test to check that an authenticated user accesses the url /downloads on my Django site but I get the following error: django.db.utils.ProgrammingError: (1146, "1146 (42S02): Table 'test_my_db_dev.filminfo' doesn't exist", '42S02') My Unit-Test looks like this: from django.test import TestCase class TestLoginView(TestCase): def test_authenticated_user_can_see_page(self): user = User.objects.create_user("SomeUser," "some_user@mymail.net", "my_testP@ss!") self.client.force_login(user=user) response = self.client.get("/downloads") self.assertEqual(response.status_code, 200) I would appreciate any help/comments. Thanks :) -
style.css not loading in django html template
I created a login page and calling a static css sheet for styling but its not working. I load static in my login.html and use <html> <head> <title>PWC Login</title> <link rel="stylesheet" href="{% static 'css/style.css'%}"> </head> <body> <div class="loginbox"> <img src="{% static 'images/avatar.png' %}" class="avatar"> <h1 class="h1">Login Here</h1> <form> <p>Username</p> <input type="text" name="" placeholder="Enter Username"> <p>Password</p> <input type="password" name="" placeholder="Enter Password"> <input type="submit" name="" value="Login"> <a href="#">Forgot your password?</a><br> <a href="#">Don't have an account?</a> </form> </div> </body> </html> css: body { margin: 0; padding: 0; background: url('static/images/pic1.jpeg'); background-size: cover; background-position: center; font-family: sans-serif; } .loginbox{ width:320px; height:420px; background: #000; color: #fff; top:50%; left:50%; position: absolute; transform: translate(-50%,-50%); box-sizing: border-box; padding: 70px 30px; } .avatar{ width: 100px; height: 100px; border-radius: 50%; position: absolute; top: -50px; left: calc(50% - 50px); } i tried the html and css file separately and it works fine. the background is the jpeg file and the login box is centered. it has to be something in django but not sure what it is. -
How do I target a ForeignKey attribute inside a loop?
I've a cart view and when a user is authenticated and has products in the cart view, I wanna check against product availability and if one product is found with availability set to False I wanna render Out of stock, the code for not authenticated users works, but for authenticated users Traceback Error is 'OrderItem' object has no attribute 'availability' Models class Product(models.Model): availability = models.BooleanField() class OrderItem(models.Model): product = models.ForeignKey(Product) order = models.ForeignKey(Order) Views def cart(request): data = cartData(request) items = data['items'] orderitemlist = OrderItem.objects.all() if not request.user.is_authenticated: available = all(x['product']['availability'] for x in items) else: available = all(x.availability for x in orderitemlist) context = {"items": items, 'available': available} Template {% if available %} <a href="#">Checkout</a> {% else %} <p>Out of stock</p> {% endif %} -
Hi everyone, I just started learning DJango and I am stuck with Jinja
In my folder Templates I created 2 html files: main.html projects.html The structure of the main.html is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DJANGO</title> </head> <body> {% block userinfo %} {% endblock userinfo %} </body> </html> The structure of the user.html is: {% extends "main.html" %} {% block userinfo %} <h2>John Doe</h2> <p>Explorer of life.</p> {% endblock userinfo %} I don't understand why <h2>John Doe</h2> <p>Explorer of life.</p> doesn't appear in the browser when I call main.html I have tried writing in this way too {% extends "main.html" %} {% block userinfo %} <h2>John Doe</h2> <p>Explorer of life.</p> {% endblock %} without user in the endblock but it does not work. In settings.py file in Templates list and DIR list I added: os.path.join(BASE_DIR,'templates'), and I importend os too. In views.py file that I've created I have written from django.shortcuts import render from django.http import HttpResponse def main(request): return render(request,'main.html') In urls.py file that I've created I have written from django.urls import path from . import views urlpatterns = [ path('main/',views.main,name='') ] When I call the page with http://localhost:8000/main/ I don't have any error. The only problem is that the page is blank. … -
How can i Access primary key in template tag
I am trying to create an update view that allows users to update their data. I am trying to access the data by using primary keys. My problem is that i do not know the syntax to implement it. views.py def updatedetails(request, pk): detail = Detail.objects.get(id=pk) form = Details(instance=detail) if request.method == "POST": form = Details(request.POST, instance=detail) if form.is_valid(): form.save() return redirect(success) return render(request, "details.html", {"form":form}) urls.py from django.urls import path from . import views urlpatterns = [ path("details/", views.details, name="details"), path("success/", views.success, name="success"), path("edit/<str:pk>/", views.updatedetails, name="updatedetails"), ] my html template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Success</title> </head> <body> <h1>Thank You for Filling Out the Form</h1> <p><a href="/edit/{{request.detail.id}}/">Click Here To Edit</a></p> </body> </html> So what i am trying to figure out is how to call the primary key in my template -
Django - use multiple fields proprieties
class Event(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) guests = models.IntegerField() description = models.CharField(max_length=300) venue = models.BooleanField(default=False) garden = models.BooleanField(default=False) candybar = models.BooleanField(default=False) games = models.BooleanField(default=False) wine = models.BooleanField(default=False) premiumphoto = models.BooleanField(default=False) premiumvideo = models.BooleanField(default=False) limo = models.BooleanField(default=False) stuff = models.BooleanField(default=False) totalprice = models.IntegerField() This is my event model, i want the user to be able to select if they want, for example games, if they do i want the total price to be updated with the price of games wich could be 500$, how can i set games to be a bool and to have a value that can be changed by the admins. I think an interesint idea could be to have some kind of model that is default and the other models to take the price from the Price model -
DRF method GET not allowed on @action based function
I have the two models: Article and Comment. I have the ArticleAPI viewset, which have methods decorated with @action to handle requests to comments model, but when I am trying to test this endpoint via Postman I get an error: { "detail": "Method \"GET\" not allowed." } ArticleAPI.py class ArticleAPI(viewsets.ModelViewSet): serializer_class = ArticleSerializer permission_classes = [ permissions.IsAuthenticatedOrReadOnly ] queryset = Article.objects.order_by('number') lookup_field = 'pk' ... @action(methods=['GET'], detail=True, url_path='comments', url_name='article-comments-list') def get_comments_queryset(self, request): instance = self.get_object() serializer = CommentSerializer(queryset=instance.comment_set.all(), many=True) return Response(serializer.data) @action(methods=['GET'], detail=True, url_path='comments', url_name='article-comments-object') def get_comment_object(self, request, pk=None): instance = self.get_object() serializer = CommentSerializer(queryset=instance.comment_set.get(pk=pk)) return Response(serializer.data) urls.py router = DefaultRouter() router.register('articles', articleAPI.ArticleAPI, basename='articles') -
Python Django session expire on redirect url is called
I have made an medium size website and am trying to implement payment gateway(paytm). In order to process the payment token is needed to start the payment, i could able to generate the token from the api request and the JS payment page is being invoked successfully. The main problem am encountering is after selecting the payment and start the payment pop up page appears to getting an error Session expired due to inactivity with in a seconds the page load. I tried contacting the payment gateway dev team but the could able to generated the payment successfully. However they are doing it in flask or through postman. when i try to run the code i have no problem processing the payment but when i use the same code in the Django am unable to process the payment.Even they are unable to understand the problem am getting(i.e session expired due to inactivity.) I am wondering this has to do something with the sessions and when i have stored the token in the session and call the payment page at then i do not get the error but am getting another issue is that the values are not being passed to … -
Django and DRF Why isn't my password hashing
I am using DRF and I have these pieces of code as models, register view and serializer But anytime I signup a user the password does not hashed and I can't see to figure out why. models.py class UserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an email") email = self.normalize_email(email).lower() user = self.model(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): if not password: raise ValueError("Password is required") user = self.create_user(email, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) role = models.CharField(max_length=255) department = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name", "role", "department"] def __str__(self): return self.email serializers.py class RegisterSerializer(serializers.ModelSerializer): email = serializers.CharField(max_length=255) password = serializers.CharField(min_length=8, write_only=True) first_name = serializers.CharField(max_length=255) last_name = serializers.CharField(max_length=255) role = serializers.CharField(max_length=255) department = serializers.CharField(max_length=255) class Meta: model = User fields = ["email", "password", "first_name", "last_name", "role", "department"] def create(self, validated_data): return User.objects.create(**validated_data) def validate_email(self, value): if User.objects.filter(email=value).exists(): raise serializers.ValidationError("This email already exists!") return value views.py class RegisterView(APIView): serializer_class = RegisterSerializer def post(self, request, *args): serializer … -
How to display the progress of a function in an html page Django?
I'm learning Django, tell me if it's possible to implement my idea. In the file views.py I have a script def index(request): .... for i in range(100000): print(i) return render(request, 'main/index.html', {'title': 'Website main page', 'tasks': ...}) How can I display these prints in the index.html page? If I insert the variable i into render, then the page is in the process of waiting and, as a result, shows only the last value in the iteration. I understand why this is happening. But how can I then display online in the process - what happens in the terminal, all the values in the enumeration? It seems to me that javascirpt is needed for this - I think or is it possible to display this in a simpler way? -
react + django, problem with file import, does not recognize boostrap
these problems enter image description here this is my webpack.config.js const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "../src/index.js", output: { path: path.resolve(__dirname, "../static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, { test: /\.css$/, exclude: /node_modules/, use: { loader: "babel-loader", } }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ "process.env": { // This has effect on the react lib size NODE_ENV: JSON.stringify("production"), }, }), ], }; my input import React from 'react'; import "bootstrap/dist/css/bootstrap.css" import { Route, Routes } from 'react-router-dom'; import Home from './pages/Home'; I've already tried installing bootstrap, both in react and in django, but it won't, I don't think it's recognizing any files that I'm importing. -
How to fix website picture problem on HTML
{% extends 'base.html' %} {% block content %} <hi>Products</hi> <div class="row"> {% for products in products %} <div class="col"> <div class="card" style="width: 70rem;"> <img src="{{ products.image_url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ products.name }}</h5> <p class="card-text">${{ products.price }}</p> <a href="#" class="btn btn-primary">Add to Cart</a> </div> </div> </div> {% endfor %} </div> {% endblock %} Is there a problem with this code I tried reformatting the code, by replacing the products. url into the alt brackets. But it was what i typed on in the brackets that showed up. Please help me. I'm frustrated. I'm a 13 year old beginner programmer. This is my first website which i have restarted about 19 times because of this problem. Help me -
Different user types with Django default auth
For my Django project, I have 3 different user types. I use boolean flags to know what kind of user is the actual one and have 3 models with one to one relation to the user model and the extra fields for each one: class Usuario(AbstractUser): es_centro = models.BooleanField(default=False) es_tutor = models.BooleanField(default=False) es_proveedor = models.BooleanField(default=False) class Centro(models.Model): usuario = models.OneToOneField(Usuario, on_delete=models.CASCADE, primary_key=True) provincia = models.CharField(max_length=20) localidad = models.CharField(max_length=50) codigo = models.PositiveIntegerField(null=True, blank=True) cursos = models.ManyToManyField(Curso) class Tutor(models.Model): usuario = models.OneToOneField(Usuario, on_delete=models.CASCADE, primary_key=True) dni = ESIdentityCardNumberField() centro = models.ForeignKey(Centro, on_delete=models.CASCADE) class Proveedor(models.Model): usuario = models.OneToOneField(Usuario, on_delete=models.CASCADE, primary_key=True) nif = ESIdentityCardNumberField() now, i want to use the default auth urls to manager the users. I have something like this: urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('centros/', include('django.contrib.auth.urls')), path('centros/registro', views.centrosregistro, name='centrosregistro'), path('tutores/', include('django.contrib.auth.urls')), #path('tutores/registro', views.tutoresregistro, name='tutoresregistro'), path('proveedores/', include('django.contrib.auth.urls')), #path('proveedores/registro', views.proveedoresregistro, name='proveedoresregistro'), ] each user type have a path where auth.urls are included. These urls look for templates in a default folder called 'registration', where there has to be a login.html, logout.html, ... My question is ¿how can I have different templates for every user type or, at least, how to know which user type is trying to login, logout, ...? So … -
Problem with logging with auth_views.loginView in Django
When I try to login via LoginView, the process seems successful. I'm redirected to LOGIN_REDIRECT_URL. urlpatterns = [ ... path('login', auth_views.LoginView.as_view(), name='login'), ] But when I try to access a view which requires login, I can't: class MyView(viewsets.ViewSet): @method_decorator(login_required(login_url='/login')) def list(self, request, server_id): .... What am I missing? Thanks by now. Here's my login form. <form method="POST" action="{% url 'login' %}"> {% csrf_token %} <div class="form-group"> <label>Username</label> <input type="text" class="form-control" id="username" name="username" placeholder="Username"> </div> <div class="form-group"> <label>Password</label> <input type="password" name="password" id="password" class="form-control" placeholder="Password"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> -
Django generated error on server log and have try to log the error but it didn’t work
I need assistant on this, i saw this error on server log: django.request.log_response:228- Bad Request: endpoint. Can anyone help with what causing this error? I try printing the request body to see maybe it request body that causes the error but it seems not to be the problem -
.env file not gitignored. I had someone do it manually for me once
So im currently working on a project and my my .env file is not greyed out (gitignore?). Trying to figure out what I need to do globally because I do have the file but my .env is never greyed out. Any suggestions? I can provide screenshots if needed. I had someone do a a few commands in the terminal and was able to get my .env to go grey once. But I believe he told me he wasn't able to do it globally. Reach out for help. -
ERROR: Could not find a version that satisfies the requirement setuptools_scm<3,>=4.1.2
I'm trying to install djangular-serve in my project but I'm unsure what version of setuptools_Scm it's asking for. Using cached djangular-serve-2.1.0.tar.gz (34 kB) Installing build dependencies ... error error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> [4 lines of output] Collecting setuptools>=49.6.0 Using cached setuptools-65.6.3-py3-none-any.whl (1.2 MB) ERROR: Could not find a version that satisfies the requirement setuptools_scm<3,>=4.1.2 (from versions: 1.0.0, 1.1.0, 1.2.0, 1.3.0, 1.4.0, 1.4.1, 1.5.0, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.6.0, 1.7.0, 1.8.0, 1.9.0, 1.10.0, 1.10.1, 1.11.0, 1.11.1, 1.13.0, 1.13.1, 1.14.0rc1, 1.14.0, 1.15.0rc1, 1.15.0, 1.15.1rc1, 1.15.4, 1.15.5, 1.15.6, 1.15.7, 1.16.0, 1.16.1, 1.16.2, 1.17.0, 2.0.0, 2.1.0, 3.0.0, 3.0.1, 3.0.2, 3.0.4, 3.0.5, 3.0.6, 3.1.0, 3.2.0, 3.3.1, 3.3.2, 3.3.3, 3.4.0, 3.4.1, 3.4.2, 3.4.3, 3.5.0, 4.0.0, 4.1.0, 4.1.1, 4.1.2, 5.0.0, 5.0.1, 5.0.2, 6.0.0, 6.0.1, 6.1.0.dev0, 6.1.0, 6.1.1, 6.2.0, 6.3.0, 6.3.1, 6.3.2, 6.4.0, 6.4.1, 6.4.2, 7.0.0, 7.0.1, 7.0.2, 7.0.3, 7.0.4, 7.0.5) ERROR: No matching distribution found for setuptools_scm<3,>=4.1.2 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error I'm confused, how can the version be greater than 4.1.2 but less than 3? Do I need to fix the setup? How do I download the … -
Django DRF how to 'multiple object update'?
I am trying to update multiple objects, however i am stumped on what i am doing wrong. I get queryset of objects i need to update, by filtering by schoolName(this is how my DB looks like), but I get "'ListSerializer' object is not iterable" when I include {% render_form serializer %} in my template. I have uploaded my project to github Relevant code: models.py: class School(models.Model): schoolName = models.CharField(max_length=200, default='No Data') className = models.CharField(max_length=200, default='No Data') studentName = models.CharField(max_length=200, default='No Data') studentGrade = models.IntegerField(null=True, blank=True) professorName = models.CharField(max_length=200, default='No Data') def __str__(self): return self.schoolName serializers.py: class SchoolPartListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): # Maps for id->instance and id->data item. school_mapping = {school.id: school for school in instance} data_mapping= {schoolName['id']: schoolName for schoolName in validated_data} # Perform creations and updates. ret = [] for school_id, data in data_mapping.schoolName(): school = school_mapping.get(school_id, None) if school is None: ret.append(self.child.create(data)) else: ret.append(self.child.update(school, data)) # Perform deletions. for school_id, school in school_mapping.schoolName(): if school_id not in data_mapping: school.delete() return ret class SchoolPartSerializer(serializers.Serializer): id = serializers.IntegerField() class Meta: list_serializer_class = SchoolPartListSerializer model = School fields = ('id', 'url', 'schoolName') extra_kwargs = { 'id':{ 'read_only': False, 'allow_null': True, }, 'schoolName':{ 'required': True, } } views.py: class SchoolDetail(APIView): renderer_classes … -
I got an error while trying to host my django application to heroku
I was following a youtube tutorial to deploy my django app to heroku, everything worked smoothly until I did the last step using the command "sudo git push heroku main" and got an error, any suggestions on how to solve it? The erorr: remote: error: subprocess-exited-with-error remote: remote: × python setup.py egg_info did not run successfully. remote: │ exit code: 1 remote: ╰─> [6 lines of output] remote: Traceback (most recent call last): remote: File "<string>", line 2, in <module> remote: File "<pip-setuptools-caller>", line 34, in <module> remote: File "/tmp/pip-install-xoccjliv/zope-interface_8de24a9b6b0c46c292079bf8aacc4563/setup.py", line 26, in <module> remote: from setuptools import setup, Extension, Feature remote: ImportError: cannot import name 'Feature' from 'setuptools' (/app/.heroku/python/lib/python3.10/site-packages/setuptools/init.py) remote: [end of output] remote: remote: note: This error originates from a subprocess, and is likely not a problem with pip. remote: error: metadata-generation-failed remote: remote: × Encountered error while generating package metadata. remote: ╰─> See above for output. remote: remote: note: This is an issue with the package mentioned above, not pip. I googled a lot about it but nothing worked! -
Wagtail CMS(Django) - Display Inline Model Fields in Related Model
I have two custom models(not inheriting from Page) that are specific to the admin in a Wagtail CMS website. I can get this working in regular Django, but in Wagtail I can't get the inline model fields to appear. I get a key error. The code... On model.py: from django.db import models from wagtail.admin.panels import ( FieldPanel, MultiFieldPanel, FieldRowPanel, InlinePanel, ) from author.models import Author class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) date = models.DateField("Date released") panels = [ MultiFieldPanel([ InlinePanel('book_review'), ], heading="Book reviews"), ] class BookReview(models.Model): book = models.ForeignKey( Book, on_delete=models.CASCADE, related_name='book_review') title = models.CharField(max_length=250) content = models.TextField() panels = [ FieldRowPanel([ FieldPanel('title'), FieldPanel('content'), ]) ] and wagtail_hooks.py: from wagtail.contrib.modeladmin.options import ( ModelAdmin, modeladmin_register, ) from .models import Book, BookReview class BookAdmin(ModelAdmin): model = Book add_to_settings_menu = False add_to_admin_menu = True inlines = [BookReview] # only added this after key error, but it didn't help modeladmin_register(BookAdmin) How can I get the InlinePanel('book_review'), line to show up in the admin. It all works until I try add the inline model fields. I looked around online and it was mentioning a third party Django modelcluster package. Is this still required? Those post were quite old(5 years or so). Or instead of using … -
GROUP By in Django ORM for page in Django Admin
I'm not very long in Django, sorry for the probably stupid question. But after many hours of trying to solve and a huge number of searches on the Internet, I did not find a solution. My Models: class Offer(models.Model): seller = models.ForeignKey()<..> # other fields class OfferViewCount(models.Model): offer = models.ForeignKey(Offer, verbose_name=_('Offer'), on_delete=models.CASCADE) user_agent = models.CharField(verbose_name=_('User Agent'), max_length=200) ip_address = models.CharField(verbose_name=_('IP Address'), max_length=32) created_date = models.DateTimeField(auto_now_add=True) The database of the OfferViewCount model has the following data: id;user_agent;ip_address;created_date;offer_id 24;insomnia/2022.6.0f;127.0.0.1;2022-11-18 14:14:52.501008+00;192 25;insomnia/2022.6.0z;127.0.0.1;2022-11-18 15:03:31.471366+00;192 23;insomnia/2022.6.0;127.0.0.1;2022-11-18 14:14:49.840141+00;193 28;insomnia/2022.6.0;127.0.0.1;2022-11-18 15:04:18.867051+00;195 29;insomnia/2022.6.0;127.0.0.1;2022-11-21 11:33:15.719524+00;195 30;test;127.0.1.1;2022-11-22 19:34:39+00;195 If I use the default output in Django Admin like this: class OfferViewCountAdmin(admin.ModelAdmin): list_display = ('offer',) I get this: Offer offer #192 offer #192 offer #193 offer #195 offer #195 offer #195 I want to get a result like this: Offer;Views offer #192;2 offer #193;1 offer #195;3 Simply put, I want to display one instance of each duplicate post in the admin, and display the total number of them in a custom field. In SQL it would look something like this: SELECT offer_id, COUNT(*) AS count FROM offer_offerviewcount GROUP BY offer_id ORDER BY COUNT DESC; I've tried many options, including overwriting get_queryset. In general, I managed to achieve the desired result like … -
How to use transaction with "async" functions in Django?
When async def call_test(request): called async def test(): as shown below (I use Django==3.1.7): async def test(): for _ in range(0, 3): print("Test") async def call_test(request): await test() # Here return HttpResponse("Call_test") There was no error displaying the proper result below on console: Test Test Test But, when I put @transaction.atomic() on async def test(): as shown below: @transaction.atomic() # Here async def test(): for _ in range(0, 3): print("Test") # ... The error below occurred: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. So, I put @sync_to_async on @transaction.atomic() as shown below: @sync_to_async # Here @transaction.atomic() async def test(): for _ in range(0, 3): print("Test") # ... But other error below occurred: RuntimeWarning: coroutine 'test' was never awaited handle = None # Needed to break cycles when an exception occurs. RuntimeWarning: Enable tracemalloc to get the object allocation traceback So, how can I use transaction with "async" functions in Django? -
Pagination doesn`t work with extra context in Django ListView
I am trying to create a simple pagination through a query of filtered instances of Need model. The problem is that pagination doesn`t work at all, and I guess this is because of extra content. Here is my current view, which shows pagination on front-end as an empty div: class CategoryNeeds(ListView): model = Need template_name = "volunteering/category_needs.html" paginate_by = 1 context_object_name = "needs" def get_queryset(self): return Need.objects.filter(category__name=self.kwargs["name"].capitalize()) def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() category = Category.objects.get(name=kwargs["name"].capitalize()) self.extra_context = { "category": category, "needs": self.object_list } return self.render_to_response(self.extra_context) And here is the template: {% extends "index/index.html" %} {% block content %} <section class="contact-section bg-black"> <div class="container px-4 px-lg-5"> <div class="row gx-4 gx-lg-5"> <div class="col-md-4 mb-3 mb-md-0"> <div class="card-body text-center"> <h1>{{ category.name }}</h1> <hr style="size: A5"> </div> </div> </div> </div> </section> <section class="about-section text-center" id="about"> <div class="container px-4 px-lg-5"> <h2>Needs:</h2> <table class="table table-dark table-striped"> <thead> <tr> <th scope="col">Photo</th> <th scope="col">Title</th> <th scope="col">Description</th> <th scope="col">Price</th> <th scope="col">Donation</th> <th scope="col">City</th> {% if user.pk == user_page.pk %} <th scope="col">Update</th> <th scope="col">Delete</th> {% endif %} </tr> </thead> <tbody> {% for need in needs %} <tr data-href="{% url "volunteering:need" need.pk %}"> <td>{% if need.photo %}<img src="{{ need.photo.url }}">{% endif %}</td> <td>{{ need.title }}</td> <td>{{ need.description|truncatechars:10 }}</td> …