Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Jinja2 does not show in the webpage correctly
Using Django I have to create a basic website to display the elements inside the SQL database on the webpage. Right now, I have created a basic HTML template to start from there but since I have included the Jinja2 syntax inside the HTML document, it does nto show correclty. It shows all the Jinja2 code there in the browser. If there is another file you need to look at, just ask. index.html { % extends "header.html" % } { % block content % } <article>Article</article> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/books.html">Books</a></li> <li><a href="/about.html">About</a></li> </ul> </nav> <aside>Aside</aside> { % endblock % } header.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Welcome</title> <link rel="stylesheet" href="/static/styles.css"> </head> <body> <header>Header</header> <div id="main"> { % block content % } { % endblock % } </div> <footer>Footer</footer> </body> </html> OUTPUT -
How to properly configure static folder for django's admin files
I have deployed project on production (django+gunicorn+nginx) My project structure is as follows forecast forecast settings.py urls.py static admin css fonts img css js In settings.py static folder configured as follows STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')] While i am trying to login to admin page it's return me 500 server error. Than i tried to see what in my nginx logs /var/log/nginx/error.log.1 There are following 2020/02/20 13:01:53 [error] 11703#11703: *5 open() "/usr/share/nginx/home/isli/projects/forecast/static/static/admin/css/base.css" failed (2: No such file or directory), client: 188.170.195.79, server: isli.site, request: "GET /static/admin/css/base.css HTTP/1.1", host: "isli.site", referrer: "http://isli.site/admin/login/?next=/admin/" -
Django Testing - SimpleCookie and Session
Problem: My testing client appears to log out once i attempt to set a cookie. I have workspace (project) object that i want my client to access. The access itself works fine, but as soon as i attempt to edit cookies in my session, the client gets logged out. My test is documented below. Code import time from http.cookies import SimpleCookie from django.contrib.auth.models import User from django.test import Client, TestCase from django.urls import reverse from myproject.models import DataSource, Workspace class TestSomeStuff(TestCase): def setUp(self): datasource1, _ = DataSource.objects.update_or_create(id=1, defaults=dict(source_name="Source 1")) workspace1, _ = Workspace.objects.get_or_create(id=1, defaults=dict(project_name="Project 1", datasource=datasource1)) self.workspace_view_url = reverse("workspace", args=[workspace1.id]) self.client = Client() print(self.client.get(self.workspace_view_url)) # 302 - redirect to login page as expected self.client.force_login(User.objects.get_or_create(username='testuser')[0]) print(self.client.get(self.workspace_view_url)) # 200 - as expected time.sleep(2) print(self.client.get(self.workspace_view_url)) # 200 - as expected time.sleep(2) self.client.cookies = SimpleCookie() print(self.client.get(self.workspace_view_url)) # 302 - why? def test_my_test(self): pass -
Unable to login in django project
Hello I am not able to log-in in my web app.When i register in the registration form the data is saved in database but when i log in using same username and password, i am unable to login Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=30,blank=False,null=False) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10,blank=True) def __str__(self): return self.fullname forms.py class UserForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','placeholder': 'Enter Username'})) password= forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Enter Password'})) email=forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Enter Email'})) class Meta: model=User fields=['username','password','email'] class ProfileForm(forms.ModelForm): fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter fullname'})) class Meta: model=Profile fields=['fullname'] views.py:- def register(request): if request.method =='POST': form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): user=form.save() profile=profile_form.save(commit=False) profile.user=user profile.save() username = form.cleaned_data.get('username') messages.success(request,f'account created for { username }') return redirect('login') else: form = UserForm() profile_form = ProfileForm() context={'form':form , 'profile_form':profile_form} return render(request, 'users/register.html',context) urls.py:- path('login/' ,auth_views.LoginView.as_view(template_name="users/login.html"),name='login'), path('logout/' ,auth_views.LogoutView.as_view(template_name="users/logout.html"),name='logout') -
How to zip multiple uploaded file in Django before saving it to database?
I am trying to compress a folder before saving it to database/file storage system using Django. For this task I am using ZipFile library. Here is the code of view.py: class BasicUploadView(View): def get(self, request): file_list = file_information.objects.all() return render(self.request, 'fileupload_app/basic_upload/index.html',{'files':file_list}) def post(self, request): zipfile = ZipFile('test.zip','w') if request.method == "POST": for upload_file in request.FILES.getlist('file'): ## index.html name zipfile.write(io.BytesIO(upload_file)) fs = FileSystemStorage() content = fs.save(upload_file.name,upload_file) data = {'name':fs.get_available_name(content), 'url':fs.url(content)} zipfile.close() return JsonResponse(data) But I am getting the following error: TypeError: a bytes-like object is required, not 'InMemoryUploadedFile' Is there any solution for this problem? Since I may have to upload folder with large files, do I have to write a custom TemporaryFileUploadHandler for this purpose? I have recently started working with Django and it is quite new to me. Please help me with some advice. -
Django: Adding social authentication to site
I'm a beginner in Django and I'm studying Django from the book "Django 2 by Example", written by Antonio Mele. I'm trying to add social authentication to my site(book page no. 251) {project name-bookmark, app name-account}. Up to this point, I'm installed the Django package "social-auth-app-django", synced python-social-auth models with database using migration and added "social_django" to the INSTALLED_APPS settings of my project. Then I've added path('social-auth/', include('social_django.urls', namespace='social')), now it is telling me to edit my hosts file located at "C:\Windows\System32\Drivers\etc\hosts" and to add "127.0.0.1 mysite.com" line which I've added. After this running server "http://example.com:8000/account/login/" should give error, here example.com is actually mysite.com, DisallowedHost at /account/login: Invalid HTTP_HOST header:'mysite.com:8000'.You may need to add 'mysite.com' to ALLOWED_HOSTS. But I don't know why it isn't showing instead of that it gives me "This site can’t be reached. mysite.com refused to connect." Please help me I'm stuck. I've searched on google as well as watched videos on youtube but still, this error can't be solved(generated) by me. -
How to print specific number of tables per pages?
While I was working on a project I needed to generate around 2000 small tables which I also have to print in pages. I was generating those tables via using a for loop within my django project using jinja code.Here I am attaching a sample code- {% load static %} {% load tempos %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <link rel="stylesheet" type="text/css" href="{% static 'css/bcard/bcard.css' %}"> <title>bcoutput</title> </head> <body> <div class="container"> <div class="row"> {% for i in 30|get_range %} <div class="col-lg-4"> <table class="table pagebreak table-bordered"> <thead> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Handle</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <th scope="row">2</th> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <th scope="row">3</th> <td colspan="2">Larry the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div> {% endfor %} </div> </div> </body> </html> The css file I am using is: @page { size: A4; margin: 0; } @media print { body { width:100% height:100% } table { width: 30% !important; height: 50% !important; } .pagebreak { page-break-inside:avoid; } } Now, the problem I am facing is-I want to generate 6 tables per page … -
Connect Django in linux container to SQL server using FreeTDS and django-pyodbc-azure
I am developing on a windows and trying to run the Django application in Linux container with Gunicorn and Nginx to deploy it to Linux machine in production. I mostly used this Connect docker python to SQL server with pyodbc post as a guide but I think I have tried every solution found online about this error. If I ping DB server from container it gets connected so the port 1433 is open and everything should be good to go. But for some reason I'm getting error django.db.utils.ProgrammingError: ('42000', "[42000] [FreeTDS][SQL Server]Login failed for user Django settings.py DATABASES = { 'default': { 'ENGINE': "sql_server.pyodbc", 'NAME': 'database1', 'HOST': '123.45.6.78', 'PORT':'1433', 'USER': "user", 'PASSWORD': "pswd", 'OPTIONS': { "driver": "FreeTDS", "host_is_server": True, "unicode_results": True, "extra_params": "tds_version=7.3", } } } Dockerfile # start from an official image FROM python:3 # arbitrary location choice: you can change the directory RUN mkdir -p /opt/services/djangoapp/src WORKDIR /opt/services/djangoapp/src #Install FreeTDS and dependencies for PyODBC RUN apt-get update \ && apt-get install unixodbc -y \ && apt-get install unixodbc-dev -y \ && apt-get install freetds-dev -y \ && apt-get install freetds-bin -y \ && apt-get install tdsodbc -y \ && apt-get install --reinstall build-essential -y # populate "ocbcinst.ini" RUN … -
In django, how can I make this specific join?
Let's say I have class A with fields a,b,c,d,e and class B with fields a,b,c,d,f,g. I want to join them in my view, BUT I want the join to apply to every field apart from d (so, the join should take into account fields a,b,c). What's more, I want to output the field d from class A as "d.A" and the field d from B as "d.B" in the json output I give. How can I perform this kind of join? I have tried annotating then using select_related() and F() functions and then showing the different fields, but both of them have the same value. Apparently, the join keeps only the value from the value that became renamed. -
How to get a pre-populated form while updating form in django
This is my forms. class CreateBooksForm(forms.ModelForm): languages = forms.CharField(widget=forms.TextInput) file = forms.FileField(widget=forms.FileInput(attrs={'accept':'application/pdf'})) class Meta: model = Book fields = "name","languages", "about","image","file" This is my view.So when I render to my update view template I get the empty form for languages and files but other are populated. @login_required def post_update(request,pk): update = get_object_or_404(Book,pk=pk) form = CreateBooksForm(request.POST or None ,request.FILES or None,instance=update) if request.method == 'POST': if form.is_valid(): post = form.save(commit=False) languages = form.cleaned_data['languages'] post.save() # must be save before adding m2m tag_list=[Language.objects.get_or_create(name=tag)[0] for tag in post.languages.lower().split()] for tag in tag_list: a = post.language.add(tag) post.language.set = a post.save() messages.success(request,'Updated successfully!') update_book.delay(post.pk) context ={ 'form':form } return render(request,'books/update.html',context) my template.So this is simple django crispy template I have used. <form method="POST" enctype="multipart/form-data"> <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}"> <img class="rounded-circle" src="/media/{{form.image.value}}" height="100px" width="150px"> {{ form|crispy }} <button type="submit" class="btn btn-dark">Update Books</button> </form> -
Serial number in Django admin list view
I have the following list view in Django admin. How do I show serial number for every entry? Also, this serial number should also take into account the pagination of the list. -
I am developing code (say Django, or Node, or even front-end React) how to correctly continuously deploy that to server as needed
So my question here is: Can I use git for example to push the code I am developing locally on my mac or my PC to the server directly? How do companies behind websites put their code correctly on a server, especially whenever they make changes? I need to know about both development situations when Im still testing the code and production situations when I need to update a live server. Also what about the code I store as I develop in a github repo. I have a server that has Django, or Node, or React installed, and I know how to push to github. What's next for me to reach a more professional level for a website I'm building. Thanks. -
Deploying django, channels and websockets with nginx and daphne
I am trying to deploy a django app that uses channels and websockets, with nginx and daphne. When I was using uwsgi, here was my nginx file: upstream django { server unix:/run/uwsgi/devAppReporting.sock; } server { listen 8090; server_name foo.bar.com; charset utf-8; location /static { alias /var/dev-app-reporting/static; } location / { uwsgi_pass django; include /var/dev-app-reporting/uwsgi_params; uwsgi_read_timeout 3600; client_max_body_size 50m; } } Now I changed it to this: upstream django { server unix:/run/daphne/devAppReporting.sock; } server { listen 8090; server_name foo.bar.com; charset utf-8; location /static { alias /var/dev-app-reporting/static; } location / { proxy_pass http://0.0.0.0:8090; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } Started daphne like this: daphne -u /run/daphne/devAppReporting.sock app.dse.asgi:application I get a 502 bad gateway error and this in the log: 2020/02/24 22:17:26 [alert] 29169#29169: 768 worker_connections are not enough 2020/02/24 22:17:26 [error] 29169#29169: *131545 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 127.0.0.1, server: dse-portfolio-dev-assessments.md.virtualclarity.com, request: "GET / HTTP/1.1", upstream: "http://0.0.0.0:8090/", host: "xx.xx.xx.xx" Any ideas on what I should have in my config file for this to work? -
Tree View structure in web form using Django
I want to create a webform in Tree view using Django. I am completely new to it and could not able to understand how to make it. I tried the following code in html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> ul, #myUL { list-style-type: none; } #myUL { margin: 0; padding: 0; } .caret { cursor: pointer; -webkit-user-select: none; /* Safari 3.1+ */ -moz-user-select: none; /* Firefox 2+ */ -ms-user-select: none; /* IE 10+ */ user-select: none; } .caret::before { content: "\25B6"; color: black; display: inline-block; margin-right: 6px; } .caret-down::before { -ms-transform: rotate(90deg); /* IE 9 */ -webkit-transform: rotate(90deg); /* Safari */' transform: rotate(90deg); } .nested { display: none; } .active { display: block; } </style> </head> <body> <h2>Tree View</h2> <p>A tree view represents a hierarchical view of information, where each item can have a number of subitems.</p> <p>Click on the arrow(s) to open or close the tree branches.</p> <ul id="myUL"> <li><span class="caret">Beverages</span> <ul class="nested"> <li>Water</li> <li>Coffee</li> <li><span class="caret">Tea</span> <ul class="nested"> <li>Black Tea</li> <li>White Tea</li> <li><span class="caret">Green Tea</span> <ul class="nested"> <li>Sencha</li> <li>Gyokuro</li> <li>Matcha</li> <li>Pi Lo Chun</li> </ul> </li> </ul> </li> </ul> </li> </ul> <script> var toggler = document.getElementsByClassName("caret"); var i; for (i = 0; i < toggler.length; … -
generating the reports based on categories and selecting the multiple attributes from those categories
I have 6 different categories, and each category has multiple attributes ( these are fetched from multiple tables) For generating the reports user should mandatory select first category attribute name ( rest all optional) then select the next attributes of other categories. this is first step for generating 1st category Facility report generating the reports of multiple category results of report of combined two categories Vf11,Vf12,Vf13 are the values for attribute F1, similarly Vm31,Vm32,Vm33 are for M3 attributes ALL the other metrics have the common key called F1 then concatinating the values from backend SQL queries. Facility category report has 2500 rows with 40 columns I need to merge the facility report (selected attributes) with other categories (with other selected attributes) I had written the API for facility report in python Django in JSON format ,list of dictionaries which involves complex SQL queries, Stored procedures, views etc [ {F1: Vf11,F2:Vf21, ... }, {F1: Vf12, F2: Vf22, ....} ] and other category row is based on the attribute F1... I have an API [ {F1: Vf11 , M2 : Vm21, M3: Vm31 .....}, {{F1: Vf12 , M2 : Vm22, M3: Vm32 .....} ] like wise I API for all other categories … -
how to create a password with multiple images in django
I am working of my college project,what extly it is create password as set of images and those images are taking from local image file folder and create a folder in database with username and thuse password images are stored in that username folder -
Python (Django) compatible web hosting service - Windows server
We are looking for a web hosting service with Windows servers which is compatible with Django development. Do you recommend any services where the Django installation is quite easy also? Price is not important. Thanks, -
'WSGIRequest' object does not support indexing
I try to write the content of a query into a xls file in a Django app. I want to access the object this way: ls_part[0].participant_first_name I tryed it into a HttpReponse and i can access the values. But when i try to use is with xlwt i = 0 for num in range(len(cols)): row = ws.row(num) for index, col in enumerate(cols): value = ls_part[i].participant_first_name row.write(index, value) i += 1 ls_part is the result of a simple query like : ls_part = Ls_part.objects.get.filter(product=productId) It produce this error : 'WSGIRequest' object does not support indexing I understand that there is a problem with the get but i don't understand how to use __getitem__ I access my def that produce xls file by a form that is passing the filters value to my method that make the query. Maybe it comes from how i designed it. Thanks in advance. -
Django - Handle all exceptions with custom templates
I want to be able to throw exceptions with any status code. I have this template structure templates |---error | |----401.html | |----403.html | |----404.html | |----451.html | |----500.html Is there any way to raise an exception something like this: raise Error("Not available here!", status_code=451) and this will automatically show the templates/error/451.html template? And when a server error occurs, templates/error/500.html should be rendered. I tried using handler401, handler500 and raising an custom exception but nothing works... # exceptions.py class HttpResponseNotAuthenticated(HttpResponse): status_code = 401 # views.py def pseudo_view(): return HttpResponseNotAuthenticated("Please login") -
Django - redirecting back to a page shows http response (Json data) and not rendering
Question: What would be the best way of dealing with this so that the json response isn't shown if the user redirects like this? Or to take the user back to the state of the quiz before the data is retrieved? Bit of an awkward one to explain. I'm creating a quiz application using django. A user can select a quiz to undertake, when they select what quiz they are taken to the following page: (Screenshot 1) When the quiz is started, an ajax request is sent to the back end to retrieve the questions for the quiz and display them to the user. The problem is if the quiz is already started and I use the browsers back button and then reload the page it shows the json response instead of (Screenshot 1) it shows: Json Response: View.py def active_quiz(request, quiz_pk): quiz = Quiz.objects.filter(pk=quiz_pk) questions = Questions.objects.filter(quiz=quiz_pk) if request.is_ajax(): if request.method =="GET": serial = serializers.serialize("json", Questions.objects.filter(quiz=quiz_pk)) response_data = serial return HttpResponse(response_data, content_type="application/json") args={'question': questions, 'quiz': quiz} return render(request, 'quiz/quiz_active.html', args -
Django fill form from model with imagefield
I'm confused with filling form fields with model fields. I have an ImageField in my model, ImageField in my form. I know I can autofill my form with MyForm(instance=MyModel.objects.all().first()) for example. But it doesn't work with ImageField. I feel like MyForm needs 2 arguments: instance and data. How do I fill my form so that 'is_valid()' is true while my form has ImageField? EDIT: Here's my code if it's helpful def create_news(request): if request.method == 'POST': form = NewsForm(request.POST, request.FILES) print(request.POST, request.FILES) if form.is_valid(): news_pk = request.POST.get('news_id') if news_pk is not None: News.objects.filter(pk=news_pk).update(added=datetime.datetime.now(), ou=form.cleaned_data['ou'], text=form.cleaned_data['text'], image=form.cleaned_data['image']) return redirect(reverse('action_status')[:-1] + '?message=Новость_изменена&color=lawngreen&redirect=create_news') else: News.objects.create(ou=form.cleaned_data['ou'], text=form.cleaned_data['text'], image=form.cleaned_data['image']) return redirect(reverse('action_status')[:-1] + '?message=Новость_добавлена&color=lawngreen&redirect=create_news') else: news_pk = request.GET.get('news_id') params = {} if news_pk is not None: params = {'instance': News.objects.get(pk=news_pk)} form = NewsForm(**params) return render(request, 'create_news.html', {'form': form, 'news': News.objects.all().order_by('-added')}) -
Django specify manually fields to include as nested JSON
With django-rest-framework I'm creating a REST API where I can access and modify information about people in a city. People belong to a city, and therefore have a foreign key linking to the City model. With the code below, I'm serializing the Person object along with the City object resulting in nested JSON. However, as this is a simplified code example, and the real project has much more data and fields, and the nesting goes deeper, it ends up slowing down the API greatly, especially when accessing all Person entries. Is there a way to optionally specify if I want to include the nested serialization, or if I just want the shallow Person model with the primary key ids? class City(models.Model): name = models.CharField(max_length=255, unique=True) class Person(models.Model): name = models.CharField(max_length=384) city = models.ForeignKey(City, on_delete=models.CASCADE) class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = '__all__' class PersonSerializer(serializers.ModelSerializer): city = CitySerializer() class Meta: model = Person fields = '__all__' JSON: [ { "id": 1, "name": "Simen", "city": { id: 1, name: "Oslo" } }, { "id": 2, "name": "Roar", "city": { id: 2, name: "Trondheim" } } ] -
Deploying to GoogleAPP ENGINE
on deploying my application to google app engine i encountered the following error when i try to click on the endpoints i have, is there away to solve this since i cant seem to do migrations on google app engine?? Traceback (most recent call last): File "/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) The above exception (relation "api_rent_record" does not exist LINE 1: ...ecord"."damaged", "api_rent_record"."faulty" FROM "api_rent_... ^ ) was the direct cause of the following exception: File "/env/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/env/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/env/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/env/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/env/lib/python3.7/site-packages/rest_framework/mixins.py", line 46, in list return Response(serializer.data) File "/env/lib/python3.7/site-packages/rest_framework/serializers.py", line 760, in data ret = super().data File "/env/lib/python3.7/site-packages/rest_framework/serializers.py", line 260, in data self._data = self.to_representation(self.instance) File "/env/lib/python3.7/site-packages/rest_framework/serializers.py", line 678, in to_representation self.child.to_representation(item) for item in iterable File "/env/lib/python3.7/site-packages/django/db/models/query.py", line 276, in __iter__ self._fetch_all() File "/env/lib/python3.7/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/env/lib/python3.7/site-packages/django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1144, in execute_sql cursor.execute(sql, params) File "/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute return … -
Store data from multiple URLs in python
I have 10 URL's which are csv file. I want to store data from multiple URL's in a list in python. All URL's are a csv file in same format. I have tried: url = request.GET.get('url') #for first url data = [] with closing(requests.get(url, stream=True)) as f: dfs = [pd.read_csv(filename) for filename in f] I am able to extract the data but how can I get data from rest of the URL's and store all of them in a list. -
How can I toggle a form having prefilled content with an edit button in django
I have a form that users can fill to leave a review. On the same page, the reviews are displayed with a button to edit the review. When the edit button is clicked, I would like for the form to be pre-filled with the appropriate review data, so that it can be edited and updated in the database. models class Clinic(models.Model): practitioner = models.OneToOneField(User, on_delete=models.CASCADE) lat = models.FloatField(null=True, blank=True) lng = models.FloatField(null=True, blank=True) web = models.CharField(null=True, blank=True, max_length=128) name = models.CharField(max_length=128, ) phone = PhoneNumberField() description = models.TextField(max_length=5000) street = models.CharField(max_length=128, ) city = models.CharField(max_length=128, ) def __str__(self): return self.name def save(self): super().save() class Reviews(models.Model): title = models.CharField(max_length=128) body = models.TextField(max_length=500) author = models.ForeignKey(User, on_delete=models.CASCADE) clinic = models.ForeignKey(Clinic, null=True, blank=True, on_delete=models.CASCADE) Form class ReviewForm(forms.ModelForm): class Meta: model = Reviews fields = ( 'title', 'body', ) View def clinic_profile(request, clinic_id): clinic = Clinic.objects.filter(pk=clinic_id) form = ReviewForm(request.POST) if request.method == 'POST': if form.is_valid(): r_clinic = Clinic.objects.get(pk=clinic_id) title = form.cleaned_data.get("title") body = form.cleaned_data.get("body") review = Reviews(title=title, body=body, author=request.user, clinic=r_clinic) review.save() messages.success(request, f'Thank you for leaving a review!') clinic_reviews = Reviews.objects.filter(clinic=clinic_id) latlng = { "lat": clinic[0].lat, "lng": clinic[0].lng, "name": clinic[0].name } def get_mods(): profile = Profile.objects.filter(user=Clinic.objects.get( pk=clinic_id).practitioner) mods = profile[0].mods.all().values('name') if profile else [] …