Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template if inside a for loop with list indexing
I want to fetch the values of a list using indexes of a list. I have a list in views.py views.py def home(request): my_list=[("xy","abc","abcd"),("abcd","abc","xy")] context={ "list"=my_list} return render(request, 'index.html',context) index.html {% for id in list%} {% if id.1 =='abc' %} {{id.0}}="Core user" {{id.0}} {% else %} {{id.0}} {% endif %} {% endfor %} So if the condition satisfies, the new values of the list would be [("xy","Core user","abcd"),("abcd","Core user","xy")] I am getting syntax errors for this. Please let me know what am I doing wrong and how to resolve this? -
Django and django rest framework saving profile information
How is possible to save profile information as I am using django rest api to login a user and the response which I am getting is with the help of requests library .what I want is to save the response and show in profile page .How can I achieve this in django?should I use cookies or session for this. -
If fetch returns object with multiple attributes (ie. object.exists and object.message) how can I use them after fetch is done?
After fetch returns object it logs it perfectly and I can see all attributes in the object. I can even change the html in the page using all the attributes. login_button=document.getElementById('submit-login'); login_form=document.getElementById('login-form'); message=document.getElementById('message'); login_button.addEventListener('click',async (e)=> { e.preventDefault(); form=new FormData(login_form); let response = await fetch('/',{ method:'POST', body: form, headers:{ 'X-CSRFToken':document.cookie, // 'X-Requested-With': 'XMLHttpRequest', }, }); let processed_response=await response.json(); console.log(processed_response); if (processed_response.exists){ console.log('success'); message.classList.remove('failure'); message.classList.add('success'); } else{ message.classList.remove('success'); message.classList.add('failure'); } message.firstElementChild.innerHTML=processed_response.message; setTimeout((processed_response) => { window.location=processed_response.next; },1000); }); However, when I try using the setTimeout function it logs the following: Uncaught TypeError: can't access property "next", processed_response is undefined And well I'm not able to use the attribute from the object in the setTimeout function. Is there something I'm missing. This is my first time dealing with async and fetch/promises so sorry for any low quality code here. Thanks in advance. -
Django Upload pdf then run script to scrape pdf and output results
I am attempting to create a Django web app that allows the user to upload a pdf then have a script scrape it and output and save certain text that the script scraped. I was able to find some code to do the file upload part. I have the script to scrape the pdf. Not sure how to tie them togther to accomplish this task. views.py from django.shortcuts import redirect, render from .models import Document from .forms import DocumentForm def my_view(request): print(f"Great! You're using Python 3.6+. If you fail here, use the right version.") message = 'Upload PDF' # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return redirect('my-view') else: message = 'The form is not valid. Fix the following error:' else: form = DocumentForm() # An empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form context = {'documents': documents, 'form': form, 'message': message} return render(request, 'list.html', context) forms.py from django import forms class DocumentForm(forms.Form): docfile = forms.FileField(label='Select a file') models.py from django.db import models class Document(models.Model): docfile = … -
how to make a view where user can select text, highlight and save as input for a readonly text field in django?
I am new to web programming and testing out a simple blog. What I am trying to make is a Django view where non editable text field can get input only as highlight and maybe able to accept some comments on each highlighted chunk.(e.g "Google docs, suggest edit and comment" style). Can anyone pls tell me what kind of view(DetialView or any others?) I would need to implement in views.py? Thanks in advance. -
loading a file in my javascript file and using the js file in django
So im trying to use three js in a django project in the javascript file i am loading files to use in my 3d scene when i build it creates a functionning website because it knows where everything should be how ever i am kinda struggling to make it work in a django project please help and i would appreciate it /* [18/May/2022 17:40:32] "GET /textures/environmentMaps/1/ny.jpg HTTP/1.1" 404 2449 Not Found: /textures/environmentMaps/1/py.jpg [18/May/2022 17:40:32] "GET /textures/environmentMaps/1/px.jpg HTTP/1.1" 404 2449 [18/May/2022 17:40:32] "GET /textures/environmentMaps/1/nx.jpg HTTP/1.1" 404 2449 [18/May/2022 17:40:32] "GET /textures/environmentMaps/1/nz.jpg HTTP/1.1" 404 2449 [18/May/2022 17:40:32] "GET /textures/environmentMaps/1/py.jpg HTTP/1.1" 404 2449 Not Found: /main.css [18/May/2022 17:40:47] "GET /main.css HTTP/1.1" 404 2374 [18/May/2022 17:40:47] "GET /static/JS/bundle.2e62d86b71032951.js.map HTTP/1.1" 404 1858 [18/May/2022 17:40:47] "GET /static/style/main.css.map HTTP/1.1" 404 1813 */ one place where my js file is trying to load other files -
how to disable User fields to show my custom form in my template?
I have a problem with a form. It is a form that works like an "edit profile". I just want to style it, I don't like how it looks if I just put {{ form }} in my template, I'm using widget_tweaks to give it a better look. The problem is that when I use widget_tweaks and click the "Save" button, it doesn't work. But if I use the unstyled form {{ form }} instead, it does edit the fields. I'm thinking that when rendering the fields with widget_tweaks I'm not including the default User fields like: password, last login, etc. because I don't need them, I think that is influencing my form not working. Do you have any idea how to disable the default User fields and can I use the widget_tweaks or is it better to use forms.py? models.py COUNTRIES=( ('EUA', ('EUA')), ('Canada', ('Canada')), ('Other', ('Other')), ) class CustomUser(AbstractUser): phone1=models.IntegerField(default=0) phone2=models.IntegerField(default=0) fax=models.IntegerField(default=0) website=models.CharField(max_length=100,default=0) socialMedia1=models.CharField(max_length=100,default=0) socialMedia2=models.CharField(max_length=100,default=0) socialMedia3 = models.CharField(max_length=100,default=0) alternativeContact=models.CharField(max_length=100,default=0) country = models.CharField(max_length=100, default=0,choices=COUNTRIES) address=models.CharField(max_length=100, default=0) city=models.CharField(max_length=100,default=0) state=models.CharField(max_length=100,default=0) zip=models.CharField(max_length=10,default=0) tax_percentage=models.IntegerField(default=0) def __str__(self): return self.phone1 admin.py # Register your models here. class CustomUserAdmin(UserAdmin): add_form = UserCreationForm form=UserChangeForm model=CustomUser list_display = ['pk','email','username','first_name','last_name'] add_fieldsets = UserAdmin.add_fieldsets+( (None,{'fields':('email','first_name','last_name','image','location','phone1','phone2','fax','website', 'socialMedia1','socialMedia2','socialMedia3','alternativeContact','country','address', 'city','state','zip','tax_percentage')}), ) fieldsets = … -
Writing url in View in Django
I want to define a link for a character in the view. I used the following code, but it has an error. Error: Encountered unknown tag 'url' code: html=""" <p> <a href="{% url index2 %}">more information</a> </p> """ I use the Folium library and want to put a link in the popup. So I can not use the normal mode and I have used the above method. -
Django deployment error "usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: "
I am trying to deploy a Django app on a Linux virtual machine created on Google Computing Engine (GCE). My domain name works fine but the wsgi server does not run because of the error in the title. supervisor.log looks like tis. . . . usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: I am having a hard time troubleshooting because it does not tell me where to look into. The error seems to occur when I run gunicorn_start via commands such as sudo supervisorvtl restart tutorial or chmod +x .../venv/bin/gunicorn_start because I can run the contents of the file directly via my terminal. This is how my file tree looks like: /webapp/user |--- req.txt |--- venv |--- tutorial |-- req.txt |--manage.py |--tutorial . . . |--wsgi.py |--settings.py . . . I thought that the cause of this error is in the contents of the gunicorn_start file. So I ran the shell scripts in the file directly in the VM's … -
How to add math operations to a field ? DJANGO
I have a CreateView that generates a form. In this form there is a field that accepts float values. On the backend, i want to add math operations to this field and save the result in the database. How do I do this? -
Path finding between models in Django
I am trying to make a graph like structure in django using models to create paths between model instances. But I am no quite sure about how to do that automatically. The basic structure of my models is something like this: class Location(TimeStampedModel): name = models.Charfield() level = models.SmallPositiveIntegerField() previous_locations = models.ForeignKey('self') next_locations = models.ForeignKey('self') related_locations = models.ForeignKey('self') That previous_locations, next_locations and related_locations were my first approach in order to get some kind of tree structure, but they are pretty useless when there are several locations with the same level. For example, location_1 (with level = 1) can go to location_2 and location_3 (both with level = 2) and then both can go to location_4 (with level = 4). Maybe changing the foreign key to a many to many relation can solve this, but it's still not clear to my how to create the paths. For the paths, I made the following model: class Path(TimeStampedModel): name = models.Charfield() locations = models.ManyToManyField(Locations) Summarizing, the goal is select two locations and automatically create the shortest path or a group of paths (as maybe 2 paths require the same amount of steps). However, I don't know how to doit with the relations I … -
how to remove <li> in django forms
at the second orange button on the left (insert file audio) there's text : record : this field is required. i want to remove that text, please help me. here's my form code. form.py : from django import forms class Audio_store(forms.Form): record=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control'})) -
How to set cookies using GraphQLTestCase
I have dug far and deep but no working solution yet, based on some things I read from a thread somewhere, it seems you have to prefix headers with HTTP_ e.g. HTTP_AUTHORIZATION ends up being the Authorization header, based on that my current attempt is: class TestImpersonatation(LogonUserMixin, GraphQLTestCase): : def test_...(self): response = self.query(''' ...mutation here... ''', headers = { "HTTP_AUTHORIZATION": f"JWT {self.token}", "HTTP_SET_COOKIE": f"my-jwt-token={self.token}" }, variables={ ...vars... } ) but alas, every time I get to my breakpoint there is only ever one cookie set, a csrf token. I am stumped but still trying... next it to se if a Client() instance can be passed in to work some magic instead of relying on the one created inside. -
how to be able to add records using Http Methods on django
I'm creating a Django rest API authentication system and I want to return data in JSON format,the main purpose of this question is : I want to add or delete users only by adding fields on json format , not in the inputs that've created : this is my views.py : # Rendering plant data as json : def plant_json(request): data=list(new_Plant.objects.values()) return JsonResponse(data,safe=False) this is my output ( don't mind the values ) : [{"id": 5, "name": "dqsd", "adress": "sdq", "type": "PV", "location": "dqd", "list_gateway": "gggdds", "status": "etude"}, {"id": 6, "name": "fdsfds", "adress": "fsdfds", "type": "PV", "location": "fdsfds", "list_gateway": "fdsfs", "status": "etude"}, {"id": 7, "name": "sdqdssd", "adress": "dsdsq", "type": "HYBRID", "location": "dqsdqs", "list_gateway": "dsdqss", "status": "online"}] normally in order to add a new plant I've created a HTML template that has inputs where the user can add a plant , but what I want is that I can add a plant only by adding fields directly using json format ( using postman for example ) no need for the inputs. Thank you -
Hvplot with django and netcdf
im working on a django project for visulisation of netcdf data , i use hvplot to plot the data and there is no interactivity , i want to know if possible how to make it possible. the plot in browser my code : import hvplot import hvplot.xarray import xarray as xr import holoviews as hv import panel as pn from panel.interact import interact import numpy as np from bokeh.plotting import figure from bokeh.embed import components from bokeh.layouts import column, grid from bokeh.models import ColumnDataSource, CustomJS, Slider,HoverTool hv.extension('bokeh') def data_visualization(request): ds = xr.open_dataset('T_mensuel.nc') def plot(variable): return ds[variable].hvplot.line() model = interact(plot, variable = list(ds.data_vars)) script, div = components(model.get_root()) return render(request,'visualization.html',{'script': script, 'div': div}) -
Database population with django models, module not found error
I am just getting started with the Django framework through the book "The Definitive Guide to Django." I used psycopg2 to write my SQL insert statements (Postgres) through a script named scrape.py. I wanted to switch to using the Django models, however, I get an django.core.exceptions.ImproperlyConfigured error when I try to run from models import articles. I first used import os os.environ['DJANGO_SETTINGS_MODULE'] = 'CannaMed.settings' But got the error File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/db/models/base.py", line 127, in __new__ app_config = apps.get_containing_app_config(module) File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/apps/registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'CannaMed' I then added import django django.setup() and got the error: Traceback (most recent call last): File "scrape.py", line 2, in <module> django.setup() File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 67, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Lastly … -
Django/Pandas/Website - Querying a pandas dataframe instead of database, is it possible?
My table has some advanced features and queries that Pandas can accomplish but a database can't, so I am wondering about the implications of using a pandas dataframe on the server as a read-only database. The setup would be the basetable being a big pandas dataframe (400mb) on the webserver, and users submit GET requests that filter it in unique ways in order to make charts off of the data. The question is are there serious costs and/or bottlenecks when many users query a webservers dataframe? I know databases are meant to serve many people concurrently, but is this a problem for my case? Further, after a user filters the table, I imagine this filtered table is temporarily saved during their session....could this lead to memory requirements of the webserver gettings wildly out of hand? (Ex: 1000 users x 200MB avg table size = 200GB of memory demanded) Any explanation and tips would be appreciated! -
Django advanced i18n url patterns
I'm trying to create urlpatterns in django that would allow me something like this: .../en/admin .../en/some_view .../api/en/another_view basically i'd like to sort some of my views under "/api/" but I would like to prepend this before the /en/ for those views. Is something like this possible in django? -
Distribution for Django_Eel not found after Django_eel converted to exe by using Pyinstaller
I try to convert Django Eel to exe so client can run the page from their end without publish the django eel to server, I try to exe the django by pyinstaller --noconfirm --onefile --console "C:\KMME\demo\manage.py" But when i run the EXE I get below error: pkg_resources.DistributionNotFound: The 'django-eel' distribution was not found and is required by the application [1712] Failed to execute script 'manage' due to unhandled exception! Please help and share ideas to overcome this even though Django EEL already being install. -
Django search Form <QuerySet []>
I am creating a Search_Model with QuerySet. For example, if i search for apples The result is displayed as Search By <QuerySet []> Why is this? My html declaration is like this <h1> Search By {{posts}} <h2 MY BASE.HTML <form class="form-inline my-2 my-lg-0" action="{% url 'search' %}"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> MY SEARCH.HTML {% extends "shopping_mall/base.html" %} {% block search %} <div> <h1> Search </h1> <h2> Search By {{posts}} </h2> </div> {% endblock %} MY urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('search/',views.search, name='search'), path('top_cloth/', views.top_cloth), path('top_cloth/<int:pk>/', views.cloth_detail, name='top_cloth_pk'), path('top_cloth/<int:pk>/comment/', views.add_comment, name='add_comment'), path('top_cloth/<int:pk>/remove/', views.comment_remove, name='comment_remove'), path('top_cloth/<int:pk>/modify/', views.comment_modify, name='comment_modify'), ] MY views.py def search(request): search_post = request.GET.get('search') if search_post: posts = ProductList.objects.filter(Q(product_name__icontains=search_post)) else: posts = ProductList.objects.all().order_by("-date_created") return render(request, 'shopping_mall/search.html', {'posts': posts}) -
What's the difference between MEDIA_ROOT = BASE_DIR / 'media'` and MEDIA_ROOT= os.path.join(BASE_DIR, "media") in Django setting.py
I wanted to know the difference between using MEDIA_ROOT = BASE_DIR / 'media' and MEDIA_ROOT= os.path.join(BASE_DIR, "media") in settings.py. I used MEDIA_ROOT = BASE_DIR / 'media' and my file uploading works fine but when I delete a file it stays in the directory. -
heroku open =>relation "main_goal" does not exist LINE 1: ...y", "main_goal"."date", "main_goal"."status" FROM "main_goal
When I run the Heroku open command , it returns an error Everything works locally heroku run manage.py migrate doesn't help, makemigrations too, manage.py migrate r run-syncdb - also does not give anything enter image description here enter image description here -
Send JavaScript value to method on views.py (Django)
I'm using django (4.0.4) to develop a 'simple' interface with three dropdown list with the data of the last two depends of the value selected of the first. This is the front: This is the project structure dir: ├── db.sqlite3 ├── manage.py ├── example_web │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── web ├── admin.py ├── apps.py ├── __init__.py ├── migrations ├── models.py ├── static │ ├── css │ │ └── style.css │ └── js │ └── app.js ├── templates │ ├── index.html ├── tests.py └── views.py This is urls.py from django.contrib import admin from django.urls import path from web.views import homePageView urlpatterns = [ path('admin/', admin.site.urls), path('', homePageView), ] views.py from django.shortcuts import render from django.template import loader from django.http import HttpResponse from jf.clients import RPClient def homePageView(request): a = _get_coaches() b = _get_devices() value_js = request.GET.get('id') print(value_js) context = { 'coaches': a, 'devices': b, } return render(request, 'index.html', context) def _get_coaches(): client = RPClient('dev', proxy_ip='10.10.1.15') a = client.get_current_value('status/coach') return [i['id'] for i in a['items']] def _get_devices(request): client = RPClient('dev', proxy_ip='10.10.1.15') a = client.get_current_value('status/cable/X') # !!!!!!!!!! # HERE is where in the X place I want to store the value_js variable … -
How to create a Django queryset based on items from another
I'm using Django 2.2.28 and Python 3.7.7 in a legacy application. I have a display page that displays People based on a class PeopleQuerySet(models.QuerySet) that's filtered and paginated. This works, but I'd like to know if it's possible to do something like this: new_people_queryset = PeopleQuerySet() for person in existing_queryset.iterator(): if some_condition: new_people_queryset.add(person) Is there a way to do what I'm implying above; create an empty PeopleQuerySet() object and then insert people into it from a queryset that's the result of filtering? The some_condition thing is some arbitrary Python logic I'm using for illustration purposes here. Any ideas, pointers, etc. would be greatly appreciated. -
populating django database using migrations
I created an api that allows to read some data with filters based on the models I created. and launch the database is empty so I created a script to populate the database. I then dockerized the app and deployed to AWS. the issue here is that everytime the container restarts the script is re-run. I would like to use migrations to do this. how? for now the docker entrypoint is python manage.py wait_for_db python manage.py makemigrations API python manage.py migrate # python import_csv.py uwsgi --socket :9000 --workers 4 --master --enable-threads --module myapi.wsgi