Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
Workaround for dictsort-ing by model method as of Django 4.0.1
It helps to read the release notes. After three hours of debugging, I finally found out that my code stopped working in Django 4.0.1 due to the removed functionality to use model method for dictsort-ing. It is documented in the release notes: CVE-2021-45116: In order to avoid [potential information disclosure], dictsort now works with a restricted resolution logic, that will not call methods, nor allow indexing on dictionaries. Now I wonder what to do. I need to sort my list by a value that is not stored in the database but is calculated based on a value in the database. Is it a bad practice? What is a better one? Unfortunately, the generally very helpful documentation is silent about it so far. -
Putting an ImageField inside a JSONField in Django
I have a jsonfield inside of a django model which is supposed to hold some other fields alongside an ImageField. How can I store the data of the image inside that JSONField and put the image inside the media directory and have it called when I want to use it inside of my template like a regular imagefield. Please note that the image have already been saved inside the media folder but I have the name of the file which i want to put inside the jsonfield -
Start telegram bot on django project
I'm developing a djnago project and want to connect a telegram bot to it. I'm using python-telegram-bot but do not know how to start the bot when the django server starts. from django.apps import AppConfig from .telegramBot import updater class SocialMediaConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'memefinder' def ready(self) -> None: updater.start_polling() pass I added this code to the apps.py file of one the project's app but it's not working. I got this error message evrytime I run the project telegram.error.Conflict: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running and this the code of telegramBot.py file. it's very simple code. from telegram import Update, ForceReply from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext updater = Updater("TOKEN") dispatcher = updater.dispatcher def start(update: Update, context: CallbackContext) -> None: """Send a message when the command /start is issued.""" user = update.effective_user update.message.reply_markdown_v2( fr'Hi {user.mention_markdown_v2()}\!', reply_markup=ForceReply(selective=True), ) dispatcher.add_handler(CommandHandler("start", start)) -
Django REST API don't see a URL
I think I have an import problem. After learning through all the tutorials and was able to get up to this point. I just want to see my database with .objects.all(). The problem is the code 404 where it can't see "receipts.url" makemigrate and migrate is all done without any issues. server was running with access to admin. I am getting this problem, but I have it all mapped out. Please help and thanks again. "Page not found (404) Request Method: GET Request URL: http://localhost:8000/receipts/ Using the URLconf defined in project.urls, Django tried these URL patterns, in this order: admin/ receipts/ [name='all'] The current path, receipts/, didn’t match any of these." My project name is "project", my app name is "receipts". "project", "receipts" and "manage.py" all are in the same level. I can see my database in the admin page, and as well as Mongodb compass. Here are all of my files: project/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'receipts', 'rest_framework', ] project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('receipts/', include('receipts.urls')), ] receipts/urls.py from django.urls import path from . import views from .views import CustomersViews urlpatterns = [ path(" … -
Django Staff Member Required Decorator does Infinite Loop if access denied
I am using the Django staff_member_required decorator to protect an admin area of the site. I am using it like this @staff_member_required(login_url=reverse_lazy('account_login')) def kommando_home(request): # business logic return render(request, 'kommando/home.html', context) I am using the custom login so users do not see the Django login page if they hit the URL. However, if a user who does not have staff permision logs in, it just results in this: I can add a redirect parameter to the decorator but that always redirects the user to the url provided even if the user has permission. I tried looking into customizing the decorator but I do not see any way to check if permission denied is raised. -
Remove plain HTML text withing a div
How can I remove the 'Currently' in the HTML withouting deleting other texts <div class="group if-description-margin"> Currently: <--- Remove this text <a href="/media/images/header-dots.png">images/header-dots.png</a> <input type="checkbox" name="profile_picture-clear" id="profile_picture-clear_id"> <input type="file" name="profile_picture" accept="image/*" id="id_profile_picture"> <p> But don't remove this </p> <label for="id_profile_picture">Profile Picture</label> </div> -
How to get Objects ID
I am trying to get the ID of Options however I do not now what I can do to get it? I am new to Django - I have got the question ID through a parameter however I am not trying to pass another parameter. Is there a filter or get command that can be used? I am trying to edit an existing option however it doesn't know which option it is looking for as there is more than one. The only way to identify is through its ID Model class Option(models.Model): OptionID = models.AutoField(primary_key=True, unique=True) OptionText = models.CharField(max_length=256, null=True) QuestionsID = models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return str(self.OptionID) View @login_required(login_url='loginPage') def question_editOption(request, id): question = Question.objects.get(QuestionsID = id) options = Option.objects.filter(QuestionsID = question) current_user = request.user c = current_user.userID if current_user.is_admin: if request.method == 'POST': edited = request.POST.get('Q') if request.POST['Q']: obj = Option.objects.filter(QuestionsID = id, ).update(OptionText = edited) messages.success(request, "Edited") return redirect('dashboardAdmin') # elif not request.POST['Q']: # obj = Question.objects.filter(QuestionsID = id).update(QuestionText = oldVal) # messages.error("Question Is Null!") # return redirect('question/edit/<int:id>/') else: messages.error("User is not admin") return redirect('dashboardPage') context = {'question' : question, 'options' : options} return render(request, 'editOption.html', context) HTML <!DOCTYPE html> <html> <head> <title>Admin Panel</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" … -
How to override data returned by self.get_serializer() in DRF?
Got mixin view (CreateAPIView, ModelViewSet) in my DRF project. In list() method I do return all of the instances of my model. def list(self, request): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) I need to override self.get_serializer() to modify the data a bit (add some stuff) and then access it via serializer.data I was trying to accomplish it via overriding init method of my serializer class but it did not work. Is there any another way?