Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make fixtures for the standard Django's apps
I need to make the fixtures for the redirect app. For site I use: python3 manage.py dumpdata sites --indent 2 > fixtures/sites.json So I tried to use the code below to make the fixtures for redirect: python3 manage.py dumpdata redirect --indent 2 > fixtures/redirect.json But I see the error below: CommandError: No installed app with label 'redirect'. I need to make the fixtures for all standard app, like migrations and the others in the image below. -
Counting number of rows in the table of mysql database and printing in django webapplication
I have successfully connected Django forms with backend (MySQL) , now I have to count the rows in the table created and print its output in an HTML webpage of my Django web application. How can I do it? -
django.db.utils.DatabaseError how to fix it
I am new to django, I have created a project and apps and I would like to connect my project to the mongodb. when I enter python manage.py migrate command , I am getting below mentioned error. Terminal Output: Operations to perform: Apply all migrations: HomePage, YouTube, admin, auth, contenttypes, forum, sessions, star_ratings Running migrations: Applying star_ratings.0004_auto_20220420_1458...Not implemented alter command for SQL ALTER TABLE "star_ratings_rating" ALTER COLUMN "id" TYPE long Traceback (most recent call last): File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 784, in __init__ self._query = self.parse() File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 876, in parse raise e File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 889, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 425, in __init__ super().__init__(*args) File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 84, in __init__ super().__init__(*args) File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 441, in parse self._alter(statement) File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "star_ratings_rating" ALTER COLUMN "id" TYPE long',) Params: ([],) Version: 1.3.6 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/a2019/opt/miniconda3/envs/myEnv/lib/python3.9/site-packages/django/db/backends/utils.py", … -
Ajax can not get data from Django view
I have a request to use Ajax to get data from Django views. This project was generated through cookiecutter Here is my code: config/urls.py: # API URLS urlpatterns += [ # API base url path("api/", include("config.api_router")),] ./config/api_router.py: from django.conf import settings from django.urls import path from rest_framework.routers import DefaultRouter, SimpleRouter from project.users.api.views import UserViewSet from app import views if settings.DEBUG: router = DefaultRouter() else: router = SimpleRouter() router.register("users", UserViewSet) app_name = "api" urlpatterns = router.urls urlpatterns += [ path("chart-data", views.chart_data), ] app/views.py: from django.shortcuts import render from django.http import JsonResponse def chart_data(request): return render(request, 'pages/home.html') def click(request): data_for_ajax = { 'a': {1: 1, 2: 2}, 'b': {3: 3}, 'c': {4: 4, 5: 5} } return JsonResponse(data_for_ajax) project/templates/pages/home.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <script defer src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script> function click() { $.ajax({ type: "GET", url: "api/chart-data", success: function(data) { console.log(data); } }) </script> </head> <body> <button onclick="click()">Click me</button> </body> When I accessed http://localhost:8000/api/chart-data and clicked the "Click me button", there is nothing in the console, and there is no error. -
How to enable autocomplete for Django HTML files in Pycharm?
I would appreciate some help with getting my Django HTML files color coded correctly. Currently none of the variables or tags are recognized by Pycharm. However, within the same file the basic html syntax is recognized (autocomplete and color coded): [snipped of Pycharm code1 I have tried to add Django in: Setting > Color Scheme Settings > Languages & Frameworks But it does not seem to show as an option. It is quite cumbersome to have to write each variable and tag manually. Thanks in advance. -
How to loop something to send in one email in Django
I like to send email to myself that contains the name of users who matches the criteria. My problem is that if I use the for loop in the mass_mail it sends every results in separated emails. So if I have 6 results it sends the email 6 times containing one results in every emails: (I am using the mass_mail because in the future I like to send emails to more users not just me.) user_weekly.py from django.core.management.base import BaseCommand from xy.models import Profile from django.core.mail import send_mass_mail recipient_list = Profile.objects.raw('SELECT * FROM auth_user LEFT JOIN xy_profile ON auth_user.id = xy_profile.user_id WHERE email = 1') messages = [(subject, 'Hello! Users are the following:' + r.last_name, from_email, ['my@email.com]) for r in recipient_list] send_mass_mail(messages) How can I reach that to send all the results in one email and not 6 separate emails in this case? I also tried that to make a variable like this: reclist = r.last_name but in this case it sends only one email with only one user's name. What should I do to get all the user's names in one email? -
model_type in Django template
I am learning Django from a book called Web Development with Django. In one of the activities there is a tag in one of the templates as below: {% block title %} {% if instance %} Editing {{ model_type }} {{ instance }} {% else %} New {{ model_type }} {% endif %} {% endblock %} what is the model_type? I have never seen this tag before. It is not in any of the view.py functions or anywhere else. Thank you -
How do I configure ORM if I want to reference foreign keys for a particular column?
class Member(models.Model): user_Id = models.CharField(max_length=50, primary_key=True) user_Nick = models.CharField(max_length=10, unique=True) user_Name = models.CharField(max_length=10) user_Driver = models.IntegerField() user_Phone = models.CharField(max_length=30, unique=True) user_Points = models.IntegerField(default=0) user_Email = models.CharField(max_length=50, unique=True) def __str__(self): return self.user_Id class Meta: db_table = 'TB_MEMBER' class LogPoint(models.Model): pot_Id = models.ForeignKey( "Member", related_name="MemberId", on_delete=models.CASCADE, db_column="pot_Id" ) pot_Amount = models.ForeignKey( "Member", related_name="MemberAmount", on_delete=models.CASCADE, db_column="pot_Amount" ) pot_date = models.DateTimeField(auto_now_add=True) pot_Reason = models.CharField(max_length=20) pot_Change = models.IntegerField() def __str__(self): return self.pot_Id class Meta: db_table = 'TB_LOGPOINT' I want to refer to the attribute user_Points in the User model as Foreign Key. I've done migration, but I don't think it's properly referenced because the data type becomes varcar, not integer. How do I configure ORM if I want to reference foreign keys for a particular column? -
Django ORM returns non-iterable object
Code Screenshot WeeklyStrMst.objects.filter(StoreId__in=stores).values() Here stores is of list datatype containing 6000-30000 values which are non-null, integer, so when I execute this, it returns me - <django.db.models.query.QuerySet object at 0x0000024FD4EAAAF0> I have tested with less than 2000 values it works fine. What could be possible reason and workaround for this scenario? How to pass a large list of array as a filter criteria? -
How to find db records valid from a certain date
Requirement I have a project where I want to store a list of prices for a given product, which are supposed to be valid after a certain date. The 'current_price' should show up on the Product list admin page (depending on the date of request) Problem My current implementation leads to excessive database queries Example product prices over time Product valid from Price 1 2022-03-01 100 EUR 1 2022-04-01 120 EUR 1 2022-05-01 130 EUR 2 2022-03-01 30 EUR 2 2022-04-01 40 EUR 2 2022-05-01 50 EUR expected result e.g. on 2022-03-15 PRODUCT CODE NAME CURRENT PRICE 2 Second product 30.00 1 First Product 100.00 e.g. on 2022-04-30 PRODUCT CODE NAME CURRENT PRICE 2 Second product 40.00 1 First Product 120.00 Code (working) I get the desired results when using the following code: models.py from django.db import models class Product(models.Model): product_code = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=100) def __str__(self) -> str: return self.name class ProductPrice(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='prices') valid_from = models.DateField() price = models.DecimalField(max_digits=8, decimal_places=2) class Meta: get_latest_by = 'valid_from' admin.py from django.contrib import admin from . import models import datetime @admin.register(models.Product) class ProductAdmin(admin.ModelAdmin): list_display= ['product_code','name', 'current_price'] def current_price(self,product): current_date = datetime.datetime.now() return product.prices.filter(valid_from__lte=current_date).latest().price def get_queryset(self, request): return super().get_queryset(request).prefetch_related('prices') … -
Moving data from a table sqlite to a new one in django
How can I move data from a sqlite tabla to another one using django? I need to do this because I want to use the table after for training a NN. -
Validation for UserCreationForm not working Django
Everything seems to be working fine, but if the form doesn't validate, instead of getting HTML validation errors, I get ValueError ar /register/: The user.register didn't return an HTTPResponse. It returned none instead. My code: if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Acount created!') else: form = UserCreationForm(): return render(request, 'users/register.html', {"form":form}) -
Django [TemplateDoesNotExist]
I am getting an error message when running server for making a django login faeture and cannot figure out why I am getting this error.. help is appreciated vs code log django error -
how to make a category of product visible in menu in all pages in django
html inside layouts and i make extends in other pages, all work fine but category menu (come from database) is hidden in some pages and i can see it just in one pages there is my code : def produit_list(request): produits = Produits.objects.all() categories = Category.objects.all() context = { 'produits':produits, 'categories':categories, } return render(request, 'shop.html', context) #categories.html <div class="col-md-4 pt-5"> <h2 class="h2 text-light border-bottom pb-3 border-light">Categories</h2> <ul class="list-unstyled text-light footer-link-list"> {% for cat in categories %} <li><a class="text-decoration-none" href="#">{{cat.name}}</a></li> {% endfor %} </ul> </div> i include this code inside base.html i want know how to load it in all website like menu in bottom of every page, now i can see it just in shop.html. Thank you -
How to restrict non-superuser users to delete with Django CBV?
I am using a function based view that restricts any users except the superuser to delete something and route the user to the same page site-list regardless if user is restricted or not. It is perfectly working. Here that working code: @login_required def delete_site(request, pk): site = TargetSite.objects.filter(primary_key=pk).first() if request.method == 'POST' and request.user.is_superuser: site.delete() messages.success(request, f'Successfully deleted "{site.site_name}" ', extra_tags='check') return redirect('site-list', project=site.project) else: messages.warning(request, f'Sorry, you\'re not authorized to execute this request', extra_tags='exclamation') return redirect('site-list', project=site.project) However, when I tried the CBV, it does not work same as the function based. The non-superuser is able to delete and not restricted: class SiteDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = TargetSite def test_func(self): site = self.get_object() if not self.request.user.is_superuser: messages.warning(self.request, f'Sorry, you\'re not authorized to execute this request', extra_tags='exclamation') return reverse('site-list', kwargs={'project': site.project}) return True def get_success_url(self): messages.success(self.request, f'Successfully deleted "{ self.object.site_name}" ', extra_tags='check') return reverse('site-list', kwargs={'project': self.object.project}) I also tried this one with test_func(self), but it just threw a 403 Forbidden message and does not route the user to the same site-list page. I believe I'm missing something. Can you please help? def test_func(self): if self.request.user.is_superuser: return True return False -
How do I specify the path of the config class in INSTALLED_APPS in Django?
The following tree, show my Django project structure. Now, in plain English, how do I add a new entry to INSTALLED_APPS in Django setting.py? (have already wasted 6 hours on this :( | manage.py | db.sqlite3 | +---journal | | asgi.py | | settings.py | | urls.py | | wsgi.py | | __init__.py | \---apps \---cards | admin.py | apps.py | models.py | tests.py | urls.py | views.py | __init__.py -
Django+React, API connection doesn't work
[Django + React API Communication fail][1] [1]: https://i.stack.imgur.com/IaSYY.jpgstrong text -
how to create download link for django uplouded files
ihave three types of files iam uploading (book,slide,question) so iwant to add this files to the a element to download this uploaded files sorry iam not very good in django and this is my last code in my project so can any body solve this for me .. and please tell me what i should put between href double couts def course_directory_path(instance, filename): return f'MU/Materials/{instance.number}/{filename}' def file_directory_path(instance, filename): if instance.type == "Slide": folder = "Study-materials" elif instance.type == "Book": folder = "Text-Books" elif instance.type == "Question": folder = "Exams-and-Homeworks" _, file_extension = os.path.splitext(filename) return f'MU/Materials/{instance.course.number}/{folder}/{instance.name}{file_extension}' class Course(models.Model): number = models.CharField(max_length=7, primary_key=True) name = models.CharField(max_length=30) # All Files download link # All Books download link # All Slides download link # All Questions download link bg_image = models.ImageField(upload_to=course_directory_path, null=True, default="defult_course.jpg") image = models.ImageField(upload_to=course_directory_path, null=True, default="defult_course.jpg") # Book picture for the card youtube = models.URLField(max_length=200, null=True, blank=True) discord = models.URLField(max_length=200, null=True, blank=True) whatsapp = models.URLField(max_length=200, null=True, blank=True) def all_files(self): files = File.objects.filter(course=self) s = StringIO.StringIO() with zipfile.ZipFile("", mode="w") as archive: for filename in files: print(f"{filename.file.url =}") fdir, fname = os.path.split(filename.file.url) print(f"{fdir = }, {fname = } ") zip_path = os.path.join("MU/Materials", fname) archive.write(filename.file.url, zip_path) return "multiple_files.zip" def __str__(self): return self.name class College(models.Model): number … -
How to do multiple request POST in django?
I have a view that sends a form to another view so that the user can review his form, and then after making another request post to save at that moment... so when the user enters the review view, he enters in request.POST and the form ends up being saved at the wrong time def resumo(request, avaliado_id): print(request.method == 'POST') perfil = Perfil.objects.filter(user_id=avaliado_id) queryDict = request.POST notas = (list(queryDict.values())) criterios = (list(queryDict.keys())) valores = (list(queryDict.values())) valores = [float(x.replace(",",".")) for x in valores[2:]] pesos = (queryDict.getlist('pesos')) pesos = [float(x.replace(",",".")) for x in pesos] res_list = [valores[i] * pesos[i] for i in range(len(valores))] media = sum(res_list) lista = zip(criterios[2:], notas[2:]) print(list(lista)) query_criterio = Criterio.objects.filter(ativo = True).values_list('id', flat=True) lista_criterio_id = list(query_criterio) if request.method == 'POST': avaliado = Perfil.objects.get(pk = avaliado_id) avaliador = request.user.perfil avaliacao = Avaliacao.objects.create(avaliador = avaliador, avaliado= avaliado, media = media) avaliacao.save() print(avaliacao.id) for nota, criterio in zip(notas[2:], lista_criterio_id): nota = Notas.objects.create(avaliacao = Avaliacao.objects.get(pk = avaliacao.id), notas = nota, criterios = Criterio.objects.get( pk = criterio)) nota.save() context = { 'media' : media, 'chaves_e_valores' : zip(criterios[2:], notas[2:]), 'perfis' : perfil, } return render(request, 'admin/resumo.html', context) in the first line "request.method == 'POST'" returns True and because of that it ends up hitting … -
Django REST - Invalid data. Expected a dictionary, but got {datatype}
Using DRF I'm attempting a PUT request to update a file in my database. I'm receiving the error seen in the title, exactly Invalid data. Expected a dictionary, but got {datatype}.. The full body says this (serializer.error_messages): { "required": "This field is required.", "null": "This field may not be null.", "invalid": "Invalid data. Expected a dictionary, but got {datatype}." } I don't see any additional helpful information in the terminal, just this exactly. My model is this: from django.db import models class File(models.Model): name = models.CharField(max_length=1024) upload_timestamp_date = models.DateField(auto_now_add=True) upload_timestamp_time = models.TimeField(auto_now_add=True) file = models.FileField() def __str__(self): return self.name My serializer is this: from rest_framework import serializers from .models import File class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = '__all__' My view so far is this: @api_view(['GET', 'PUT', 'DELETE']) @csrf_exempt def file(request, file_id, format=None): try: data = File.objects.get(pk=file_id) except File.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = FileSerializer(data) return Response({'file': serializer.data}, status=status.HTTP_200_OK) elif request.method == 'PUT': serializer = FileSerializer(data, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST) It comes down to the is_valid() call being false, with those error messages. I know that a GET request returns data like this: { "file": { "id": 1, "name": "test", … -
Django request doesn't save the logged in user
So I'm starting to learn Django authentication. from django.contrib.auth import login as log_in def login(request): ... if request.method == "POST": form = UserLoginForm(request.POST) if form.is_valid(): user = User.objects.filter(email=form.cleaned_data["email"]) if user.exists(): user = user.first() if check_password( form.cleaned_data["password"], user.password ): log_in(request,user) return redirect("/main/") else: messages.warning(request, "email/password are incorrect") else: messages.warning(request, "User not found") ... and I'm trying to access the request.user in another view like this: if request.user.is_authenticated: #do somthing but while debugging I found that after the first code log_in() statement the request.user is authenticated, but in the seconed code it's not. -
Why is Django generating a new session_key every time I refresh and hit a route?
I don't have SESSION_EXPIRE_AT_BROWSER_CLOSE set to true, I don't have req.session.modified set to true. And it seems like my browser cookie has a session id that's not changing on refresh. BUT, when I refresh the page and it re-hits the route, poof, I get a new session_key. So what could be causing this? I would like to keep the same session key, because I'm using it for user analytics tracking. -
IntegrityError at /signup UNIQUE constraint failed: auth_user.username
I'm trying to make an authentication system using Django using only 3 fields for SignUp (username & email & password ) and 2 fields for sign in ( username & password ) I think that the error that I get has relation to database, which I haven't used my models file yet, I don't know where the problem is coming from, is it from the signup function or the signing function IntegrityError at /signup UNIQUE constraint failed: auth_user.username Request Method: POST Request URL: http://127.0.0.1:8000/signup Django Version: 3.2.6 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: auth_user.username Exception Location: C:\Users\dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\dell\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.0 Python Path: ['C:\\Users\\dell\\Desktop\\greenaftech', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32\\lib', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\Pythonwin'] Server time: Sat, 30 Apr 2022 00:24:12 +0000 this is my views.py: from django.shortcuts import render,redirect from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib import messages # Create your views here. def home(request): return render(request,"website/index.html") def signup(request): if request.method=="POST": username=request.POST.get('username') password=request.POST.get('password') email=request.POST.get('email') myuser= User.objects.create_user(username,email,password) myuser.save() messages.success(request,"Your Account has been created.") return redirect('signin') return render(request,"website/signup.html") def signin(request): if request.method=='POST': usern=request.POST.get('username') passs=request.POST.get('password') user=authenticate(username=usern,password=passs) if user is not None: login(request,user) userr=user.username return render(request,"website/index.html",{'username':userr}) else: messages.error(request,"Wrong Infos") return redirect('home') return render(request,"website/signin.html") def … -
HTMX hx-trigger two functions
I have a selected dropdown list that triggers a function in my Django application. So I need to execute another function too. is it possible? this is the HTML code I tried to use hx-trigger with load after 0.5s but is executed once before the user selects the item! then I moved the function inside the page that it run after the user selects the item. it works but the returned request is shown in the wrong place! and I need it to be at the down of the page? <div class="col-md-3"> <select class="custom-select mb-4" name="fields" hx-get="{% url 'select_field' %}" hx-trigger="change" hx-target="#Wells" hx-include="[name='Toggle']"> <option selected>Select a field</option> {% for Field in TFTFields %} <option ue="{{Field.Perimeter}}">{{Field.Perimeter}}</option> {% endfor %} </select> </div> <div class="row"> <div class="col-md-12" > <div id="Wells"> {% include 'Home/Data_visa/part_Wells.html' %} </div> </div> </div> <div class="col-md-12" > <div id="part_MyWellsList"> {% include 'Home/Data_visa/part_MyWellsList.html' %} </div> </div> And this my part_Wells.html as <div class="col-md-3" > <select class="custom-select mb-4" name="Wells" hx-get="{% url 'addplotly' %}" hx-trigger="change" hx-target="#plotly_production" hx-include="[name='Toggle']"> <option selected>Select Well</option> {% for well in TFTWells %} <option value="{{well.WellID}}">{{well.WellID}}</option> {% endfor %} </select> </div> <div id="part_MyWellsList" class="d-inline-flex" hx-get="{% url 'LoadWells' %}" hx-trigger="load delay:0.5s" hx-include="[name='fields']"> </div> and this part_MyWellsList page: {% if FieldWells %} <div … -
Dynamically Sending Email
I have email verification working in Django, it sucessfully sends an email to inbox when I click the submit button at the bottom of the signup page, but the only problem is that it does not yet have the function where it sends an email to the address of the user who just signed up, instead, it only sends the email to the email address hard coded in the views .py file . Signup page: Views.py: Settings.py Register.html I don't even know where to begin here. I think I need a get function to pull the value from the email address form field, but I have no clue how I would even get that. Anyone have any idea?