Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
display:'table' is not working as it supposed to be
I want the table to be visible only after the submit button clicks. But it's not staying on the screen as it is supposed to be. Once I click the submit button, the table comes up for a second and then again becomes invisible. Please let me know what I am doing wrong in my code. Also please let me know if there is any other way to do it. index.html <form action="#" id="form" method="post"> <div style="margin-left: 2rem;"> <!-- <input class="btn btn-primary" type="submit" value="Submit" id="btn" onclick="hide()"> --> <input class="btn btn-primary" type="button" value="Submit" id="btn" onclick="hide()"> </div> </form> <div style="margin-top: 4rem; display: flex; justify-content: center; align-content: center;"> <table style="display: none;" id="table"> <tbody> <tr> <th scope="row">Profile No. : </th> <td>{{ProfileNo}}</td> </tr> <tr> <th scope="row">Name : </th> <td>{{Name}}</td> </tr> </tbody> </table> </div> <script> function hide() { document.getElementById("form").submit(); let table = document.getElementById("table"); if (table.style.display === 'none') { table.style.display = 'table'; } } </script> -
Selecting items from a many to many field to link specific items in the list to a model in the admin panel
I am working on a recipe book app, and I currently have my models connected in this way: class Tool(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=200) def __str__(self): return self.name class Recipe(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=200) servings = models.IntegerField(default=1, blank=False) tools = models.ManyToManyField(Tool) def __str__(self): return self.name The admin panel input currently looks like this: Upon saving the data as shown in the screenshot, I get the following error: OperationalError at /admin/recipeBook/recipe/add/ no such table: recipeBook_recipe_tools Here is my admin.py, just incase it's useful: from django.contrib import admin from .models import Recipe, Ingredient, Instruction, Tool # Register your models here. class IngredientInline(admin.TabularInline): model = Ingredient extra = 2 class RecipeAdmin(admin.ModelAdmin): fieldsets = [ ('Information', {'fields': ['name', 'description', 'servings']}), ('Tools', {'fields': ['tools']}) ] inlines = [IngredientInline] list_display = ('name', 'description', 'servings') search_fields = ['name'] list_filter = ['servings'] admin.site.register(Recipe, RecipeAdmin) admin.site.register(Ingredient) admin.site.register(Instruction) admin.site.register(Tool) -
Django POST getlist for dynamic content
I a database I have a list of products. If they are need to be found = True they will appear in the screen : <h2>Shopping list</h2> <section> {% for market in markets %} <button class="collapsible">{{market.name}}</button> <div class="content"> <ul> {% for shopping in shoppings %} {% if shopping.marketplace.name == market.name %} <div id="conteneurs"> <div class="product"><label for="stock" class="control-label">{{shopping.name}}</label></div> <div class="stock"><input type="number" name="stock" value="{{shopping.quantitytobuy}}" id="stock"></div> <div class="checkbox"><input type="checkbox" name="found"></div> </div> {% endif %} {% endfor %} </ul> </div> {% endfor %} </section> <div id="validation"> <div class="validation"><input type="submit" value="Found"></div> </div> If I found the product I can check a box. I would like to recover the amount for the products where I check the box the quantity to can update the stock of them. I have no idea where to start : should I need to define a variable for the checkbox ? how do I recover the quantity with the associate product for all the line checked in the file views.py def shopping(request): marketplaces = Marketplaces.objects.order_by('name') products = Products.objects.all().filter(buy=True) template = loader.get_template('stock/shopping.html') context = {'markets' : marketplaces, 'shoppings' : products, } return HttpResponse(template.render(context, request=request)) -
Django / Access to previous or next instance from the same class
My app starts with Scene1 Here is my Models.py where Scenes are defined class Scenes(models.Model): name = models.SlugField('Scene name', max_length=60,unique=True) description = models.TextField(blank=True) fileGltf = models.FileField(null=TRUE, blank=False, upload_to="3dfiles/") record_date = models.DateTimeField('Scene date') manager = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) prev = models.ForeignKey( 'self', related_name='next', blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.name The creation is ok. Then in views.py, let's say my current scene is : myScene=Scenes.objects.get(name=whichScene) If I want to list all next scenes from this scene : scene_list=myScene.next.all() If I want to access to the previous scene, what is the correct syntax ? scene_previous=myScene.prev -
Load foreign model instances into queryset.values()
I have queryset that groups and aggregates some data: EmployeeAssessment.objects.all().annotate(month=TruncMonth('assessment_date')).values( 'month', 'assessed_employee', 'subject' ).annotate(average_score=Sum('scores__score') / Count('scores__score', distinct=True)) And because of .values() I get assessed_employee and subject as IDs rather than model instances I know that there are some similar questions here, but they're all talking about single relation, that can be reversed to get the needed data from related model. My problem is that I need to get two nested objects: "assessed_employee" and "subject". Both of them are ForeignKeys I use DRF serializer like this: class EmployeeAverageScoreSerializer(Serializer): month = DateField() assessed_employee = EmployeeSerializer() # <- ModelSerializer subject = AssessmentSubjectSerializer() # <- ModelSerializer average_score = FloatField() It is ok if I will have some subqueries or something, but I need a single queryset that still can be paginated. How can I load models by ID after applying ".values" or maybe what other way can I use to get that data without losing model instances in resulting queryset? -
No module named 'crispy_formsecommerce' error
I already installed crispy forms, and fixed settings. But raising an error. The Error: enter image description here My settings.py file: enter image description hereenter code here enter image description here my pipenv installed apps : enter image description here some template: enter image description here my forms.py: enter image description here Please help!