Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get output of jquery code in django views
I want to get the output of the jquery function which appends the selected rows ID into views.py I am using the code from this link: https://jsfiddle.net/snqw56dw/3182/ Need your help to get the selected data into views.py file. $('#frm-example').on('submit', function(e){ var form = this; var rows_selected = table.column(0).checkboxes.selected(); // Iterate over all selected checkboxes $.each(rows_selected, function(index, rowId){ // Create a hidden element $(form).append( $('<input>') .attr('type', 'hidden') .attr('name', 'id[]') .val(rowId) ); }); -
ImportError: cannot import name function from module
I am very new to Django and React. Using WSL2 and VSCode, I was trying to link my React frontend to the Django backend, and I'm getting the following error: ImportError: cannot import name 'index' from 'FastTravelDjango.views' (/root/dev/fast-travel/FastTravelDjango/views.py) FastTravelDjango was created by using "django-admin startproject FastTravelDjango" FastTravelDjango/urls.py from django.contrib import admin from django.urls import path, include from .views import index urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('index/', index) ] FastTravelDjango/views.py from django.shortcuts import render def index(request): return render(request, 'index.html') I was previously getting the same error with my api functions saying that it could not import the main function from views.py, but that mysteriously seemed to solve itself after a while without changing anything. api/urls.py from django.urls import path from .views import main urlpatterns = [ path('home', main) ] api/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def main(request): return HttpResponse("<h1>Hello</h1>") Here is the console log: (.venv) root@LAPTOP-436E19C3:~/dev/fast-travel# python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/root/dev/fast-travel/.venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File … -
Need ideas or suggestions in creating a Survey App using Django Rest Framework
I got a project requirement for a survey app where an admin will create a survey and share the created survey link through the mail while the survey options should be point-based from 5 to 1. Kindly share with me any code samples or references -
Django form fails to validate
I have this form that I am passing a parameter to disable or enable the fields based on certain user clicking a particular hyper link. URL path("update-request/<str:pk>/", update_request, name="update_request"), path("update-request/<str:pk>/<str:action>", update_request, name="update_request"), views.py def create_new_request(request, action=None): description_form = DescriptionForm(action=action) forms.py class DescriptionForm(forms.ModelForm): prefix = "description" .... def __init__(self, action=None, *args, **kwargs): super(DescriptionForm, self).__init__(*args, **kwargs) print(action) example hyperlink: New Request My problem starts when I want to save the data to the database, I get all fields are displayed as being required even when data is in them. removing the action from DescriptionForm.init stops the problem, how do I circumvent this issue? The reason I needed to add the action in init is because I need to enable of disable fields if a condition is met. def __init__(self, action=None, *args, **kwargs): super(DescriptionForm, self).__init__(*args, **kwargs) if action == "new_request" or "review": for field in self.fields: self.fields[field].disabled=True My errors look like this: title This field is required. category This field is required. job_description This field is required. urgent_request This field is required. detailed_job_description This field is required. -
FORCE_SCRIPT_NAME in Djanog setting keeps adding the prefix to the URL
I have a URL: https://servername/appname/, so I defined in my Django settings.py like FORCE_SCRIPT_NAME='appname/' which does what I want to have the first time, but if redirect, it keeps adding the appname/ to the URL. How can I prevent adding the prefix multiple times to the URL? For example, I am here https://hammbwdsc02/culture-crawler/dashboards/dashboard/, now if I click logout, the URL will be https://hammbwdsc02/culture-crawler/culture-crawler/logout/, which does not exist and I got a 404 error. By the way, it is working on localhost perfectly but the problem ist only on the server. (Linux server, serving with Gunicorn and Nginx -
django in docker compose don't see posgresql
I have a problem with my django + postgresql docker compose. docker-compose.yml: version: '3.8' services: db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env web: build: . command: python MoreEnergy/manage.py runserver 0.0.0.0:8000 volumes: - ./MoreEnergy/:/MoreEnergy/ ports: - 8000:8000 env_file: - ./.env depends_on: - db volumes: postgres_data: Dockerfile: FROM python:3.9-alpine WORKDIR /app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev # install dependencies COPY requirements.txt /app/requirements.txt RUN pip install --upgrade pip RUN pip install --no-cache-dir -r requirements.txt # copy project COPY . . db container check: (shell) $ docker compose exec db psql --username=dmitriy --dbname=more_energy_db psql (12.0) Type "help" for help. more_energy_db=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges ----------------+---------+----------+------------+------------+--------------------- more_energy_db | dmitriy | UTF8 | en_US.utf8 | en_US.utf8 | postgres | dmitriy | UTF8 | en_US.utf8 | en_US.utf8 | template0 | dmitriy | UTF8 | en_US.utf8 | en_US.utf8 | =c/dmitriy + | | | | | dmitriy=CTc/dmitriy template1 | dmitriy | UTF8 | en_US.utf8 | en_US.utf8 | =c/dmitriy + | | | | | dmitriy=CTc/dmitriy (4 rows) more_energy_db=# error: django.db.utils.OperationalError: could not connect to … -
Django Many to Many arrange sequence of selected item
Hey all have created a model in django and using django admin i want to import values in many to many fields according to their values placed in order the results are displayed IN my case :- max_combo then max_table etc How can a user from front end choose this particular sequence in django admin Click to view image -
"permission matching query does not exist" errors i encounter with django guardian
Am trying to enable my website users block other users they don't want again as friends just like we can on Facebook. I decided to implement it with Django guardian. when a user clicks a button, a view(block_user_view) is called and the profile the user wants to block is added to group which is assigned a custom permission i created(cant_view_profile). But i always get this error "permission matching query doesn't exist". I can assign these permissions from the admin panel but it runs into error when i try it from my views. I don't know of other ways to actualize this functionality with Django. this is my view def block_user_view(request, id): if request.method == "POST": grouped = Group.objects.get(name="blockedusers") friend = Profile.objects.get(id = id) assign_perm("cant_view_profile", grouped, friend) return render(request, "profiles/blockuser.html", {}) -
Django: handling changes of Datatable structure
Right now I use Django to get data out of my database served to an endpoint to use it. I import data to the mySQL database via php scripts so not via Django. If i go into the WebPanel of phpmyadmin and change the name of a datatable field, Django gets confused and can't use the data anymore. Is there a way to make Django understand the changes I did directly in the db? My idea was to just migrate again, but this just adapts the database, not the Django structure. Is there a way of doing this? -
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