Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm trying to read CVS file in Django
I'm new to Django trying to read data from CSV file and display data in form of a table using Django templates. Please help me with how I can do it. -
Prefetch doesn’t sim
My queryset is product = Prosucts.objects.all().prefetch_related(Prefetch(‘prod_sale’, Sales.objects.filter(type__in=(1,2)).annotate(quantity_sold=Sum(‘quantuty’)), to_attr=‘prod_sold’)) So if I have product juice=3, apple =6, apple=4 My queryset gives me juice = 3, apple = 6 , 4 I can’t get Apple to be 10 -
Python manage.py command showing ImportError
When hit the command python manage.py makemigrations i get the immport error the error is like this ImportError : Module 'Backend.apps'does not contain a 'BackendConfigrest_framework'class. Choices are : 'BackendConfig' -
Filtering by Foreign Key in ViewSet, django-rest-framework
I want my api to return certain objects from a database based on the foreign key retrieved from the url path. If my url looks like api/get-club-players/1 I want every player object with matching club id (in this case club.id == 1). I'm pasting my code down below: models.py class Club(models.Model): name = models.CharField(max_length=25) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name class Player(models.Model): name = models.CharField(max_length=30) club = models.ForeignKey(Club, on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.name serialziers.py class ClubSerializer(serializers.ModelSerializer): class Meta: model = Club fields = 'id', 'owner', 'name' class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = 'id', 'name', 'offense', 'defence', 'club', 'position' views.py, This is the part where I get the most trouble with: class ClubViewSet(viewsets.ModelViewSet): queryset = Club.objects.all() serializer_class = ClubSerializer class PlayerViewSet(viewsets.ModelViewSet): queryset = Player.objects.all() serializer_class = PlayerSerializer class GetClubPlayersViewSet(viewsets.ViewSet): def list(self, request): queryset = Player.objects.all() serializer = PlayerSerializer(queryset, many=True) def retrieve(self,request, clubId): players = Player.objects.filter(club=clubId, many=True) if not players: return JsonResponse({'error': "No query found!"}) else: serializer = PlayerSerializer(players) return Response(serializer.data) urls.py from rest_framework import routers from django.urls import path, include from .views import (GameViewSet, PlayerViewSet, ClubViewSet, GetClubPlayersViewSet, create_club, set_roster) router = routers.DefaultRouter() router.register(r'clubs', ClubViewSet, basename="clubs") router.register(r'players', PlayerViewSet, basename="players") router.register(r'get-club-players', GetClubPlayersViewSet, basename="club-players") urlpatterns = … -
Django error with views for form display and save
I have a víews to display and save a form as below: @login_required(login_url='/login') # Check login def addlisting(request): if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = ProductForm() return render(request, 'listing/addlisting.html', { 'form': form }) But When I load the html file I got this error ValueError at /addlisting The view listing.views.addlisting didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://127.0.0.1:8000/addlisting Django Version: 3.2.3 Exception Type: ValueError Exception Value: The view listing.views.addlisting didn't return an HttpResponse object. It returned None instead. Exception Location: C:\Users\Daisy\OneDrive\Documents\Work\django\shecodes\bookapp\env\lib\site-packages\django\core\handlers\base.py, line 309, in check_response Python Executable: C:\Users\Daisy\OneDrive\Documents\Work\django\shecodes\bookapp\env\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\bookapp', 'C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\env\\Scripts\\python38.zip', 'c:\\users\\daisy\\appdata\\local\\programs\\python\\python38\\DLLs', 'c:\\users\\daisy\\appdata\\local\\programs\\python\\python38\\lib', 'c:\\users\\daisy\\appdata\\local\\programs\\python\\python38', 'C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\env', 'C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\env\\lib\\site-packages'] Server time: Sun, 30 Jan 2022 07:41:40 +0000 Please take a look. Thanks in advance !!!!!!!!!!!!!!!!!!!! -
How to work with nested if else in django templates?
Here, In this project I'm building a Ecommerce website and I'm using Django here. So, here I want to show that if there is no product of category Electric "Sorry, No Product is Available Right Now !!!" will be shown. where n is the number of product which is sent to this template from app views. But I'm not getting "Sorry, No Product is Available Right Now !!!" as I've no product of Electric category in my database. How to fix this? where I'm doing wrong? views.py def electric(request): product = Product.objects.all() n = len(product) params = {'product': product, 'range':range(1,n), 'n':n} return render(request,'electric.html',params) electric.html {% if n is 0 %} <div class="p-3 mb-1 bg-warning text-white text-center my-0"> <h1><b>Sorry, No Product is Available Right Now !!! </b></h1> </div> {% else %} <div class="album py-2 bg-gradient"> <div class="container"> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"> {% for i in product %} {% if i.category == "Electric" %} <div class="col"> <div class="card shadow-sm"> <img src="{{i.image}}" /> <div class="card-body"> <h4 class="card-title">{{ i.product_name}}</h4> <h6 class="card-subtitle mb-2 text-muted"> Category: {{i.category}} </h6> <p class="card-text">{{i.description}}</p> <div class="buy d-flex justify-content-between align-items-center"> <div class="price text-success"> <h5 class="mt-4">Price: {{i.price}} BDT</h5> </div> <a href="#" class="btn btn-danger mt-3"><i class="fas fa-shopping-cart"></i> Add to Cart</a> </div> … -
how to check is staff is True before login into dashboard which i have created by myself in Django?
I have created a dashboard and in my dashboard superuser creates the username, password, and all this thing but in my dashboard, I want to check first the username is staff or not before login into the dashboard. how to do that? can anyone help me from django.shortcuts import redirect, render from django.contrib import auth, messages from orderkitchen.models import kitchenData from django.contrib.auth.models import User def login_dashboard(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username = username, password = password) if user is not None: auth.login(request,user) messages.success(request, 'You are Logged in') return redirect('dashboard') else: messages.error(request,'Your Username or Password is incorrect') return redirect('login_dashboard') return else: return render(request,'accounts/dashboard_login.html') def dashboard(request): return render(request, 'accounts/dashboard.html') only the staff status is True then only then can logged in -
How i can to delete record when import file using django-import-export?
My project use Django framework and installed django-import-export plugin. I can import and export everything normally. But when i imported file to database. All new records from file upload was imported successfully. but old record that is not in the new records not delete. old data in database ID , Name , wage 1 , Mr.A , 100 2 , Mr.B , 110 3 , Mr.C , 150 new file upload ID , Name , wage 1 , Mr.A , 100 2 , Mr.B , 150 4 , Mr.D , 130 the result when imported ID , Name , wage 1 , Mr.A , 100 2 , Mr.B , 150 3 , Mr.C , 150 # < this not delete 4 , Mr.D , 130 I want it to be like this in database. ---------- ID , Name , wage 1 , Mr.A , 100 2 , Mr.B , 150 4 , Mr.D , 130 How i can to delete old record when imported using django-import-export plugins? -
Django how to query on many to many relationship
This is my model class MenuItem(models.Model): name = models.CharField(max_length=500, null=False) description = models.CharField(max_length=500, null=True) image_url = models.CharField(max_length=1000, null=True) menu_category = models.ForeignKey(MenuCategory, on_delete=models.CASCADE) def __str__(self): return f'{self.name}' class Venue(models.Model): name = models.CharField(max_length=500, null=False) def __str__(self): return f'{self.name}' class VenueMenu(models.Model): venue = models.ForeignKey(Venue, null=False, on_delete=models.CASCADE) menu_item = models.ManyToManyField(MenuItem, null=False) This is my serializer class MenuItemSerializer(serializers.ModelSerializer): menu_category = MenuCategorySerializer() class Meta: model = MenuItem fields = '__all__' class VenueMenuSerializer(serializers.ModelSerializer): menu_item = MenuItemSerializer(many=True) class Meta: model = VenueMenu fields = '__all__' And this Is my view @api_view(['GET']) def venue_menu_response_detail(request): if request.GET.get('venue'): venue_menu_list = VenueMenu.objects.filter(venue__name=request.GET.get('venue')) serializer = VenueMenuSerializer(venue_menu_list, many=True) return Response(serializer.data) this is my URL http://127.0.0.1:8000/venue_menu_response_list?venue=venu_name I want to get all the venue and menu item associated with that venue ,this query is returning empty result, so i think the problem is in my query. -
Django custom US phone number validation
I need to write a function that takes in Us phone number as argument and validates it how do i write for django field validation. models.py: class Mymodel: phone = PhoneField(max_length=255, blank=True) validators.py: def validate_phone(v): #code# -
How to store both User data and timeseries data in Django Database
I want to build a website that needs to store "User data" and "time series data" in the database. How to achieve that using Django? Is it possible to achieve that using single database such as postgresql with timescale extension? Or do I need to use separate database for User data and timeseries data? Kindly help me with some detailed code and instructions, as I am a beginner in Django and database management. Thanks in advance. -
django can't display form on templates
I've created a model and a form for users to upload their data but somehow the form can't appear on html page. Here's my model: class Product(models.Model): STATUS = ( ('True', 'True'), ('False', 'False'), ) VARIANTS = ( ('None', 'None'), ) SALESTATUS = ( ('True', 'True'), ('False', 'False'), ) SIZES = ( ('small','small'), ('medium','medium'), ('large','large') ) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) #many to one relation with Category title = models.CharField(max_length=150) keywords = models.CharField(max_length=255) description = models.TextField(max_length=255) author = models.CharField(max_length=150,default="unknown") image=models.ImageField(blank=True) amount=models.IntegerField(default=0) detail=RichTextField(blank=True,null=True) slug = models.SlugField(null=False, unique=True) status=models.CharField(max_length=10,choices=STATUS) create_at=models.DateTimeField(auto_now_add=True) update_at=models.DateTimeField(auto_now=True) variant=models.CharField(max_length=10,choices=VARIANTS, default='None') rating = models.IntegerField(default=0) def __str__(self): return self.title ## method to create a fake table field in read only mode def image_tag(self): if self.image.url is not None: return mark_safe('<img src="{}" height="50"/>'.format(self.image.url)) else: return "" def get_absolute_url(self): return reverse('category_detail', kwargs={'slug': self.slug}) def avaregereview(self): reviews = Comment.objects.filter(product=self, status='True').aggregate(avarage=Avg('rate')) avg=0 if reviews["avarage"] is not None: avg=float(reviews["avarage"]) return avg def countreview(self): reviews = Comment.objects.filter(product=self, status='True').aggregate(count=Count('id')) cnt=0 if reviews["count"] is not None: cnt = int(reviews["count"]) return cnt Here's my form: from django.forms import ModelForm from .models import Product class ProductForm(ModelForm): class Meta: model = Product fields = '__all__' Here's my views: @login_required(login_url='/login') # Check login def addlisting(request): form = ProductForm() context={ … -
Django different set of permissions for a user
In my project a user and office have many to many relationship and each user may have different roles in different offices hence he has different set of permissions how can I achieve this in django, should I use object-level permissions and set permissions in the through model between office and user or can I use the django's built in Permission model and have a permissions field in the through model and I don't think using groups is the nice solution for this -
How can I update "last_updated" field, whenever user changes data
I am trying to make a custom user model in django and adding the additional field "last_updated" which is supposed to update the date and time whenever a user makes changes or saves new data. class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) photo = models.ImageField(upload_to='avatars/', null=True, blank=True) last_updated = models.DateTimeField(null=True, blank=True) #defining field in the model. USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email -
Struggling with Understanding flask and implementing in django
I want to implement django project which already made by flask. I am new to django and i dont have knowledge on flask. I want to understand the logic behind there. here i will post related codings from flask, flask - models.py class Organization(db.Model, CRUDMixin, AuditLogMixin): __tablename__ = 'organization' code = db.Column(db.String, nullable=False) name = db.Column(db.String, nullable=False) organization_type = db.Column(db.String, nullable=False) internal_organization = db.Column(db.Boolean, nullable=False, default=True) location_id = db.Column(db.Integer, db.ForeignKey('location.id'), nullable=False) currency_id = db.Column(db.Integer, db.ForeignKey('currency.id')) ) @classmethod def contractors(cls): return db.session.query(Organization).filter( Organization.internal_organization == False, Organization.organization_type == ORGANIZATION.COMPANY ).order_by(Organization.name, Organization.organization_type) forms.py class ContractorForm(TypeCodeForm): MODEL = Organization CODE_PREFIX = 'SUB' location = QuerySelectField(__('Location'), [InputRequired()], get_label='name') views.py @route(bp, '/create', methods=['GET', 'POST']) def create() form = CompanyForm() form.location.query = Location.query.order_by(Location.name) form.currency.query = Currency.query.order_by(Currency.code) if form.validate_on_submit(): org = Organization.create( organization_type=ORGANIZATION.COMPANY, **form.data) flash(_("Created organization <strong>%(name)s</strong>", name=org.name), 'success') return redirect(url_for('.list')) return render_template('pim/organization/create.html', form=form) I have done organization part.but i dont know how to implement contractor part. I dont have contractor model they used organization model for that. Note: companyForm has organization fields.. Really need help... -
How to add/transfer the values list from one model to another in django?
Let me show you what I have done successfully and what I am trying to achieve now. I have 2 models. Both has same 3 fields. Name, Month, Number. Two models are Main and BMO. I filter the first model based on name and month and get the values list of the number column. Code looks like this- result= Main.objects.filter(name="John", month='apr').values_list('number', flat=True) Then I display that on django template with a for loop and conditional. Code looks like this - <p>result: <span> {% for i in result %} {{i}}{% if not forloop.last %}+{% endif %} {% endfor %} </span> </p> result = 2+4+12+7+18 The last line showing you how it actually looks on the template. You can see I display it with + signs between the values. What I want to achieve: I want to get the sames values list but instead of showing it on the template I want to insert it to another model's field. Just to be clear I want all the values with plus sign included (the way it looks on my template) to be inserted in a single field of the second model BMO. If I have 10 values they should all be joined by … -
chainig permission in Django rest framework ViewSet
class UserViewSet(viewsets.ModelViewSet): def list(self, request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def create(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(raise_exception=True): pass def retrieve(self, request, pk): user = get_object_or_404(User, pk=pk) self.check_object_permissions(request, user) serializer = UserSerializer(user) return Response(serializer.data, status=status.HTTP_200_OK) def get_permissions(self): if self.action == "list": permission_classes = [ IsAdminUser, ] elif self.action == "create": permission_classes = [AllowAny] else: permission_classes = [AccountOwnerPermission, IsAdminUser ] return [permission() for permission in permission_classes] and custom permission is: class AccountOwnerPermission(permissions.BasePermission): def has_object_permission(self, request, view, obj): print(object) print(request.user) return obj == request.user first i dont get object permission but with help of @brian-destura at this question i fixed that part the previous question now the problem is when i chain 2 permission together it behave like AllowAny i check them one by one and both permissions work fine, one of them allow admin and one of them allow owner but when they are or together it mess everything up -
Auto Increment In Django SQLIite Database
I have set a field image_id as auto increment. But the issue comes when lets say: I enter an image in the database from the django admin panel, it is assigned an auto inc id 1. Then I delete the same image. And then when I insert a new image its ID gets assigned as 2, why isn't it getting assigned as 1? As I have deleted the image with id 1, so technically id 1 is empty and it should be assigned to next incoming image. Can you suggest its solution please. Thanks -
Custom django validation function
i have written validaiton function for an attribute is it correct and how should i write for same attribute with blank = True and add_1 is required field any conditions to add add_1 = models.CharField(max_length=255) add_2 = models.CharField(max_length=255, blank=True) Note: All validators must return True or False validators.py def validate_add_1(value): if value is not None: try: if len(value) <= 255: return True except ValidationError: return False -
How to check group permissions in Django view?
I have created two groups group1 and group2 and assigned users accordingly. I have found that i can decline access in templates using {% if perms.app1 %} // app1 is a app in project ///show something {% endif %} In the above code, am just check if the user has any permission related to the app and if true it will show and if false it will hide. This is how it works i believe. Now, how to implement this on views ? How to just give app name and check if the user has permission to the view functions in view.py ? Adding a list of permissions is not a good practice i believe, is there a way to just give app name to check permissions ? And I already have a role check decorator : def is_agent(login_url=None): actual_decorator = user_passes_test(lambda u: u.role == 1) if actual_decorator: return actual_decorator else: raise Http404 So is there i can add things to decorator or how to handle it ? -
Django Rest-Framework: how to add/remove entries in ManyToMany relations?
I've just gone through the Django-Rest-Framework (DRF) tutorial and tried to adapt it to a simple photos app I am working on with models Album and Photo in a M-2-M relationship: an album can have many photos, and a photo can be in many albums. The db has tables myapp_album, myapp_photo and myapp_album_photos, as you'd expect. But what I want is to be able to create albums and photos independent of each other and then to create the relations between them. I can do that easily in the shell with the photo.add(album), etc. but it's not clear to me how to do this via the generated DRF routes. The problem is that using the terse DRF abstractions that I gleaned from the tutorial (using ModelSerializer, viewsets, etc.), I only end up with routes to /albums and /photos, and it's not clear to me how to create a route (or how otherwise) to associate existing photos with existing albums. Could someone please help clarify the situation? Thanks ### models.py class Photo(models.Model): title = models.CharField(max_length=100, blank=True) caption = models.TextField(blank=True) datetime = models.DateTimeField(auto_now_add=False, blank=False) filename = models.CharField(max_length=100, blank=False) class Album(models.Model): name = models.CharField(max_length=100, blank=False, default='') description = models.TextField() photos = models.ManyToManyField(Photo) ### serializers.py … -
What is Football game statistics Django Model logic?
I am creating an app that visualizes football game statistics on Django. I take data from https://fbref.com/ as a CSV file. I have a python script that cleans data and create data frame with ['Player', 'Shots', 'SCA', 'Touches', 'Pass', 'Carries', 'Press', 'Tackled', 'Interceptions', 'Blocks'] columns (I can add Team name, Game Date, Home/Away or whatever). And now I need to create models to store this data. I don't know what models do I need. Option 1 (only one model): class GameStats(models.Model): date = models.DateField() team_name = models.CharField(max_length=20) home_away = models.CharField(max_length=20, choices=HOME_AWAY) name = models.CharField(max_length=20) number = models.IntegerField() age = models.IntegerField() shots = models.IntegerField() SCA = models.IntegerField() touches = models.IntegerField() passes = models.IntegerField() But it will give one Row of data. Technically, I can group rows by Team_name and Date. Option 2: from django.db import models class Team(models.Model): name = models.CharField(max_length=200) league = models.CharField(max_length=200) def __str__(self): return self.name class Player(models.Model): name = models.CharField(max_length=200) number = models.IntegerField() age = models.IntegerField() team = models.ForeignKey(Team, related_name='team', on_delete=models.CASCADE) def __str__(self): return self.name class HomeTeam(models.Model): team = models.ForeignKey(Team, related_name='home_team', on_delete=models.CASCADE) players = models.ManyToManyField(Player) def __str__(self): return self.team class AwayTeam(models.Model): team = models.ForeignKey(Team, related_name='away_team', on_delete=models.CASCADE) players = models.ManyToManyField(Player) def __str__(self): return self.team class Game(models.Model): title = models.CharField(max_length=200) … -
How to access drf api from react after userd logged in in django
I have mostly been using Django templates for my front end and everything works fine. I want to learn about DRF and React and I want to be able to have both communicate to each other. I have react running on port 3000 and react on 8000 so there is a miscommunication and I can't test my code as I get the error 403 (forbidden). I have the following view: @api_view(['GET']) @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def user_details_api(request, *args, **kwargs): current_user = request.user id = current_user.id status = 200 try: obj = CustomUser.objects.get(id=id) data = userSerializer(obj) return Response(data.data, status=status) except: status = 404 return Response(status=404) I have the following react end point: function loadUserInfo(callback){ const xhr = new XMLHttpRequest(); const method = 'GET'; const url = "http://127.0.0.1:8000/api/userdetails"; xhr.responseType = "json"; // Let the xhr request know that its getting a json xhr.open(method, url); //This opens the request with the method and url entered xhr.onload = function(){ console.log("This is the response: ",xhr.response) callback(xhr.response, xhr.status) } xhr.onerror = function(){ callback({"message":"The request was an error"}, 400) } xhr.send();//Trigger that request } I see in the details that the credentials were not provided and I am wondering how to fix this as the tutorial I watched … -
Entering wrong username and password still django authenticate it as correct
I am trying to create a login page in Django when the login details are filled in correctly it redirect to a certain page the problem I am facing is that when I enter wrong username or password Django authenticate them as correct and redirect it to another page my login code is as follows def loginpage(request): if request.method=='POST': use=request.POST.get('username') pas=request.POST.get('password') user=authenticate(request,username=use,password=pas) if user is not NONE: login(request,user) return redirect('data') else: messages.info(request,'Username or Password is incorrect') return render(request,'login.html') ``` even after entering the username that doesn't even exist in the database Django authenticate as right and doesn't show the error that I am expecting -
How to make image dynamic in Flutter?
Want to make this already written code for image to have a dynamic image functionality so aspect ratio can adjust according to the window size. It is a code snippet of app consist of flutter & Django as a backend. This is a code for image posting on a type of news feed. Want to make this already written code for image to have a dynamic image functionality so aspect ratio can adjust according to the window size. It is a code snippet of app consist of flutter & Django as a backend. This is a code for image posting on a type of news feed. import 'dart:convert'; import 'package:Mazaj/bloc/post_bloc/post_bloc.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class PostScreen extends StatelessWidget { int id; String post; int upvotes; PostScreen(this.id, this.post, this.upvotes); @override Widget build(BuildContext context) { //Widget for image posting var _bytesImage = Base64Decoder().convert(post); Stack buildPostPicture(String urlPost) { return Stack( children: [ Container( height: 150, //MediaQuery.of(context).size.width - 400, width: 150, decoration: BoxDecoration( borderRadius: BorderRadius.circular(30), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.3), spreadRadius: 2, blurRadius: 20, offset: const Offset(0, 10), ), ], image: DecorationImage( fit: BoxFit.cover, //cover //image: NetworkImage(urlPost), image: Image.memory(_bytesImage) .image, // or _MemoryImage(bytesImage) )), ), Positioned( bottom: 20, right: 20, child: Icon(Icons.favorite, size: 35, …