Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a list showing how many posts every user has posted on site
I'm working (or better I'm learning) in django, i want to create an html page with a list that shows how many posts every user has published so far. in views.py i set: @user_passes_test(lambda u: u.is_staff) #<-Because I want that only admin will see this def num_post(request): num_post = Post.objects.filter(author=request.user).count() return render(request, 'api/post_numbers.html', {'num_post' : num_post}) and in post_numbers.html i set: {{user.username}} : {{ num_post }} but i can only obtain the name and the post number of the current user... how can i solve this? Thank you in advance! -
Can't load static files in Django:
I've already invoked collectstatic with no effect Errors from chrome: Failed to load resource: the server responded with a status of 404 (Not Found) logo.png':1 Failed to load resource: the server responded with a status of 404 (Not Found) bootstrap.bundle.min.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) lightbox.min.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) main.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) all.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) style.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) bootstrap.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)lightbox.min.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) settings.py STATIC_ROOT= os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATIC_DIRS = [os.path.join(BASE_DIR, 'btre/static')] base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/all.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link rel="stylesheet" href="{% static 'css/lightbox.min.css' %}"> <title>BT Real Estate</title> … -
How to get the most liked users in django rest-api
So I have a social media app, where users can like the posts of other users. Now I want to fetch the top 20 users who have received the most number of likes. I am pretty much confused how to query my Likes Model My LIKES MODEL class PostLike(models.Model): user_who_liked = models.ForeignKey(User, on_delete=models.CASCADE) post_liked = models.ForeignKey(Post, on_delete=models.CASCADE) liked_on = models.DateTimeField(default=timezone.now) SIMPLIFIED POST MODEL class Post(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) caption = models.TextField() date = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField( User, blank=True, through=PostLike) image = models.TextField() class Meta: ordering = ['-id'] SIMPLIFIED USER MODEL class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) user_name = models.CharField(max_length=100, unique=True) date = models.DateTimeField(default=timezone.now) profile_picture = models.TextField( default="https://www.kindpng.com/picc/m/24-248253_user-profile-default-image-png-clipart-png-download.png") bio = models.CharField(max_length=200, default="") objects = CustomManger() def __str__(self): return self.user_name ** My View ** @api_view(["GET"]) @permission_classes([IsAuthenticated]) def leaderboard(request): # I dont know how to query the PostLike model now to get the most liked user pass -
Show, for each field, how many items has each field DjangoREST
I'm working on a Django project, coding some API calls where people can reserve a parking place. I have a database, and I want to display how many reservations has each user. I know this can be done easily on SQL, but I can't find the way to do this on Python. I've already tried to do what the documentation says: https://docs.djangoproject.com/en/3.1/topics/db/aggregation/#cheat-sheet but it doesn't work for me. -
Django VariableDoesNotExist, Failed lookup for ket [currency]
I am facing to this problem with my django application on production dream-access.com I have 500 for this issue below: VariableDoesNotExist at /fr/ Failed lookup for key [currency] in <django.contrib.sessions.backends.db.SessionStore object at 0x7f31c7411ba8> can somebody hekp to fix this error ? Please. Thanks. -
Django dose not validate form
I have form with the name of CommentForm when the form is validated it has to return HttpResponse which is saying that the form is valid if does nothing forms.py models.py views.py Templat code -
Django: Allow Users With Permission to Edit Project Page
I have a model: uProjects that associates a user and a project and if that user has admin status, i.e. ifAdmin. I am trying to create a way to allow a user to editproject if that user has ifAdmin=True for that project. The way I am currently doing it is with a wrap function, but I have a problem because even if I am logged in with a user who has ifAdmin=True for project "x," and I go to project "x" page and try to edit project, I still get the HttpResponseRedirect('/'). model: class uProjects(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) ifAccepted = models.BooleanField(null = True, blank=False, default=False) #ifLeader = models.BooleanField(null = False, blank=False) ifAdmin = models.BooleanField(null = True, blank=False, default=False) title = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.user.username + ',' + self.project.name views.py def admin_check(function): @wraps(function) def wrap(request, *args, **kwargs): user = request.user name = kwargs.get('name') if uProjects.objects.filter(title=name, user=user, ifAdmin=True).exists(): return function(request, *args, **kwargs) else: return HttpResponseRedirect('/') return wrap @admin_check def update(request): if request.method == "POST": pr_form = ProjectUpdateForm(request.POST, request.FILES, instance=request.project.name) if pr_form.is_valid(): pr_form.save() messages.success(request, f'This project has been updated.') return redirect('project') else: pr_form = ProjectUpdateForm(instance=request.user.profile) context = { 'pr_form': pr_form } return render(request, 'projects/updateproject.html', context) … -
Creating endpoints inside an endpoint in fastapi
suppose there as an audio server, you can upload Songs, podcasts, or Audiobook. So in the create endpoint i have created 4 endpoints, so i have put an condition if the audio_type is a song, return all audio of that type but unfortunately this return null @app.get('/audio/{audio_type}') def show_all(audio_type): if audio_type == "Songs": @app.get("audio/song") def all(db: Session = Depends(database.get_db)): songs = db.query(models.Song).all() print("songs = ", songs) return songs elif audio_type == "podcast": @app.get('audio/podcast') def all(db: Session = Depends(database.get_db)): podcast = db.query(models.Podcast).all() return podcast elif audio_type == "audiobook": @app.get('audio/audiobook') def all(db: Session = Depends(database.get_db)): audiobook = db.query(models.Audiobook).all() return audiobook else: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f' {audio_type} - audio type is not valid') -
Django can't upload file
I'm doing a django app with a form using image file upload. I have a default image in case user doesnt choose an image. But when I save the form, my image isn't saved in my files. Any idea ? Here's my code : First my views.py class AnimalCreateView(generic.CreateView): model = Animal form_class = AnimalForm template_name = 'myApp/animal_create.html' success_url = reverse_lazy('animal:index') Then my models.py class Animal(models.Model): name= models.CharField() animal_photo= models.ImageField(upload_to="images/",default="images/noPhoto.svg", null=False, blank=True) def __str__(self): return f'{self.name}' When I save my file and then check my html or django admin page, all the rows of animal_photo are using the default file... -
Can I host Django REST and React in the same cpanel account?
I have developed a Django REST API with a react frontend in separate repositories. I tried to publish them in my cpanel account (godaddy) but once I upload the React after having configured the API, then my API won't work, even though I put a subdomain (api.domain.com) for the it. I get a 500 internal server error :(( . Is there any way of solving that? -
Django AttributeError: 'QuerySet' object has no attribute 'fitler'. Trying to filter the manytomany relation objects [closed]
I try to filter manytomany queryset objects. I have 2 models: class Product(models.Model): environment = models.CharField(choices=PRODUCT_ENVIRONMENTS, max_length=25) ... class TelegramUser(models.Model): last_query_products = models.ManyToManyField( Product, related_name='users_from_query', blank=True ) ... Filtering def environment_response(query): # TELEGRAMUSER OBJECT user = get_user(query.message.chat.username) filtered_products_by_env = user.last_query_products.all().fitler(environment=query.data) user.last_query_products.clear() user.last_query_products.add(*filtered_products_by_env) Here's I just get saved query products and filter them by the environment parameter. Error: Traceback (most recent call last): ... File "/Users/kalik/Desktop/agrochemistry-telegram-bot/agrochemistry/calculator/bot/bot.py", line 106, in environment_response filtered_products_by_env = user.last_query_products.all().fitler(environment=query.data) AttributeError: 'QuerySet' object has no attribute 'fitler' -
Create 4 dependant dropdown django with only 1 model
Right now i am able to filter 4 dependent dropdown, but the problem is i write script onchange for each dropdown seperately, and i am unable to get variables from other dropdown and pass it back to views to filter my tables. My 4 dropdowns are Thickness,Grade,Weight,Color All of these fields are in one single model I am trying to chain these 4 dropdowns so that: Grade filter(thickness = thickness) Weight filter(thickness = thickness,Grade = Grade) Color filter(thickness = thickness,Grade = Grade,Weight = Weight) Right now i'm only able to do this: Grade filter(thickness = thickness) Weight filter(Grade = Grade) Color filter(Weight = Weight) views.py thickness_id = request.GET.get('thickness') grade_id = request.GET.get('grade') weight_id = request.GET.get('weight') print(thickness_id) print(grade_id) grades = FormulasTable.objects.filter(thickness=thickness_id).values('grade').distinct() weights = FormulasTable.objects.filter(grade=grade_id).values('Weight').distinct() colors = FormulasTable.objects.filter(Weight=weight_id).values('Color').distinct() return render(request,'first_app/formula_options.html', {'grades': grades,'weights':weights,'colors':colors}) models.py class FormulasTable(models.Model): thickness = models.IntegerField() grade = models.CharField(max_length=50) Weight = models.IntegerField() Color = models.TextField(max_length=50) def __str__(self): return str(self.thickness) +" "+ str(self.grade) +" "+ str(self.Weight) +" "+ self.Color jquery <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#thickness_id").change(function () { var url = $("#formula_pageForm").attr("data-grades-url"); var thicknessId = $(this).val(); $.ajax({ url: url, data: { 'thickness': thicknessId }, success: function (data) { $("#grade_id").html(data); } }); console.log(thicknessId) } ); </script> <script> $("#grade_id").change(function () { var url = $("#formula_pageForm").attr("data-grades-url"); var … -
Customizing size of django admin portal text fields
How do I make a text field in the django admin portal bigger? Right now its one line, I want to make it about 5, so I can type in a small paragraph and see the whole thing. -
When I click on the save button it will check that data on the database before saving it in Django?
When I click on the save button it will check that data on the database before saving it in Django. search data at database before insert in Django administration. I don't want to save the same data that already save in the database. like this on: Here Home save to double. But I want that if home already save then the second time I try to Save the same name it will not save. How can I code it? models.py class Brand(models.Model): brand_id = models.id = models.AutoField(primary_key=True, auto_created=True) brand_name = models.CharField(max_length=50) brand_date = models.DateTimeField(auto_now_add=True, null=False) -
Django is not migrating migrations that exist
when first I did the makemigrations command, django did it sucessfully. But after migrate it says no migrations to apply. Than I tried to do delete migrations folder than make and migrate delete migrations and pycache and same thing migrate --fake migrate -f -
how to make the page redirects to the same page after the event occured
I am trying to make a upvote and downvote functionality on my website. however there is a particular behaviour that i don't like which is that whenever a user clicks the button, he should not be redirect to another page but should remain on the same page. What happens after clicking the upvote button is that it goes to the url http://localhost:8001/upvote/2/ which i don't want. I want it to remain on the same page which is http://localhost:8001/view-supplier/ models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) # CUSTOM USER FIELDS firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) def get_email(self): return self.email views.py @login_required def upvote(request, pk): supplier_vote = get_object_or_404(User, id=pk) supplier_vote.upvotes += 1 supplier_vote.save() upvote_count = supplier_vote.upvotes context = {"supplier_vote":supplier_vote, "upvote_count":upvote_count} return render(request, "core/view-suppliers.html", context) @login_required def downvote(request, pk): supplier_vote = get_object_or_404(User, id=pk) supplier_vote.downvotes -= 1 supplier_vote.save() downvote_count = supplier_vote.downvotes context = {"supplier_vote":supplier_vote, "downvote_count":downvote_count} return render(request, "core/view-suppliers.html", context) urls.py from django.urls import path from . import views urlpatterns = [ path('upvote/<int:pk>/', views.upvote, name='upvote'), path('downvote/<int:pk>/', views.downvote, name='downvote'), ] view-supplier.html <table class="table table-borderless table-data3"> <thead> <tr> <th>No</th> <th>Country</th> <th>Votes</th> </tr> </thead> <tbody> {% for supplier in suppliers %} … -
How can pass primary key to url Django
I have basically 3 issues I am trying to pass the primary key of vendor in url after creating it, but when i go the vendor page it shows the error ' Reverse for 'vendorCategory' with arguments '('',)' not found. 1 pattern(s) tried: ['vendorCategory/(?P<vendor_id>[0-9]+)/$'] ' In Vendor Category when i am trying to store multiple products against the specific vendor it show the error 'Field id int but You got ['12', '11'] ' in Vendor Category template when i select any category it just show the last category which i added View.py class Vendor(TemplateView): template_name = 'purchase/vendor.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request, vendor_id): try: data = self.request.POST.get vendor = VendorModel( name=data('name'), email=data('email'), Contact_No=data('Contact_No'), address=data('address') ) vendor.save() vendor.objects.get(id=vendor_id) return redirect('vendorCategory') except Exception as e: return HttpResponse('failed{}'.format(e)) class Vendor_Category(TemplateView): template_name = 'purchase/vendorCategory.html' def get(self, request, vendor_id=None, *args, **kwargs): categories = CategoryModel.objects.all() categoryId = self.request.GET.get('SelectCategory') products = ProductModel.objects.filter(category_id=categoryId) vendor= VendorModel.objects.get(id=vendor_id) args = {'categories': categories, 'products': products, 'selectedCategory': categoryId, 'vendor': vendor} return render(request, self.template_name, args) def post(self, request): categoryobj = self.request.GET.get('SelectCategory') productobj = self.request.POST.getlist('ProductSelect') try: vendor = VendorCategory( vendor_id=self.request.vendor_id, category_id=categoryobj, product_id=productobj ) vendor.save() return redirect('menu') except Exception as e: return HttpResponse('failed{}'.format(e)) Urls.py urlpatterns = [ path('vendorCategory/<int:vendor_id>/', Vendor_Category.as_view(), name='vendorCategory') … -
How to use const values from JavaScript as an argument of Django Custom template tags and filters?
If I have custom filters and write {% load file_name %} into index.html, How to write: <script> const x = 10; const = "{{ obj|function:x }}"; </script> -
Django perform CRUD function in Pop-Up form without reloading the page
I'm currently working(Practicing) on a task To-Do App where I want to perform CRUD functionality in Pop-Up(Modal) form. As I want to perform many CRUD functions I don't want to reload the page every time I do some actions. Image-1 is the overview of the application. A todo item has an update option. Once it was clicked update todo Pop-up form(modal) displayed. Image-2 is the update todo pop-up form(modal) Here I can add a task that will be displayed under its corresponding todo item. Also, I want to update the task item via another pop-up form. The problem I'm facing was If I do some action on any of the pop-up forms the page is getting reloaded. So, that it is redirecting to the home page. models.py from django.db import models from django.conf import settings class Todo(models.Model): date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) title = models.CharField(max_length=200) user_id = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title class Task(models.Model): heading = models.CharField(max_length=100) todo = models.ForeignKey( Todo, on_delete=models.CASCADE, related_name='tasks') date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.heading views.py from django.shortcuts import render, redirect from django.http import Http404, HttpResponse from django.utils import timezone from django.contrib.auth import login, logout … -
Use tmp table to run multiple django queries from a postgres function
I have two versions of a recursive psql function that both select from the same table but return different results. function a (simplified for example): create or replace function public.all_link_traversal(source_ids bigint[], depth_count integer) returns table (id bigint) begin if depth_count > 0 then return query select id from service_item_links where child_service_item_id = any(source_ids) union all select id from all_link_traversal( select distinct parent_service_item_id from service_item_links where child_service_item_id = any(source_ids) else return query select id from service_item_links where child_service_item_id = any(source_ids) function b does a very similar traversal over service_item_links table, but returns a distinct list of child_service_item_ids. In Django, I call both functions separately (but within the same rest call) like so: service_item_links_raw = ServiceItemLinks.objects.filter( id__in=RawSQL(f"select id from {function_query_a}", params=query_params) ) child_service_item_ids = ServiceItems.objects.filter( id__in=RawSQL(f"select id from {function_query_b}", params=query_params) ) return child_service_item_ids.values_list('id', flat=True), service_item_links_raw.values("parent_service_item_id", "child_service_item_id", "link_type", "action_date", "action_key") Due to having to traverse the tree twice, performance with this query has been slow. I'm looking at a solution of creating a tmp table, then having both of these functions run against the tmp table, then deleting it but I'm unsure of how postgres can return two sets of results, or how Django can interact with the tmp table and run both … -
Django forms custom field Left Outer Join
I have a form where I add CUSTOM FIELD checkbox miltiple. The data is simply loaded like this widget = forms.CheckboxSelectMultiple, queryset = Product.objects.all (), required = False, ) This is a good solution when I create a new instance of the Component model. In the case of editing, however, it is a problem because some of the checkboxes can be filled. So I need to change the queryset for this field a little. I wanted to do it like prod = Product.objects.annotate (dupa = FilteredRelation ('product', condition = Q (product__component = 120))). Values ('short_name', 'name', 'dupa__component'), but it gets error django.db.utils.ProgrammingError: missing FROM-clause entry for table" t7 LINE 1: ... a ON ("epm_product". "Id" = ass. "Product_id" AND (T7. "Comp ...". Query returns : SELECT "epm_product "." Short_name "," epm_product ". "name", "epm_productitem_component". "component_id" FROM "epm_product" LEFT OUTER JOIN "epm_productitem" dupa ON ("epm_product". "id" = dupa. "product_id" AND (T5. "component_id" = 120)) LEFT OUTER JOIN "epm_productitem_component" ON (ass. "Id" = "epm_productitem_component". "Productitem_id") To test the data and how it is presented, I used the usual SQL query: "select pr.name, pr.short_name , (select count (*) from epm_productitem pi left join epm_productitem_component pic on pic.productitem_id = pi.id where pic.component_id = 120 … -
How to assign model fields to a custom variable in the view, and use it in context to pass to the template?
so I have a model in models.py, and it has a few fields. Next, I make a form in forms.py to make a creative form. Then I import that form from forms.py into views.py. In the views.py, I make the create view, with the creat form. But here's the problem. In the views.py, I have the model field space. now I want to do something with that field. I assign a custom variable to this space field and pass it in the context. But it gives an error called local variable not defined. models.py class NewJax(models.Model): title = models.CharField(max_length=60) description = models.TextField(max_length=140) space = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-date_created'] verbose_name_plural = "New Jax" def __str__(self): return str(self.title) forms.py class CreateNewJaxForm(forms.ModelForm): class Meta: model = NewJax fields = ('title', 'description', 'space') widgets = { "title": forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'name your jax' } ), 'description': forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'add a brief description for jax', 'rows': 4, } ), 'space': forms.Textarea( attrs={ 'class': 'form-control', } ) } views.py def create_new_jax(request): if request.user.username == "Assasinator": logout(request) return redirect('banned_user') if request.method == "POST": form = CreateNewJaxForm(request.POST or None) if form.is_valid(): title = form.cleaned_data.get('title') … -
for < slides in python DJango templating
for x in range(1,slides): do something i want to write something like this in Django templating how's can I achieve that i searched a lot in google but could not find anything helpful kindly help me out -
How to allow only users associated with certain permissions to access certain urls in Django?
I am trying to figure out how to allow certain users who have a value: ifAdmin=True the ability to edit a project page. That being said, I have a model called uProjects that associates a user and a project with a uProjects, and I am currently trying to use the @wraps function, but would welcome a different approach, or a correction on my code because I am returned the HttpResponseRedirect when I am logged in with a user who has ifAdmin=True and I try to edit a project associated with the uProjects for that user. Here is my code: model: class uProjects(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) ifAccepted = models.BooleanField(null = True, blank=False, default=False) #ifLeader = models.BooleanField(null = False, blank=False) ifAdmin = models.BooleanField(null = True, blank=False, default=False) title = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.user.username + ',' + self.project.name views.py def admin_check(function): @wraps(function) def wrap(request, *args, **kwargs): user = request.user name = kwargs.get('name') if uProjects.objects.filter(title=name, user=user, ifAdmin=True).exists(): return function(request, *args, **kwargs) else: return HttpResponseRedirect('/') return wrap @admin_check def update(request): if request.method == "POST": pr_form = ProjectUpdateForm(request.POST, request.FILES, instance=request.project.name) if pr_form.is_valid(): pr_form.save() messages.success(request, f'This project has been updated.') return redirect('project') else: pr_form = ProjectUpdateForm(instance=request.user.profile) context = { … -
Why doesn't my form validation work in django?
I am trying to have user validation in my django social media/blog app. I do not understand why this code does not work. The problem: No matter what name I type in the form it says the user does not exist even though the user does in fact exist. Any help would be amazing. from django.shortcuts import render, redirect from sign_in.forms import SignInForm from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth.forms import forms from django.http import HttpResponseRedirect def sign_in(request): if request.method == "POST": form = SignInForm(request.POST) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = User.objects.filter(username=username, password=password) if user.exists(): return HttpResponseRedirect("boom/") else: messages.error(request, f"User {user} does not exist.") else: form = SignInForm() return render(request, "sign_in/sign_in.html", {"form": form})