Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and HTMX active search issue
I'm trying to make an active search with HTMX in Django, and it's working, but happens that if I delete the search terms in the form the entire page is rendered twice and can`t fix it. This is ok: But this happens if I delete the text introduced in the form: view.py class SearchView(View): @staticmethod def get(request): search_term = request.GET.get('search', None) if search_term: roads = Road.objects.filter(name__contains=search_term).all()[:100] template = 'search_results.html' else: roads = [] template = 'pkes/search.html' return render(request=request, template_name=template, context={ 'roads': roads, }) search.html {% extends "pkes/base.html" %} {% block content %} <form action="/action_page.php"> <label for="search">Carretera</label> <input class="input" name="search" type="search" placeholder="Ej: EX-118" hx-get="/search" hx-trigger="keyup changed delay:500ms, search" hx-target="#search-results" hx-swap="innerHTML"/> <label for="kilometro">Kilómetro</label> <input class="input" name="kilometro"> <input type="submit" value="Enviar"> </form> <div id="search-results"> {% include "search_results.html" %} </div> {% endblock %} search_results.html {% for road in roads %} <div> {{ road.name }} </div> {% endfor %} Thanks!!! Django 4.1.6, Python 3.11.1, HTMX 1.8.5 Reference: rockandnull.com -
why is django-admin runserver giving me this error
I have no idea about this error . Please help i have set envoirment variable and pythonpath variable but its showing me error : C:\Users\Admin\AppData\Local\Programs\Python\Python310\python.exe: Error while finding module specification for 'main' (ValueError: main.spec is None -
How to make user inactive if not active for 1 day using django fsm
Need to change user status to inactive if not active for 1 day using django fsm library class UserValidity(models.Model): state = FSMField(default="active") name = models.CharField(max_length=10) date = models.DateField(auto_now_add=True) def state_inactive(self): if self.date < datetime.date.today(): self.state = 'inactive' return self.save() else: return True @transition(field=state, source="active", target="inactive", conditions=[state_inactive]) def state_change(self): print('State Inactive') -
Get Latest row values from MySQL Database in Django
I am working on a Django project. I am stuck in a situation, Where I want to retrieve latest row values of different attributes from MySQL database in django, but my query always return first row values. I am using orm query. I want latest row values entered by user through input form. Here is my code: views.py: def success(request): ip_value = NewDevice.objects.values('ip').latest('created_at') start_time_value = NewDevice.objects.values('start_time').latest('created_at') end_time_value = NewDevice.objects.values('end_time').latest('created_at') return response models.py: class NewDevice(models.Model): id = models.BigIntegerField(primary_key=True) ip = models.CharField(max_length=150) start_time = models.TimeField() end_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "live" Database Results: with live (id,ip,start_time,end_time,created_at) as (values (1 ,'1.1.1.1','10:57:00','18:23:00','13:22:29'), (2, '0.0.0.0','11:57:00','11:58:00','05:57:30'), (3 ,'10.10.10.10','13:49:00','13:50:00','08:49:20') ) Whenever my function def success executes, the query inside this function always print row 1 value which is: (1 ,'1.1.1.1','10:57:00','18:23:00','13:22:29') But I want always latest row values when record will insert into database. Kindly help to get rid of this issue. -
Django CSRF Failed: CSRF token missing or incorrect when using client on localhost
I am using django 3.2 , i had implemented csrf using below link Link Everything works fine when using same domain for client and server. But while testing locally i get the error when sending post, put or delete requests. I can see csrftoken in the request headers under cookie, but can't see it using document.cookie. csrfcookies is non httponly cookies, still i don't know why it not visible in document.cookie in client side. -
Wagtail - Image Optimisation ( How to do it with static and dynamically added image files?)
so I want to run my site with my images displayed as quickly as possible and the images are added either by giving the {% static "path/to/image.jpg" %} or by rendering the image tag for wagtail image uploads {% image image_name original as img %}. Currently, the site has considerably slowed down with lots of images, especially loading time for the images. Any possible options to optimise those images through Wagtail? It would be of great help. Thanks An example with images loading by static tag as well as image tag in wagtail. {% extends "base.html" %} {% load static wagtailcore_tags wagtailimages_tags %} {% block extra_css %} <link rel="stylesheet" href="{% static 'css/technologies.css' %}"> {% endblock %} {% block nav_projects %} class="active" {% endblock %}{% block content %} <div class="inner-page project-page"> <div class="inner-hero" style="background-image: url(/static/images/banner_a/project_bg.png);background-attachment: fixed;"> <div class="container-fluid inner-top-section mt-0 px-5"> <div class="row flex-lg-row-reverse align-items-center g-5 py-5 p-4"> <div class="col-10 col-sm-8 col-lg-6"> </div> <div class="col-lg-6"> <h1 class="display-5 fw-bold lh-1 mb-3">{{self.header_title}}</h1> <p class="lead">{{self.meta_content}}</p> <!-- <div class="d-grid gap-2 d-md-flex justify-content-md-start"> <a href="#" class="btn-two"><span class="txt">Know more</span></a> </div> --> </div> </div> </div> </div> {% if page.dblock_content %} <div class="d-block sub-hero position-relative" style="background-color: #4A4A4A"> <div class="bg-set-wrp"> <div class="left-bg-set"> <img class="zoom-fade" src="{% static 'images/project-elm/elm-1.png' %}" alt=""> </div> … -
how can i solve this in Django = UnboundLocalError at / local variable 'form' referenced before assignment
how can i solve this in Django UnboundLocalError at / local variable 'form' referenced before assignment def home(request): if request.user.is_authenticated: form = MeepForm(request.POST or None) if request.method == "POST": if form.is_valid(): meep = form.save(commit=False) meep.user = request.user meep.save() messages.success(request,('Meep has been posted')) return redirect('home') meeps = Meep.objects.all().order_by("-created_at") return render(request, 'home/home.html', {'meeps':meeps,'form':form}) else: meeps = Meep.objects.all().order_by("-created_at") return render(request, 'home/home.html', {'meeps':meeps,'form':form}) -
How to create a new pk if there is no pk in the table i refers to
I am working on a web project using django drf. There was a problem during the development, so I want someone who can help me. 😥 First, let me show you my models. Container class Container(models.Model): cont_no = models.CharField(primary_key=True, max_length=11) cont_sz = models.ForeignKey('Size', models.PROTECT, db_column='cont_sz') cont_type = models.ForeignKey( 'Type', models.PROTECT, db_column='cont_type') class Meta: managed = False db_table = 'container' Size class Size(models.Model): sz = models.CharField(primary_key=True, max_length=5) use_yn = models.BooleanField() class Meta: managed = False db_table = 'size' Type class Type(models.Model): type = models.CharField(primary_key=True, max_length=10) type_name = models.CharField(max_length=20) use_yn = models.BooleanField() class Meta: managed = False db_table = 'type' Import class Import(models.Model): wo_no = models.OneToOneField( 'Wo', models.PROTECT, db_column='wo_no', primary_key=True) cont_no = models.ForeignKey( Container, models.PROTECT, db_column='cont_no', blank=True, null=True) category = models.CharField(max_length=6) . . . class Meta: managed = False db_table = 'import' As you can see, the cont_no field in the Import table refers to the Container table. The following data exists in the Container table: cont_no | cont_sz | cont_type -------------+---------+------------ ABCD0000001 | 4000 | DRY ABCD0000002 | 2000 | DRY ABCD0000003 | 4000 | DRY I want a new value with pk 'ABCD0000004' in the Container table when the cont_no of the data present in the Import table is changed … -
Add extra file to database, path is wrong python django
Hello everyone. I am creating a website using Python Django and the main purpose of the website is to convert XML files to modified XML files. I have uploaded the files to the hosting server and when I try to perform the conversion, I need to add another file to the database record that was created. On my local server, the process works smoothly without any issues, but when I try to do it on the hosting server, I get an error message "SuspiciousFileOperation at /test/ Detected path traversal attempt in '/home/t/tkor470gma/converter/new_CUST.xml". My models.py looks like this: class Document(models.Model): document = models.FileField(verbose_name='Document (old structure with settings)',upload_to='documents/') document1 = models.FileField(verbose_name='Document (new structures without settings)',upload_to='documents/') author = models.ForeignKey(User,on_delete=models.CASCADE) resdocument = models.FileField(upload_to='documents/',blank=True) transaction_date = models.DateTimeField(auto_now_add=True) forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ['document','document1'] views.py This form uploads files to the database def model_form_upload(request): form = DocumentForm() pathresdoc = '' if request.method == 'POST': user = request.user form = DocumentForm(request.POST, request.FILES) obj = Document.objects.filter(author_id=user).order_by('-id') if obj.count() >= 1: return HttpResponse('it is impossible to convert first <button>Pay</button>') else: if form.is_valid(): instance = form.save(commit=False) instance.author = user form.save() create_file(request.user.id) respeople = instance.id add_file_to_database('/home/t/tkor470gma/converter/new_CUST.xml',respeople) pathresdoc = Document.objects.get(id=respeople).resdocument.path else: form = DocumentForm() return render(request, 'model_form.html', … -
Django Simple JWT logout view
I was trying to implement JSONWebTokenAuthentication using djangorestframework-simplejwt. After creating the access token I can authenticate with the token. Now I need to create a LogoutAPI view to revoke the token. I tried to delete and revoke the token but there is no reference in the documentation. How this token is managed? Now I copy the Token and paste it in the authorization section in Postman. I checked the cookie and there is no information of token. So how can I create a Logout view? Storing the token in cookie and delete it from the cookie will do the job? Guide me. -
django's clean method doesn`t load form errors
i have a problem with Django clean method because clean method of form doesn`t load error in template. Could someone help me ? template.html {% extends "index.html" %} {% block header %} <div id="container-register"> <div class="logo-register">Zarejestruj się</div> <div class="register-form"> <form method="post"> {% csrf_token %} {% for field in form %} {{ field }} {{ field.errors }} <br> {% endfor %} <input type="submit" value="Zarejestruj"> </form> </div> </div> {% endblock %} view.py class AddUserView(View): template_name = 'add_user.html' def get(self,request): return render(request, self.template_name,{ 'form': AddUserForm() }) def post(self,request): form = AddUserForm(request.POST) if form.is_valid(): User.objects.create_user( username=form.cleaned_data.get('username'), email=form.cleaned_data.get('email'), password=form.cleaned_data.get('password'), first_name=form.cleaned_data.get('first_name'), last_name=form.cleaned_data.get('last_name') ) return redirect('/login') else: return render(request, self.template_name, context={ 'form': AddUserForm() }) forms.py class AddUserForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Nazwa użytkownika'}), max_length=100) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Hasło'}), max_length=100) password_repeat = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Powtórz hasło'}), max_length=100) first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Imię'}), max_length=100) last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Nazwisko'}), max_length=100) email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'}), max_length=100) def clean_username(self): if User.objects.filter(username=self.cleaned_data.get('username')).exists(): raise ValidationError('Ten login jest już zajęty') return self.cleaned_data.get('username') def clean_password_repeat(self): if self.cleaned_data.get('password') != self.cleaned_data.get('password_repeat'): raise ValidationError('Podane hasła różnią się od siebie!') return self.cleaned_data.get('password_repeat') I checked the page source to see if the errors class was added in the html file. -
Show popup message without reload page using Ajax in Django
`Hi all! I'm using Ajax in Django to add items to cart and wishlist without reloading the page. For user feedback without reloading the page, I need to call a popup message from their Ajax function. My view: def add_cart(request): basket = Basket(request) if request.POST.get('action') == 'POST': product_id = int(request.POST.get('product_id')) entered_quantity = int(request.POST.get('quantity')) product = get_object_or_404(Product, id=product_id) basket.add(product, entered_quantity) basket_qty = basket.__len__() response = JsonResponse({'qty': basket_qty}) return response JS function with Ajax: $(document).on('click', '#add-button', function (e){ e.preventDefault(); var prodid = $('#add-button').val(); $.ajax({ type: 'POST', url: add_cart, data: { product_id: prodid, quantity: $('#qty').val(), csrfmiddlewaretoken: window.CSRF_TOKEN, action: 'POST' }, success: function (json) { document.getElementById('cart_icon_count').innerHTML = json.qty; }, error: function(xhr, errmsg, err) {} }); }); file messajes.html {% block messages %} <ul class="messages" id="messages-list"> {% if messages %} {% for message in messages %} <li> {% if message.tags %} <div class="alert alert-{{ message.tags }} msg fade show" role="alert">{{ message }}</div> {% else %} <div class="alert alert-info msg fade show" role="alert">{{ message }}</div> {% endif %} </li> {% endfor %} {% endif %} </ul> {% endblock %} Fade out message alerts function fade_alerts() { alerts = document.getElementsByClassName("alert msg"); var i = alerts.length; for (let elem of alerts) { i--; time = 3250+(1000*i); setTimeout(function() { … -
How to show messages for Integrity Error and similar database level errors in Django with DjangoRestFramework?
I had a unique constraint for a attribute on a model. Upon a post request to create it, if you enter a duplicate name, the server gives an Exception (which would be status 500). For now I am checking for the condition in the post request before creating the object. However I feel like this is not a good idea. I would want any kind of integrity error messages to be displayed in the response. Another idea is to use a try/except block and display whatever error/Integrity error occurs, but is there any other way to do this? Like not keeping the constraint in the model? or something else Is there any standard practice? -
Can't we create a field in Model Serializer which is not being used in Object Creation?
Models.py class Palika(CreatedInfoModel): name = models.CharField( max_length=50, help_text="Unique | Max: 50 characters | Gaun/Nagar Palika", ) district = models.ForeignKey( District, on_delete=models.PROTECT, help_text="Link to District" ) is_default = models.BooleanField(default=False, help_text="By default=False") active = models.BooleanField(default=True, help_text="by default=True") class Ward(CreatedInfoModel): name = models.CharField( max_length=50, # unique=True, help_text="", ) palika = models.ForeignKey( Palika, on_delete=models.PROTECT, related_name="wards", help_text="link to Gaun/Nagar Palika" ) active = models.BooleanField(default=True, help_text="by default=True") def __str__(self): return f"{self.name}" serializers.py class PalikaCreateSerializer(BaseModelSerializer): wards_names = serializers.ListField(child=serializers.CharField()) class Meta: model = Palika # Write only fields # 1. Common Write Only fields common_write_only_fields = get_common_write_only_fields_create() # 2. Custom Write Only fields with respect to model custom_write_only_fields = [ "name", "district", "wards_names", "is_default", "active", ] fields = common_write_only_fields + custom_write_only_fields # Extra Kwargs extra_kwargs = get_common_extra_kwargs_create() extra_kwargs.update( { "name": {"write_only": True}, "district": {"write_only": True}, "wards_names": {"write_only": True}, "is_default": {"write_only": True}, "active": {"write_only": True}, } ) def create(self, validated_data): print(validated_data) ward_names = validated_data.pop("wards_names") print(validated_data) validated_data["name"] = validated_data["name"].title() palika = super().create(validated_data=validated_data) for ward_name in ward_names: Ward.objects.create( app_type=palika.app_type, device_type=palika.device_type, created_date_ad=palika.created_date_ad, created_by = palika.created_by, name=ward_name, palika=palika ) return palika def validate(self, attrs): super().validate(attrs) model_name = get_model_name_by_self_obj(self) # Unique (Case Insensitive) validation unique_keys_to_be_checked = [] unique_ci_char_create_validator = UniqueCICharCreateValidator( CORE_APP_IMPORT_STRING, model_name, unique_keys_to_be_checked, attrs ) unique_ci_char_create_validator( CORE_APP_IMPORT_STRING, model_name, unique_keys_to_be_checked, attrs ) # Default Check … -
Django/Gunicorn Logging Redis exceptions
Background I noticed that when Django is incorrectly configured to connect with Redis, say for example transport encryption is enabled but the auth token is incorrect, then the application fails silently without anything in the logs, other than NGINX reporting the following: 2023/02/13 05:17:44 [info] 35#35: *248 epoll_wait() reported that client prematurely closed connection, so upstream connection is closed too while sending request to upstream, client: *.*.*.*, server: _, request: "GET /sup/pleasant/ HTTP/1.1", upstream: "http://127.0.0.1:8000/sup/pleasant/", host: "myhost.com" The application logs do not report anything until I refresh the page a few times (F5). At this point, the container locks up for some reason and stops responding to ALB health checks, and is terminated by the Fargate service. Interestingly, when I turn the Redis server off and have Django Redis settings set to "IGNORE_EXCEPTIONS": False, then connection errors are reported in the application logs. django_redis.exceptions.ConnectionInterrupted: Redis ConnectionError: Connection closed by server. NOTE: Just to make it clear, even with "IGNORE_EXCEPTIONS": False, nothing is reported when the Redis server is online but the Django/Redis configuration details are misconfigured. Redis is being used for channels and caching. I've tested with DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS but it hasn't had an impact. Question How do enable exception logging … -
How do I test if the current logged in user's id is in a list of id's
I have this question model: class Question(models.Model): title = models.CharField(max_length=100) body = models.TextField(max_length=10000) user = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "question" verbose_name_plural = "questions" db_table = "questions" def __str__(self): return self.body and then I have this question feeling model which is just for someone to like a question: class QuestionFeeling(models.Model): like = "like" feelings = [ (like , "like"), ] feeling = models.CharField(max_length=15,choices=feelings, default=like) question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='feelings') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="question_feelings") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: unique_together = ['question', 'user'] verbose_name = "Question feeling" verbose_name_plural = "Question feelings" db_table = "question_feeling" def __str__(self): return str(self.feeling) I am using Django rest framework and I would like to see if a user already likes a question. I don't want to do a serializer method field where the database needs to be queried twice. I would just like to see if the logged in user's id matches any of the feelings' user ids On the front end the array for feelings that appear for each question looks like this: feelings: Array [ {…} ] 0: Object { id: 1, feeling: "like", created_at: … -
Error while Installing Module Chatter Box
"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD "-IC:\Users\Wajahat Murtaza\AppData\Local\Programs\Python\Python311\include" "-IC:\Users\Wajahat Murtaza\AppData\Local\Programs\Python\Python311\include" "-IC:\Users\Wajahat Murtaza\AppData\Local\Programs\Python\Python311\Include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\cppwinrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" /EHsc /Tppreshed/maps.cpp /Fobuild\temp.win-amd64-cpython-311\Release\preshed/maps.obj /Ox /EHsc maps.cpp c1xx: fatal error C1083: Cannot open source file: 'preshed/maps.cpp': No such file or directory error: command 'C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe' failed with exit code 2 [end of output] I got this error Please Help Me I have been trying Different tutorial from google but nobody help me -
Manage caching from Django Admin
I am currently looking for a way to manage the Django cache from the administration (having the possibility to turn it off, turn it on, or leave it on with a timeout of 8 hours). I have tried to use for this the django cache framework, with 3 buttons in the administration to different functions that turn off, activate or modify the cache timeout with no results (the cache remains activated with no possibility to turn it off or modify its timeout). I tried to use a script that restarts the server once one of these options is chosen, but it doesn't work as it should (this must happen because I can't dynamically modify the settings.py file). Any different approach to this problem? Thanks in advance -
Is space matter in Jinja?
What David has written in CS50 2022 - Lecture 9 - Flask, layout.html is {% block body %}{% endblock %} What I typically do in Django, a similar Python web framework is {% block body %} {% endblock %} Is space matter in Jinja? Is it a matter of style? Because I know HTML is also space insensitive. -
Trouble with custom column ordering in Django app using django_tables2, using calculated ForeignKey relationships
I'm trying to make ordering possible for one of my columns in a Django project using django_tables2. I'm getting a FieldError, Cannot resolve keyword 'job_code' into field. Choices are: PO_num_is_fixed, PO_number, amount, currency, description, id, invoice_status, job, job_id, notes, vendor, vendor_id I'm trying to sum all of the Cost objects that pertain to each job so I can sort them. I don't totally understand how F() works, so I have the feeling that's where I'm going wrong. Would love some feedback on how I can get this to work/improve on what I have. tables.py: import django_tables2 as tables from .models import Job, Cost from django.utils.html import format_html from django.db.models import F class JobTable(tables.Table): class Meta: model = Job template_name = "django_tables2/bootstrap5.html" fields = ("client", "job_name", "job_code", "budget", "total_cost", "profit_rate", "job_type", "job_date") # Doesn't work, cannot resolve keyword 'job_code' into field. def order_total_cost(self, queryset, is_descending): queryset = queryset.annotate( total_cost = sum([cost.amount for cost in Cost.objects.filter(job__job_code = F("job_code"))]) ).order_by(("-" if is_descending else "") + "total_cost") return (queryset, True) models.py Cost class: class Cost(models.Model): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, related_name='cost_rel') description = models.CharField(max_length=30, blank=True) amount = models.IntegerField(default=0, blank=True) currency = models.CharField(max_length=10, default='JPY ¥', choices=( ('¥','JPY ¥'), ('US$','USD $'), ('CA$','CAD $'), ('AU$','AUD $'), ('€','EUR €'), … -
How do I solve the issue where my django primary key (id) is null?
I am expecting that the primary key (id) to be inserted automatically E.g. 1 However, when I run my server, it is reflected as null instead. I have tried deleting the migration and previous records in the database, but it still reflects a null value in new entries. null_id In my settings.py file, I have the following option on default DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' I have the following Camera model class Camera(models.Model): status = models.BooleanField(default=True) location = models.CharField(max_length=2) liveURL = models.URLField(max_length=200) I created the Camera Object and save it using the django shell (python manage.py shell) test = Camera(status=False,location='b1',liveURL='http://test.com') I am using Django version 4.1.5 -
Ask for more information depending on a the input of the user on a from - Django ModelForms
To elaborate a little bit more Ill explain exactly what I want to do. So I have a database of employees, the issue is that some employees are under the age of 18, and when they are under that age I should ask some extra information. You can take a look into my code that I ask for the Date of birth (variable name is fecha_de_nacimiento which is the spanish for date of birth) of the employee you are registering. So my Idea is to make my program to understand the age of the entry, then see if its over 18, if not, then ask for some other details. If this is not clear enough, feel free to ask questions. BTW I am new in python and django, so if you notice something that I can do better, even if its not related to my question, feel free to let me know, feedback is well taken. models.py: from django.db import models from django.urls import reverse from django.utils import timezone from datetime import date class EmployeesInfo(models.Model): employee_number = models.AutoField(primary_key=True) nombre_completo = models.CharField(max_length=50) fecha_de_nacimiento = models.DateField(default = timezone.now) def get_age(self): age = date.today() - self.fecha_de_nacimiento return int((age).days/365.25) def get_absolute_url(self): return reverse("lista_empleados", kwargs={"pk": … -
listing the time from an api increase in plus 1
I have an error in listing an api that only use get and pull the normal database but at the time of listing increases me the date plus 1 and that in the database I register correct the api is normal and the same time zone q could it be? I have an error in listing an api that only use get and pull the normal database but at the time of listing increases me the date plus 1 and that in the database I register correct the api is normal and the same time zone q could it be? -
Server Error After Setting DEBUG=False Django
I keep getting Sever error- 500 after setting DEBUG=True both on localhost and the hosted version and I don't know the cause of the error. Here are some my code in my settings.py file import os from pathlib import Path from decouple import config import django_heroku import dj_database_url BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = str(os.getenv('SECRET_KEY')) DEBUG = config("DEBUG", default=False, cast=bool) ALLOWED_HOSTS = ["127.0.0.1", "localhost", "cv-build.onrender.com"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "cloudinary_storage", "cloudinary", 'app', ] MEDIA_URL = "/cv-build/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] STATIC_ROOT = os.path.join(BASE_DIR, "app/static") STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" DEFAULT_FILE_STORAGE = "cloudinary_storage.storage.MediaCloudinaryStorage" CLOUDINARY_STORAGE = { "CLOUD_NAME": config("CLOUDINARY_CLOUD_NAME"), "API_KEY": config("CLOUDINARY_API_KEY"), "API_SECRET": config("CLOUDINARY_API_SECRET"), } DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' I've tried to sort it out by checking the Allowed Host, static settings and all but it is the same result. Thanks. -
django template: how to access form.fields[key] with dynamic keys?
Iam trying to access my form.fields in django template by using a dynamic key with two integers in its name. My goal is do render a checkbox matrix. Thats my form.py from django import forms class Mounting_Calc_Form(forms.Form): def __init__(self, rows, columns, *args, **kwargs): super().__init__(*args, **kwargs) self.rows = range(rows) self.columns = range(columns) for i in range(rows): for j in range(columns): self.fields['checkbox_{}_{}'.format(i, j)] = forms.BooleanField(required=False, widget=forms.CheckboxInput, label=str(i)+","+str(j)) print(type(self.fields)) print(self.fields) thats my template {% extends "admin/base.html" %} {% block content %} <form method="post"> {{ form.as_p }} {% csrf_token %} <table> {% for i in form.rows %} <tr> {% for j in form.columns %} <td>{{ form.fields[checkbox_{{ i }}_[{ j }}].widget }}</td> {% endfor %} </tr> {% endfor %} </table> <input type="submit" value="Submit"> </form> {% endblock content %} Thats the error i get: Could not parse the remainder: '[checkbox_{{ i' from 'form.fields[checkbox_{{ i' What iam doing wrong?