Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Combining serializers and sorting with filtering
I have a problem with the API JSON (serializers). I need to display only the last added price for a store and sort by lowest price for an article. There is no possibility to change the relationship in the database. DB schema looks like. DB Schema models.py from django.db import models class Shop(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.data() def data(self): return "{}".format(self.name) class Article(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.data() def data(self): return "{}".format(self.name) class Price(models.Model): article = models.ForeignKey(Article, on_delete=models.PROTECT, related_name='prices') shop = models.ForeignKey(Shop, on_delete=models.PROTECT, related_name='shops') name = models.CharField(max_length=100) date = models.DateField(null=True, blank=True) def __str__(self): return self.data() def data(self): return "{} {}".format(self.name, self.date) serializers.py from .models import Article, Price, Shop from rest_framework import serializers class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = ['name', 'date'] class ShopSerializer(serializers.ModelSerializer): prices = PriceSerializer(many=True) class Meta: model = Shop fields = ['name', 'prices'] def to_representation(self, instance): bdata = super().to_representation(instance) bdata ["prices"] = sorted(bdata["prices"], key=lambda x: x["date"], reverse=False) return bdata class ArticleSerializer(serializers.ModelSerializer): prices = PriceSerializer(many=True) class Meta: model = Article fields = ['name', 'prices'] views.py from .models import Shop, Article, Price from rest_framework import viewsets, permissions, filters from apitest.serializers import ArticleSerializer, PriceSerializer, ShopSerializer #from rest_framework.response import Response #from django.db.models import Prefetch class … -
Saving to database an object after celery task is finished successful
I'm a newbie and need some help with saving some datas after a successful celery task, i have these models and serializers: texts/models.py class MyTexts(models.Model): TxTitle=models.CharField(max_length=300) TxText=models.TextField() TxAnnotatedText=models.TextField(blank=True) TxAudioURI=models.CharField(max_length=200, blank=True) TxSourceURI=models.CharField(max_length=1000,blank=True) TxTLang=models.ForeignKey(Language, related_name="TextLang",on_delete=models.CASCADE) TxtUser=models.ForeignKey(Learner, related_name="TextUser",on_delete=models.CASCADE) TxtTag=models.ForeignKey(to="tags.MyTags",on_delete=models.CASCADE,related_name="TextTags",blank=True,null=True) TxtArchived=models.BooleanField(default=False) TxtDifficulty=models.IntegerField() def __str__(self) -> str: return self.TxTitle Learner/models.py class Learner(AbstractUser): SelLanguage=models.OneToOneField(Language,on_delete=models.CASCADE,null=True,related_name="SelLanguage") is_teacher=models.BooleanField(default=False) can_post=models.BooleanField(default=False) level=models.IntegerField(default=0) def __str__(self) -> str: return self.username Learner/serializer.py from django.contrib.auth import authenticate, get_user_model from djoser.conf import settings from djoser.serializers import TokenCreateSerializer User = get_user_model() class CustomTokenCreateSerializer(TokenCreateSerializer): def validate(self, attrs): password = attrs.get("password") params = {settings.LOGIN_FIELD: attrs.get(settings.LOGIN_FIELD)} self.user = authenticate( request=self.context.get("request"), **params, password=password ) if not self.user: self.user = User.objects.filter(**params).first() if self.user and not self.user.check_password(password): self.fail("invalid_credentials") # We changed only below line if self.user: # and self.user.is_active: return attrs self.fail("invalid_credentials") language/models.py class Language(models.Model): LgName=models.CharField(max_length=40) LgDict1URI=models.CharField(max_length=200) LgDict2URI=models.CharField(max_length=200) LgGoogleTranslateURI=models.CharField(max_length=200) LgExportTemplate=models.CharField(max_length=1000) LgTextSize=models.IntegerField() LgRemoveSpaces=models.BooleanField() LgRightToLeft=models.BooleanField() LgSkills=models.TextField() def __str__(self) -> str: return self.LgName language/serializers.py class LanguageSerializer(serializers.ModelSerializer): class Meta: model=Language fields='__all__' tags/models.py class MyTags(models.Model): T2Text=models.CharField(max_length=30,blank=True) T2Comment=models.CharField(max_length=200,blank=True) TagsUser=models.ForeignKey(Learner, on_delete=models.CASCADE,related_name="MyTagsUser",blank=True) TagsText=models.ForeignKey(to="texts.MyTexts",on_delete=models.CASCADE,related_name="MyTagsText",blank=True) TagsLang=models.ForeignKey(Language,on_delete=models.CASCADE,related_name="MyagsLang",blank=True) TagsArchived=models.BooleanField(blank=True) tags/serializers.py class MyTags(models.Model): T2Text=models.CharField(max_length=30,blank=True) T2Comment=models.CharField(max_length=200,blank=True) TagsUser=models.ForeignKey(Learner, on_delete=models.CASCADE,related_name="MyTagsUser",blank=True) TagsText=models.ForeignKey(to="texts.MyTexts",on_delete=models.CASCADE,related_name="MyTagsText",blank=True) TagsLang=models.ForeignKey(Language,on_delete=models.CASCADE,related_name="MyagsLang",blank=True) TagsArchived=models.BooleanField(blank=True) and these two endpoints in texts/view.py: @api_view(['POST']) def match_patterns_request_view(request): username = request.data.get("username" ) document = request.data.get("document") language = request.data.get("language") user=Learner.objects.get(username=username) priority=user.level task = match_patterns.apply_async(args=(username,document,language),priority=priority) return Response(status=status.HTTP_200_OK, data={"id":task.id}) @api_view(['GET']) def match_patterns_result_view(request, task_id): task_result = AsyncResult(task_id) # Check … -
how to pass `request` info to Django form Widget
I am trying to pass a filter queryset for a Django form widget. Normally, I would do something like # views.py class MyView(SuccessMessageMixin, CreateView): model = MyModel form_class = MyCreateForm template_name = 'create.html' success_message = "You new object has been created." success_url = reverse_lazy('mymodel-index') # forms.py class MyCreateForm(forms.ModelForm): class Meta: model = MyModel fields = [ 'title', 'car', # etc ] widgets = { 'car': forms.widgets.Select( required=True, queryset=Car.objects.all(), # I need to filter this to the current user ), } However, I need to filter the queryset (in the car select Widget) to by the currently logged in user. I could try passing the user to __init__ from the View, but I don't know how to access that from the Meta subclass. Any pointers in the right direction would be appreciated. -
Postgres db index not being used on Heroku
I'm trying to debug a slow query for a model that looks like: class Employee(TimeStampMixin): title = models.TextField(blank=True,db_index=True) seniority = models.CharField(blank=True,max_length=128,db_index=True) The query is: Employee.objects.exclude(seniority='').filter(title__icontains=title).order_by('seniority').values_list('seniority') When I run an explain locally I get "Gather Merge (cost=1000.58..196218.23 rows=7 width=1)\n Workers Planned: 2\n -> Parallel Index Only Scan using companies_e_seniori_12ac68_idx on companies_employee (cost=0.56..195217.40 rows=3 width=1)\n Filter: (((seniority)::text <> ''::text) AND (upper(title) ~~ '%INFORMATION SPECIALIST%'::text))" however when I run the same code on Heroku I get costs of 1000x, seemingly because the former is using an index while the second is not: "Gather Merge (cost=216982.26..216982.90 rows=6 width=1)\n Workers Planned: 2\n -> Sort (cost=215982.26..215982.26 rows=3 width=1)\n Sort Key: seniority\n -> Parallel Seq Scan on companies_employee (cost=0.00..215982.25 rows=3 width=1)\n Filter: (((seniority)::text <> ''::text) AND (upper(title) ~~ '%INFORMATION SPECIALIST%'::text))\nJIT:\n Functions: 4\n Options: Inlining false, Optimization false, Expressions true, Deforming true" I confirmed the model indexes are identical for my local database and on Heroku, this is what they are: indexname | indexdef ----------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------- companies_employee_pkey | CREATE UNIQUE INDEX companies_employee_pkey ON public.companies_employee USING btree (id) companies_employee_company_id_c24081a8 | CREATE INDEX companies_employee_company_id_c24081a8 ON public.companies_employee USING btree (company_id) companies_employee_person_id_936e5c6a | CREATE INDEX companies_employee_person_id_936e5c6a ON public.companies_employee USING btree (person_id) companies_employee_role_8772f722 | CREATE INDEX companies_employee_role_8772f722 ON public.companies_employee USING btree (role) companies_employee_role_8772f722_like | … -
Cannot assign "1": "Account.country" must be a "Country" instance
class MyAccountManager(BaseUserManager): ... class Country(models.Model): country_name = models.CharField(max_length=50) class Account(AbstractBaseUser): image = models.ImageField(upload_to='photos/profils/', default='media/photos/profils/constantly_img.jpg') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=50, unique=True) GENDER_CHOICES = [ ('MALE', 'Мужской'), ('FEMALE', 'Женской') ] gender = models.CharField(max_length=7, choices=GENDER_CHOICES) birthday = models.DateField() phone_num = models.CharField(max_length=50) password = models.CharField(max_length=50) country = models.ForeignKey(Country, on_delete=models.PROTECT) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'phone_num', 'country'] When i am creating the superuser in terminal and if i want to populate the Account.country field by binding it to the Country model. I got an error. What am I doing wrong? -
Django Windows ./manage.py
I have saw a lot of posts regarding about how to do ./manage.py for windows and linux but i find the instructions unclear as a beginner. I have tried using "chmod +x manage.py" in my django project directory ("C:\Users\user\Django\Project") in windows command prompt and it does not work as it is not recognised by an internal or external command. So how would you do this in Windows? -
ValueError: Cannot assign "'1'": "Post.user" must be a "User" instance
I am doing a group project for a bootcamp and we just started Django for the back-end. We also are using React for front-end. Our project is basically a knockoff reddit. We have a User model: `from django.db import models class User(models.Model): firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) email = models.CharField(max_length=100, unique=True) username = models.CharField(max_length=32, unique=True) password = models.CharField(max_length=255) def __str__(self): return '%s' % (self.username)` and a Post model: `from django.db import models from auth_api.models import User class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=255) formBody = models.TextField(null=True, blank=True) imageURL = models.CharField(max_length=200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True)` Our Post Serializers(pretty unfamiliar with this): `from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): user = serializers.CharField(required=True) class Meta: model = Post fields = ('id', 'user', 'title', 'formBody', 'imageURL', 'created',)` And our Post Views: `from django.shortcuts import render from rest_framework import generics from .serializers import PostSerializer from .models import Post from auth_api.models import User class PostList(generics.ListCreateAPIView): queryset = Post.objects.all().order_by('id') serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Post.objects.all().order_by('id') serializer_class = PostSerializer` The idea was when a user created a post their info would be saved with the post so that way when we display the post we could say who … -
Django website runs but none of the frontend shows
I am running my Django website using Amazon Linux EC2 instance. Everything runs correctly but for some reason, the actual front end of the website is not displayed. It even shows the title of the website in the search bar but can't display the actual content for me to interact with the website. It is just a white screen. Any help would be greatly appreciated. When I load the website, the GET requests display in my CLI: "GET / HTTP/1.1" 200 847, "GET /static/js/main.b1d3e335.js/ HTTP/1.1" 302 0, etc. I'm not sure what to try next. I used the collectstatic command for Django so I am thinking there may be a problem with the static files. But it is weird that my actual title of the website displays in the search bar but everything else is simply a white screen. -
Is it possible to include a view directly from the html?
I would like to know if it's possible, with Django, to include a view in another view like: Declare a view: def ads(request): param = ["first_ads_title"] return render(request, "blog/ads.html", context={"param": param}) With the following html : <div>ads {{ param[0] }}</div> And be able to call it from another html view like: <body> <h1>hello article {{ article }}</h1> {% include "blog/ads" %} </body> To display first_ads_title in my body ? -
AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'
I have been getting this error anytime i run my project with (runserver_plus --cert-file cert.crt)...I already installed the django extensions and pyOpenSSL I tried running without the (--cert-file cert.crt), that one seems to work fine buh doesnt provide me with what I am looking for . -
Is saving the user object to sessions safe to do when logging them in?
I am writing my own 2FA functionality (I know that django-otp and django-two-factor-auth exist, this is just for fun). Everything is fine except for the log in view. I know that you can use the following to authenticate the user: user = authenticate(request, username=cd['username'],password=cd['password']) login(request, user) What I want to do though is pass the user variable into the .view function that I will be using to do the 2FA on. That way, once the user enters their totp, I can use the already authenticated user as the user in the login function. Everything is fine other than on how to pass this data along. Is it safe security wise to pass the user along via sessions? I would do: request.session['authenticate_user'] = user And in the 2FA view put the following to retrieve the user: user = request.session.get('authenticate_user', None) I know that passing the password along is not safe, even if it is encrypted. Is the way I am proposing alright to do though? If not, what should you do instead? I have contemplated posting the password and user to the view using the requests module. Would this be security safe as an alternative, assuming it is not safe to … -
Merging Paginator and export html to xlsx and large amount of data
I'm trying to create a way to export the HTML table to xlsx, but I have a large amount of data in the queries. So I need to use pagination with Paginator so the browser doesn't load the data all at once and end up causing TimeOut. But when applying the Paginator and exporting, it only exports what is on the current page. Any suggestions to improve this code, such as creating a loop so that it can export all pages? View function: def export_project_data(request, pk): if str(request.user) != 'AnonymousUser': # só vai ter acesso se for diferente de AnonymousUser individuals_list = Individual.objects.filter(Project=pk) traps = Sample_unit_trap.objects.filter(Project=pk) page = request.GET.get('page', 1) paginator = Paginator(individuals_list, 1000) try: individuals = paginator.page(page) except PageNotAnInteger: individuals = paginator.page(1) except EmptyPage: individuals = paginator.page(paginator.num_pages) path_info = request.META['PATH_INFO'] context = { 'individuals': individuals, 'pk': pk, 'traps': traps, 'header': 'export_project_data', 'path_info': path_info } return render(request, 'inv/index.html', context) HTML paginator code: <div class="table-div"> {% if individuals.has_other_pages %} <ul class="pagination pagination-sm"> {% if individuals.has_previous %} <li><a href="?page={{ individuals.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in individuals.paginator.page_range %} {% if individuals.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ … -
Highcharts. Django won't load. Highcharts with Django
There is a wonderful library of js - Highcharts. I'm trying to link it to Django, and everything actually works, but not when I'm trying to insert a variable with content into data. Here's the code. This function returns what I substitute in data in Highcharts. def get_series(context): data_ser = [] for i in context: if i in ['One', "Two", "Three", "Four", "Five"]: data_ser.append({ 'name': i, 'y': context[i], 'z': 22.2 }) data_ser = json.dumps(data_ser) return data_ser And this is the jquery code itself <script> $(document).ready(function () { var data_ser = '{{ data_ser|safe }}' console.log(data_ser) Highcharts.chart('container', { chart: { type: 'variablepie' }, title: { text: 'Stats' }, series: [{ minPointSize: 10, innerSize: '20%', zMin: 0, name: 'countries', data: data_ser }] }); }) </script> In series in data, I try to substitute data_ser, but the graph is not output. Although, if you write it manually, then everything will work. Similar code works: `<script> $(document).ready(function () { var data_ser = '{{ data_ser|safe }}' console.log(data_ser) Highcharts.chart('container', { chart: { type: 'variablepie' }, title: { text: 'Stats' }, series: [{ minPointSize: 10, innerSize: '20%', zMin: 0, name: 'countries', data: [ { "name": "One", "y": 50.0, "z": 22.2 }] }] }); }) </script>` I really hope … -
I want to implement the dj-rest-auth Google OAuth feature, but I cannot understand where to get code to access google endpoints
I cannot understand where to get code or acsess_token to login user with google. I cannot find the endpoint to which I should send a request to get a code as a response. And I somewhat confused how to implement dg-rest-auth SocialAuth feature( I want my app to be able to login users with github, facebook and google). I have found these endpoint for Google OAuth2 https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=http://127.0.0.1:8001/ &prompt=consent&response_type=code&client_id=364189943403-pguvlcnjp1kd9p8s1n5kruhboa3sj8fq.apps.googleusercontent.com &scope=openid%20%20profile&access_type=offline Implicit Grant https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=http://127.0.0.1:8001/ &prompt=consent&response_type=code&client_id=364189943403-pguvlcnjp1kd9p8s1n5kruhboa3sj8fq.apps.googleusercontent.com &scope=openid%20%20profile Could you guys analyse my code and tell me what's wrong or what needs to be improved, please? And can you please provide me with a link to proper Google and Facebook Docs for OAuth2? settings.py Django settings for resume_website_restapi project. Generated by 'django-admin startproject' using Django 4.1.3. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-b#t)ywiymb&@+mv^%j$p&4*y)iq2z-1da*z@beo4s-6-qu9ba%' # SECURITY WARNING: don't run with debug turned on … -
In django, how do you code this type of relationship model?
here's my code: from django.db import models class Parent(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return str(self.name) class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) name = models.CharField(max_length=50, unique=True) def __str__(self): return str(self.name) Parents in my database: Rogan Smith Doe In admin dashboard: First, I create a child that has a name of John and his parent is Smith.. it works! Now, after that, whenever I create a child that also has a name of John and this time with a parent of Doe or Rogan, it says: "Child with this Name already exists." here I tried searching on google but I can't seem to find the answer. Not a native english speaker here, please bare with me. -
Not able to Sumit data from Vue Js to Django Rest
I built a web app with Vue js and Django, django rest framework , I am only able to post data from the backend. When I try and fill in the data from the form with vue js nothing posts. here is my code hope someone smart can solve this. Thank you for your help it is appreciated. I followed the tutorial from: https://blog.logrocket.com/how-to-build-vue-js-app-django-rest-framework/ I attempted it twice there may be some code issues with her code. but I am open for anyone to help thank you. Tasks.vue <template> <div class="tasks_container"> <div class="add_task"> <form v-on:submit.prevent="submitForm"> <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" v-model="title" /> </div> <div class="form-group"> <label for="description">Description</label> <textarea class="form-control" id="description" v-model="description" ></textarea> </div> <div class="form-group"> <button type="submit">Add Task</button> </div> </form> </div> <div class="tasks_content"> <h1>Tasks</h1> <ul class="tasks_list"> <li v-for="task in tasks" :key="task.id"> <h2>{{ task.title }}</h2> <p>{{ task.description }}</p> <button @click="toggleTask(task)"> {{ task.completed ? "Undo" : "Complete" }} </button> <button @click="deleteTask(task)">Delete</button> </li> </ul> </div> </div> </template> <script> export default { data() { return { tasks: [], title: "", description: "", }; }, methods: { async getData() { try { // fetch tasks const response = await this.$http.get( "http://localhost:8000/api/tasks/" ); // set the data returned as tasks this.tasks = response.data; … -
Django Aggregation on date field
Hi I have two following models class Store(models.Model): store_name = models.CharField(max_length=100) class Meta: db_table = 'stores' class Sales(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, related_field='sales') product_id = models.BigInteger() sale_date = models.DateTimeField() total_mrp = models.FloatField() I am trying to fetch sum(total_mrp) of each store day wise but seem to unable to group by date col in my Sales Table I am using django_rest_framework I tried to do above using following serializers class SalesSerializer(serializers.RelatedField): queryset = Sales.objects.all() def to_representation(self, value): data = self.queryset.annotate(day=functions.ExtractWeekDay('sale_date'), total_sale=Sum('total_mrp')) return data.values('day', 'total_mrp') class StoreSerializer(serializers.ModelSerializer): primary_sales = SalesSerializer(many=False) class Meta: model = Store exclude = ['id'] The output result doesn't get grouped as I expect. Instead I get same data for primary sales for each store. -
Django - Pass Form data in URL
I want to pass the forms data to another view (if possibleby GET params) def post(self, request): form = SomeForm(request.POST) if form.is_valid(): response = HttpResponse(reverse('page_to_go')) How can I accomplish that? -
Android app problem: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 207: invalid start byte
So I have two ubuntu servers stage and dev, and one single API for android, IOS and web front on reactjs. I get this error when I try to upload a photo to my server from ANDROID app, basically I can upload the same photo to DEV server from Postman and IOS, but I keep getting this error when I try uploading from android. But from the same android app I can upload this exact photo to stage server and prod server, so basically nothing wrong with android app, but something is wrong on the server, even tho it correctly works with IOS and postman and web app. I believe that the code and settings are almost the same on both servers, so I have no idea where is the problem... Traceback (most recent call last): File "/home/project/.local/share/virtualenvs/blabla_backend-B039YcMy/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/project/blabla_backend/dating/middleware.py", line 144, in call body_repl = str(request.body, 'utf-8').replace('\n', '') if request.body else 'null' UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 207: invalid start byte Uploading a photo from android just like from other apps, but it just dissapears and I get this error in django logs. But still same android app … -
Setting permissions by group in Django
I am working with a Django project that requires user, group, and permission management to be done only through the admin panel. So I used Django's user system and created a login with this view.py # Django from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from django.contrib import messages def LoginView(request): """ Login Se utiliza el modulo de usuarios de Django """ template_name = "login.html" if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) if request.user.groups.filter(name="administradores").exists(): return redirect('inicio') else: return redirect('listarS') else: messages.error(request, 'Error en el ingreso') else: messages.error(request, 'Error en CUIT o contraseña') context = {} return render(request, 'login.html', context) def LogoutView(request): """ Logout de Django """ template_name = "login.html" context = {} logout(request) return redirect(request, 'login.html', context) Groups are administradores and operadores. Users from operadores group only have permissions on specific model group permissions But when I add a user to this group: user group When logging in, this user can do anything (add, modify, delete or list) in any model of the application. How should I do so that the users of the operadores group only have the permissions of that … -
Adding values to cells in a specific column in HTML
I am creating a very basic table in HTML for my Django project. I got some help from Here to learn how to pass a list from my Django app to my HTML and generate rows for my values. My question this time is: how can I target the second, third, or any particular column for my list? For example, suppose I have a list of values and want to add all of them to Column 3 of my table. Here is the code I tried to use where i wanted to have {{ name }} values added to column two, but it keeps adding the cells to the first column <html> <body> <table border="1" cellpadding = "5" cellspacing="5"> <tr> <th> IDs </th> <th> Names </th> <th> Heights </th> </tr> {% for id in myIDs %} <tr> <td>{{ id }}</td> </tr> {% endfor %} <tr> {% for name in myNames %} <td> <tr> <td>{{ name }}</td> </tr> </td> {% endfor %} </tr> </table> </body> </html> -
image post feed with django does not display images
Currently working on a very simple social media and since yesterday the images in the post feed either disappear or i get a value error: ValueError at / The 'image' attribute has no file associated with it. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.16 Exception Type: ValueError Exception Value: The 'image' attribute has no file associated with it. Exception Location: C:\Users\Render_2\PycharmProjects\djangoProject\venv\lib\site-packages\django\db\models\fields\files.py, line 40, in _require_file Python Executable: C:\Users\Render_2\PycharmProjects\djangoProject\venv\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\Users\Render_2\PycharmProjects\djangoProject', 'C:\Users\Render_2\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\Render_2\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\Render_2\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\Render_2\AppData\Local\Programs\Python\Python37-32', 'C:\Users\Render_2\PycharmProjects\djangoProject\venv', 'C:\Users\Render_2\PycharmProjects\djangoProject\venv\lib\site-packages'] Server time: Thu, 05 Jan 2023 12:14:48 +0000 I have honestly no idea why it is messed up now, since it was running just fine yesterday morning. Please help me out to understand this issue. Here is the rest of the code. the index.html: {% for post in posts reversed %} <div class="bg-white shadow rounded-md -mx-2 lg:mx-0"> <!-- post header--> <div class="flex justify-between items-center px-4 py-3"> <div class="flex flex-1 items-center space-x-4"> <a href="#"> <div class="bg-gradient-to-tr from-yellow-600 to-pink-600 p-0.5 rounded-full"> <img src="{% static 'assets/images/avatars/user.png' %}" class="bg-gray-200 border border-white rounded-full w-8 h-8"> </div> </a> <span class="block capitalize font-semibold "><a href="/profile/{{ post.user }}">@{{ post.user }} </a></span> </div> <div> <a href="#"> <i class="icon-feather-more-horizontal text-2xl hover:bg-gray-200 rounded-full p-2 transition -mr-1 "></i> </a> <div … -
TemplateSyntaxError Could not parse the remainder: '"{%' from '"{%'
I have TemplateSyntaxError Could not parse the remainder: '"{%' from '"{%' and I don't know how to write the code in a different way. I tried JS but it also didn't work. <ul> {% for key1, value1 in menu.items %} <li><a href="{% url key1.slug %}" {% if request.path == "{% url key1.slug %}" %} class="active" {% endif %}>{{ key1 }}</a></li> {% endfor %} </ul> Highlighted in TemplateSyntaxError: {% if request.path == "{% url key1.slug %} jQuery(function($) { var path = window.location.href; $('a').each(function() { if (this.href === path) { $(this).addClass('active'); } }); }); -
Django q process does not get cleared from memory
I have integrated Django Q in my project and i'm running a task from django q but after task ran successfully i can still see the process is in memory is there any way to clear the process from memory after it has finished the job. Here is the django q settings Q_CLUSTER = { 'name': 'my_app', 'workers': 8, 'recycle': 500, 'compress': True, 'save_limit': 250, 'queue_limit': 500, 'cpu_affinity': 1, 'label': 'Django Q', 'max_attempts': 1, 'attempt_count': 1, 'catch_up': False, 'redis': { 'host': '127.0.0.1', 'port': 6379, 'db': 0, }} -
Sum and Annotate does not returns a decimal field Sum as a decimal
I am writing a query in which I want to Sum amount using annotate and Sum decimal field in a foreign key relationship. The field is summed correctly but it returns the Sum field in integer instead of decimal. In the database the field is in decimal format. The query is like... **models.objects.filter(SourceDeletedFlat=False).annotate(TotalAmount=Sum("RequestOrderList__PurchaseOrderAmount")).all(). I do not want to use aggregate because I don't need overall column sum.