Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 'The current path, dict_list2.html, didn’t match any of these.'
I wanna make dictionary by using Django. I made a code like this but it caused an error 'The current path, dict_list2.html, didn't match any of these.' Help me.. urlpatterns = [ path('admin/', admin.site.urls), path('^/$', views.csvToModel1, name='dict_list1'), path('^/$', views.csvToModel2, name='dict_list2'), path(r'^dialect/$', views.csvToModel3, name='dict_list3'), path(r'^dialect/$', views.csvToModel4, name='dict_list4'), path(r'^dialect/$', views.csvToModel5, name='dict_list5'), path(r'^dialect/$', views.csvToModel6, name='dict_list6'), path(r'^dialect/$', views.csvToModel7, name='dict_list7'), path(r'^dialect/$', views.csvToModel8, name='dict_list8'), path(r'^dialect/$', views.csvToModel9, name='dict_list9'), path(r'^dialect/$', views.csvToModel10, name='dict_list10'), path(r'^dialect/$', views.csvToModel11, name='dict_list11'), path(r'^dialect/$', views.csvToModel12, name='dict_list12'), path(r'^dialect/$', views.csvToModel13, name='dict_list13'), path(r'^dialect/$', views.csvToModel14, name='dict_list14'), ] -
Update a geodjango field after surface computation
I've got a database with a list of building in multiple areas. I want to update all area instances at once with the density of building. Here are my models: class Area(models.Model): mpoly = models.MultiPolygonField() surface = models.DecimalField(max_digits=8, decimal_places=2) density = models.DecimalField(max_digits=3, decimal_places=2) class Building(models.Model): mpoly = models.MultiPolygonField() Here my code (but it fails): sub_qs = Building.objects.filter(mpoly__intersects=OuterRef("mpoly")) sub_qs = sub_qs.annotate( intersection=Intersection("mpoly", OuterRef("mpoly")), intersection_area=Area(Transform("intersection", 2154)), ) sub_qs = sub_qs.aggregate(Sum("intersection_area")) Area.objects.all().annotate( surface_built=Cast( Subquery(sub_qs[:1]), DecimalField(max_digits=3, decimal_places=2) ) ).update(density=F("surface_built")/F("surface")) How would you do it ? -
The @login_required decoration is not working in Django (user not authenticated?)
I am new to Django and I am trying to set up a login page and I am trying to use the @login_required decoration. However, whenever I try and log in with valid credentials I am re-directed to the 'login' page (set to re-direct unauthenticated users). I am not sure if the problem is in the @login_required decoration or perhaps the login() function is not authenticating the user Here is my code for the register form: class RegisterForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] code for login function in views.py: def login_user(request): if request.method =="GET": return render(request, "main/login.html", {}) else: username = escape(request.POST['userfield']) password = escape(request.POST['passfield']) try: user = User.objects.get(username=username) except: user = None if user is None: try: user = User.objects.get(email=username) except: user = None if user is None: messages.info(request, "*Sorry, that username or email does not exist") return redirect('login') pword = user.password if check_password(password, pword): login(request, user) return redirect('homepage') else: messages.info(request, '*Sorry, that was an incorrect password') return redirect('login') my model for User in models.py: class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100) email = models.EmailField(unique=True) password = models.CharField(max_length=100) admin = models.BooleanField(default=False) last_login … -
Can I make a Django query that returns a list per item?
I have 3 models like this: class Person(models.Model): name = models.CharField(max_length=100) class Place(models.Model): name = models.CharField(max_length=100) # ManyToMany Through Table class PersonPlace(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) place = models.ForeignKey(Place, on_delete=models.CASCADE) PersonPlace links Person and Place in a ManyToMany relationship. I want a database query that will give me a list of place id's per person (a list of places every person has visited). Is it possible to make that aggregation through the ORM without having Python put this together? -
How can I allow my dictionary to accept duplicate keys [closed]
I have a function that is creating a dictionary of lists: def Planner(calories, dislikes): carbs = Food.objects.filter(category='Carbs').exclude(name__in=dislikes) proteins = Food.objects.filter(category='Protein').exclude(name__in=dislikes) vegs = Food.objects.filter(category='Vegetables').exclude(name__in=dislikes) carb1 = random.choice(carbs) protein1 = random.choice(proteins) veg1 = random.choice(vegs) carb2 = random.choice(carbs) protein2 = random.choice(proteins) veg2 = random.choice(vegs) veg_exclude = [veg1, veg2] veg3 = Food.objects.filter(category='Vegetables').exclude(name__in=veg_exclude)[0] meals = [carb1, protein1, carb2, protein2] carb3 = random.choice(carbs) protein3 = random.choice(proteins) meals.append(carb3) meals.append(protein3) total_cals = sum(meal.calories * meal.portion_size_in_grams / 100 for meal in meals) calories_short = calories - total_cals calories_per_gram = sum(meal.calories * 1 / 100 for meal in meals) extra_grams_needed = calories_short // calories_per_gram meal_dict = { meal.name: [meal.portion_size_in_grams + extra_grams_needed, meal.calories, meal.category, meal.pack_size] for meal in meals} meal_dict[veg1.name] = [veg1.portion_size_in_grams, veg1.calories, veg1.category, veg1.pack_size] meal_dict[veg2.name] = [veg2.portion_size_in_grams, veg2.calories, veg2.category, veg2.pack_size] meal_dict[veg3.name] = [veg3.portion_size_in_grams, veg3.calories, veg3.category, veg3.pack_size] for key, value in meal_dict.items(): meal_plan_total_cals += value[0] * value[1] / 100 meal_dict['total_calories'] = meal_plan_total_cals meal_dict['total_meals'] = 3 return meal_dict I need the dictionary to be able to accept duplicate keys as sometimes the function will generate the same meal twice (which is fine) but when it gets added to the dictionary it will just overwrite the existing key which is not the intended functionality. How can I modify my code so that the … -
Objects of model does not have primary key
Good morning, unfortunately I can't get out of a problem found in the code: I created a new model to distinguish between sales orders and purchase orders. The problem is that in no way is a primary key recognized when I create the object in question. Through the admin section I create the object but if I try to click on it, it is not recognized, nor can I delete it. Through Robo 3T I notice that compared to the orders of the first model, the second model has one less field, the one related to the id. The models in question are virtually identical, but one works, the other doesn't. models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.utils import timezone class Profile(models.Model): user_profile=models.ForeignKey(User,on_delete=models.CASCADE) btc=models.IntegerField(default=5) usd=models.IntegerField(default=100000) initial_balance=models.IntegerField() class Order(models.Model): profile=models.ForeignKey(User,on_delete=models.CASCADE) datetime=models.DateTimeField(default=timezone.now()) price=models.FloatField() quantity=models.FloatField() class SellOrder(models.Model): buyer_profile=models.ForeignKey(User,on_delete=models.CASCADE) buyer_datetime=models.DateTimeField(default=timezone.now()) buyer_price=models.FloatField() buyer_quantity=models.FloatField() views.py from django.shortcuts import render,redirect,get_object_or_404 from django.contrib.auth import authenticate,login,logout from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from .models import Profile,Order, SellOrder from django.views.decorators.csrf import csrf_exempt from .forms import OrderForm, SellOrderForm import requests def home_page(request): price=get_price() return render(request,'app/home_page.html',{'price':price}) @csrf_exempt def register_user(request): price=get_price() if request.method=='POST': form=UserCreationForm(request.POST) if form.is_valid(): form.save() username=form.cleaned_data['username'] password=form.cleaned_data['password1'] user=authenticate(username=username,password=password) login(request,user) messages.success(request,"Registration Successful!") … -
Check if specific channel name exists (is connected) in Django Channels
I'm using Django Channels and need to limit the maximum number of currently active connections by a single user. I'm storing data about present users with django-channels-presence. Basically, I add and remove db records whenever connect and disconnect methods on my consumer are called. That works well unless there's a server crash or reload and I'm looking for a better way to determine currently connected users. Specifically, I'm trying to check if a specific channel name (which is stored in the database record) exists and is connected. Hoped to find some method for it on the channel_layer object (it's returned with get_channel_layer() function), but no luck there. -
Session are not passing between function
I have been trying to pass data between the functions using sessions. The problem is that while testing locally it works perfectly, while testing the same in a development server it doesnt works. Following is my code: views.py def pre_login(request): ... ... if login_obj['success'] == True: request.session['pre_login'] = "Abcd" return JsonResponse("Success", safe=False) def login(request): pre_login = request.session.get('pre_login') print(pre_login) Above works locally but not in server. Development server is simply running using manage.py runserver. What might be the possible cause of it? -
facebook's sharer.php shows 403 Forbidden in share box
I am using this for sharing on Facebook. <meta property="og:image" content="https://url.com/{{ article.img_path }}"> <meta property="og:type" content="website"/> <meta property="og:title" content="{{ article.title }}"/> <meta property="og:description" content="{{ article.title }}"/> <meta property="og:url" content="https://url.com/{{ article.path }}"/> . . <a href="https://www.facebook.com/sharer/sharer.php?u=https://url.com/{{ article.path | urlencode }}"> <i class="fa fa-facebook-square fa-2x"></i> </a> I also get a 403 Forbidden in the box. Default is mobile view even on Desktop ? -
How to create invoice depending upon template give by User in django
I am making a web application built on django which has a feature of Invoice which should be downloadable. I want that invoice to be created depending upon the template provided by User. Eg: If a doctor uses my application he can upload the template of his medical clinic and whenever we generate invoices of patients for medicines all the invoice generated for prescribed medicines must be downloadable in that template. Please help me -
how to change EmailValidator Error Message
models.py class User(AbstractBaseUser): email = models.EmailField( verbose_name='Email', max_length=255, unique=True, error_messages={'msg':"Enter a valid Email Address"}, ) name = models.CharField(max_length=200) phone_number= models.CharField(max_length=200, blank=True) address= models.CharField(max_length=200, blank=True) tc = models.BooleanField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'tc'] serializer.py class UserRegistrationSerializer(serializers.ModelSerializer): # We are writing this becoz we need confirm password field in our Registratin Request password2 = serializers.CharField(style={'input_type':'password'}, write_only=True) class Meta: model = User fields=['email', 'name' ,'phone_number', 'address','password', 'password2','tc' ] extra_kwargs={ 'password':{'write_only':True}, } def validate(self, attrs): password = attrs.get('password') password2 = attrs.get('password2') if password != password2: raise serializers.ValidationError("Password and Confirm Password doesn't match") return attrs def create(self, validate_data): return User.objects.create_user(**validate_data) Output i am getting when i put an invalid email id { "email": [ "Enter a valid email address." ] } Expected Output { "msg": "Enter a valid email address." } I have used error_message in models to get the output i want and i have also used EmailValidator(message="") but nothing is working. I tried to use def clean_email in serializers.py but that also didn't worked. please help -
ERROR: TypeError at /admin/myapp/booking/19/change/
I've created a model using an abstract user model class for Online flight ticket booking. I'm new to this so haven't added many functionalities to it. I'm sharing my model.py, admin.py, serializer.py, views.py. My question: In the link below shows a screenshot of an error occurring while I want to GET PUT DELETE booking data using ADMIN panel. I'm not able to figure out the problem yet. Error while trying to GET PUT DELETE booking #models.py import email from pyexpat import model from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) class UserManager(BaseUserManager): def create_user(self, email, name,contact_number,gender,address,state,city,country,pincode,dob ,password=None, password2=None): if not email: raise ValueError('User must have an email address') user = self.model( email=self.normalize_email(email), name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name,contact_number,gender,address,state,city,country,pincode,dob , password=None): user = self.create_user( email, name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, password=password, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = … -
when i am django date filter not working?
This is my query : I given the below dates: startdate : 2022-06-06 enddate : 2022-06-07 user=Model.objects.filter(agent=fullnames['username']).filter(status=ticket_status)).filter(completed_date__gt=startdate,completed_date__lt=enddate) output: after filter the query im getting this output , in this 2022-06-08 not required, but it is showing { "reference": "9802047093", "name": "Caliber", "completed_date": "2022-06-07" }, { "reference": "9802510868", "name": "Caliber", "completed_date": "2022-06-06" }, { "reference": "9738614446", "name": "Caliber", "completed_date": "2022-06-08" } -
Django: [Errno 2] No such file or directory: '/tmp/tmpmhi9gua5/texput.pdf' during generate a pdf
I need some help please, Hi for all here am trying to generate a pdf with latex in my django applicaton but i keep see an error when i add a specific data in my template-latex.tex. This is my views.py: if request.user.is_authenticated: if request.method == 'POST': form = ReportForm(request.POST, ) form.instance.user=request.user if form.is_valid(): form.save() obj_Formulaire = MyModel.objects.filter(user=request.user).last() field_obj_load_between_posts = MyModel._meta.get_field('load_between_posts') field_value_load_between_posts = field_obj_load_between_posts.value_from_object(obj_Formulaire) load_between_posts = field_value_load_between_posts if load_between_posts == True: field_obj_custom_load = MyModel._meta.get_field('custom_load') field_value_custom_load = field_obj_custom_load.value_from_object(obj_Formulaire) qh = float(field_value_custom_load) else: qh = float(0) #----some other code about getting the value fields---- w_profile = float(sizes_column_wprofile) w_project = round(float((1.5 * qh * distance * height) / fy),2) if w_profile >= w_project: resultat_mechanical = "Wprofile={0} > Wproject={1}".format(w_profile, w_project) resultat_resistance_criteria = "Profile Verified ✔" else: resultat_mechanical = "Wprofile={0} < Wproject={1}".format(w_profile, w_project) resultat_resistance_criteria = "Profile Not Verified" context = { 'qh': qh, 'resultat_resistance_criteria': resultat_resistance_criteria, 'resultat_mechanical' : resultat_mechanical } template = get_template('pages/my_latex_template.tex') rendered_tpl = template.render(context).encode('utf-8') # <3> with tempfile.TemporaryDirectory() as tempdir: # <4> for i in range(2): process = Popen( ['pdflatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') # <5> r.write(pdf) return r form = ReportForm() context = {'form': form} return render(request, 'pages/form_gelander_report.html', context) everything … -
Cannot open any page when implemented next parameter in Django 3.2
I am using Django 3.2. I have my custom LoginView and I'd like to implement the next parameter so if somebody will try to access the page where login is required then after log-in it will redirect the user to this page. I have seen many solutions but they are old and I cannot implement them in my code. views.py class UpdatedLoginView(LoginView, CategoryMixin, TagMixin): form_class = LoginForm template_name = 'user/login.html' redirect_field_name='main/homepage.html' def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): if 'next' in request.POST: return redirect(request.POST.get('next')) else: return(redirect('homepage')) else: return render(request, self.redirect_field_name, {'form': form}) class HomePageView(LoginRequiredMixin, TemplateView): template_name = "main/homepage.html" login.html <form method="post" novalidate> {% csrf_token %} {{ form|crispy }} {% if request.GET.next %} <input type="hidden" name="next" value="{{ request.GET.next }}"/> {% endif %} <button type="submit">Login</button> </form> settings.py LOGIN_REDIRECT_URL = 'homepage' LOGOUT_REDIRECT_URL = 'login' The problem with my solution is that it redirects me to homepage but once I click on any hyperlink it redirects me to login page again and the url looks like this: http://127.0.0.1:8000/?login=/article_list/ In all my views I am using LoginRequiredMixin mixin. How can I fix this issue? -
Django tests self.client.post using wrong url
I have a test which throws a NoReverseMatch exeption. In the test I define the url add_collection_url = reverse('add-cc-collection', args=[client.code, order.code]) and I can check that the url is found print(add_collection_url) which finds the correct url /crm/clients/A00001/order/O00001/add-cc-collection/ However, on the next line I post to the url response = self.client.post(add_collection_url, {'order': order.id, 'deadline': deadline, 'instructions': "Some instructions etc"}) and this line throws the exception django.urls.exceptions.NoReverseMatch: Reverse for 'add-collection' not found. 'add-collection' is not a valid view function or pattern name. note the reference to 'add-collection', which was the name of the url before I changed it to 'add-cc-collection'. When I run the server everything works as it should, it's just the test which throws the exception. My guess is something weird happening with caching but, for what it's worth I make sure to cache.clear() in TestCase tearDown -
Django model with multiple inheritance raises 'django.core.exceptions.FieldError' exception on delete
I am using django 3.2. I am writing a social app, which necessitates (makes necessary) the use of multiple inheritance. I am having a problem with one of the inheritable models, in that when I inherit from that model, I can't delete instances of the derived (child) class. Code (relevant parts only): class Actionable: def __init__(self, *args, **kwargs): self.owner = None self.owner_id = None self.actionable_object = None self.ct = None self.object_id = None self.is_setup = False def setup_variables(self, args): if not self.is_setup: self.owner = args['owner'] self.owner_id = args['owner_id'] self.actionable_object = args['actionable_object'] self.ct = args['ct'] self.object_id = args['object_id'] self.is_setup = True # This MUST be implemented by ALL CONCRETE sub classes @abstractmethod def get_actionable_object(self): raise NotImplementedError("Subclasses MUST implement get_actionable_object()") # This MUST be implemented by ALL CONCRETE sub classes @abstractmethod def get_owner(self): raise NotImplementedError("Subclasses MUST implement get_owner()") # .... class SocialActivity(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, db_index=True, related_name='%(app_label)s_%(class)s_content_types', related_query_name='%(app_label)s_%(class)s_content_type') object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey('content_type', 'object_id') actor = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s_users', related_query_name='%(app_label)s_%(class)s_user') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"SocialActivity: {self.content_type.name}, {self.object_id}, {self.actor.username}, {datetime.strftime(self.created_at,'%Y-%B-%d %H:%M:%s')} " class Meta: abstract = True constraints = [ models.UniqueConstraint(fields=['content_type', 'object_id', 'actor'], name="%(app_label)s_%(class)s_user_unique") ] class SocialMediaSharingPlatform(models.Model): name = models.CharField(max_length=64, unique=True) endpoint = models.URLField() post_params = JSONField() … -
Python based web application using Panel/ Dash
I am exploring different python libraries like Panel/ Dash for building an analytics tool. My question is should I consider using a Django framework and then integrating Panel/Dash features in Django? Or, if I have experience with web app development (in JS) can I just go for building the app purely using Panel/ Dash? (I know that there are Django + Dash and pure Dash applications out there; just trying to understand the pros/ cons of these options) Thanks in advance for your answers! -
NameError at / name 'HttpResponce' is not defined
enter image description here enter image description here from django.http import HttpResponse from django.shortcuts import render Create your views here. #i'm trying to print hello world in django but i'm facing error's def fun(request): return HttpResponce("hello world") -
Django: FileNotFoundError: [Errno 2] No such file or directory: 'pdflatex': 'pdflatex' during generate a pdf with latex
i want to generate a pdf with latex in my django application , I have tried this but it gives me an error. This is my views.py: if request.user.is_authenticated: if request.method == 'POST': form = ReportForm(request.POST, ) form.instance.user=request.user if form.is_valid(): form.save() obj_Formulaire = MyModel.objects.filter(user=request.user).last() field_obj_load_between_posts = MyModel._meta.get_field('load_between_posts') field_value_load_between_posts = field_obj_load_between_posts.value_from_object(obj_Formulaire) load_between_posts = field_value_load_between_posts if load_between_posts == True: field_obj_custom_load = MyModel._meta.get_field('custom_load') field_value_custom_load = field_obj_custom_load.value_from_object(obj_Formulaire) qh = float(field_value_custom_load) else: qh = float(0) context = { 'qh': qh, } template = get_template('pages/my_latex_template.tex') rendered_tpl = template.render(context).encode('utf-8') # <3> with tempfile.TemporaryDirectory() as tempdir: # <4> for i in range(2): process = Popen( ['pdflatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') # <5> r.write(pdf) return r form = ReportForm() context = {'form': form} return render(request, 'pages/form_gelander_report.html', context) ----> but it gives me : FileNotFoundError: [Errno 2] No such file or directory: 'pdflatex': 'pdflatex' How i could solve this error. THANKS IN ADVANCE. -
ModuleNotFoundError: No module named 'decouple'
I have a working Django project. If I run it - everything works fine Here is the structure of the project titest_project tibrains_app tools __init__.py load_django.py countries_add.py apps.py models.py load_django.py import sys import os import django sys.path.append('/mnt/HDD/tibrains/03/titest_project') os.environ['DJANGO_SETTINGS_MODULE'] = 'titest_project.settings' django.setup() countries_add.py import load_django from tibrains_app.models import ShopCountry When I run countries_add.py it gives the error - No module named 'decouple'. Though when I run the project itself - it works without errors. What could be the problem? -
Django post_delete instance is still present in the database
One of the keyword argument in he post_delete is the instance, which is the actual instance being deleted. According to the django docs - Note that the object will no longer be in the database, so be very careful what you do with this instance. I am testing the following code -> @receiver(post_delete, sender=Dummy) def post_delete_callback(**kwargs): print('inside post_delete ----------') instance = kwargs.get('instance') raise Exception('Exception from the post delete receiver') But even after the exception, the object should be deleted in the database, but I am getting the exception, as well as the object is not getting deleted from the database. In case of pre_delete signal this is justifiable, but what is with the post_save signal? Am I missing something here? -
Django Sum by category
Sorry if the question has already been asked elsewhere. I have a travel tool. I have my travel model, containing the activity model. Each activity has a category and a price. I would like to add up the prices of the activities for each category, and I admit I am stuck. models.py : class Activity(models.Model): TRANSPORT = 'Transport' HEBERGEMENT = 'Hébergement' RESTAURATION = 'Restauration' LOISIR = 'Loisir' ROLE_CHOICES = ( (TRANSPORT, 'Transport'), (HEBERGEMENT, 'Hébergement'), (RESTAURATION, 'Restauration'), (LOISIR, 'Loisir'), ) category = models.CharField(max_length=30, choices=ROLE_CHOICES) trip = models.ForeignKey(Trip, null=True, blank=True, on_delete=models.SET_NULL) place = models.ForeignKey(Place, null=True, on_delete=models.SET_NULL) date_start = models.DateField(default=date.today) time_start = models.TimeField(auto_now=False, auto_now_add=False, null=True, blank=True) date_end = models.DateField(default=date.today) time_end = models.TimeField(auto_now=False, auto_now_add=False, null=True, blank=True) visitor = models.ManyToManyField(Character) price = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) prepaid = models.BooleanField(null=True) class Meta: verbose_name_plural = "Activities" views.py : def travel_detail(request, travel_id): travel = get_object_or_404(Trip, id=travel_id) activities = Activity.objects.filter(trip_id=travel_id) travellers = travel.traveller.all().order_by("last_name", "first_name") prices = Activity.objects.aggregate(Sum('price')) template = 'travel/travel_detail.html' context = { 'travel': travel, 'activities' : activities, 'travellers' : travellers, 'prices' : prices, } return render(request, template, context) template : {% for price in prices %} {{prices}} {% endfor %} My template returns this for now: {'price__sum': Decimal('43.6000000000000')} -
can we cache count query before request hits django
I have home page which lists from a very large table. It is paginated by PageNumberPagination. The loading time of this page is affected because of the count() query of the paginator. I resolved slowness for all other requests by installing django-cachalot. However the first request still takes up a lot of time. I tried to create a fake request in AppConfig.ready() so that the count() query gets cached every time when the project loads up. But it didn't work. Is there a clean hack for caching the count(*) query before the first request is made? -
JSON decode error JSONDecodeError at /admin/forms/export-entries [closed]
This is code in my views.py file where i am getting error for n in entries: row = [n.id] columns = n.columns.all() for col_id in cols: exist = False for d in columns: if col_id == d.field_id: exist = True row.append(d.value) elif type(col_id) == str: x = col_id.split('_') if int(x[0]) == d.field_id: dic = json.loads(d.info) l_key = '_'.join(x[1:]) if l_key in dic: exist = True row.append(dic[l_key]) I am getting error in this line dic = dic = json.loads(d.info) i am getting entries from my database and making its csv file and give it to user to dowload it from my website