Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Long running Celery tasks result in ConnectionResetError: [Errno 104] Connection reset by peer
At my Django application, I use Celery to process very long-running tasks. One of these tasks has to write a record into the database at the very end, to confirm that the process is completed. For some reason if the tasks runs for so long (talking 4 hrs or more here) I get this back: ConnectionResetError: [Errno 104] Connection reset by peer This happens as soon as I trigger a write operation against the Database at the very end of the task, e.g.: Files.objects.filter(pk=files_obj).update ... etc It would be interesting to know why the peer resets the connection (MariaDB in my case). Doesn't Django manage database connections for me using a connection pool? I also checked my Redis config on Django side where in my opinion only these lines really matters: BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 86400} # 24 hrs. CELERYD_TASK_TIME_LIMIT = 86400 # 24 Hrs. CELERYD_TASK_SOFT_TIME_LIMIT = 86400 # 24 Hrs. Isn't there a way to make the function trigger a new connection or so? To me, it seems that the Celery task keeps the SQL connection alive for as long as the task is running. But the DB backend doesn't respect this for so long. This is how I start … -
Django : Add a searchbar to filter the dropdown menu of form.ChoiceField
I want to add a search to filter the items of the dropdown menu because it can contain 100 items depending on the user. How can I add that to my code ? Is it in the view or in the Form. forms.py class SelectClient(forms.Form): ID_Customer = forms.ChoiceField(label="Company :", widget=forms.Select(attrs={'onchange': 'submit();'})) def __init__(self, *args, **kwargs) : self.user = kwargs.pop('user') super(SelectClient, self).__init__(*args, **kwargs) id_client_list = AADJNTGroupAPI.objects.filter(ID_User_id=self.user.id).values_list('ID_Group_id', flat=True) id_client_list = list(id_client_list) client_choices = GroupsAPI.objects.all().filter(ID__in=id_client_list).values_list('UUID_Group','GroupName') self.fields['ID_Customer'].choices = client_choices views.py @authenticated_user def selectcontrat(request) : context = initialize_context(request) form_client = SelectClient(request.POST, user=request.user) if form_client.is_valid(): uuid_contrat = request.POST.get("ID_Customer") return redirect(reverse('home', args=(uuid_contrat,))) context['form_client'] = form_client return render(request, 'classify/selectcontrat.html', context) html <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>Document</title> <link rel="stylesheet" href="{% static 'selectcontrat.css' %}"> </head> <body> <div class="selectcontract"> <h2>{{ user.name }}, Bienvenue chez EFID</h2> <div class="imagedroite"> <img src="{% static 'image/logo.svg' %}" alt=""> </div> <div class="contrats"> <h2>Veuillez selectionner un contrat :</h2> <form method="post" id="SelectCompany"> {% csrf_token %} {{ form_client.as_p }} <input type="submit" value="Select"> </form> </div> </div> </body> -
quiz.js:12 Uncaught TypeError: Cannot read properties of undefined (reading 'forEach')
I keep getting this error so this code is responsible for displaying questions on the screen from a JSON response. I also attached my views if needed I have been googling and still can't seem to find anything to help me fix this issue not sure what I am doing wrong I am new to Django and ajax from the backend s://i.stack.imgur.com/kMnJw.png -
Dynamically assign HTML values to django for loop
I want to assign an innerHTML value to a django for loop in my django templates. Currently, when I click on a button, the HTML changes to reflect the innerHTML of the button ("individual_project_container"). I then want to run the innerHTML captured in the "individual_project_container" through a for loop in my django template {% for project in projects %} {% if project.project == "HTMLVariable" %} Pass {% else %} Fail {% endif %} {% endfor %} I know that I cannot add a element into my for loop and I am not sure how else to pull the variable. In my template, I am using the following JavaScript to assign the innerHTML of "individual_project_container" to "new_note_header" <script> document.addEventListener('DOMContentLoaded', function() { const nnHead = document.getElementById('new_note_header'); document.getElementById("project_container").addEventListener("click", e => { const tgt = e.target.closest("button"); if (!tgt.matches(".individual_project_container")) return; // not a button nnHead.textContent = tgt.textContent.trim(); }); }); </script> The relevant HTML is below: <div class = "project_container", id = "project_container"> {% for project in projects %} <button class = individual_project_container> {{ project }} </button> {% endfor %} </div> <div class = note_header_container> <div class = new_note_header, id = new_note_header> New Note </div> </div> {% for project in projects %} {% if project.project == … -
send information from a js variable to python
I need to send an object that contains a variable in js, the idea is to be able to send that information to python (I use django) and capture that info to be able to perform the validations that I need from the backend (python) and not from js, how can I do it ? code ajax: function CapturarDatosOrden() { $.ajax({ url: window.location.pathname, type: 'POST', data: { 'action': 'prueba', }, beforeSend: function (jqXHR) { $.xhrPool.push(jqXHR); $(".loader").fadeIn('fast'); }, dataType: 'json', complete: function (jqXHR) { // boton.disabled = false; $('.loader').fadeOut('fast'); var index = $.xhrPool.indexOf(jqXHR); if (index > -1) { $.xhrPool.splice(index, 1); } }, }).done(function (data) { // alert('entro al primer ajax para comparar el tipo de orden y su tecnologia') var info = data.find(data => data.id__ordenes == idOrden); the "info" variable has the object I need to capture in python, the object is something like this: { id__ordenes: "219661981", fk_ot__tipo_orden: "4", fk_bss__contratos: "3257733", otciudad: "1", otdireccion: "----", fk_ot__cc: "1", open_orden: "42588165", instalador: "4320", fk_contratistas__equipos_vendedores: "1", fk_ot__causales: "88" } how can i do it? -
Using foreign key as object in Django Telmplates
I'm trying to build a structure using django rest framework for show some data in my html templates. But I can not show data from a model with foreignkey. My structure should be like this: {% for category in categories %} {{ category.category }} #category is the variable name {% for channel in category.channel_set.all %} {{ channel.title }} {{ endfor }} {{ endfor }} But I never can print the channel variables in html files. models.py: class Category(models.Model): user = models.ForeignKey( 'auth.User', on_delete=models.DO_NOTHING, unique=False, ) category = models.CharField( max_length=255, unique=True, ) _id = models.ObjectIdField(auto_created=True, serialize=False) event_creation = models.DateTimeField(auto_now=True) event_updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'category' verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.category class Channel(models.Model): user = models.ForeignKey( 'auth.User', on_delete=models.DO_NOTHING, ) _id = models.ObjectIdField(auto_created=True, serialize=False) date_creation = models.DateTimeField(auto_now=True) date_updated = models.DateTimeField(auto_now=True) category = models.ForeignKey( Category, max_length=255, on_delete=models.PROTECT, related_name='channel', unique=False, to_field='category', ) channel = models.CharField( max_length=255, unique=True, ) def __str__(self): return self.category views.py: class Gallery(viewsets.ModelViewSet): renderer_classes = [TemplateHTMLRenderer] template_name = '/gallery.html' queryset = Category.objects.all() queryset2 = Channel.objects.all() permission_classes = [permissions.IsAuthenticated] def get(self, request, **kwargs): kwargs['categories_list'] = self.queryset serializer = CategorySerializer(self.queryset,many=True) serializer2 = ChannelSerializer(self.queryset2,many=True) return Response({ 'categories':serializer.data, 'channels':serializer2.data }) # @login_required(login_url='/login/') def list(self, request): queryset = Category.objects.all() response = … -
Using multiple custom event as triggers in HTMX, can I identify which of the triggers is being used?
I am using HTMX in my Django project to change elements in a form depending on previous selections. At some point I use a custom event and listen for it as indicated in solution 3 here: https://htmx.org/examples/update-other-content/ Everything works as expected, also when using two triggers separated by a comma. However, I would like to pass a header, the value of which depends on the event being used as trigger. Trigger foo -> header A, trigger bar -> header B. Below is some code that should help understand. <div hx-get="{% url 'someurl' %}" hx-trigger="foo from:body, bar from:body" hx-target="#sometarget" hx-swap="outerHTML" hx-headers='{"someheader":"foo_value"}' OR '{"someheader":"bar_value"}'> So far, I have tried: putting target.value as header value (you can use it as trigger filter, so I thought it might work in hx-headers too) Passing headers or context variables in the view that causes the trigger to go off, so that then I can use Django's {% if %} in the template. But they don't get here because that view renders a different part of the template, and this is just being triggered because it listens for the event on the body due to event bubbling Any suggestions? -
save an object with django createview from a form and additional fields
I'm confused about how to add additional fields in my_model that are excluded from my HTML form defined in forms.py while saving with createview! models.py: class My_model(models.Model): # attrs in the form that are saved already with now problem ... #attrs excluded in forms.py but I want to save them along with the form attr_1=models.CharField(max_length=30) attr_2_type=[('a','A'),('b','B')] attr_2=models.Charfield(max_length=8,choices=attr_2_type) ... def get_absolute_url(self): return reverse("application:redirectin_pattern_name", kwargs={"pk":self.pk}) views.py: class StagesInitCreateView(CreateView): model= My_model form_class = MyModelForm template_name = "satges/mymodel.html" mymodel.html <div class="row "> <div class="col-md-3"></div> <div class="col-md-6"> {% block form %} <form method="post" action="{% url 'application:pattern_name' %}"> {% endblock form %} {% csrf_token %} {{ form.as_p }} <input class="form-control btn-primary" type="submit" name="save" value="send your demand" /> </form> </div> </div> here everything is working fine the form is showing and I can submit data and save it to the database then I get automatically redirected to the details page of the object I saved and all the details are correct I even checked passing ids of another object to see if it changes and show the details of each object called and it works too. now I just want to save the remaining attributes of the model at the same time when I'm saving the form … -
Django ORM where in two columns with subquery
Imagine I have two tables. One lists licenses customers have, each with a specific version and type. The other table has general shared info about the licenses (eg name, price, duration), also listed by type and version. I need to query the information table for any rows pertaining to licenses a given customer has. In pure SQL, that can be accomplished with this subquery: select * from version_details where (version, type) in (select version, type from licenses where company_id = '6f65e5cc-cd1f-4888-a236-38295bae393a'); Is there a way to accomplish this with Django ORM? I know how to use a subquery but I can't figure out how to do a wherein with two columns. -
Django Admin Page, Part addition
OperationalError at /admin/parts/part/add/ no such table: parts_part It keeps showing this error no matter how many times I have edited the models.py and admin.py code, whenever I try to add a part as a superuser it is showing the same error -
Make form with dynamical amount of inputs in django template
The crux of the problem is this: I have a Schema that will later be converted to a .csv file. However, I need to populate this schema with data. To do this, I need columns that will have fields (Name, data type, order, etc.) But I don't know how many columns the Schema will have Therefore, the wording sounds like this: Create a form with a dynamic number of columns. While I was writing the question, I had an idea to create a "Scheme" table in the database and bind a table - "Column" to it Thus, when you click "add column", a new instance will appear that will already be bound to this Schema. Am I thinking in the right direction or do you have another idea? The picture below will allow you to convey the essence of the problem more accurately. Thank you in advance -
Unable to push on heroku
I'm trying to push my code on heroku but keep getting this error below Things I've tried Make new branch and add and commit to it and push using git push heroku newbranch:master Change requirements.txt encoding to UTF-8 and ANSI -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app -----> Python app detected -----> Using Python version specified in runtime.txt Traceback (most recent call last): File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> r = f.read().strip() File "/usr/lib/python3.8/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 5: warning: command substitution: ignored null byte in input ! Requested runtime (��python-3.10.2 ! Aborting. More info: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed -
Division, district, upzilla, pourosova/Union, ward, zip code implement in django
I want to implement Bangladeshi Division, district, upzilla, pourosova/Union, ward,zip code in django website..how i can implement it using django ? Can anyone help me or give me some suggestions .. -
How to update model object when testing UpdateView Django
I'm having some issues when I test an update view in my code.Here's the view: class PatientUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): permission_required = 'main.change_patient' model = Patient template_name = 'patient/edit_patient.html' form_class = PatientUpdateForm And this is the patient model: class Patient(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) middle_name = models.CharField(max_length=50, blank=True, default='') hospital_number = models.IntegerField(unique=True, default=0) age = models.IntegerField(blank=False) sex = models.CharField(max_length=6, choices=gender_choices, default='female') weight = models.CharField(max_length=10, choices=gender_choices, default='female') def __str__(self): return f' {self.hospital_number} --> {self.first_name} {self.last_name}' def get_absolute_url(self): return reverse('patient_detail', args=[str(self.id)]) Here's the form: class PatientUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PatientUpdateForm, self).__init__(*args, **kwargs) gender_choices = [ ('male', 'Male'), ('female', 'Female') ] marriage_choices = [ ('married', 'Married'), ('single', 'Single') ] self.fields['gender'] = forms.ChoiceField(choices=gender_choices) self.fields['marriage_status'] = forms.ChoiceField(choices=marriage_choices) class Meta: model = Patient fields = [ 'first_name', 'last_name', 'hospital_number', 'age', 'sex', 'weight' ] And the test case: class PatientsTest(TestCase): def setUp(self): self.superuser = get_user_model().objects.create_user( email='genuis@gmail.com', username='supergenius', password='password', is_superuser = True ) def test_patient_update_view(self): data = { 'first_name':'Joe', 'sex' :'female', } new_patient = Patient.objects.create( first_name='John', last_name = 'doe', hospital_number = 2, age=24, sex = 'male', weight='79 Kg', ) self.client.login(username=self.superuser.username, password='password') response = self.client.post(reverse('patient_edit', kwargs={'pk': new_patient.id}), data) self.assertEqual(response.status_code, 302) # should go through for superusers, response code … -
How to add a new foreign key field in model django without migration error?
I have two models A, B, they contain a lot of data(int database). Suddenly I decided to add a foreign key in model B to A. But Django can't migrate it because existing rows in table B haven't value for this FK. What should I do in such a situation? -
how to correct text orientation for scanned pdf file
I am trying to correct the orientation of the scanned pdf file to correct alignment. I have been attempting with image format using Deskew packagebelow I have uploaded image but I need to correct orientation for the pdf file but I need to update the orientation of the pdf file. Please suggest any resources or code or documentation. -
JavaScript Redirect to Django view with parameters
These lines of code produce an error, my question is, how can I pass the IDS and MESSAGES parameters to windows.location.href in Django view. $(function () { console.log("HOME"); let ids = 1; let messages = "My personal Message"; let myurl = "{% url 'message-page' ids messages %}"; //ERROR HERE: IDS and MESSAGES are variables return window.location.href = myurl }); -
Problem with handling nested dictionary on Django Rest Framework
Testing Django Rest Framework. I receive the following JSON as a result of the POST request for entry (it is important here that the keys of the dictionary, the rest are trifles): { "title": "Test title10", "description": "Test description10", "client": { "name": "Egor10", "surname": "Egor11", "phone": "1645342534532", "adress": "st. Egor9, 53453" }, "products": ["Karamel", "Shokolad", "Limon", "Banan"], "delivery_adress": "st. Egor44", "delivery_date": "2022-23-09:44:00", "delivery_code": "4562gdgll" } I have two models: from django.db import models class Client(models.Model): name = models.CharField(max_length=100, blank=True) surname = models.CharField(max_length=100, blank=True) phone = models.CharField(max_length=100, blank=True) adress = models.CharField(max_length=150, blank=True) class Order(models.Model): title = models.CharField(max_length=100, blank=True) description = models.CharField(max_length=255, blank=True) delivery_code = models.CharField(max_length=50, blank=True) delivery_adress = models.CharField(max_length=150, blank=True) client = models.ForeignKey('Client', on_delete=models.CASCADE, null=True, related_name='orders') Next, I want to make a serializer and look towards SlugRelatedField or Nested relationships to process the nested dictionary relationship: "client": { "name": "Egor10", "surname": "Egor11", "phone": "1645342534532", "adress": "st. Egor9, 53453" } For SlugRelatedField I tried this story in the serializer: class OrderSerializer(serializers.ModelSerializer): orders = serializers.SlugRelatedField( read_only=True, slug_field='phone' ) class Meta: model = Order fields = ['title', 'description', 'delivery_code', 'delivery_adress', 'orders'] In views.py I do the standard processing: def post(self, request): serializer = OrderSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() And this whole story does not work … -
ModuleNotFoundError: No module named 'api.company'
I'm doing a Django project and the only thing I've seen today is this error: File "/home/user/Work/ud_pytest_2/api/company/admin.py", line 4, in <module> from api.company.models import Company ModuleNotFoundError: No module named 'api.company' 1)I set up a virtual environment with pipenv, and it's activated and has all the packages installed. 2)I can easily import packages I installed like django, pytest 3)When I'm trying to import packages from the ACTUAL project, let's say, the class Company from the models section, VSCode doesn't give me any error and actually recognizes the file exists... 4)But when I runserver, it says the module wasn't found. I think it's some kind of path issue but I can't figure out what 5) Already selected the correct interpreter 6) Already trying the Python Path https://i.ibb.co/4KfHhRr/Project.png From the image, I'm showing my project tree. Whenever I try to import what's marked as yellow (I marked it yellow), I get that error, even though VSCode doesn't warn me and even sugest that actual import. Can't figure why the interpreter isn't recognizing the import. I think it's something related to the virtual environment and the Paths but i'm not sure Thanks in advance -
AttributeError at <URL> During Email Verification Python Django
I'm developing the backend of my React-Native application on Python Django. I'm trying to implement registration + email verification. First, the user sends their information for registration in a request. The is_active field is set to False by default. A verification_token is created for each user, stored in a separate table in the DB. The user receives an email which has a link appended with the created verification_token. The VerifyPatient class handles the email verification by checking if the token is equal to the token in the db. I receive the email just fine but get an AttributeError when I click the link, so the user doesn't get registered. My models.py file: from django.db import models from django.contrib.auth.models import User class VerificatonToken(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='token') verification_token = models.CharField( max_length=256, blank=True, null=True) My serializers.py file: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework_jwt.settings import api_settings from .models import VerificatonToken class TokenSerializer(serializers.ModelSerializer): class Meta: model = VerificatonToken fields = ('user', 'verification_token',) class PatientSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( required=True, max_length=32, validators=[UniqueValidator(queryset=User.objects.all())] ) first_name = serializers.CharField( required=True, max_length=32 ) last_name = serializers.CharField( required=True, max_length=32 ) # DOB … -
Increment Django database value every day
let's assume I've created a Django model with an integer field of count, with initial value for every record equal to 0. How do I increment this value, for every record of the db, once every day? -
Cache.get returns None when using Memcache
Would like to use Memcache to store and retrieve a list of all online users. I am using my console to test if my cache and memcache work but not getting the correct output/ So example when I run this $ python manage.py shell >>> from django.core.cache import cache >>> cache.set("foo", "bar") >>> cache.get("foo") I do not receive any output after running cache.get("foo"). I would be expecting to receive the output bar This is what I have in my settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } USER_ONLINE_TIMEOUT = 300 USER_LASTSEEN_TIMEOUT = 60 * 60 * 24 * 7 my middleware: import datetime from django.core.cache import cache from django.conf import settings class ActiveUserMiddleware: def process_request(self, request): current_user = request.user if request.user.is_authenticated(): now = datetime.datetime.now() cache.set('seen_%s' % (current_user.username), now, settings.USER_LASTSEEN_TIMEOUT) and models.py: from signup import settings ... class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... def last_seen(self): return cache.get('seen_%s' % self.user.username) def online(self): if self.last_seen(): now = datetime.datetime.now() if now > self.last_seen() + datetime.timedelta( seconds=settings.USER_ONLINE_TIMEOUT): return False else: return True else: return False -
Django - Print Dictionary of List of Lists in a Table in HTML
I have a Dictionary of List of Lists. I want to print this as a structured way preferably a table. For each hostname, i want its specified rows in the table with three columns (Address Interface State ID ) with apprpriate entries printed out. It seems a very complicated nested loop if possible. Here is the dictionary ospfdictkey being passed to the template {'hostname': [['R1-ISP'], ['R2-ISP']], 'ospfneighboraddress': [['192.168.5.2', '192.168.5.13', '192.168.5.25'], ['192.168.5.1', '192.168.5.6', '192.168.5.32']], 'ospfneighborinterface': [['ae1.0', 'ae4.0', 'ae7.0'], ['ae1.0', 'ae2.0', 'ae9.0']], 'ospfneighborstate': [['Full', 'Full', 'Full'], ['Full', 'Full', 'Full']], 'ospfneighborID': [['172.0.0.2', '172.0.0.4', '172.0.0.5'], ['172.0.0.1', '172.0.0.3', '172.0.0.6']]} HTML Code {% for ip in listip %} {% for ospfadd in ospfdictkey.ospfneighboraddress %} {% for a in ospfadd %} <tr> <td>{{ a }}</td> </tr> {% endfor %} {% endfor %} {% endfor %} Here is the end result im getting but its repeating keys data and how do i iterate over other keys to print next as table data ? -
django.security.SuspiciousOperation.response_for_exception:99- Attempted access to '/mediafiles/some' denied
The following line raw_file = fileUpload.objects.get(fileName=str(raw_file_fetch)) path_temp = fileUploadSerializer(raw_file).data["local"] The path_temp returns the error django.security.SuspiciousOperation.response_for_exception:99- Attempted access to '/mediafiles/some' denied. Any ideas how to fix this? -
Django graphene accept any mutation input
In mutation, I just need to save the event name and its payload that might differ and I do not need any validation for it. How can I say graphene that I just need to accept an object? class SendEvent(MutationMixin, relay.ClientIDMutation): class Input: event = graphene.String(required=True) payload = # any object