Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku app successfully deploying, but receiving application error when loading site , please help to fix it
My logs don't indicate any errors as far as I can tell, but I'm receiving the following error when loading the site: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail Below you can find the logs. Am I missing something here? 2022-11-18T17:15:57.358840+00:00 app[web.1]:time.sleep(0.1) 2022-11-18T17:15:57.358856+00:00 app[web.1]:File "/app/.heroku/python/lib/python3.10/sitepackages/gunicorn/arbiter.py", line 242, in handle_chld 2022-11-18T17:15:57.359058+00:00 app[web.1]:self.reap_workers() 2022-11-18T17:15:57.359074+00:00 app[web.1]:File"/app/.heroku/python/lib/python3.10/sitepackages/gunicorn/arbiter.py", line 525, in reap_workers 2022-11-18T17:15:57.359331+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2022-11-18T17:15:57.359539+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2022-11-18T17:15:57.580886+00:00 heroku[web.1]: Process exited with status 1 2022-11-18T17:15:57.719991+00:00 heroku[web.1]: State changed from starting to crashed 2022-11-18T17:16:10.573305+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=darazhar.herokuapp.com request_id=4a4e1fcd-e155-462e-8e2e-75b26cac0315 fwd="117.234.2.104" dyno= connect= service= status=503 bytes= protocol=https 2022-11-18T17:16:12.917542+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=darazhar.herokuapp.com request_id=a74a6a4f-15d0-4451-b4d1-1f6fbec726db fwd="117.234.2.104" dyno= connect= service= status=503 bytes= protocol=https 2022-11-18T17:19:33.515138+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=darazhar.herokuapp.com request_id=2ea9b3e5-635c-4d3f-b419-2bbbb7523858 fwd="117.234.2.104" dyno= connect= service= status=503 bytes= protocol=https 2022-11-18T17:19:34.042904+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=darazhar.herokuapp.com request_id=c3c23553-a780-4527-ba81-bba249e5aee3 fwd="117.234.2.104" dyno= connect= service= status=503 bytes= protocol=https python django heroku -
Impossible export django-parler translated fields with the common comand dumpdata
Is there any way to dump and load data with a TranslatableModel because with the common python manage.py dumpdata app.Organization -o fixtures/organizations.json Django command translated fields do not appear in the file. models.py: class Organization(TranslatableModel, Entity): translations = TranslatedFields( name = models.CharField(verbose_name=_("Name"), max_length=200), description = RichTextField(verbose_name=_("Description"), blank=True, null=True, config_name='default') ) status = models.CharField(verbose_name=_("Status"), max_length=50), organizations.json: [ { "model": "app.organization", "pk": 1, "fields": { "status": "Active" } }, { "model": "app.organization", "pk": 2, "fields": { "status": "Active", } } ] Any idea ? Thanks in advanced. -
How Django rest IsAdminUser does not pass even the user is admin?
class Admin(models.Model): username = models.CharField(primary_key=True, max_length=30) password = models.CharField(max_length=255) email = models.EmailField(unique=True) created_on = models.DateTimeField(auto_now=True) django_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='admin') class AdminAPIViewSet(viewsets.ModelViewSet): queryset = Admin.objects.all() serializer_class = AdminSerializer permission_classes = [permissions.IsAdminUser] def get_queryset(self): if self.request.user.is_authenticated: return Admin.objects.filter(username=self.request.user.admin.username) else: return [] def create(self, request, *args, **kwargs): serializer = AdminSerializer(data=request.data) if serializer.is_valid(): email = serializer.data['email'] username = serializer.data['email'] password = serializer.data['password'] with transaction.atomic(): django_user = User.objects.create_user(username, email, password) admin = Admin.objects.create(**serializer.data, django_user=django_user) #User.objects.filter(pk=1001).update(is_superuser=True, is_staff=True) return Response(admin.pk) return Response('/error') class ClientFullAccessAPIViewSet(viewsets.ModelViewSet): queryset = Client.objects.all() serializer_class = ClientSerializer permission_classes = [permissions.IsAdminUser] def create(self, request, *args, **kwargs): serializer = ClientSerializer(data=request.data) if serializer.is_valid(): email = serializer.data['email'] username = serializer.data['email'] password = serializer.data['password'] with transaction.atomic(): django_user = User.objects.create_user(username, email, password) client = Client.objects.create(**serializer.data, django_user=django_user) return Response(client.username) return Response('/error') `Here am trying to make the admin see the all the clients and the client see his data only ,... but I couldn't find why the i cant see the all the list clients as an admin, I am keep getting not authorized to access this endpoint.. ` urls.py from django.contrib import admin from django.urls import path, include from rest_framework import routers import user_management.views router = routers.DefaultRouter() router.register(r'clients', user_management.views.ClientReadOnlyAPIViewSet) router.register(r'clientslist', user_management.views.ClientFullAccessAPIViewSet) router.register(r'admin', user_management.views.AdminAPIViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', … -
Django Many2Many constraint
I am using Django with Django-Rest-Framework (no forms, no django_admin). I have the following models class Company(models.Model): ... class Sector(models.Model): ... company_id = models.ForeignKey(Company) employees = models.ManyToManyField(Employee) class Employee(models.Model): ... company_id = models.ForeignKey(Company) Employee can be in multiple Sectors and a Sector can have multiple Employees. (ManyToMany). I want to add a constraint employee.company_id == sector.company_id in order to add a record into the Many2Many table. I can do this validation in the serializers from the DRF, but I also want to handle this on the model level. I added a through table in the ManyToManyField class Sector(models.Model): ... company_id = models.ForeignKey(Company) employees = models.ManyToManyField(Employee, through='M2MTable') class M2MTable: ... def save(): # employee.company_id and sector.company_id validation is done here This will handle saving an M2MTable object, but however this will not handle related object references Sector.employees.add(Employee) From here I found out I can achieve this with m2m signals. Is there another way of handling this -
How to track mailto clicks in an email
I am sending emails via Mailgun using a django backend. Mailgun sends me back webhooks with information about url clicks in the email. However they do NOT ping me back about mailto clicks. I asked their support team and they confirmed this is expected behavior and they only track "urls"... which the mailto is not considered as. example: <a href="mailto:test@test.com"> Reply</a> How can i actually track mailto clicks in my email, what have people done in the past? I looked at the mailgun event logs and noticed none of the mailto clicks are registered. -
django-recaptcha error <urlopen error [Errno 11001] getaddrinfo failed>
*I implemented Google's reCAPTCHA to my site with the django-recaptcha plugin. All works well. But when I validate the captcha and launch the form I get this error <urlopen error [Errno 11001] getaddrinfo failed>. I would like to know how to interpret it and display a correct message to the user. Thanks in advance.* here is the error: URLError at /connexion/ <urlopen error [Errno 11001] getaddrinfo failed> Request Method: POST Request URL: http://127.0.0.1:8000/connexion/ Django Version: 4.1.2 Exception Type: URLError Exception Value: <urlopen error [Errno 11001] getaddrinfo failed> Exception Location: C:\Python310\lib\urllib\request.py, line 1351, in do_open Raised during: connexion.views.index_connexion Python Executable: C:\Users\User\Documents\Travail\sms-chapchap-2022\env\Scripts\python.exe Python Version: 3.10.4 Python Path: ['C:\\Users\\User\\Documents\\Travail\\sms-chapchap-2022\\src', 'C:\\Python310\\python310.zip', 'C:\\Python310\\DLLs', 'C:\\Python310\\lib', 'C:\\Python310', 'C:\\Users\\User\\Documents\\Travail\\sms-chapchap-2022\\env', 'C:\\Users\\User\\Documents\\Travail\\sms-chapchap-2022\\env\\lib\\site-packages'] Server time: Fri, 18 Nov 2022 16:19:54 +0000 Connexion.Views : def index_connexion(request): if request.user.is_authenticated: return redirect('index_accueil') if request.method == 'POST': form = UserLoginForm(request.POST) email = request.POST['email'] password = request.POST['password'] user = auth.authenticate(email=email, password=password) if form.is_valid(): if user is not None: if user.is_active: auth.login(request, user) return JsonResponse(True, safe=False) else: messages.error(request, 'Votre compte n\'est pas activé, consultez vos Email!!') return JsonResponse(False, safe=False) else: messages.error(request, 'Email ou mot de passe invalide!') return JsonResponse(False, safe=False) else: for key, error in list(form.errors.items()): if key == 'captcha': messages.error(request, "Vous devez réussir le test reCAPTCHA") … -
Wrong model._meta.app_label (from other app) in Django database router
i have two different SQL databases and three apps in my django project. The apps are named PROD, TEST and common. I am trying to route everything that comes from an url of PROD to models.py from PROD and database1, and everything that comes from an url of TEST to models.py from TEST and database2. TEST -- models.py PROD -- models.py common It worked fine, until i introduced 'common'(after cloning the project to another folder) and i don't know why. settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'cfg_db_ic2_net_dev_test', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', }, 'proddb': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'cfg_db_ic2_net_dev_prod', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } DATABASE_ROUTERS = ['PROD.dbRouter.ProdDBRouter'] PROD/dbRouter.py: def db_for_read(self, model, **hints): "Point all operations on prod models to 'proddb'" from django.conf import settings print(model._meta.app_label) if model._meta.app_label == 'PROD': return 'proddb' return None ... PROD/views.py: def hosts(request): print("I did this") return render(request=request, template_name="common/hosts.html", context={"hosts": NetDefined.objects.all, "landscape": landscape}) The models.py for each TEST and PROD is pretty identical. The issue that i have is that the template hosts.html is populated with data from the default data base and not from proddb database. The reason for this is that the DBRouter … -
Extension "postgis" is not available even in postgis/postgis Docker image. [Django]
I'm building Docker image for my Django app. Tried both latest ubuntu and postgis/postgis base images with the following build step: RUN apt-get install --no-install-recommends -y --no-install-recommends \ python3 python3-pip wget gcc postgresql-15-postgis-3 postgresql-15-postgis-3-scripts \ libnewlib-arm-none-eabi avr-libc git libpq-dev libssl-dev libc6 gdal-bin When I run pytest I get the following error: self = <django.db.backends.postgresql.base.CursorDebugWrapper object at 0x7fa258c06e20> sql = 'CREATE EXTENSION IF NOT EXISTS postgis', params = None ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0x7fa265a6f3a0>, 'cursor': <django.db.backends.postgresql.base.CursorDebugWrapper object at 0x7fa258c06e20>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: # params default might be backend specific. > return self.cursor.execute(sql) E django.db.utils.NotSupportedError: extension "postgis" is not available E DETAIL: Could not open extension control file "/usr/share/postgresql/15/extension/postgis.control": No such file or directory. E HINT: The extension must first be installed on the system where PostgreSQL is running.``` -
django .objects.values_list how to exlude None value
I'm using django .objects.values_list to get all the values of a filed of Model: def gen_choice(filed): return list(Mymodel.objects.values_list(filed, flat=True).distinct()) I want to exclude all the None value in the above query set : Mymodel.objects.values_list(filed, flat=True).distinct() Or the list: list(Mymodel.objects.values_list(filed, flat=True).distinct()) I have tried: def gen_choice(filed): return list(Mymodel.objects.exclude(filed=None).values_list(filed, flat=True).distinct()) Error: django.core.exceptions.FieldError: Cannot resolve keyword 'filed' into field. Choices are: -
Is it possible to expose a Django dev server running on a local machine to the public internet?
I'm new to Django and in trying to learn a little about running a server (firewall, permissions, ...) and deploying to production, I installed Ubuntu Server on an old laptop and connected it to my (wireless) router. I was able to set up port forwarding on the router, and to serve a static html page using nginx. I also bought a domain name and was able to change its DNS A record to point to my public IP address. This allowed me to go to mydomain.com and see my static html page. I tried to do something similar with the Django dev server but I could only access it on the local network. I set ALLOWED_HOSTS = ['*'] and ran the server on 0.0.0.0:8000 (after allowing incoming traffic on port 8000 using ufw on Ubuntu), and was able to access it from another computer on my local network by going to the local address 192.168.1.x. However, when I went to mydomain.com the page timed out. Is it possible in principle to achieve this? I know it's not a good idea to run a site this way but I only want to do it to learn and will allow access only … -
Applying DRY-principles to django: When to use class based views, when to use custom decorators?
I have an app consisting of function-based views. As the app is growing, I realize I need to implement DRY-principles in order to keep it manageable. The first thing I want to apply this to is a user status validation that is included with every view today: views.py def myview(request): user_profile = UserAccount.objects.get(user=request.user) if user_profile.type != "internal" and user_profile.type != "flex": if user_profile.duration < datetime.date.today(): return redirect('expired') If I understand it correctly, I can apply DRY here by building a custom decorator, or by building class-based views for my app - for example by extending a DetailView and building a base class for all my views around this. Are there any trade-offs to be aware of when choosing approach? I imagine class based views may be more scaleable in terms of applying DRY to other parts of the app, but the learning curve also seems a bit more steep in order to get to a point where it's actually working. -
Get the intersection of a django queryset with a __in
So I have an array and a queryset. some_array = [...] queryset = queryset.filter(some_field__in=some_array) Actually it returns every object that the "some_field" is in the array. What I want is only the objects that have all the fields from the array. Thx -
How I manage barbershop bookings based on length of service in Django
I'm supposed to manage barber salon bookings during the day based on length of service. For example: cut: 30 minutes cut + shampoo: 40 minutes There are multiple barbers in the salon. for now I have developed the barbershop and services models but I don't know how to implement the appointments and have them displayed for available time slots. class Barber(models.Model): name = models.CharField(max_length=255) surname = models.CharField(max_length=255) role = models.CharField(max_length=255) def __str__(self): return self.name + ' ' + self.surname class Service(models.Model): name = models.CharField(max_length=255) duration = models.PositiveIntegerField() price = models.FloatField() info = models.TextField(blank=True, null=True) def __str__(self): return self.name The appointment model I thought of implementing it in this way: class Appointment(models.Model): barber = models.ForeignKey(Barber, on_delete=models.CASCADE, related_name='appointments') service = models.ForeignKey(Service, on_delete=models.CASCADE, related_name='appointments') start_date = models.DateTimeField() name_client = models.CharField(max_length=255) client_email = models.EmailField() number_phone_client = models.CharField(max_length=10) def end_date(self): return self.start_date + timedelta(minutes=self.service.duration) But now I don't know how to manage the various slots available in a possible view based on the service and the barber chosen. -
AWS_QUERYSTRING_AUTH = False not working with cached AWS S3 images of public S3 bucket
I have a public AWS S3 bucket where I store mostly images for our site. I use boto3 to access and update images in the bucket. Usually, I wrap my calls to images in my templates in sorl thumbnail tags like so: {% thumbnail post.get_thumbnail_image.url '350x230' crop='center' as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}" alt="{{ post.title }}"> {% endthumbnail %} which results in the returned images looking like: https://mybucket.s3.amazonaws.com/cache/e4/8f/e48f5547cec7e4a869696527fac12a8f.jpg I now want to use Memcached to cache entire views on the website. I wouldn't think that would be a problem for a public bucket, because I don't expect the images requested to require a signature. Which is true once I set AWS_QUERYSTRING_AUTH = False in my settings.py - the images stop carrying signatures. The problem is though that even for a public bucket with AWS_QUERYSTRING_AUTH = False, the thumbnail files I get back throw an Access Denied error when the signatures are removed. Is this a matter of flushing some S3 cache somewhere? How can I make these cache thumbnail files respect my AWS_QUERYSTRING_AUTH = False? -
ModuleNotFoundError: No module named 'config.wsgi'
I'm trying to run a .py file and in the file I have this import from config.wsgi import * import os from django.template.loader import get_template from weasyprint import HTML, CSS from config import settings The whole project works, if I set runserver, the project starts without any problem, but this file does not work. The structure of the project is as follows NombreDelProyecto --app ---config ----__init__.py ----asgi.py ----settings.py ----wsgy.py ----db.py ---core ----general ----login ----user ----archivodetest.py the case as I say the project works, but in the views of the applications that I have been doing to put imports I get in red underlined but as I say it works for example: from core.general.forms import ActividadForm That comes out in red, if I put in front of the core, app.core as follows from app.core.general.forms import ActividadForm it does not show red but the project does not work and I get the following error from app.core.general.forms import ActividadForm ModuleNotFoundError: No module named 'app' I understand that it is the routes or something I did wrong from the beginning, please could someone help me. Thank you very much. I tried adding the route, changing the app's route in settings, but to no avail. -
Showing objects in models django
i'm trying to show all the data that i have saved in my admin page to users visiting my website . this is what i have in models: class Movie(models.Model): name = models.CharField(max_length=255) genre = models.CharField(max_length=255) date_of_release=models.CharField(max_length=255) IMDb=models.CharField(max_length=250) cast=models.TextField(max_length=500,null=True) summary=models.TextField(max_length=500,null=True) image=models.TextField(max_length=500,null=True) def __str__(self): return self.name i want the movie name to be shown to users and when they click on the name it takes them to another page that contain all the information about the movie . i'd appreciate it if you have any idea how to do that. -
Django OneToOneField and queryset
counter_app: class Logs(models.Model): name = models.CharField(max_length=250) number = models.PositiveIntegerField(default=0) ... mail_app: class Logs(models.Model): subject = models.CharField(max_length=250) counter = models.OneToOneField(Logs, on_delete=models.CASCADE) ... def save(self, *args, **kwargs): c = Logs(name=self.subject, number=0) c.save() self.counter = c super(Mail, self).save() How can I get access to the "c" object? How should I connect it with 'counter' field? And also I need it's 'number' field to be used further. Many thanks in advance! -
how to combine to class base views into one class base view?
I have to class base views. And I want to combine them together to just a single one class base view: class ReadingFile(View): def get(self, request): form = ProfileForm() return render(request, "main/controle_punt140.html", { "form": form }) def post(self, request): pass class ReadingExcel(View): def get(self, request): form = ExcelForm() return render(request, "main/controle_punt140.html", { "form": form }) def post(self, request): pass and then I want to two above classes combined in this class: class readingPDFAndExcelForm: reading_file = ReadingFile() reading_file.get() reading_file.post reading_excel = ReadingExcel() reading_file.get() reading_excel() Or is there a other solution for? -
Django how to shuffle a queryset without speed lose
I want to shuffle a list of objects without losing any speed in terms of optimization and performance speed. let's say I have the following query. related_products = Announcement.objects.filter(category=category).exclude(id=announcement.id) pythonically, i would import the random module and then random.shuffle(related_products). But I am not sure if it will store something in the memory on my view or use some CPU speed or whatever terminology I don't know. So I wonder what's the best way to make it optimized. Thanks! -
Good practice to use a single update view function for multiple tasks?
I was wondering whether it is considered DRY and good practice to aggregate many small actions such as updating first name, last name, email, etc... using the same update method? First, I thought that it was a good idea because my validation is model based but right now I became septic due to the fact that my ability to custom the http response is greatly impaired. I attach my case to the question. Thanks class Update_Mixin(ModelViewSet): @action(detail=False, methods=["patch"], url_path="update_sdata") def update_few_things(self, request): WHAT_TO_UPD = ('bio', 'user__first_name', 'user__last_name', 'user__email', 'user__phone_number', 'user__gender') usr_profile = self.get_object() serializer = self.serializer_class( instance=usr_profile, data=request.data, context=self.get_serializer_context(), fields=WHAT_TO_UPD, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=204) -
How to dynamically calculate field using a function and order by that calculated field?
The context is the following: I have a model of products. And i need to make a queryset on products calculating a new field compatibility that is not in the model because i need to dynamically calculate it based on the user that makes the request, and finally I need to order the queryset based on this new field. I was trying to do something like this using annotate but since the logic to calculate the compatibility is kinda complex and for that i need to know some m2m of the current product i can't call a function inside of Value. qs = MyModel.objects.all().annotate(compatibility=Value(my_func_to_calc_compatibility(), output_field=FloatField())).order_by('compatibility') Is there another way of doing this? Do you have any ideas on how to achieve this? -
onclick function is running only once
I am using an edit button to edit the posts but when I am clicking the button the onclick function executes and it works perfectly like it edits the post and updates the post content(not from backend). But the problem is when I click the edit button again the onclick function is not running. My HTML code :- <div class="post"> <b><a href="{% url 'profile' post.author.id %}">{{post.author}}</a></b> <input type="hidden" name="postid" value={{post.id}}> <!-- <br><br> --> <p>{{post.content}}</p> {% csrf_token %} <textarea name="edit_content" id="edit_content" cols="50" rows="5"></textarea> {% if user.is_authenticated %} {% if post.author == user %} <button class="edit" onclick="edit(this)">Edit</button> {% endif %} {% endif %} <p><small class="text-muted">{{post.created_on}}</small></p> Here textarea display is set to 'none'. My javascript code :- function edit(ele){ var parent = ele.parentNode; console.log(ele.parentNode); var post = parent.querySelector('p'); var textarea = parent.querySelector('textarea'); var id = parent.querySelector('input'); post.style.display = 'none'; textarea.style.display = 'block'; ele.innerHTML = "Save"; ele.id = "save"; ele.disabled = true; const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; textarea.onkeyup = () => { if( textarea.value.length > 0){ ele.disabled = false; } else{ ele.disabled = true; } } var save = document.getElementById('save'); save.onclick = () => { fetch("http://127.0.0.1:8000/edit", { method : "PUT", headers: {'X-CSRFToken': csrftoken}, body : JSON.stringify({ "postdata" : textarea.value, "id" : id.value }) }).then(() => … -
How do I call a function inside another function from different files in django and display its objects on the frontend?
Please, can anyone help me out. I am trying to call a function I defined in my views.py under food_app into another application in my project. after calling it, it works but I have a problem in reading out the function objects on my html template. it usually displays "₦<HttpResponse status_code=200, "text/html; charset=utf-8">" But the objects prints out on the terminal after when printed. This is the first function defined views.py #food_app def price_in_packs(request): total_price1 = "" total_price2 = "" total_price3 = "" total_price4 = "" total_price5 = "" total_price6 = "" total_price7 = "" total_price8 = "" total_price9 = "" total_price10 = "" total_price11 = "" total_price12 = "" price_pack_box1 = "" price_pack_box2 = "" price_pack_box3 = "" price_pack_box4 = "" price_pack_box5 = "" price_pack_box6 = "" price_pack_box7 = "" price_pack_box8 = "" price_pack_box9 = "" price_pack_box10 = "" price_pack_box11 = "" price_pack_box12 = "" food = "" food_price = "" #try and except is used here to avoid a null or empty value input by the user. A user can forget to input a price in pack value, which can break the code. if request.method == "POST": if request.POST["form"] == "form1": try: price_pack_box1 = int(request.POST.get("price1")) food = Food.objects.get(pk=1) … -
Is it possible to apply list_filters for parent's object's fields in django?
I want to display the timestamp stored in my parents model to be shown in my model. Also, I want to display it in german format. This is not the problem, but of course I want to be able to sort by this timestamp. One solution would be to create a new DateTimeField in model B, but then I would store redundant information. How can I do that with Django? For example: #models.py class A(models.Model): timestamp = models.DateTimeField(null=True) class B(models.Model): key_to_a = models.ForeignKey(DjangoPage, on_delete=models.CASCADE, null=True) ########## #admin.py class BAdmin(admin.ModelAdmin): def german_timestamp(self, B): return B.key_to_a.timestamp.strftime('%d-%m-%Y %H:%M:%S') german_timestamp.short_description = "timestamp" list_display = ("german_timestamp") list_filter = ("german_timestamp") #This breaks my code as there is no field called "german_timestamp" -
Computing difference between two datefields in Django Model
I have two datefields fields in a Django model, start_date and end_date. I want to calculate and store the total number of days between the two, which will be used alongside a daily fee to return total cost. models.py class Booking(models.Model): """Stores the bookings, for example when it was made, the booking date, and the car ID.""" # Unique ID for this booking. start_date = models.DateField(default=timezone.now) end_date = models.DateField(null=True) Most answers recommend extracting the days function (using start_date.day) but that doesn't work. If a booking starts on November 30, and ends on December 2, the function will return 28 days because it subtracts the integers alone. Using simple addition and subtraction: duration = end_date - start_date returns an error: TypeError: Unsupported Operand type(s) for -: 'DateField' and 'DateField' I've tried using a function nested within the model, which subtracts each day from end_date until it reaches start_date: def get_total_days(self): """Computes total number of days car will be rented from with a basic While loop.""" # Create separate instances of start and end day so as not to tamper with db values. start_day = self.start_date end_day = self.end_date days = 0 while end_day > start_day: days += 1 end_day -= 1 …