Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve 'User' object is not callable error in Django?
I am trying to serialize my user permissions, including the associated group permissions, and access them via an API endpoint. The goal is to create something like this: { "permissions": { "auth.add_user" : True, "auth.add_group" : True, "auth.add_userproxy" : False, } } But somehow I get the following error message when I call my API:TypeError: 'User' object is not callable. The error message is refering to line all_permissions = self.request.user(is_superuser=True).get_all_permissions() # Get User Permission API class UserPermissionAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserPermissionSerializer def get(self, request): #permissions = self.request.user.get_all_permissions() all_permissions = self.request.user(is_superuser=True).get_all_permissions() # Line Error Message is refering to user_permissions = self.request.user.get_all_permissions() permissions = {p: p in user_permissions for p in all_permissions} data = { 'permissions': permissions } serializer = UserPermissionSerializer(data) return Response(serializer.data) I work with a custom user model class User(AbstractUser):. Im happy for any clarification. Why can i not call the user? -
Python and Django ,<built-in function id> error function, where is the issue
I have the following class: class Income(models.Model): income=models.DecimalField() date=models.DateField() In my views I have created an algo that give me the possibility to collect all date monthly, like the following: now=datetime.datetime.now() now=now.year income=dict() for year, month, totals in(Income.objects.values_list( 'date__year', 'date__month'). annotate(totals=ExpressionWrapper(Sum(F('income')), output_field=FloatField())).values_list('date__year', 'date__month', 'totals')): if id not in income.keys() and year == now: income[id]=list(defaults) index=month-1 income[id][index]=totals If I set now in the following manner, it works perfectly: now=datetime.datetime.now() now=now.year But If I set a form in the following manner: #models class Timing(models.Model): reference_year=models.DateField() #views nows=[] form = TimingForm(request.POST or None) if request.method == 'POST': if form.is_valid(): nows = form.cleaned_data['reference_year'] nows=nows.year Python give me the following errors: <built-in function id> Why?? -
Python Django Edit HTML rows and update database
I have a table and I wish to add an edit button that updates the certain record both visually and in the database. The HTML I have. {% for work_entry in work_entries %} {% if work_entry.date == date.date %} <form action="{% url 'work_entries:object_edit' work_entry.id %}" method="post"> {% csrf_token %} <tr> <td> <button onclick="return confirm('Are you sure you want this edit?')">Edit </button> </td> <td> <form action="{% url 'work_entries:object_delete' work_entry.id %}" method="post"> {% csrf_token %} <button onclick="return confirm('Are you sure you want to delete this record?')">Delete </button> </form> </td> <td>{{ work_entry.id }}</td> <td><input type="text" value="{{ work_entry.description }}" name="description"></td> <td><input type="number" value="{{ work_entry.num_hours }}" name="hours"></td> </tr> </form> {% endif %} {% endfor %} The views.py def object_edit(request, object_id): record = get_object_or_404(WorkEntry, pk=object_id) if request.method == "POST": record.description = request.POST["description"] record.num_hours = request.POST["hours"] record.save() return redirect("/employeePage") return render(request, "employeePage.html") And urls.py app_name = "work_entries" urlpatterns = [ path("", views.employee_view, name="employeePage"), url(r"^delete/(?P<object_id>[0-9]+)/$", views.object_delete, name="object_delete"), url(r"^edit/(?P<object_id>[0-9]+)/$", views.object_edit, name="object_edit"), ] I used an input tag in the as I thought that would allow me to change data and save it. However this is giving me MultiValueDictKeyError at /employeePage/edit/14/ 'description' error. I am not too experienced with jquery which from research I saw that could work but I … -
why pk_range method of Django not working?
views.py from django.shortcuts import render from .models import images def next_img(request,pk): if request.method == "GET": images_data = images.objects.filter(pk_range=(int(pk)+1,int(pk)+8)) return render(request,"images.html",{'image':images_data}) I just want to retrieve the images list objects from the given range by using their primary keys and pk_range=(int(pk)+1,int(pk)+8) giving below error. FieldError at /images/next/8/ Cannot resolve keyword 'pk_range' into field. Choices are: id, image, name, type, user, user_id -
How to test/simulate broken database connection
I have written logic to return custom errors when my application cannot connect to the database (why that can happen is out of the scope for this question). I wish to write unit tests for this, specifically to see the response status codes when: there is a valid connection to the database. This is easy as Django automatically creates a "test" database whenever I run any tests. there isn't a valid connection to the database. Unfortunately, I cannot find any documentation about this. Is it possible to run that test by somehow simulating that something has gone wrong with the database connection? -
django invalid form in user field
views.py def view_form(request, template_name='form.html'): user = request.user if request.method == "POST": form = my_Form(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.user_mytable = request.user instance.save() else: print('invalid') else: form = my_Form() return render(request, template_name,{'form':form}) forms.py class my_Form(forms.ModelForm): class Meta: model = my_table fields = ('__all__') models.py class my_table(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) user_mytable = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) field1 = models.FloatField(blank=True, null=True) field2 = models.FloatField(blank=True, null=True) field3 = models.TextField(max_length=150,blank=True, null=True) time = models.TextField(blank=True, null=True) i get invalid form in user_mytable This field is required. any idea how to fix it ?because i use request.user -
Deploying Django API to Heroku fails because of pkg-resources
I'm trying to deploy to Heroku a Django API. I've set everything up but when I run git push heroku master while installing the requirements.txt file the following error comes up: remote: ERROR: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /tmp/build_7907c86d507c2a1ffc4ecbbc0e82799b/requirements.txt (line 25)) (from versions: none) remote: ERROR: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_7907c86d507c2a1ffc4ecbbc0e82799b/requirements.txt (line 25)) remote: ! Push rejected, failed to compile Python app. and the push fails. I've deleted this package from the requirements file but if you notice it seems the Heroku is trying to install from some tmp/build file and the one in my project. How can I fix this? -
Sometimes I am unable to see printed string (print()) in console or terminal (CLI) in django.Iam using powershell
Suppose while debugging I print something (using print()), inorder to get some idea regarding bug.But all of a sudden the print sops working.Iam using Django 2.2. -
Distance function requires a geometric argument in position 2
I have two model shop and customer shop class Shop(models.Model): distance = models.PositiveIntegerField(null=True) shop_location = models.PointField(null=True, default=Point(28.49, 77.33)) customer class Customer(models.Model): customer_location = models.PointField(null=True, default=Point(28.49, 77.33)) I want to set the filter on the shop. The shop will show to the customer if the distance between shop and customer under the distance given by the shop and my views.py from django.contrib.gis.db.models.functions import Distance Shop_list = Shop.objects.filter( distance_gte=Distance('shop_location', Customer.customer_location) ) I am getting the error Distance function requires a geometric argument in position 2 -
Does Sequelize have a way to find or select a subset of fields?
Say I have the following Django code using .only(): Person.objects.only("name") Is there a similar way in Sequelize to generate SQL (preferably not using Raw Queries) which returns only a subset of all the fields stored in my DB? -
django-admin sum multiple columns
I have a model with several fields. And I wanted to add another field in django-admin (list_display), where it is the sum of all fields. Model's class Model1(models.Model): field1 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) field2 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) field4 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) def __str__(self): return str(self.id) Model's Admin class Model1Admin(admin.ModelAdmin): model = Model1 list_display = ('field1','field2',<!--Sum of (field1,field2,field3,field4,field5-->) admin.site.register(Modell,Model1Admin) i am using the last version of django. -
How to properly import list of functions with import * and __all__?
I have this simplified structure of files: utils/ |- __init__.py |- script1.py |- script2.py |- script_report.py /views.py script_report.py has lots of classes and functions and I want to import some of them in other scripts. On my views.py (and also other scripts) which are outside utils/ I want to import a specific list of functions from script_report.py (this list is always the same) but I don't want to list them all in every script I use, also because I keep adding more functions that need to be imported, so I would like to use from .utils.script_report import * and only add the new functions to one place only. In my __init__.py file I have: from .utils.script_report import (function1, function2) __all__ = ['function1', 'function2'] So in views.py I tried from .utils import * but that doesn't seem to work. What is the correct way to do it? I know that if I define __all__ inside script_report.py then from .utils.script_report import * works fine. Note: I have gone through this but can't find the correct way to adapt it. -
Infinite Scroll Django does not work proprely
Note: Intro: I am using this https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html to add infinite scroll with django. Just in case anyone wants the detailed code its on Github.It is a very simple code The Problem: Rather than having infinite scroll I only get more link so it does not work properly In my static folder. I made a folder called js and added 3 files in it infinite.min.js, jquery-3.1.1.min.js, jquery.waypoints.min.js I copied the code exactly from the github in my files BELOW IS MY VIEW from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.contrib.auth.models import User from .models import Post from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.http import HttpResponse def home(request): numbers_list = range(1, 1000) page = request.GET.get('page', 1) paginator = Paginator(numbers_list, 20) try: numbers = paginator.page(page) except PageNotAnInteger: numbers = paginator.page(1) except EmptyPage: numbers = paginator.page(paginator.num_pages) return render(request, 'blog/home.html', {'numbers': numbers}) class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') MY base.html <!DOCTYPE html> {% load static %} <html> <head> <!-- … -
Choosing between makefile and setup.py for a django project
I have a Django project with backend(Djangorest) and frontend(React) as two apps in the same project. I want to create a script to activate the virtual environment and install requirements. How do I choose between using a makefile or setup.py? -
Condition not working for 2 different apps in a Django template
I have created a project with 2 apps: 1.Core for items model to be viewed in home page 2. Score with posts model The home.html is mainly for listing items by designers, the designers/users might have posts as well so I am trying to show buttons for designers/userswho have posts and hide them if the users don't have posts. I have added the code but the button for the designers/usersposts is still showing. App No. 1 CORE Core Models.py class Item(models.Model): designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) Core views.py class HomeView(ListView): model = Item paginate_by = 12 template_name = "home.html" ordering = ['-timestamp'] # context_object_name = 'posts' (I have commented this part as it is from Score Models when included the home page become 404 error) Here is the Core URL urlpatterns = [ path('', HomeView.as_view(), name='home'), App No.2 Score Score Models.py: class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to=upload_design_to) Home.html template {% if post.designer %} <a href="{% url 'score:user-posts' item.designer.username %}"> <button style="margin-top: 10px;text-transform: none;" button type="button" class="btn btn-success btn-sm btn-block"> Check my posts</button> </a> {% else %} Show Nothing {% endif %} I dont know what might the reason for now working … -
Django how to create dynamic dropdown filter to the queryset
I have created an app that give me the possibility to collect and store all daily income. In this case I have created the following model: class Income(models.Model): income=models.DecimalField() date=models.DateField() In my views I have created an algo that give me the possibility to collect all date monthly, like the following: now=datetime.datetime.now() now=now.year income=dict() for year, month, totals in(Income.objects.values_list( 'date__year', 'date__month'). annotate(totals=ExpressionWrapper(Sum(F('income')), output_field=FloatField())).values_list('date__year', 'date__month', 'totals')): if id not in income.keys() and year == now: income[id]=list(defaults) index=month-1 income[id][index]=totals All works perfectly. But now I want to give the possibility to be able to choose the year manage the now variable. So for this aim I have tried to create a new model, as the following: class Timing(models.Model): TYPE=[ ('2020','2020'), ('2021', '2021'), ] reference_year=models.CharField('Azienda/Privato', max_length=30, choices=TYPE, default="") Now I want to create a dropdown menu in my templates to choose the year and subsequently to update the views updating the now variable. Do you have any ideas to implement this function? -
Django table model
I am relatively new to Django and would like to use it to build the back end of my app. I am using Django.DB models and Django rest-framework. I am trying to make a system where each company in my DB has a table that stores 3 records. Item, Price, and Description but I have no idea what type of field that would be or how one would do that. I was assuming that you would use a one-to-many field but there doesn't seem to something like that. Thank You in advance. -
dj-rest-auth: get access_token/code for facebook social media authentication
I was trying to implement Social Media Authentication with Facebook using dj-rest-auth. I am following the instructions in the docs Where could I get the access_token/code that's mentioned in the docs when calling the API endpoint /dj-rest-auth/facebook/ (POST) Thank you -
Edit Validation Errors in Django
I have a registration form on my website. Im having trouble editing the errors when the registration form is filled out incorrectly. I have done this code in my forms.py but it also displays djangos regular validation error. class lageBruker(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2'] def clean_brukernavn(self): brukernavn = self.cleaned_data.get('username') bruker_qs = User.objects.filter(username = brukernavn) if bruker_qs.exists(): raise forms.ValidationError('Brukernavn allerede i bruk') return brukernavn def clean(self, *args, **kwargs): passord1 = self.cleaned_data.get('password1') passord2 = self.cleaned_data.get('password2') if passord1 != passord2: raise forms.ValidationError('Passordene må være like') return super(lageBruker, self).clean(*args, **kwargs) I there any way i can edit the validation error that django is throwing? -
ManyToMany Django show field in my template
I have a make in my model a manytomany relationships like this: from django.conf import settings from django.db import models class Company(models.Model): user = models.ManyToManyField( settings.AUTH_USER_MODEL, ) name = models.CharField(max_length=200) siret = models.CharField(max_length=200, blank=True) ape = models.CharField(max_length=200, blank=True) adresse = models.TextField(blank=True) cp = models.CharField(max_length=200, blank=True) ville = models.CharField(max_length=200, blank=True) code_cfast = models.CharField(max_length=200, blank=True) code_dolibarr = models.CharField(max_length=200, blank=True) marque_blanche = models.BooleanField(default=False) marque_blanche_couleur = models.CharField(max_length=200, blank=True) created_at = models.DateTimeField('date published') All is working fine on my Company View and template, i can access to the users of my company like this: {% render_field form.user type="select" class="selectpicker form-control show-tick" data-live-search="true" %} But i have create a User View and on my template i can retrieve the value in input like this: {% render_field form.groups type="select" class="form-control" %} But i want to have on my edit view of my user the same select when i have on my company edit. I have try: {% render_field form.company type="select" class="form-control" %} With no success. I use the default user model. An idea ? Sorry for my english i'm french. Thx. -
Django Import-export: Import CSV files errors
I`ve spent a few hours trying to debug this issue. I am trying to import a catalog of product into my app. I am using Django Import-export to import a csv file. I have tried to import it via the admin site and via a simple upload file. In both case, I am encountering some errors. Would you have an idea how to resolve them? 1st Method: Import the csv file via the admin site Error encountered: Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x9d in position 13365: character maps to It looks like this method cannot accept some character(""). How can I change my code to accept any character? I`ve already removed the following characters: £, - and try to encode it in UTF-8. I have also done a search to remove every non ASCII characters(128-255) 2eme Method: Import the csv file via the website Error encountered: 'MultiValueDict' object is not callable views.py def simple_upload(request): if request.method == 'POST': file_format = request.POST.get('file-format') product_resource = ProductResource() dataset = Dataset() new_products = request.FILES['Price_List'] if file_format == 'CSV': imported_data = dataset.load(new_products.read().decode('utf-8'),format='csv') result = product_resource.import_data(dataset, dry_run=True) elif file_format == 'JSON': imported_data = dataset.load(new_products.read().decode('utf-8'),format='json') # Testing data import result = … -
Django OpenCV Exception Value: libSM.so.6: cannot open shared object file: No such file or directory
I am trying to deploy my simple OpenCV based app to Heroku. The app capture live stream only from webcam. My App worked well in the local environment while it gives the following error on Heroku platform. Exception Value: libSM.so.6: cannot open shared object file: No such file or directory How can I resolve it? -
How to check a condition in a DRF Serializer and then skip that iteration and go to the next
I have a serializer as follows: class CustomerSerializer(serializers.ModelSerializer): product = serializers.SerializerMethodField() def get_product(self, obj): obj.product = Customer.check_is_product(obj.product_id) return obj.product.name class Meta: model = Customer fields = ['name', 'product'] and I have a models.py as follows: class Product(models.Model): name = models.IntegerField() class Meta: db_table = 'items' class Customer(models.Model): name = models.CharField(max_length=255) product_id = models.IntegerField() class Meta: db_table = 'items' @staticmethod def check_is_product(id) try: product_obj = Products.objects.get(id=id) except: <if product with that id isn't there, then i wanna skip that iteration in serializer> return product_obj Now imagine I have three customers in my Database, out of that, one customer doesn't have any product, then I wanna skip that entire customer's detail in my API response. So my final API response would have a list with only 2 items. Does anyone know how to skip an iteration of the serializer on any condition check? -
Using Django tenants on the same domain, rather than subdomains or multiple domains
If I am using django-tenant-schemas (or django-tenants fork), the way they appear to be set up is that you would access the tenants on a separate subdomain or separate domain. This means accessing tenant1 using tenant1.mysite.com or tenant1.com. However, I would like to access tenants using mysite.com/tenant1/, mysite.com/tenant2/. This is because I am using DRF, and so I just want their information stored separately. And I want to access them via the API in the same way. So, for instance I can make calls to mysite.com/tenant1/api/token/. How would I set this up? -
Circumventing F expression problem of django-simple-history by overriding save
Django-simple-history is inserting new record on each save of target model. In docs the problem with F expressions is described. I try to circumvent this with overriden save method. def save(self, *args, **kwargs): super().save(*args, **kwargs) # some other actions self.refresh_from_db() But it seems, that this is not working. Is the post_save signal of base model called directly after super().save() call? If so, is there a way to solve this problem keeping the F expression in target model update?