Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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'" -
Adding encode header for REST framework
I am using Django REST framework It returns Content-Type: application/json in header. Normally it works, but some browser needs the precise header such as Content-Type: application/json; charset=utf-8 How can I do this ?? I just return the Response here where should I set the header?? class SmartTagViewSet(viewsets.ModelViewSet): queryset = Mood.objects.all() serializer_class = SmartTagSerializer def list(self,request,*args,**kwargs): objs = SmartTag.objects.all() custom_data = { 'items': SmartTagSerializer(objs, many=True).data } custom_data.update({ 'meta':{"api":"SmartTag"} }) return Response(custom_data) -
order_by date_join in Django
I am displaying user information to the admin dashboard I want to order Users by their join date. and on another page, I want to display only 10 users information which are recently logged in I am filtering user data like this data = Profile.objects.filter(Q(user__is_superuser=False), Q(user__is_staff=False)) please help me to do this. Thanks in Advance -
Django: view tracking data with tens-of-thousands of views per day
I have a Django app with a Postgres backend. Users can make posts and view them. "Views" sit around the high-tens-of-thousands to 100K+ per day total. We want to track views so that we can filter out posts users have already seen from their home timeline. In the future, this will also be used for algorithmically surfacing content to users better. My original thought was to store these views as rows in the database as another table: class PostView(models.Model): post = models.ForeignKey(Post) user = models.ForeignKey(User) count = models.IntegerField(default=1) However this would quickly overwhelm the database with hundreds of thousands (or millions) of extra rows in weeks, (which I believe would overwhelm the database? Would or slow it down)? Is there perhaps another way that people typically store this sort of view data? Or is my approach effectively fine? -
Django HTML Create Buttons for Not Null Fields Only
I'm fairly new to Django and couldn't find a way to do this yet. I have a model like this: class Profile(models.Model): user = models.OneToOneField("User", on_delete=models.SET_NULL, null=True) user_name = models.CharField(max_length=50) linkedin = models.URLField(max_length=254, null=True, blank=True) instagram = models.URLField(max_length=254, null=True, blank=True) spotify = models.URLField(max_length=254, null=True, blank=True) On my HTML, I have buttons for each social media field, but I don't want to show them if they are null. How can I create a for loop that will loop through the social media fields only and create buttons for only not null fields? -
How can I Properly use Django Class Based View UserPassesTestMixin in UpdateView
I am working on a Django project where users would have one bank record. And I don't want them to be able to update another one's bank record except their own. I want to use Django UserPassesTestMixin to perform this restriction but I am getting 403 Forbidden error any time I try to access the UpdateView. Here is my Models code: class BankDetails(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True) bank = models.CharField(max_length=30, choices=BANK, blank=True, null=True) account = models.CharField(max_length=20, blank=True, default=None, null = True) name = models.CharField(max_length=60, blank=True, null=True) branch = models.CharField(max_length=60, blank=True, null = True) date = models.DateTimeField(auto_now_add=True) Here is Class based views code: from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin, UserPassesTestMixin class UpdateBank(LoginRequiredMixin, UserPassesTestMixin, UpdateView): template_name = 'user/edit_bank.html' model = BankDetails form_class = ApplicantBankForm def get_success_url(self): return reverse_lazy('bank-detail',kwargs={'pk': self.get_object().id}) def test_func(self): return self.get_object().applicant_id == self.request.user.pk class BankDetailView(LoginRequiredMixin, DetailView): template_name = 'user/bank_detail.html' model = BankDetails def get_success_url(self): return reverse_lazy('app-submit', kwargs = {'pk' : self.get_object().id}) Someone should please help. Thanks in anticipation for your answer. -
Django ORM objects.get() Related Questin: Is it legit to use .get() as if it's .filter()?
I often see that, regardless of the model, people often use Model.objects.get(id=id) or .get(product_name=product_name) or .get(cart=my_cart) -- but I now see a piece of code that is using .get() like it's a filter such as .get(product=product, cart=my_cart), is this going to work as intended? -
Django Cookiecutter Database restore
I'm trying to restore the database with the maintenance script provided. But there is a check in the script which doesn't allow me to restore if the user is postgres. Any reason for that ? -
Unable to access request headers in decorator - django 4.0.4
Using class based views. I have a decorator that retrieves headers for verification. However I get this error accessing the request headers in the decorator: Decorator exception 'DetailsView' object has no attribute 'headers' I must emphasize that accessing request headers in the view function works fine. View function: class DetailsView(View): @check_access def get(self, request): res = { 'status': 200, 'response': 'heeaders test.', 'test': 'okay' } return HttpResponse(JsonResponse(res, safe=False), content_type='text/json') Decorator: def check_access(): def decorator(view_function): def wrap(request, *args, **kwargs): try: print("headers", request.headers) return view_function(request, *args, **kwargs) except Exception as e: return HttpResponse('Unauthorized', status=401) return wrap return decorator Kindly assist. Thanks in advance. -
Django rest framework function base view how to get object by string not id
Problem: I trying to path like this --> path('Image/<str>', views.getImage, name='imageCategory'), to get image filter by category --> http://127.0.0.1:8000/Image/TV #-->Model.py from django.db import models class Post(models.Model): Topic = models.CharField(max_length=250, default='') Desc = models.CharField(max_length=750, default='') Link = models.TextField(default='') def __str__(self): return str(self.Topic) class Category(models.Model): categoryName = models.CharField(max_length=50, default='') def __str__(self): return str(self.categoryName) class PostImage(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, null=True, related_name='post_name') category = models.ForeignKey( Category, on_delete=models.CASCADE, null=True, related_name='category_name') images = models.FileField(upload_to='images/') def __str__(self): return str(self.post) #-->Serializer.py from rest_framework.serializers import ModelSerializer from rest_framework import serializers from .models import Post, PostImage class BlogSerializer(ModelSerializer): class Meta: model = Post fields = '__all__' class ImageSerializer(ModelSerializer): topic_link = serializers.CharField(source='post.Link', read_only=True) Category = serializers.CharField(source='category', read_only=True) class Meta: model = PostImage fields = '__all__' #-->view.py from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Post, PostImage from .Serializer import BlogSerializer, ImageSerializer # Create your views here. @api_view(['GET']) def getNames(request): Blog = Post.objects.all() serializer = BlogSerializer(Blog, many=True) return Response(serializer.data) @api_view(['GET']) def getName(request, pk): Blog = Post.objects.get(id=pk) serializer = BlogSerializer(Blog, many=False) return Response(serializer.data) #my problem part @api_view(['GET']) def getImage(request): image = PostImage.objects.get(Category=request.Category) serializer = ImageSerializer(image, many=True) return Response(serializer.data) #-->urls.py from django.urls import path from . import views urlpatterns = [ path('blogs/', views.getNames, name='blog'), path('blogs/<pk>', …