Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Join Two Different Models, One 'unmanaged', in Django Without a Foreignkey Relation
I have the following two Django models: class Project(models.Model): identifier = models.CharField(max_length=128) target_value = models.CharField(max_length=64) ... Meta: managed='False' db_table='projects' class MainProjects(models.Model): mp_identifier = models.CharField(max_length=128) some_value = models.CharField(max_length=256) ... The database housing the Project model is actually off in a cloud database somewhere and is actually used by a completely different application written by a separate team. I need to be able to ask Django to pull a list of MainProjects and somehow annotate the target_value from the Project model into the QuerySet. I've tried using .extra() but the documentation is slim and the examples I've been able to find so far haven't worked for me. I'd also like to avoid using raw SQL if at all possible. Right now, I'm getting around the problem by using a management command I wrote for the Django application to go and fetch the target_value from the remote database and store it as MainProjects model attribute so that I can just reference it locally but - yuck. Thoughts? Suggestions? adsf -
Delete instance in django ModelForm
I am trying to delete an instance form in django ModelForm but it's not deleting, the update part is working perfectly though. my views.py: def update_component(request, pk): component = Component.objects.all() component_id = Component.objects.get(id=pk) form = ComponentModelForm(instance=component_id) if request.method=='POST' and 'form-update' in request.POST: form = ComponentModelForm(request.POST,request.FILES, instance=component_id) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) if request.method=='POST' and 'form-delete' in request.POST: form.delete() return redirect('/maintenance') context = { 'components': component, 'form': form, 'component_id':component_id, } return render(request, 'update_component.html', context) the delete form: <form class="component-delete-button"><input name="form-delete" type="submit" class="button1" value='Delete Component' /></form> -
Displaying the data from db in a table, one row/object at a time with Ajax python django
I am working on a Django project where I display a list of data. When the list is too long the page takes longer to load due to the amount of data that are displayed in that list. Instead of having a Django for loop to get all the data first and then display the page, I am thinking of first displaying the page and then loading all the data from the database via ajax in the background. In order to do that I was thinking of first displaying the whole template without the objects' data to load the page fast and then use an Ajax call to fetch the data with a view function, one object at a time. Is this viable and how can I do it? My datalist.py: from __future__ import absolute_import from __future__ import print_function from django.views.generic import ListView from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required, user_passes_test from django.urls import reverse_lazy , reverse from django.apps import apps from django.http import HttpResponse , HttpResponseRedirect , Http404 from .models import * from .forms import * from .common import * from django.http import JsonResponse import json from django.forms.models import model_to_dict from django.core import serializers from django.core.serializers.json import DjangoJSONEncoder … -
¿Cómo realizo una petición a mi aplicación desde el servidor en el que se encuentra alojada? [closed]
Estoy intentando hacer una petición a una aplicación que tengo desplegada en un servicio apache2 configurado en una maquina virtual ubuntu server, y para hacer la petición utilizo Python. Al momento de hacer la petición desde el navegador de algún equipo perteneciente a la red funciona común y corriente, el problema radica en el momento en el que intento hacer la misma petición pero estando dentro del servidor, bien sea en el navegador o ejecutando la petición por consola. A continuación dejo el error que me deja la consola del interprete de python, espero me puedan ayudar. >>> import requests >>> resp = requests.get('http://service-mails-customer.johannaortiz.local/') Traceback (most recent call last): File "/var/www/servicemailscustomer/sermacu_venv/lib/python3.6/site-packages/urllib3/connection.py", line 175, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw File "/var/www/servicemailscustomer/sermacu_venv/lib/python3.6/site-packages/urllib3/util/connection.py", line 72, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File "/usr/lib/python3.6/socket.py", line 745, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -2] Name or service not known During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/var/www/servicemailscustomer/sermacu_venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 710, in urlopen chunked=chunked, File "/var/www/servicemailscustomer/sermacu_venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 398, in _make_request conn.request(method, url, **httplib_request_kw) File "/var/www/servicemailscustomer/sermacu_venv/lib/python3.6/site-packages/urllib3/connection.py", line 239, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File "/usr/lib/python3.6/http/client.py", line 1285, … -
Error Deploying Project to Heroku With Git
I am trying to deploy my django project to heroku with git. I am runnning: git push heroku main And I get: error: src refspec main does not match any error: failed to push some refs to 'heroku' I also tried: git push heroku master That gave me: fatal: 'heroku' does not appear to be a git repository fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. I also tried git pull which gave me other errors. Nothing is working. -
Api testing issue with Json
Im new to the Django Rest Framework i think i did the serializer thing and views correctly, and it looks like this: class MyAnimalSerializer(serializers.ModelSerializer): class Meta: model = MyAnimal fields = ('id', 'user', 'name', 'animal', 'race', 'birthyear', 'color', 'sex', 'height', 'father', 'mother', 'doc_num',) class MyAnimalFormApi(APIView): permission_classes = (AllowAny,) def post(self, request): serializer = MyAnimalSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) Now when i try to test it with Postman { "data": { "name": "name", "animal": "dog"}, } i get { "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 1 column 47 (char 46)" } but it is enclosed in double quotes. Do you have any idea what's wrong or how to make it accessible only via {"name": "", "animal": ""} instead of nesting dictionary? -
ValueError: Cannot assign must be a instance
Because of a method to obtain the choices that I want to add to a field, it is giving me this error when saving the form. ValueError: Cannot assign "'17'": "Con_Transaccioncab.doc" must be a "Adm_Documento" instance. As I read in this post ValueError: Cannot assign object must be a instance the value is not being returned to me as an object, what other way can I do to retrieve the values in my get_choices method? get_choices method # Select de 3 tablas para obtener el nombre y valor del documento de la tabla adm_documento_periodo def get_choices(self): all_tipoaux = Adm_DocumentoPeriodo.objects.select_related('doc').filter \ (per=self.AIGN_PER_ID).select_related('doc__mod').filter(doc__mod__mod_codigov='CON').values("doc__doc_id", "doc__doc_nombre") DOC = [(d['doc__doc_id'], d['doc__doc_nombre']) for d in all_tipoaux] return DOC and this way I place it in the choicefield inside my form: self.fields['doc'] = ChoiceField(label='Acción: ', choices=self.get_choices(), required=False) any suggestion is welcome and appreciated -
How to associate newly created file model
I have this code, @receiver(post_save, sender=FileAnswer) def save_category_signals(sender, instance, **kwargs): file_types = ["image", "image-multiple"] file_type = instance.question.form_input_type if file_type in file_types: image_path = instance.body.path image = Image.open(image_path) img = image.convert('RGB') new_path = image_path.rsplit('.', 1) pdf = img.save(f'{new_path[0]}_{instance.id}.pdf', format="PDF") # os.remove(image_path) instance.body = pdf instance.save() # os.remove(image_path) # remove old image This code does not associate the file to the model instance. I have looked at django ContentFile and File. still can't really wrap my head around it as the examples aren't that helpful. -
Why am I getting "OperationalError: No Such Table" in Django
I am trying to store values in an sqlite database and them pull them from the database to use on my project using django models. There are two applications in my django project: 'main' and 'apply.' I have run migrate and makemigrations for both. When I save values to the model fields for 'main' it works fine. However, when I try to save values to the model fields for 'apply', I always get "utils.OperationalError: No Such Table apply_(model name)" I have set up a different database for my 'apply' models and the 'main' models use the default database. Relevant settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'apply': { 'NAME': 'apply_data', 'ENGINE': 'django.db.backends.sqlite3' }, } DATABASE_ROUTERS = ['django_webpage_project.routers.ApplyRouter'] projectname/routers.py class ApplyRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {'apply',} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'apply' return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'apply' return None def allow_relation(self, obj1, obj2, **hints): """ … -
How to use a modbus protocol with Django?
I'm using django to develop a monitoring system. This monitoring system uses the Modbus RTU communication protocol. A device can be used to use the inline form, as a device can have multiple records, this device is working properly. What happens is that I can't get the saved bank, because it needs the slave's data and the registration number to request the information. I'm using the mimimalmodbus library. Note: I can't get the slave_id and register_number from the database. My code is in Views.py in django instrument.serial.stopbits = 1 instrument.serial.timeout = 0.05 # seconds instrument.serial.xonxoff = False instrument.precalculate_read_size = False instrument.mode = minimalmodbus.MODE_RTU # rtu or ascii mode instrument = minimalmodbus.Instrument('/dev/ttyUSB1', 1) a =instrument.read(register_number , slave_id) -
Migrating Homepage from Django to React
i built a Homepage using the Django templating engine and on one page is a js application i wrote. Now i moved to a Frontend <-> Backend architecture with React and Django-rest-framework. The Application i had in Django was served as a .html file with <script> tags for the js part. Now i moved to React and i'm serving the html elements through a React component and through React-helmet i'm adding the <script> tags for this specific page. The actual .js files reside in the /public folder of react. I thought i can replicate this way the old structure. But now i get Errors that the .js files don't find functions,variables etc. (The application consists of several js files). What could be the difference in this setup ? Thank you in advance for every answer :) -
Django filter, many queries in array
need an array where Q() object are added filter with many value Anime.objects.filter(Q(question__startswith='Who') & Q(question__startswith='What')) but need something like this val_arr = [] val_arr.append(Q(question__startswith='Who')) val_arr.append(Q(question__startswith='What')) Anime.objects.filter(val_arr) -
Django aws figure out how much current traffic my site can handle?
I have a django app running in aws EC2,my question is how to figure out, how much exact current traffic my site can handle and how to improve that? -
представление многочисленного выбора из формы django [closed]
Используя форму в Django я создал поле с многочисленным выбором. Как обработать в представлении полученный результат. Я каждый раз получаю только одно VALUES а хотелось получить комбинацию. есть код views.py from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import * def attl(request): if request.method == 'POST': form = AttlForma(request.POST) if form.is_valid(): #print form.cleaned_data['gender'] return HttpResponseRedirect('/thanks/') else: form = AttlForma() return render(request, 'attl/attl.html', {'form': form}) def attl_input(request, form=None): gender = request.POST['gender'] return render(request, 'resalt.html', { 'gender': gender, }) forms.py from django import forms from django.forms import RadioSelect HAS_BLED = [ ('a', 'Артериальная гипертензия (систолическое АД выше 160 мм рт. ст.)'), ('b', 'Нарушенная функция почек (диализ, трансплантация почки или креатинин сыворотки выше 200 мкмоль/л)'), ('c', 'Нарушенная функция печени (тяжелое хроническое заболевание или повышение билирубина в 2 раза и более выше верхней границы нормы в сочетании с повышением активности АсТ/АЛТ в 3 раза и более выше верхней границы нормы).'), ('d', 'Инсульт'), ('e', 'Кровотечение в анамнезе и/или предрасположенность к кровотечениям (в т.ч. анемия)'), ('f', 'Лабильное МНО (нестабильное/высокое или в терапевтическом диапазоне менее 60% времени)'), ('g', 'Возраст более 65 лет'), ('h', 'Злоупотребление алкоголем'), ('i', 'Прием препаратов, повышающих риск кровотечения (антиагреганты, НПВС)'), ] class AttlForma(forms.Form): gender = forms.ChoiceField(widget=forms.CheckboxSelectMultiple, choices=HAS_BLED, label="Пол") -
How to get django allauth google sign in to redirect to home page?
Hello I am using django and django all auth for authentication and am using the google feature so that when a user decides to sign in it authenticates with his google account then it will redirect him to the home page in my case to localhost:8000 in developement. But when I do try it does authenticate but instead of sending to localhost:8000 the home page it sends to this url: http://localhost:8000/accounts/profile/# not sure why. Here is my settings.py file. ACCOUNT_LOGOUT_REDIRECT_URL ='/' ACCOUNT_LOGIN_REDIRECT_URL ='task_list' ACCOUNT_SIGNUP_REDIRECT_URL = '/' SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } any help I would appreciate Thank you. -
Django-CKEditor Image Upload File Types
I have successfully installed Django CKeditor with Uploader but I have one problem I cannot find information about. When I select Upload I get the standard Windows file browser but it is set to all files. How can I configure CKUploader to just show supported image file types? Thanks. -
Issues with my +/- buttons inside an input-group
Wondering what I'm missing here... I'm whipping up a shop using django and have come across a real head-scratcher in my product details html. For some reason the +/- buttons don't work properly as they are not adding/subtracting quantities, and are adding the products straight to the shopping bag. Code for my product_detail.html: <form class="form" action="{% url 'add_to_bag' product.id %}" method="POST"> {% csrf_token %} <div class="form-row"> <div class="col-12"> <p class="mt-3"><strong>Quantity:</strong></p> <div class="form-group w-50"> <div class="input-group"> <div class="input-group-prepend"> <button class="decrement-qty btn btn-black rounded-0" data-item_id="{{ product.id }}" id="decrement-qty_{{ product.id }}"> <span class="icon"> <i class="fas fa-minus"></i> </span> </button> </div> <input class="form-control qty_input" type="number" name="quantity" value="1" min="1" max="99" data-item_id="{{ product.id }}" id="id_qty_{{ product.id }}"> <div class="input-group-append"> <button class="increment-qty btn btn-black rounded-0" data-item_id="{{ product.id }}" id="increment-qty_{{ product.id }}"> <span class="icon"> <i class="fas fa-plus"></i> </span> </button> </div> </div> </div> </div> <div class="col-12{% if s %}-12 mt-2{% endif %} mb-3"> <a href="{% url 'products' %}" class="btn btn-outline-black rounded-0 mt-5"> <span class="icon"> <i class="fas fa-chevron-left"></i> </span> <span class="text-uppercase">Keep Shopping</span> </a> <input type="submit" class="btn btn-black rounded-0 text-uppercase mt-5" value="Add to Bag"> </div> <input type="hidden" name="redirect_url" value="{{ request.path }}"> </div> </form> My JS to enable/disable and increment/decrement is : <script type="text/javascript"> function handleEnableDisable(itemId) { var currentValue = parseInt($(`#id_qty_${itemId}`).val()); var minusDisabled … -
Django REST Framework: If the backend is a subdomain, set-cookie will be present but no cookie will be stored in the browser
I'm trying to use the Django REST Framework and dj-rest-auth, djangorestframework-simplejwt to do JWT cookie authentication, but I'm having problems with CORS communication between domains and subdomains. I'm not sure if it's a CORS problem or not, but the cookie is not saved in the browser. The communication from the frontend is done using axios, and withCredentials: true. In the local environment, communication between different ports of the same IP is saved successfully, so I think it is caused by the different domain. What values can I set or change to correct this? DRF domain: api.example.com frontend domain: example.com .env CORS_ORIGIN_WHITELIST='https://example.com' # settings.py CORS_ORIGIN_WHITELIST = os.environ.get("CORS_ORIGIN_WHITELIST").split(" ") CORS_ALLOW_CREDENTIALS = True if not DEBUG: JWT_AUTH_SECURE = True chrome devtools -
creates a binary or combination of all attributes
I want to create a query that creates a binary or combination of attributes. For example, I have the following class class foo(models.Model): m_person= models.ForeignKey('Person', on_delete=models.CASCADE) m_rang = models.ForeignKey('Rang', on_delete=models.CASCADE) m_a = models.BooleanField(default=True, name='a') m_b = models.BooleanField(default=False, name='b') m_c = models.BooleanField(default=False, name='c') m_d = models.BooleanField(default=False, name='d') ... I am currently reading this class as follows: obj = foo.objects.all().first() attributes = [i for i in dir(obj) if i.startswith('m_')] for tag in attributes: if hasattr(foo, tag.__name__): t = foo.objects.filter(person_id=aperson.pk, rang=arang).values_list(tag.__name__, flat=True) if True in t: do somthing So I run through all the instances that match the person and the rank to then check the attribute. I bet it's somehow more intelligent in combination. I would actually like to read a combined "or" class from the database in order to process it further. instead of questioning each attribute individually... since I need a or link, you could use first(value = true) somehow. my wish would be something like this: f = foo.objects.filter(person_id=aperson.pk, rang=arang).OR() where the attributes then combine into something like this: f.m_a = foo[0].m_a | foo[1].m_a | foo[2].m_a... f.m_b = foo[0].m_b | foo[1].m_b | foo[2].m_b... f.m_c = foo[0].m_c | foo[1].m_c | foo[2].m_c... f.m_d = foo[0].m_d | foo[1].m_d | foo[2].m_d... ... with: … -
Django & ajax when you click on the span to open select, the page will refresh
I am looking for a solution to send the form when you click on the span to open select, the page will refresh <span id="update-button" data-index="{{product.id}}"> <label for="select{{ product.id }}"></label> <select id="select{{ product.id }}" > <option value="" selected disabled hidden>{{ item.qty }}</option> <option value="">1</option> <option value="">2</option> <option value="">3</option> <option value="">4</option> </select> </span> thanks for helping you guys -
Django: How to add button to the object creation page?
I have the following models: from django.db import models class Teacher(models.Model): name = models.fields.CharField(max_length=255) favorite_student = models.ForeignKey("Student", blank=True, null=True, on_delete=models.RESTRICT, related_name="+") class Student(models.Model): name = models.fields.CharField(max_length=255) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) def set_as_favorite_student(self): self.teacher.favorite_student = self I've also registered both Teacher and Student in the admin page: from .models import Teacher, Student class TeacherAdmin(admin.ModelAdmin): list_display = ( "id", "name", "favorite_student", ) class StudentAdmin(admin.ModelAdmin): list_display = ( "id", "name", "teacher", ) Each teacher must have a favorite student. So when there is a new teacher, I do the following steps: Go to django admin page Create a teacher Create a student Go back to the teacher, and set favorite_student to the created student Question: For step #3, how do I create a button next to existing buttons that is Save and set as favorite so that I can avoid step #4? -
Django 4.0 wildcard subdomain preventing from setting csrf token
I'm having a problem with Django 4.0 backend in debug mode where I use session auth with csrf token. I use wildcard subdomains: CSRF_TRUSTED_ORIGINS = ["http://*.local.lab:8080"] ALLOWED_HOSTS = [".local.lab"] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE = False SESSION_COOKIE_HTTPONLY = True When I'm accessing app on http://local.lab:8080 CSRF token is being sent and set in browser storage, all works as intended. When I'm accessing app with any other URL combination i.e. http://www.local.lab:8080 or http://subdomain.local.lab:8080 CSRF request comes back with the correct cookie but the cookie is never set in a browsers storage and that prevents me from creating x-csrf token and making any post requests. Everything I'm testing on local domain where I mapped my local IP to the domain local.lab with help of the tool dnsmasq. What am I doing wrong in here? -
How to deserialize an array of primary keys with Django Rest Framework PrimaryKeyRelatedField
I followed the docs when setting up my serializer. class PlaylistSerializer(serializers.ModelSerializer): songs = serializers.PrimaryKeyRelatedField(queryset=Song.objects.all(), many=True, allow_empty=True, required=False) class Meta: model = Playlist fields = ['id', 'name', 'songs', 'created_at'] If I add a few songs to the playlist in the django admin and send a get request, I get the result I want. { "id": 4, "name": "teszt3", "songs": [ 351, 350 ], "created_at": "2022-01-14T14:04:36.238350Z" } But I want to create or update a playlist with a similar list of primary keys of songs. If I send a POST request with this body: { "name": "test2", "songs": [350, 351] } I get this error: Incorrect type. Expected pk value, received str If there's only one number (primary key) in the songs field, it works, but I want to create playlists with many songs at once. Is there a way to parse that array, or how could I solve this? -
Django user authentication with case insensitive username
I'm completing my first project in Django, I'm still struggling when I need to find documentation about the problem that I cannot manage to solve, then I thought to post a question here. In my django project I installed the app "users" for the authentication, I have the following views.py in the folder "users": from django.shortcuts import render, redirect from django.contrib.auth import login from django.contrib.auth.forms import UserCreationForm def register(request): """Register a new user:""" if request.method != 'POST': # Display blank reigistration form. form = UserCreationForm() else: # Process completed form. form = UserCreationForm(data=request.POST) if form.is_valid(): new_user = form.save() # Log the user in and then redirect to home page. login(request, new_user) return redirect('learning_journals:index') # Display a blank or invalid form context = {'form':form} return render(request, 'registration/register.html', context) Models.py is empty at the moment. Everything is perfect and everything works well, both the form and the backend. Users can access with no problem. When a user signs in, is obliged to use a case sensitive username. I would like the user to be able to log in with a case insensitive username, but I have no idea how to start and make this possible. Thank you very much in advance for … -
How to serialize a django model and keep new lines?
I am trying to serialize a django model to store any changes made. I have to convert some of the values to a string in order to avoid errors. Here's what I have so far: associated_objects = {"parts":{}} for item_part in item_parts: part = Part.objects.get(id=item_part.part.id) part_name = part.part_name part = part.__dict__ keys_values = part.items() part = {key: str(value) for key, value in keys_values} part = json.dumps(part, indent=4) associated_objects['parts'][f'{part_name}'] = part record = Record.objects.create(associated_objects=associated_objects) record.save() This saves to a model named record that has a TextField() named associated_objects. I have to convert the values to a string in order to avoid errors caused by ImageField() objects in the part model. Here's what I end up getting: {'parts': {'battery': '{\n "id": "37",\n "created_date": "2022-01-12 20:55:44.980636+00:00",\n "created_by_id": "1",\n "part_name": "battery",\n "part_no": "BATTERY",\n "alt_part_no": "None",\n "description": "test_description.",\n "qty": "99",\n "reorder_qty": "5",\n "cost": "45.0",\n "side": "1",\n "row": "1",\n "column": "1",\n "warranty": "None",\n "vendor_id": "4",\n "alt_vendor_id": "None",\n "category_id": "10",\n "img": "images/parts/battery.jpg",\n "barcode": "barcodes/parts/BATTERY_barcode.jpeg",\n "updated_date": "2022-01-13 18:42:30.818788+00:00",\n "updated_by_id": "1",\n }'}} Unfortunately, it turns the dictionary into a string, so the \n are ignored. What I need is: {'parts': {'battery': { "id": "37", "created_date": "2022-01-12 20:55:44.980636+00:00", "created_by_id": "1", "part_name": "battery", ... } } }