Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display join date and last_login in Django
I have User default Django User model to register user. I want to print user last_login and join_date on the template. And also I want to check if user is active or not. I want to check user active status like this, If user is currently using my website the status should be "Active" If User logged out Then status should be "Loged out" if it is possible please provide me solution for this as well I am filtering user data like this data = Profile.objects.filter(Q(user__is_superuser=False), Q(user__is_staff=False)).order_by('-user__last_login')[:10] Model.py class Profile(models.Model): user = models.OneToOneField(User,default="1", on_delete=models.CASCADE) image = models.ImageField(upload_to="images",default="default/user.png") def __str__(self): return f'{self.user} profile' -
Error reading webpack-stats.json. Are you sure webpack has generated the file and the path is correct?
I installed django with django and got this eror in runtime: Error reading webpack-stats.json. Are you sure webpack has generated the file and the path is correct? alongside manage.py: vue create frontend Default ([Vue 3] babel, eslint) cd frontend npm run serve list of files in frontend directory is: babel.config.js jsconfig.json node_modules package.json package-lock.json public README.md src vue.config.js npm --version 6.14.15 nodejs --version v10.19.0 node --version v14.17.6 npm list webpack-bundle-tracker └── webpack-bundle-tracker@1.5.0 pip install django-webpack-loader pip freeze django-webpack-loader==1.5.0 INSTALLED_APPS = ( ... 'webpack_loader', ... ) # vue.config.js const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true }) index.html {% load render_bundle from webpack_loader %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta http-equiv="x-ua-compatible" content="ie=edge" /> <title></title> {% render_bundle 'app' 'css' %} </head> <body> <div class="main"> <main> <div id="app"> </div> {% endblock %} </main> </div> {% render_bundle 'app' 'css' %} </body> </html> -
KeyError 'some_field_for_form_a' is not found in FormB during concurrent requests
I am posting this because I am out of ideas. I have tried to find the cause of this issue for the last 2 years. Say I have 4 model admins: TabbedAdminMixin, ModelAdmin a: BasketAdmin b: ConsumerAdmin Normal Django ModelAdmin c: RoleAdmin d: BranchAdmin It took me veeeery long to be able to find a way to re-create this error but as of yesterday, I can easily re-create it by using locust to simulate concurrent requests. When I run locust with 5 concurrent users, each doing requests to /basket//change/ and /consumer//change/ I get a keyerror where render_tab_fieldsets_inlines want to create a, for example, BasketAdmin with fields from ConsumerAdmin's form and vice versa. When I run the same locust file on /role//change/ and /branch//change/ (vanilla django modeladmins) I don't get keyerrors. This happend locally with runserver and in production with uwsgi. Any help will be very much appreciated! -
How to get rid of pytz UnknownTimeZoneError in my Django logs?
I've deployed a Django Application on Windows Server 2022 and error logs are flooded with the following message: pytz.exceptions.UnknownTimeZoneError: 'Europe/Paris'\r, referer: https://my_server_url During handling of the above exception, another exception occurred I've checked my pytz installation and it seems to work just fine : # run Windows cmd as Apache service account python manage.py shell from django.conf import settings import pytz pytz.timezone(settings.TIME_ZONE) <DstTzInfo 'Europe/Paris' LMT+0:09:00 STD> settings.TIME_ZONE in pytz.all_timezones True I've tried to uninstall and reinstall my virtual environnement and upgrade/downgrade pytz, without success. I've no idea on how to investigate this problem furthermore and how to solve it. Here is the application setup : Apache 2.4.52 (built from sources) Python 3.10.4 Mod_wsgi 4.9.0 Django 3.2.9 pytz 2021.3 -
authenticate individual users using api keys or public/private key pairs for api calls in django rest framework
i need to provide authentication method for my users so they can interact with my api endpoints out of the client side (frontend) . something like developer authentication . i've made research and realized that api keys are not recommended for authenticating individual users . on the other hand using ssh key pairs are good approach but saving private keys in order to decrypt the public key message is a security breach . all i need is just to understand the concept of implementing such authentication methods and the flow of how to do it.do you have any suggestion , advice or resource so i can figure out how to implement it ? Thanks -
django-admin: why there is table list inside the table
In the django-admin page, When i click into File table, there are table list above my File data list. How can i unshow the list of table? -
How can I click on any of the categories in the list and be redirected to all active listings in that category? Django
Im working on a django project (im newb) and I`ve made a html page displaying a list of available categories. I want to make each a link and when the user clicks it he/she should be redirected to a list of active listings based on that category. I simply cannot understand how. Here is my code: models.py class Category(models.Model): category = models.CharField(max_length=64) def __str__(self): return self.category class Listings(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=128) description = models.CharField(max_length=822) price = models.FloatField() sold = models.BooleanField(default=False) category = models.ForeignKey(Category, on_delete=models.CASCADE,blank=True, null=True, related_name="listings_category") categories = models.ManyToManyField(Category, blank=True, related_name="select_category") image_url = models.CharField(max_length=128,blank=True, null=True) def __str__(self): return f"{self.title}" urls.py path('category/', views.category, name="category"), path("listing/<str:listing_id>", views.listing, name="listing") views.py def category(request): cat = Category.objects.filter().values('category') category_id = Category.objects.filter().values('id') z = [] for c in category_id: z.append(c['id']) listing = Listings.objects.filter(category__in= z) categories = Category.objects.all() category = Category.objects.filter(id__in=z) print(category) return render(request, "auctions/category.html",{ "categories":categories, "category":category, "listing":listing }) def listing(request, listing_id): listing = Listings.objects.get(id=listing_id) user = request.user owner = True if listing.user == user else False category = Category.objects.get(category=listing.category) comments = Comments.objects.filter(listing=listing.id) watching = WatchList.objects.filter(user = user, listing = listing) if request.method == "POST": comment = request.POST["comment"] if comment != '': Comments.objects.create(user=user, listing=listing, comment=comment) return HttpResponseRedirect(listing_id) return render(request, "auctions/listing.html", { "listing": … -
How to fix Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed?
I created an application with a Django backend and an Angular frontend, I am trying to display the list of my fleet table with its information However I get this error my data is saved in the database but I have this error when I want to display them Html <div class="flotte-list"> <ul class="flottes"> <li *ngFor="let flotte of flottes"> <span class="badge">{{flotte.id}}</span> {{flotte.name}} {{ flotte.nb_engins}} <button class="delete" title="delete flotte" (click)="delete(flotte)">x</button> </li> </ul> </div> <div class="flotte-box"> <div class="flotte-form"> <div class="textbox"> <input #flotteName placeholder="Name"> </div> <div class="textbox"> <input #flotteNbengins placeholder="nb_engins" type="number"> </div> <div class="textbox"> <input #flottetest placeholder="nb_b" > </div> <div class="textbox"> <input #flottefichier placeholder="Type fichier" > </div> <input type="button" class="btn" value="Add flotte" (click)="add( flotteName.value, flotteNbengins.valueAsNumber, flottetest.value, flottefichier.value ); flotteName.value=''; flotteNbengins.value=''; flottetest.value=''; flottefichier.value=''; "> </div> </div> Component.ts getAllFlottes() { this.api.getAllFlottes() .subscribe(data => this.flottes = data) } add(name: string, nb_engins: number, calculateur: string, type_fichier: string){ name = name.trim(); if (!name) { return; } if (!nb_engins) { return; } calculateur = calculateur.trim(); if (!calculateur) { return; } type_fichier = type_fichier.trim(); if (!type_fichier) { return; } this.api.registerFlotte({name, nb_engins, calculateur, type_fichier} as Flotte) .subscribe(data => { this.flottes.push(data); }); } service.ts // GET Flottes getAllFlottes(): Observable<Flotte[]> { return this.http.get<Flotte[]>(this.base_url); } registerFlotte(flotte: Flotte): Observable<Flotte> { return this.http.post<Flotte>(this.base_url, flotte, { headers: … -
Differnece between Q, SearchVector and TrigramSimilarity
I am learning django at the moment and i cant understand the difference between Q, SearchVector and TrigramSimilarity. Which one should I use? -
django cannot annotate queryset in custom model manager
I seem to have some code that works when run manually in the shell, but not when run as part of a custom model manager method. Any hints on what I'm doing wrong? models.py: from django.db import models from django.db.models import Q, ExpressionWrapper class MyTag(models.Model): name = models.CharField(max_length=128, unique=True) class MyManager(models.Manager): def get_queryset(self): queryset = MyQuerySet(self.model, using=self._db).all() queryset.annotate( is_nice=ExpressionWrapper( Q(tags__name__in=["nice"]), output_field=models.BooleanField() ) ) return queryset class MyQuerySet(models.QuerySet): def nice(self): return self.filter(_is_nice=True) class MyModel(models.Model): objects = MyManager() #.from_queryset(MyQuerySet)() name = models.CharField(max_length=64) tags = models.ManyToManyField( MyTag, blank=True, related_name="models", ) This works (explicit y calling annotate): >>> from models.py import * >>> queryset = MyModel.objects.all() >>> queryset.annotate(is_nice=ExpressionWrapper(Q(tags__name__in=["nice"]), output_field=models.BooleanField()) >>> queryset.values_list("is_nice", flat=True) [True, False, ...] But this fails: >>> from models.py import * >>> queryset = MyModel.objects.all() >>> queryset.values_list("is_nice", flat=True) *** django.core.exceptions.FieldError: Cannot resolve keyword 'is_nice' into field. Choices are: id, name, tags -
How to deploy a machine learning model in a django web app?
My project is the conception and realization of a web application for the detection of ransomwares based on machine learning. For the realization, I made a web application with python, Django, HTML and CSS. On the other hand i have to create a machine learning code that makes the detection of these ransomware viruses. Now what I have to do is deploy the machine learning code in my web app. I'll explain a little how it works, the user first registers and then he chooses a csv file to scan, he uploads it and then he chooses the machine learning model he wants use and then he clicks on scan, when he clicks on scan the file will be scanned by the model he has chosen and a result will be returned to him which is either 1: the file is a ransomware or 0: it is not a ransomware. So, I built the web app, I built the model Now my problem is how to pass user input to the model And than take the model's out put to the user. Need help please. -
Does I need to install django for every time I start project?
I use these commands: py -m venv myproject myproject\Scripts\activate.bat `` Than I can't use: django-admin startproject myproject I need to install django for every time: (myproject) C:\Users\Your Name>py -m pip install Django Does i have wrong someting? -
Django doesn't connect to postgresql database using docker
I am pretty new to Django and very new to docker. This is my first time using docker. I am trying to connect my django app in one docker container to postgreSQL database in another docker container. I was following a youtube tutorial when I encountered this problem. I wasn't following the tutorial exactly as shown in the video though. I am using Docker on Windows 10. My 'docker-compose.yml' file: version: '3.8' services: db: container_name: db_ramrobazar image: postgres restart: always environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - '5432:5432' volumes: - postgres_data:/var/lib/postgresql/data/ # env_file: .env networks: - djangonetwork web: container_name: web_ramrobazar build: context: . depends_on: - db command: > sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - "8000:8000" env_file: .env links: - db:db networks: - djangonetwork volumes: - .:/usr/src/app volumes: postgres_data: networks: djangonetwork: driver: bridge My Dockerfile file: FROM python:3.8-slim-buster # setting work directory WORKDIR /usr/src/app # env variables ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWEITEBYTECODE 1 # install psycopg dependencies RUN apt-get update && apt-get install -y \ build-essential \ libpq-dev \ && rm -rf /var/lib/apt/lists/* # install dependencies RUN pip install --upgrade pip COPY requirements.txt . RUN pip install -r requirements.txt … -
Create dynamic model field in Django?
In my models.py my model store contain name, brand_name field Now,I want to create new field called brand_type dynamically from Django admin,how can I do this? -
Render Form Elements Individually in Django
I'm a newbie to django and I'm trying to figure out how to render my form elements individually, since I think it's the best way for my file as I have several parent CSS classes. I want to replace pretty much every label and input you see with my forms.py form models with keeping the CSS Styling. Here is my HTML code: <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} <div id="Profile" class="tabcontent"> <div class="profile-show"> <div class="profile-show-content"> <div class="avatar-upload"> <div class="avatar-edit"> <input type="file" id="imageUpload" accept=".png, .jpg, .jpeg"> <label for="imageUpload"></label> </div> <div class="avatar-preview"> <div id="imagePreview" style="background-image: url(http://i.pravatar.cc/500?img=7);"> </div> </div> </div> <div class="user-first"> <h2>{{user}}</h2> <p>Created: 10.3.2022</p> </div> <hr> <div class="user-second"> <div class="user-roles"> <ul class="list-wrapper"> <li id="member"><i class="fa-solid fa-user"></i><p>Member</p></li> <li id="admin"><i class="fa-solid fa-shield-halved"></i><p>Admin</p></li> </ul> </div> <div class="user-second-bio"> <p> Lorem Ipsum Biography, Lorem Ipsum dolor sit amum amoret dolor sit mum amoret dolor sitmum amoret dolor sit </p> </div> </div> </div> </div> <div class="user-edit"> <div class="user-info"> <h2>User Informations</h2> <div class="info-1"> <label for="username">Username</label> <br> <input type="text" id="username" placeholder="Username"> </div> <div class="info-2"> <label for="mail">E-Mail</label> <br> <input type="text" id="mail" placeholder="user@gmail.com"> </div> <div class="info-3"> <label for="password">Password</label> <br> <input type="password" id="password" placeholder="*********"> </div> </div> <div class="user-bio"> <label for="bio">Your description</label> <br> <textarea id="bio" rows="11" cols="50">Hey This is my bio.</textarea> </div> </div> … -
Django and Digital Signatures
I have a project where a user can upload documents on the server and I want people to be able to sign them digitally with either an e-token or remote signature (through email), and be able to see on the list of documents which ones are signed. How can I go about checking if a file stored on the server has digital signature? I was thinking that since those documents are only PDFs I could convert them to XML and look for specific data or something. But is there another more pythonic way to do this? How do I utilize a usb e-token? Or is it that I utilize my certificates stored in the browser? Do I get the signature data from the certificate stored in the usb device for the process of signing the document? I have seen several apps that do digital signing that I have seen several apps that do digital signing (create their signatures, sign a document and validate the signature), but I get confused by the part that they create their signatures from text files. Correct me if Im wrong, but from what I understand the signature is created on the signed item utilizing the … -
check if user following to post author django
Here I am creating blogging website. where user can like, bookmark Post and follow User/Post-writter. What i want is when requesting blog by slug url. it also check if requested user has liked that post and bookmarked that post and also check whether if user following to author or not. now everything is working fine except following check. please suggest how should i apply following logic logic CustomUser Model class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True, null=False, blank=False) username = models.CharField(max_length=150, unique=True, null=True, blank= True) .... .... likes = models.ManyToManyField(Blog, blank=True, related_name="users_likes") bookmarks = models.ManyToManyField(Blog, blank=True, related_name="users_bookmarks") followers = models.ManyToManyField("self",blank=True, symmetrical=True , related_name='user_follower') Blog Model class Blog(models.Model): title = models.CharField(max_length=200, unique=False) slug = models.SlugField(max_length=300, unique=True, null=True, blank=True) author = models.ForeignKey("accounts.CustomUser", on_delete=models.CASCADE) .... .... def get(self, request): print("slugggggggggggggg", request.query_params['slug']) if "slug" not in request.query_params.keys(): return Response({"error": "slug required"}, status=status.HTTP_400_BAD_REQUEST) try: query = Blog.objects.annotate( liked=Case( When(users_likes=request.user.id, then=Value(True)), default=Value(False), ), bookmarked=Case( When(users_bookmarks=request.user.id, then=Value(True)), default=Value(False), ), # following is not working # following=Case( # When(author__user_follower=request.user.id, then=Value(True)), # default=Value(False), # ), total_likes=Count('users_likes'), about=F('author__about'), followers_number=Count('author__followers'), ).get(status=True, slug=request.query_params['slug']) serializer = BlogUserSerializer(query) return Response(serializer.data,) -
Django admin model field validation
I am developing a web application using django admin template. In that application I require a model field validation based on another model field input. Lets say an example, If the user provided "yes" as input value in a file_required model field, Browsefile model field should be considered as mandatory field. If the user provided "no" as input value in a file_required model field, Browsefile model field should be considered as optional. Please advise -
getting null all field response except id in django rest framework
Hi Everyone i am creating on api for with nested serialization but getting null response of every field except id, please help me out. models.py class Name(BaseModel): first_name=models.CharField(max_length=255,null=True, blank=True) middle_name=models.CharField(max_length=255,null=True, blank=True) last_name=models.CharField(max_length=255,null=True, blank=True) class Role(BaseModel): role=models.CharField(max_length=255,null=True, blank=True) name=models.ForeignKey(Name, models.CASCADE, null=True, blank=True) serializer.py class RoleSerializer(serializer.ModelSerializer): class Meta: model = Role fields= "__all__" class NameSerializer(serializers.ModelSerializer): role=RoleSerializer() class Meta: model = Name fields = ['id','first_name','last_name','middle_name','role'] views.py class Profile(viewsets.ModelViewSet): queryset = Role.objects.all() serializer_class = NameSerializer api response { "id": 1, "first_name": null, "middle_name": null, "last_name": null, "role": { "id": 1, "name": null } } -
CSRF verification failed for Django-admin
I recently installed Django==4.0.4 and tried to login to Django-admin panel, It is working fine in local. But got this CSRF exception in production Request aborted(403) CSRF verification failed. Request aborted. any ideas ? -
I can't start project without activation
I'm a new student of python django framework. I saw most of video in YouTube that they can start project without use these commands py -m venv project-name project-name\Scripts\activate.bat But when i tried. It's not working for me: 'django-admin' is not recognize d -
How to save token in frontend with security
I have a token-based authentication. In the frontend, how can I handle token security? I heard localstroage and cookie(without httppnly) are not safe. so how can I save that token to localstroage? by encrypting? is frontend encryption safe? -
Django model save not working in daemon mode but working with runserver
I am saving github repo to server once user add their github repo, see this models. class Repo(models.Model): url = models.CharField(help_text='github repo cloneable',max_length=600) def save(self, *args, **kwargs): # os.system('git clone https://github.com/somegithubrepo.git') os.system('git clone {}'.format(self.url)) super(Repo, self).save(*args, **kwargs) Everything is working fine what I want in both local server and remote server like digitalOcean Droplet, when I add public github repo, the clone always success. it works when I run the server like this: python3 manage.py runserver 0.0.0.0:800 But when I ran in daemon mode with gunicorn and nginx, it doesn't work, Everything is working even saving the data in database, only it is not cloning in daemon mode, what's wrong with it? this is my gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/var/www/myproject Environment="PATH=/root/.local/share/virtualenvs/myproject-9citYRnS/bin" ExecStart=/usr/local/bin/pipenv run gunicorn --access-logfile - --workers 3 --bind unix:/var/www/myproject/config.sock -m 007 myproject.wsgi:application [Install] WantedBy=multi-user.target Note again, everything is working even the gunicorn, the data is saving in database, only it is not cloning github repo, even not firing any error.\ What's the wrong with this? can anyone please help me to fix the issue? -
Adding custom data to Django's admin dashboard
I'm having a bit of trouble with Django again. I have a simple e-commerce website project that I'm working on for my graduation. It sells books. I've got basic functionalities down, such as adding categories and products, client sign-ups and logins, a session-based shopping cart, a checkout page fully connected to a payment API, and an orders model to keep track of data. My professor has asked me now to to add relevant reports in the Admin panel, talked to me a while about what would be relevant to see and all. So, I've got in mind what I'm hoping to make. I want to have two containers in the main dashboard page, which would display some quick analytics (like, how many books the store has sold in the past seven days, how much money from sales the site has made in the past month), as well as links in the sidebar: I want each relevant app within my project to have their own reports section in the Admin panel, maybe led to from a link underneath their models. I've separated the storefront, accounts, orders, shopping cart, and checkout, for instance, in different apps The problem is I can't really … -
error while filtering from document in mongo engine
def receipeslist(request): try: schema = { "meal_type": {'type': 'string', 'required': True, 'empty': False} } v = Validator() # validate the request if not v.validate(request.GET, schema): return Response({'error': v.errors}, status=status.HTTP_400_BAD_REQUEST) meal_listing = [] mealtype = request.GET['meal_type'] def Convert(string): li = list(string.split(" ")) return li mealtype1 = Convert(mealtype) print(mealtype1) for i in range( 0 , len(mealtype1)): recipe_info=Recipes.objects(meal_type=mealtype1[i]) serializer_Recipes_info = RecipeSerializer(recipe_info, many=True) response = serializer_Recipes_info.data print(type(response)) print("-------",meal_listing) meal_listing.append ({ # "id": str(id) "title": response.title, # "meal_type": response['meal_type'], # "image": response['image'], # "thumbnail": response['thumbnail'], # "video": response['video'], # "details": response['details'] }) print(meal_listing) return Response({'data': meal_listing}, status=status.HTTP_200_OK) model.py for recipes after this I cant able to append the meal_list. with the response i got from serializers class Recipes(Document): title = fields.StringField() description = fields.StringField() image = fields.StringField() meal_type = fields.StringField() calories = fields.IntField(default=0) carbs = fields.IntField(default=0) fiber = fields.IntField(default=0) prep_time = fields.StringField() cooking_time = fields.StringField() prep_time = fields.StringField() ingredients = DictField() servings = DictField() directions = DictField() nutrition = DictField() category_id = ReferenceField(RecipesCategory) created_at = fields.DateTimeField(default=datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')) thumbnail = fields.StringField() video = fields.StringField() details = fields.StringField() error while hitting this API "error": "'ReturnList' object has no attribute 'title'"