Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add as many lines as needed in a certain form field
I'm using crispy-forms to render my forms correctly. I want to have a field in which the user can add as many lines of input as he wants. Let's say it's a "hobbies" field, with only 1 line at first, then the user can click an 'add line' button which allows him to enter a second hobby on another line. I found out that it was pretty similar to the choices part of the django tutorial (see how it looks like) which uses a TabularInline : class ChoiceInline(admin.TabularInline): model = Choice extra = 3 However, this TabularInline only works with models, and not a custom field like what I need, so I couldn't use it. I had some ideas but couldn't find a way to implement them. For example, last thing I tried was using a MultiValueField with only one field with the idea to add a CharField in it by clicking the button, however I didn't find how to do that. forms.MultiValueField(fields=(forms.CharField(),)) As my fields are dynamically created using user inputted variables, I can't just reference to the fields like with a set form. If anybody has any idea, I'd be glad as I see no way out. My … -
How to share (initialize and close) aiohttp.ClientSession between Django async views to use connection pooling
Django supports async views since version 3.1, so it's great for non-blocking calls to e.g. external HTTP APIs (using, for example, aiohttp). I often see the following code sample, which I think is conceptually wrong (although it works perfectly fine): import aiohttp from django.http import HttpRequest, HttpResponse async def view_bad_example1(request: HttpRequest): async with aiohttp.ClientSession() as session: async with session.get("https://example.com/") as example_response: response_text = await example_response.text() return HttpResponse(response_text[:42], content_type="text/plain") This code creates a ClientSession for each incoming request, which is inefficient. aiohttp cannot then use e.g. connection pooling. Don’t create a session per request. Most likely you need a session per application which performs all requests altogether. Source: https://docs.aiohttp.org/en/stable/client_quickstart.html#make-a-request The same applies to httpx: On the other hand, a Client instance uses HTTP connection pooling. This means that when you make several requests to the same host, the Client will reuse the underlying TCP connection, instead of recreating one for every single request. Source: https://www.python-httpx.org/advanced/#why-use-a-client Is there any way to globally instantiate aiohttp.ClientSession in Django so that this instance can be shared across multiple requests? Don't forget that ClientSession must be created in a running eventloop (Why is creating a ClientSession outside of an event loop dangerous?), so we can't instantiate … -
Understanding Django DRF ordering warning pagination will yield incosistent results
so i am getting this warning and the questions is: Does that mean that my total serialized objects will be different if i combine all the paginated results(can also contain duplicates) or just that they ll be unordered? Also, where exactly does class Meta: ordering=['something'] get applied? surely not in get_queryset. Does it happen before? The Django drf docs say it's passed in the template to render, but i have no template. I render json by myself. -
How to make Django admin update the file name
My django server uses file creation date as the file name in admin side. The files are added by software as well as by user. In the latter case my django server always uses the timestamp of the server start. How can I change it to use the time stamp of the file creation ? admin.py from django.contrib import admin from .models import SyncScriptLog from django.core.management import call_command class SyncScriptLogAdmin(admin.ModelAdmin): actions = ['make_sync'] def make_sync(self, request, queryset): call_command('update_rdf_from_api', "90", int(request.POST['_selected_action'])) messages.add_message( request, messages.INFO, 'Amazing synchronization from multiple API sources to RDF TripleStore is DONE!') make_sync.short_description = "Run Sync from API to RDF" make_sync.acts_on_all = True admin.site.register(SyncScriptLog, SyncScriptLogAdmin) models.py from django.db import models from datetime import datetime class SyncScriptLog(models.Model): title = models.CharField(max_length=20, default=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), editable=False) content = models.TextField() def __str__(self): return self.title -
Can't find request module even if its installed python django
I'm making a django website, in one of my scripts, I import the requests module. I've installed the requests module with my virtual environnement but I can't import it in my scripts. I have already tried to install and desinstall it. My request module is installed in ProjectFolder.env\Lib\site-packages\requests and my script is located in the folder ProjectFolder\app_name\matches\get_matches.py The strangest part is that I can import other modules that are installed in this folder in my scripts but not request in particular. Do you know what could be the origin of the problem? Thanks -
Add sound player to django admin panel
I have model with FileField, which contains audio file: class Word(models.Model): theme = models.ManyToManyField(Theme, related_name='words') name = models.CharField(max_length=200, null=True, blank=True) sound = models.FileField(upload_to='sounds/', blank=True) I need show audio player on admin panel for this model. For example, for ImageField I did this: from django.utils.html import mark_safe and add property to model code @property def icon_preview(self): if self.icon: return mark_safe(f'<img src="{self.icon.url}" width="100" height="100" />') return "" in admin.py add code: list_display = ('id', 'name', 'icon', 'icon_preview') readonly_fields = ('icon_preview',) def icon_preview(self, item): return item.icon_preview icon_preview.short_description = 'icon preview' icon_preview.allow_tags = True And I need to do something similar for the sound -
ModuleNotFoundError at / when django heroku host
[i can't integrate my Django project, it says ModuleNotFoundError at / ]1 -
How to view relational data in both snippets in Django Wagtail?
I have define two models "A" and "B" in Django Wagtail. Model "A" has many to many relation with "B" in it's model. I use wagtail snippets to edit them in Admin panel. Is it posible to view both relational data in each admin snippets? If so I wanted to restrict the edit feature in model "A" -
Django Insert Data into database via php
For now I always created the structure and logic of my backend with Django. But when I insert data into the database I alwas did that directly via a http request to a php script. When the projects grows it is getting pretty messy. As well, there were always complications with timestamps from the database to the backend. I want to eliminate all these flaws but could not find any good example If I could just make a request to a certain view in Django, containing all the information I want to put into the database. Django and the database are on the same machine, but the data that is being inserted comes from different devices. Maybe you could give me a hint how to search further for this -
Django display data from two different models
I have two seperated models. One with two text fields and one for multiple images. Now I want to display the entire data in one html div. What do I have to change in the projects view and in projects.html? Thanks models.py class Project(models.Model): title = models.CharField(max_length=200) describtion = models.TextField(null=True, blank=True) class ProjectImage(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) image = models.FileField(upload_to="products/") forms.py class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['title', 'describtion'] class ProjectImageForm(forms.ModelForm): class Meta: model = ProjectImage fields = ['image'] widgets = { 'image': ClearableFileInput(attrs={'multiple': True}), } views.py def createProject(request): form = ProjectForm() form2 = ProjectImageForm() if request.method == 'POST': form = ProjectForm(request.POST) form2 = ProjectImageForm(request.POST, request.FILES) images = request.FILES.getlist('image') if form.is_valid() and form2.is_valid(): title = form.cleaned_data['title'] describ = form.cleaned_data['describtion'] project_instance = Project.objects.create( title=title, describtion=describ) for i in images: ProjectImage.objects.create(project=project_instance, image=i) context = {'form': form, 'form2': form2} return render(request, 'projects/project_form.html', context) def projects(request): projects = Project.objects.all() context = {"projects":projects} return render(request, 'projects/projects.html', context) projects.html {% for project in projects %} <div class="column"> <div class="card project"> <img class="project__thumbnail" src="{{project.image.url}}" alt="project thumbnail" /> <div class="card__body"> <h3>{{project.title}}</h3> <h2>{{project.describtion}}</h2> </div> </a> </div> </div> {% endfor %} -
How to convert html to pdf in django?
I'm starting with Django and I working with HTML and I would like to convert to pdf. I have this view wich I get the data registered in my DB by id: def contrato(request, id): return render(request,'contrato\contrato.html', {'asociado': get_queryset(id)}) This renders me the following html, it is something simple: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CPS</title> </head> <body> <h1>Contrato de Prestación de Servicios</h1> <div> <ul> {% for dato in asociado %} <li>Función/Título: {{ dato.job_title }}</li> <li>nombre completo: {{ dato.first_name }} {{ dato.last_name }}</li> <li>Email: {{ dato.email }}</li> <li>RFC: {{ dato.rfc }}</li> <li>CURP: {{ dato.curp }}</li> <li>Clabe: {{ dato.interbank_key }}</li> <li>País: {{ dato.country }}</li> <li>Status: {{ dato.status }}</li> <li>Creado: {{dato.created}}</li> {% endfor %} </ul> </div> </body> </html> How can I convert this html to pdf with the registered data to download. I have only achieved an empty pdf (without the data) or only with the H1 header. I will appreciate any help! -
How can i attach django models data as Excel file and send it as mail with SMTP
i have some data in django models and i want to make excel file from that data and attach it in SMTP as file and send it to target user. i am also using django-import-export to export the excel files .but in this case i want to attach the file in email. Model class FinalBill(models.Model): shipDate = models.DateField(blank = True, null = True, auto_now=False, auto_now_add=False) customerReference = models.CharField(max_length = 200, blank = True, null = True) customerConfirmation = models.CharField(max_length = 200, blank = True, null = True) deliveryConfirmation = models.CharField(max_length = 200, blank = True, null = True) address = models.CharField(max_length = 200, blank = True, null = True) service = models.CharField(max_length = 200, blank = True, null = True) weight = models.FloatField(blank = True, null = True) pricingZone = models.CharField(max_length = 200, blank = True, null = True) uspsCompRate = models.FloatField(blank = True, null = True) charges = models.FloatField(blank = True, null = True) surcharges = models.FloatField(blank = True, null = True) totalSavings = models.FloatField(blank = True, null = True) totalCharges = models.FloatField(blank = True, null = True) customerID = models.CharField(max_length = 200) is_exported = models.BooleanField(default=False) exported_date = models.DateField(blank = True, null = True, auto_now=False, auto_now_add=False) def __str__(self): return … -
Exception Value: no such column: blog_app_article.slug in django
I have a problem with slug. my code is running well but just when I add slug=models.SlugField(default=True,max_length=40) to my model. it stops and give me the error : OperationalError at / no such column: blog_app_article.slug when I delete the slug, my code run well again. I've deleted database and make it again but it doesnt work. what's the problem? I'm coding on Pycharm 2020.1.3 and Django 4.0.4 -
How do I create a group as well as add members to it to make a queryset for Postman?
class AddUserToGroupApiView(APIView): """ Create a hello message with our name """ def post(self, request): serializer = GroupSerializer(data=request.data) if serializer.is_valid(): data = serializer.validated_data group = Group.objects.create(group_name=data.get('group_name')) print(group) group_name = request.data.get('group_name') members = request.data.get('members') print(members) print(group_name) user = UserProfile.objects.filter(name=members) print(user) groups = Group.objects.get(group_name=group_name) print(groups) if not groups.members.filter(members=user).exists(): groups.members.add(user.email) return Response({"status": "Group Created"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) How can add users to the created group and make a group_name , members query in Postman? -
name 'c' is not defined in python
I tried to make a calculator with Django, but got this error this view function takes the input from html page and do the calculation where is the problem here? views.py - from django.shortcuts import render from django.template import loader from django.http import HttpResponse # Create your views here. def indx(request): template = loader.get_template('calculator/calc_home.html') if request.method=='POST': global c,a,b a=request.POST.get('num1') b=request.POST.get('num2') option=request.POST.get('select_val') if a=="" or b=="" : c='please select 2 numbers' else: if option=='add': c=int(a)+int(b) elif option=='multiply': c=int(a)*int(b) elif option=='substract': c=int(a)-int(b) elif option=='devide': if int(b)+0== 0: c='infinity' else: c=int(a)/int(b) else: c='please choose an option' context={ 'sum':c } return HttpResponse(template.render(context,request)) calc_home.html html code takes the input and passes it to the view <h1>welcome to calculator</h1> <p>enter 2 numbers</p> <form method="POST"> {% csrf_token %} <label for="num_1">enter 1st number:</label> <input type="number" name="num1" value='num_1'><br> <label for="num_2">enter 2nd number:</label> <input type="number" name="num2" value='num_2' ><br> <input type="radio" value="add" name="select_val" id="add" > <label for ="add">+</label><br> <input type="radio" value="substract" name="select_val" id="subs" > <label for ="subs">-</label><br> <input type="radio" value="multiply" name="select_val" id="multiply" > <label for ="multiply">*</label><br> <input type="radio" value="devide" name="select_val" id="devide" > <label for ="devide">/</label><br> <input type="submit" name="submit" value="submit"> </form> <h1>{{ sum }}</h1> <br><a href="{% url 'home:homex' %}">go to home</a> error this error is coming in the html page name 'c' … -
Module not found: Error: Can't resolve '@popperjs/core' in 'C:\Users\jkids\mit-tab\node_modules\bootstrap\dist\js'
I'm trying to do a python devserver and keep getting this error, it's running with MySQL and Django; I've tried npm installing @poppyjs/core and poppy.js and neither work -
Linked the css file in django html template but no output
I linked my django html template with the css file, but there is no error and no changes in the page. And when I write the same css code in the same html file under the tag, it works correctly, can someone please guide on what is going wrong? Attaching the code of html file and settings file. HTML File <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>TPC - Student Dashboard</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> ::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */ color: white; opacity: 1; /* Firefox */ } :-ms-input-placeholder { /* Internet Explorer 10-11 */ color: white; } ::-ms-input-placeholder { /* Microsoft Edge */ color: white; } *{ background:#E7E9F0; font-family: "Segoe UI", Arial, sans-serif; } </style> <link rel='stylesheet' src="{% static 'Dashboards/student_dashboard.css' %}"> </head> <body> </body> </html> settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = DEBUG = TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'loginRegistration', 'dashboards', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'tpcAutomation.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, … -
How to change the behaiour of django_spanner application on entire djano project? As I am using 2 databases inside my django application
My Django application has 2 databases (spanner and AWS RDS). I am trying to integrate spanner DB with existing RDS (following the Django spanner document mentioned at the link below). It says we should include the django_spanner application inside the INSTALLED_APPS list. I have multiple applications inside my Django project but I want to use spanner only for one app. After following the steps that are mentioned in the below document, it says The django_spanner application changes the default behavior of Django's AutoField so that it generates random values (instead of automatically incrementing sequentially). This seems to be done to avoid a common anti-pattern in Cloud Spanner usage. I don't want this to happen for other tables where auto-generated id keys are getting randomly generated after including django_spanner, because the other tables will still be in AWS RDS(where we need automatically increasing ids). Can anyone please suggest any solution? https://cloud.google.com/blog/topics/developers-practitioners/introducing-django-cloud-spanner-databas -
how to instance and update multiple row in a table with Django
I have a simple table with some rows: My goal is to instantiate the current value of the quantity and eventually save the new data for all the lines. At the moment I have a simple view: @login_required def compilaDocMultiRow(request,pk): member = get_object_or_404(testaDoc, pk=pk) family = corpoDoc.objects.filter(doc=pk) if request.method == "POST": form = multiCorpoDocForm(request.POST or None) if form.is_valid(): reg = form.save(commit=False) reg.doc_id = member.pk reg.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) else: print(form.errors) else: form = multiCorpoDocForm() return render(request, "compilaDocMultiRow.html", {'family':family, 'member':member, 'form':form}) Is there a way to do this using only Django? -
One to Many field in Model of Django
I am creating a model in Django, but quite confuse about the type of field should i take: Problem: I have to access multiple domains in one web classification, advice me please how do i make these field relationship so that if I try to get one web classification details then it will also contain list of related domain in that as well. Model.py: class WebClassification(models.Model): vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) domain_name = models.[what type i take here] def __str__(self): return self.name Domain.py class Domain(models.Model): id = models.IntegerField() domain_name = models.CharField(max_length=200) def __str__(self): return self.domain_name -
How to create a url for two apps that have index function in django?
I am a newbie in Django. In one django project, I have two apps say college app and company app. In the college app, I have in the college\urls.py path('', index, name="index") and in another company app, I have path('company/', HomeView.as_view(), name="index"). How do I create a url of both these in the header.html ? I tried these but its not working College Home Page ||` Company Home Page || -
print out celery settings for django project?
I'd like to know if celery settings specified in the settings.py file is actually being recognized. How can I tell if celery picked up the options? -
Two .css file in Django static folder only one can be found
I can't understand as the title described. Please refer to image below: The two css files is under the same folder and in the template file I copy the link line just changed the file name. Why the abc.css file can't be found as shown in the command line screen? I just can't understand. Also anther image file is also not found either, also a mystery to me. -
DeleteView lead to error 405 when submit is clicked on django
I have this small blog post where everything works fine apart from delete view. As soon as I hit confirm from DeleteView html page I get 405 error my views.py looks like this my html file where the link is mentioned is like this urls looks this way and html for deleteview -
Django celery unregistered task
I'm running two django projects in one VM and for that two separate celery process is running with supervisor. Now suddenly the tasks is getting clashed with other process. I'm getting unregistered task error. I don't know how of sudden i'm facing this issue. Earlier it was working and nothing changed in the configurations. The above attached image is a reference and task is registered in other service but how of a sudden it's running here. I tried so many solution not able to find the root cause. Any help is appreciated.