Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Show list datetime values in template
I have below code which outputs datetime values as shown below: available_hours = [hour for hour in hours_between if hour not in reserved_times] print(available_hours) [datetime.datetime(2021, 12, 8, 12, 0), datetime.datetime(2021, 12, 8, 13, 0), datetime.datetime(2021, 12, 8, 14, 0), datetime.datetime(2021, 12, 8, 16, 0), datetime.datetime(2021, 12, 8, 17, 0), datetime.datetime(2021, 12, 8, 18, 0), datetime.datetime(2021, 12, 8, 19, 0), datetime.datetime(2021, 12, 8, 20, 0), datetime.datetime(2021, 12, 8, 21, 0)] I render them in the template like: {{ available_hours }} and i got all above datetime values. How can i change the format so i can show them like Mon 12 2021, 21:00? Thank you -
django cascade delete on 2 foreign keys of the same table
I have a model A and model B. Model B has 2 foreign keys to model A as shown. There is a 1 to many relationship between Model A to B such that a dataset (A) can have multiple data elements(B). Model A: id (primary key) dataset_id dataset_version dataset_name Model B: id (primary key) dataelement_id dataelement_version dataelement_name fk_dataset_id fk_dataset_version My question is: How to cascade delete a row from Model A such that the deletion occurs on Model B using fk_dataset_id and fk_dataset_version together ? Currently, django runs 2 separate queries to delete data from Model B on columns fk_dataset_id and fk_dataset_version but I want the deletion query to use an AND condition for deletion for e.g. DELETE from model B where B.fk_dataset_id = 1 AND B.fk_dataset_version = 3 Iam using a django rest framework with ModelViewSet for both Model A and B -
How to skip validation in django model serializers?
Its a general question. I have a code where I have implemented the validation of the serializer. Now when I make a post request and validate the data by is_valid function, it should run the validate method. But when I make a patch request it validates the data again. I want to skip this part because in my validate function I am validating data using some fields which are sent by the client during the post request but not during the patch request. I am not sure how to deal with this. Can someone help me with this ? -
Django ORM using external database to unmanaged model in view says relation does not exist
I have two Postgres database connections and when using another than default ORM calls fail on views, but not raw. I am using docker and containers are connected and using Django's own runserver command. Using ORM in django command or django shell works fine, but not in a view. As a side note, both databases are actually Django-projects, but main project is reading some data directly from another project's database using own unmanaged model. Python: 3.9.7 Django: 3.2.10 Postgres: 13.3 (main project), 12.2 (side project) # settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'pguser', 'PASSWORD': 'pguser', 'NAME': 'mainproject', 'HOST': 'project-db', # docker container 'PORT': '5432', }, 'external': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'pguser', 'PASSWORD': 'pguser', 'NAME': 'sideproject', 'HOST': 'side-db', # docker container, attached to same network 'PORT': '5432', }, } # My unmanaged model class MyTestModel(models.Model): class Meta: # table does not exist in 'default', but it does exist in 'external' db_table = 'my_data_table' managed = False # my_data_table is very simple it has id field as integer # and primary key (works out of the box with django) # it has normal fields only like IntegerField or CharField # But even if this model is empty then … -
Update inheritance for multiple objects using django signal
I am implementing django signals to update a model which has been inherited by multiple other models. For instance, class A: name = models.CharField(max_length=199, blank=True, null=True) class B(A): id = models.PositiveIntegerField() class C(A): id = models.PositiveIntegerField() class D(A): id = models.PositiveIntegerField() If there are any changes upon save, I want to perform an operation. My implementation for Signal is as follows: @receiver(post_save, sender=B) def base_update(sender, instance, **kwargs): try: obj = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: # raise an error else: # do something At the moment, it works for B , but if I consider rest of the models I'd end up replicating the same function with different sender names. Is there a way to make a generic Signal that applies to all the models that inherits A ? -
How to Make a div fit A4 page
I have a django admin action function that display Transactions and loops through as many as queryset selected that will be rendered in html page, and converts the html to pdf. I want at the pdf that each transaction object fit in A4, not to have another transaction object in same page. here is code.. def report_pdf(self, request, queryset): if request.user.is_superuser: transaction = queryset else: transaction = queryset.filter(user=request.user) template_path = "single-pdf.html" context = {"transactions": transaction} template = get_template(template_path) html = template.render(context) file = open('test.pdf', "w+b") pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') file.seek(0) pdf = file.read() file.close() return HttpResponse(pdf, 'application/pdf') and here is my html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Report</title> <style> </style> </head> {% for transaction in transactions %} <body> <div class="container"> {% if transaction.complete %} <table class="tg" > <thead> <tr> <th class="tg-4rlv">Report for Tenant</th> </tr> </thead> <tbody> <tr> <td class="tg-c6of" CHP Reference</span></td> <td class="tg-c6of">{{transaction.chp_reference}}</td> </tr> <tr> <td class="tg-c6of"> Rent Effective From(dd/mm/yyyy)</td> <td class="tg-c6of">{{transaction.rent_effective_date}}</td> </tr> <tr> <td class="tg-c6of"> CRA Fortnightly Rates valid for 6 months from</td> <td class="tg-c6of">{{transaction.cra_rate_from}}</td> </tr> <tr> <td class="tg-l8qj">Market Rent of the property :</td> <td class="tg-c6of">{{transaction.property_market_rent}}</td> </tr> <tr> <td class="tg-l8qj" >Number of Family Group(s) :</td> … -
Getting data from javascript ID to django views
how can I get data from javascript? lets say, my website show a input option, which I can't use with 'name="username"' like we do in forms, but it does that with document.getElementById('username') and show it later on site, is there anyway from which I can do the same with django? like request.POST.getById? I'm not good with english. -
Getting Django model.index has no field problem (django.core.exceptions.FieldDoesNotExist)
I am trying to create an index.The problem is that I am getting no 'has no field' error but I added that field. I tried to add that field but I got "column "click_count" of relation "oyunlar" already exists". How can i solve this situation? -
How can do not delete post and comment whose deleted user in django?
Hello i recently study django and make board my question was that how can do not delete post and comment whose deleted users how can display deleted user's name in post and comment like 'deleted user' in board's user name (not blank or Null) yeah i know in this code user was conneted with post and comment through foreign key and on_delete=models.CASCADE and if user deleted the post and comment deleted automatically then how can i connect this table? using nickname? it was unique but can changed i wanna know how to solve this problem, need to some tips class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) content = models.TextField() create_date = models.DateTimeField(default= timezone.now()) def __str__(self): return self.title class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField() create_date = models.DateTimeField(default=timezone.now()) -
VS Code not using selected python interpreter
What's up fellas. I always seem to have this problem and I've tried various ways of fixing it. Including creating the settings.json file that you can see in the picture attached. The problem: VS Code isn't using my selected python interpreter (pictured in the bottom left hand corner of photo) which is in venv/bin/python. Even though I can select it as the interpreter in vs code when I do python manage.py runserver for Django it gives me an error due to it using an older version of python that came with my computer. I just tried to use pycharm for the first time because of this and ended up having the same problem. Is it just that the terminal isn't using the right version of Python maybe? VS Code Version: 1.62.3 Also I am on iOS (M1) Let me know if I can provide you with any further information, thanks. [![Image of my vscode set up][1]][1] ➜ Akutagawa . venv/bin/activate (venv) ➜ Akutagawa which python /usr/bin/python (venv) ➜ Akutagawa which python /usr/bin/python (venv) ➜ Akutagawa cd Djanrest/backend (venv) ➜ backend git:(main) ✗ which python /usr/bin/python (venv) ➜ backend git:(main) ✗ python manage.py runserver File "manage.py", line 17 ) from exc … -
Добрый день, кто может подсказать как реализовать данную задумку на DJANGO REST
Схема работы: 1 Пользователь регистрируется в нашей системе. При регистрации указывает логин, пароль и имя 2 Пользователь находит бота в Telegram и подписывается на него. На этом этапе требуется создать Telegram бота. 3 В личном кабинете генерирует токен и привязывает этот токен к своему чату. Простой способ реализации: любое входящее сообщение от пользователя бот запоминает как токен пользователя 4 Пользователь отправляет на API своё сообщение. В этот момент бот сразу дублирует его в Telegram. Пользователь должен получать только свои сообщения. Добрый день, кто может подсказать как реализовать данную задумку на DJANGO REST, или же вы видели похожие проекты на github -
Django web project not running
My Web Application is not running on the new system it says it does not recognize "python"/ "pip as an internal and external command. My Powershell Terminal ''' PS C:\Users\Nawaf Bhatti\Desktop\learn> python -m pip install pillow python: The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + python -m pip install pillow + ~~~~~~ + CategoryInfo : ObjectNotFound: (python:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException ''' My cmd ''' C:\Users\Nawaf Bhatti\Desktop\learn\web_app>python manage.py runserver 'python' is not recognized as an internal or external command, operable program or batch file. ''' -
insert or update on table "django_admin_log" violates foreign key constraint
Trying to save a post on a django project I got this error The above exception (insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(1) is not present in table "auth_user". ) was the direct cause of the following exception: The model: from django.conf import settings class Tag(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField() image = models.ImageField(upload_to='', blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title The view: from django.views.generic import ListView, DetailView from django.shortcuts import get_object_or_404 from .models import Post class BlogView(ListView): template_name = 'base/blog.html' queryset = Post.objects.all() paginate_by = 2 class PostView(DetailView): model = Post template_name = 'base/post.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) pk = self.kwargs['pk'] slug = self.kwargs['slug'] post = get_object_or_404(Post, pk=pk, slug=slug) context['post'] = post return context How can I solve this problem? -
Able to run Dockerized Django app with supervisor locally, but timing out when deployed to Azure app services
So I have a Dockerized Django app running with uWSGI and NGINX, managed by supervisord (so both of them are run in the same container). It works fine and dandy when running it locally, but when I deploy it to a Azure web-app for containers, it fails to respond on the http warmup-request. I've tried doing different kinds of adjustments regarding the ports on Azure/in the app, but nothing seems to be working. The set-up I've been trying is: NGINX exposing the app in port 80, adding configuration in the Azure portal with PORT=80 NGINX exposing the app in port 8000, adding configuration in the Azure portal with PORT=80 and WEBSITES_PORT=8000 In both cases exposing both 80 and 8000 in the Dockerfile Increase the timeout-limit for the app to 1800 seconds But I'm still receiving the same error, and I really feeling I don't know where to go from here. Can anyone help me figure this one out? I'll post the logs and the relevant files below. As you can see in the logs, supervisor seems to be starting up, but not giving the response that Azure seems to need to start up the server. Repository structure myapp/ ┣ .devcontainer/ … -
Django making migrations
Consider the following three classes: class UUIDModel(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) class Meta: abstract = True class TimeStampedUUIDModel(UUIDModel): created = models.DateTimeField(auto_now_add=True, editable=False) modified = models.DateTimeField(auto_now=True, editable=False) class Meta: abstract = True class UsefulClass(TimeStampedUUIDModel): name = models.CharField(max_length=150, unique=True) creator = models.ForeignKey('OtherClass', on_delete=models.SET_NULL, null=True) Based on these classes, when I am running the makemigrations command, Django will create two migrations. One contains the id, created, modified and name (!) fields and the second one adds the creator foreign key. What could be the reason of the creation of two migrations, instead of just one? -
how do i get all my object instances as an int
i am creating a ToDo app and i want to calculate the percentage of activities completed based on the total activities set my views.py def progress(request): todo1 = int(ToDo.objects.all().count()) complete1 = int(ToDo.objects.filter(completed=True)) todo = int(todo1) complete = int(complete1) percent = complete // todo * 100 context = { 'percent' : percent, } return render(request, 'percent.html', context) but i receive a TypeError: int() argument must be a string, a bytes-like object or a number, not 'QuerySet' i really need help -
hello how to change string type into <class 'django.db.models.query_utils.Q'>
''' string = Q(run_date = '2016-05-01') & Q(distance__gt = 20) | Q(distance__lt = 10) data = Test_allowed.objects.filter(q_pickled) return HttpResponse(data) got error "too many values to unpack (expected 2)" because type is str ''' -
Django - Find reserved times
I would like to show all the available times for the not booked appointment dates with a time interval between 11:00AM to 21:00PM: models.py class Appointment(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) seat = models.ForeignKey(Seat, on_delete=models.SET_NULL, null=True) work = models.ManyToManyField(Therapy, related_name='work', verbose_name=_('Work'), blank=True) start_appointment = models.DateTimeField(default=timezone.now, blank=True) end_appointment = models.DateTimeField(default=timezone.now, blank=True) views.py def check_available_hours(request): day_request = date.today() day_request1 = str(day_request) date_of_reference = datetime.strptime(day_request1, "%Y-%m-%d") initial_time = datetime.combine(date_of_reference.date(), time(11, 0)) final_time = datetime.combine(date_of_reference.date(), time(21,0)) appointments_of_day = Appointment.objects.filter( start_appointment__gte=initial_time, start_appointment__lte=final_time ) print(appointments_of_day) # This returns all appointments in a day reserved_times = [datetime(2021, 12, 8, 11, 0), datetime(2021, 12, 8, 15, 0)] hours_between = [datetime.combine(date_of_reference.date(), time(hour + initial_time.hour, 0)) for hour in range(((final_time - initial_time).seconds // 3600) + 1)] available_hours = [hour for hour in hours_between if hour not in reserved_times] return render(request, "name_template.html", {"hours": avaliable_hours}) If i set reserved_dates like above it works. However i'm trying to set it based on my models so i used below code but it doesn't return anything. reserved_times = [ appointment.start_appointment + timedelta(hours=i) for appointment in appointments_of_day for i in range((appointment.end_appointment - appointment.start_appointment).seconds//3600)] print(reserved_times) Any suggestions? Thank you -
Django - Return only checked object from nested JSON
I have a problem returning checked data from html page views.py: First I open JSON file and store it to data from django.shortcuts import render from django.http import HttpResponse, request import json from fpdf import FPDF from django.db import models # Create your views here. #invalid = '<>:"//\t\|?*' url = 'podaci.json' class PDF(FPDF): def header(self): self.image('Logo_SAVA_osiguranje_RGB.png',w=60) self.ln(20) with open(url,encoding="utf8") as f: data=json.load(f) def remove(string, i): a = string[ : i] b = string[i + 1: ] return a + b def display_data(request): render(request,'home.html',{'data':data}) if request.method=='POST': for podatak in request.POST.getlist('checks'): print(podatak) return render(request,'home.html',{'data':data}) html: in HTML i set a value of Checkbox to be an object of data <body class="container"> <form method="post"> {% csrf_token %} <button type="submit">Submit</button> {% for duznici in data %} <div class="card"> <div class="card-header" > {{duznici.NazivDuznika}} <input class="form-check-input" type="checkbox" name="checks" value='{{data}}'> </div> <div class="card-body"> <blockquote class="blockquote mb-0"> {% for podaci in duznici.DunningItems %} <p name="checks" value="{{NazivDuznika}}">{{podaci.BrojPolise}}</p> {% endfor %} </blockquote> </div> </div> {% endfor %} </form> </body> podaci.json structure: [ { "NazivDuznika": "xxxxxxxx", "Pib": "xxxxxxxx", "Mtbr": "xxxxxxxx", "IdLica": xxxxxxxx, "Email": xxxxxxxx, "DunningItems": [ { "BrojPolise": "xxxxxxxx", "Broj_dokumenta_Z": "xxxxxxxx", "Dug": xxxxxxxx, "Datum_Dospeca_Z": "xxxxxxxx", "RbRate": xxxxxxxx, "VrstaOsiguranja": "xxxxxxxx", "Rocnost": xxxxxxxx }, { "BrojPolise": "xxxxxxxx", "Broj_dokumenta_Z": "xxxxxxxx", "Dug": xxxxxxxx, "Datum_Dospeca_Z": "xxxxxxxx", … -
Storing Data in Database without Tables (Because I don't need Entities/Objects) Django Models class
Let me Explain the Whole Question Correctly. I have a class called CData and I just want to store 6 values in it. I don't want different instances/Objects of it because it is global data that is not related to its instances i.e. Its static and should be accessed only by Class itself No objects are to be created. Model.py from django.db import models # Create your models here. class Patient(models.Model): name = models.CharField(max_length=100, default='') dob = models.DateField() fever = models.BooleanField(default=False) cough = models.BooleanField(default=False) headache = models.BooleanField(default=False) diarrhea = models.BooleanField(default=False) diarrhea = models.BooleanField(default=False) tasteless = models.BooleanField(default=False) def __str__(self): return self.name class CovidPatient(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) def __str__(self): return self.patient.name class CData: total = 0 covid = 0 treatment = 0 recovered = 0 dead = 0 discharged = 0 def total_patient(self): self.total = len(Patient.objects.all()) return self.total def add_patient(self, pid): patient = CovidPatient.objects.get_or_create(id = pid) self.covid += 1 return patient.name def covid_patient(self): return self.covid def under_treatment(self): self.treatment = len(CovidPatient.objects.all()) return self.treatment def add_recovered(self, cpid): patient = CovidPatient.objects.get(id = cpid) self.recovered += 1 patient.delete() def total_recovered(self): return self.recovered def add_dead(self, cpid): patient = CovidPatient.objects.get(id = cpid) self.dead += 1 patient.delete() def total_dead(self): return self.dead def add_discharged(self, cpid): patient = CovidPatient.objects.get(id = … -
how to calculate gain loss in python
I have to calculate the gain loss of stocks in python,I used python library "capital-gains" which is only support python3.9+ version. Can anyone know any python library that i can use for calculate the capital gain loss which will support python 3.6,3.7,3.8 version.or older version of capital-gains which will support python older versions. -
Django testing views for logged user
I have a blocker which driving me to creazy. I would like to test view which is intended only for log in users. So basically in setUp(), I've created a user and in my test case I am trying to log in with his credentials, but still I can't get positive result. def setUp(self): self.custom_user = User.objects.create_user( username='test', first_name='test name', email='test@test.test', password='password', is_active=True, ) and then in tests case: def test_create_view_logged(self): login = self.client.login(email='test@test.test', password='password') self.assertTrue(login) response = self.client.get(reverse("new")) self.assertEqual(response.status_code, 200) Status: self.assertTrue(login) AssertionError: False is not true Any idea how to test Views for logged in users in Django? EDIT: Ok, so basically it was a simple as ... :) Authentication is provided via username field not as I tought vie email field. So the answer is: login = self.client.login(username='test', password='password') -
Importing Data from .sql file into postgresql database (Django)
I have a .sql file containing a 1 year amount of records, and I have a running Django app with a Postgresql database. I would like to import all the records on the .sql file into the new empty database. I used to use these two commands on a different project running with Docker : To export the database : docker exec -t *** pg_dumpall -c -U *** > dump_date +%d-%m-%Y"_"%H_%M_%S.sql To import the database : cat dump_***.sql | docker exec -i *** psql -U *** -d *** But without really understanding what I am doing, so I can't find the equivalent command to use in case I am not using Docker. Thank you for your help. -
how show product by subcategory in django?
i want to show product in category by subcategory. I wrote this but it show all product in category except subcategory!!!? i tested {% if category.childern.all %} in list.html but its not work model.py class Category(TranslatableModel): translations = TranslatedFields( name = models.CharField(max_length=200,db_index=True), slug = models.SlugField(max_length=200,db_index=True), ) parent = models.ForeignKey('self', related_name='children',on_delete=models.CASCADE,blank=True,null=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class Product(TranslatableModel): translations = TranslatedFields( name = models.CharField(max_length=200,db_index=True), slug = models.SlugField(max_length=200,db_index=True), description = models.TextField(blank=True), price = models.PositiveIntegerField(), ) category = models.ForeignKey(Category, related_name='products' ,on_delete=models.CASCADE) image = models.ImageField(upload_to='products/%Y/%m/%d',blank=True) available = models.BooleanField(default=True) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id,self.slug]) def __str__(self): return self.name view.py def product_list(request,category_slug=None): category = None categories = Category.objects.filter(parent=None) products = Product.objects.filter(available=True) if category_slug: language = request.LANGUAGE_CODE category = get_object_or_404(Category,translations__language_code=language,translations__slug=category_slug) products = products.filter(category=category) context = { 'categories':categories, 'category':category, 'products':products, } return render(request,'shop/product/list.html',context) list.html (it show when user click on subcategory in menu bar) {% extends "shop/index.html" %} {% block title %} product list {% endblock title %} {% block content %} <div class="container-fluid"> <div class="row mt-4"> <div class="col-9"> … -
How to insert image file using modal in django?
I want to insert image file using modal form in django framework? the html is not accepting the forms i am using right now. Below is the form I am using Views.py: Forms.py: Html: I am not able to use the below html in modal: def free_upload(request): if request.method == 'POST': imgform = ImageUForm(request.POST, request.FILES or None) if imgform.is_valid(): img_obj = imgform.instance imgform.save() return render(request, 'temp_test.html',{'form': imgform, 'img_obj':img_obj}) else: return HttpResponse("not valid") else: form = ImageUForm() return render(request, 'temp_test.html',{'form': form}) Forms.py: class ImageUForm(forms.ModelForm): class Meta: model = Image fields = ['title', 'image',] HTML: <form method="POST" enctype="multipart/form-data" > {% csrf_token %} <div class="row"> <div class="col-lg-6 col-md-12"> {{form.title|as_crispy_field}} </div> <div class="col-lg-6 col-md-12"> {{form.image|as_crispy_field}} </div> </div> <p> <button type="submit" href="{% url 'userload' %}" class="btn btn-primary">Upload </button> </p> </form> class Meta: model = Image fields = ['title', 'image',]