Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass mulltiple values for same column in get request, vector-tile, djangorestframework-mvt?
I followed the https://corteva.github.io/djangorestframework-mvt/html/index.html to serve the vector tiles for Geodjango application. As mentioned in the documentation, the filter for vector tile can be done as: GET api/v1/data/example.mvt?tile=1/0/0&my_column=foo HTTP/1.1 Now i want to get the vector tiles for the query like, api/v1/data/example.mvt?tile=1/0/0&my_column__in=foo,foo1,foo2 but I am not able to get results with this statement. I am using OpenLayers to visualize the results. the code sample used for this action is: var urlFilter = '/api/v1/data/house.mvt?tile={z}/{x}/{y}&houseId__in=547090906080,547090105191'; var vectorRiver = new ol.layer.VectorTile({ declutter: true, // style:simpleStyle, source: new ol.source.VectorTile({ // tilePixelRatio: 20, // oversampling when > 1 tileGrid: ol.tilegrid.createXYZ({maxZoom: 24}), // projection: 'EPSG:3857', format: new ol.format.MVT(), url: urlFilter }) }); spatialMap.addLayer(vectorRiver); Note: I have no problem in the filter for single values, this task can be simply accomplished but the problem is when i need to have filter with multiple values using "In" operator. -
django.urls.exceptions.NoReverseMatch: Reverse for 'home' not found. 'home' is not a valid view function or pattern name
I have a problem where my url is seen as an invalid url. None of my URLS are working for my Django Application. I have made the mistake of using the same secret key that I used for another application. Here is a picture of my error message, url page, and my views. Error Message urls.py views.py -- James Francies -
Django: Unknown field(s) (avatar) specified for User
So I have this models from django.db import models from django.conf import settings # Create your models here. class ProfileImage(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, editable=False ) avatar = models.ImageField() And my admin.py from django.contrib import admin # Register your models here. from django.contrib.auth.admin import UserAdmin UserAdmin.fieldsets += ('Custom fields set', {'fields': ('avatar',)}), I am using the User model, and I add to it a imagefield, but I want to see the image field in the admin page so a did that in admin.py but when I enter to the users admin this error appear: Unknown field(s) (avatar) specified for User. Check fields/fieldsets/exclude attributes of class UserAdmin. -
How does this method of save in django works
Hi Im learning django from a textbook and It used this method to save the image but i can not understand the concept where did the image.image.save come from ` ''' forms.py def save(self, force_insert=False, force_update=False,commit=True): image = super().save(commit=False) image_url = self.cleaned_data['url'] name = slugify(image.title) extension = image_url.rsplit('.', 1)[1].lower() image_name = f'{name}.{extension}' # download image from the given URL response = request.urlopen(image_url) image.image.save(image_name,ContentFile(response.read()),save=False) if commit: image.save() return image ''' -
File Explorer like sFTPClient/Filezilla (Preferred lang- python with Django) in web application to access file system of any server with any OS
Detailed Requirement:- user log in into web application, he will find multiple group of servers shown on UI section (Stored in database) In group of server, there will be multiple servers (can be Linux, windows, fadora, etc.) User clicks on any of the server (No need to put username, password of that server as it will be handled in backend). Server gets connectivity. File System link will appear (Button click) On the click of File System link, it will browse the directory structure like (C dirve,D drive in case of windows server), sub-directories, files present on that particular server depending upon the permissions logged in User have. User should able to delete the directory/sub-directory/files, open the file, edit, and save it again like filizilla. All these operations need to perform in web application, just like any SFTP Clients e.g., sFTP Client, FileZilla, User should have the file explorer on UI(not desktop file explorer, totally on webapplication). We have tried to achieve this using network library PARAMIKO which can be used to run the custom commands on any remote server. In this we accessed the directories, sub-directories, files present on remote server But for building directory structure with filesystem functionality as … -
AWS EC2 django file creation permission error
AWS EC2 Django help needed. my django backend has function wherein a file is created with : f = open("xyz.txt", "w") when i run it with runserver command on ec2 aws it runs fine. but when i run it with apache it says permission denied and give me an error -
Passing variables/data in other components in django
I've been trying to pass my email variable which is stored in my login component, to my info component in django! I'm using redirect to transfer my URL to info app, but its not accepting any parameters of other components. What should I do to pass my data to other components?? -
How to close the Django admin editable popup on clicking "Save" button
I am having a link on the parent admin page. When I clicks on the link, an editable django admin popup page opens. After updating the details, When I clicks on the Save button, details are saved. But the requirement is to close that popup after clicking on Save button. My editable admin Django model looks like below @admin.register(SellOwnership) class SellOwnershipAdmin(admin.ModelAdmin): list_display = ("sell", "owner", "amount") list_editable = ("amount") Kindle advise how to achieve to close the popup while clicking on save button. Thanks. -
returning html file with django after user input
I have some HTML tables which I extract from a third party program which I'd like to show without using a javascript. The user gets to see 4 categories and each category has multiple options. From each category only 1 item can be selected. For instance: https://simpleisbetterthancomplex.com/tutorial/2016/11/28/how-to-filter-querysets-dynamically.html This site takes information from a database, but what I want to do is, is to filter for a specific HTML table. Since i have like 2800 tables I want a quick way to filter for it. Using: Checkmarks, and a slider for percentages from 0% to 100% that defines a range. now I'd like to receive the input and link them to an html table which I have stored. I have tried linking my javascript to it, but it will only load images and not an HTML table. What's my course of action? Thank you so much -
How to show Error on Django Admin Panel after entering invalid data at save process
How can I suspend save process and show errors with friendly description on admin panel. For example there is CharField title with unique=True parameter. How to show error to user if he/she enter duplicate value to title and click to save? Note: I don't use forms yet. I use only models and input all of the values with Admin Panel -
Accessing fields of OneToOne related model in wagtail edit
How to get another fields of related model inside ModelAdmin panels List? Tried this: 'user__first_name', doesn't work. It seems that its not possible out of the box, but maybe have some one already done this? There are my models, User is just regular django.auth User model and it has first_name by default. # models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='customers') org_title = models.CharField(max_length=500, default='', blank=True) # wagtail_hooks.py class CustomerAdmin(ModelAdmin): model = Customer menu_label = 'Customer' menu_icon = 'pilcrow' menu_order = 200 add_to_settings_menu = False exclude_from_explorer = False list_display = ('user', 'org_title') list_filter = ('user', 'org_title') search_fields = ('user', 'org_title') panels = [ FieldPanel('user__first_name'), FieldPanel('org_title') ] -
Docker image not running, db error: django.db.utils.OperationalError could not translate host name "postgres" to address: Name or service not known
So I've managed to build my Docker image locally using docker-compose build and I've pushed the image to my Docker Hub repository. Now I'm trying to get it working on DigitalOcean so I can host it. I've pulled the correct version of the image and I am trying to run it with the following command: root@my-droplet:~# docker run --rm -it -p 8000:8000/tcp mycommand/myapp:1.1 (yes, 1.1) However I soon run into these two errors: ... File "/usr/local/lib/python3.8/dist-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.8/dist-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "postgres" to address: Name or service not known ``` ... File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.8/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.8/dist-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known ``` This may be due to how I have divided my application (using docker-compose,yml) into two services and have only pushed the image of the app since my previous post. Here is my docker-compose.yml file: Here is my … -
django-leaflet custom map
I'm trying to add my own game map using django-leaflet. Followed https://leafletjs.com/examples/crs-simple/crs-simple.html, but this does not work for me, I only get to see the normal default world map. My code: function map_init_basic (map, options) { var map = L.map('map', { crs: L.CRS.Simple, }); var bounds = [[0,0], [1000,1000]]; var image = L.imageOverlay('West_Virginia_Map.jpg', bounds).addTo(map); } Settings.py: LEAFLET_CONFIG = { 'ATTRIBUTION_PREFIX': 'Powered by django-leaflet', } What am I doing wrong? Thanks. -
How to bulk update objects in a list
I have a list of objects that I update: membership_list = list(Memberships.objects.all()) for member in membership_list: member.status = var # could be 1/2/3 etc member.save() However, this is very inefficient as with 100 memberships it hits the DB 100 times. Instead I want to use bulk_update: for member in membership_list: member.status = var # could be 1/2/3 etc Memberships.object.bulk_update(membership_list) However this obviously doesn't work, as the original list is not updated. What's the most efficient way to achieve this? I could reconstitute the list, but this doesn't feel very DRY: another_list = [] for member in membership_list: member.status = var # could be 1/2/3 etc another_list.append(member) Memberships.object.bulk_update(another_list) Is there a better way? -
Django: I can´t delete users in django admin
So I have a the get_user_model for my users, but when I try to delete one of them this appear OperationalError at /admin/auth/user/6/delete/ no such table: main.auth_user__old Does anyone know what is going on? -
Are there limits with Celery and Django
I have a Django app that uses Celery to do lots of polling and Celery beat to schedule those polls. I use gevent instead of perfork worker. It polls network devices using various things such as a vendor api, SNMP, and, if needed, ssh to the command line. It works but I don't think it will scale well, nor do I think Celery was built for this. Anyone have thoughts on this? -
While running a project from Git on my pycharm, showing some error
Every Django project that I'm trying from git is showing the same error. Although I install all the requirements it is still showing error while I try to run the server. Image Link-This is the command which I try to execute. Image Link-And this is the final error And here is the error. G:\Study\Python\Django Project\Airline-reservation-django-master>py manage.py makemigration Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\vivek\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\vivek\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Users\vivek\Python\Python38-32\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\vivek\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\vivek\Python\Python38-32\lib\site-packages\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "C:\Users\vivek\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "G:\Study\Python\Django Project\Airline-reservation-django-master\Airline\models.py", line 2, in <module> from django.contrib.auth.models import User File "C:\Users\vivek\Python\Python38-32\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\vivek\Python\Python38-32\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagat … -
Delete Files from Post
I built a Django Content App, where the user can create posts. He should also be able to upload multiple files to every post. This works fine so far. Where I struggle: How can I implement, that the user, given the permissions, is able to delete uploaded files within a specific post? I tried writing an own DeleteView for the many-to-one model but that somehow doesn't work. I would appreciate every input. Please find below my models, views, forms and url patterns: Model: class SoftDeletionModel(models.Model): deleted_date = models.DateTimeField(blank=True, null=True, default=None) objects = SoftDeletionManager() all_objects = SoftDeletionManager(alive_only=False) class Meta: abstract = True def delete(self): self.deleted_date = timezone.now() self.save() def hard_delete(self): super(SoftDeletionModel, self).delete() class Categories(models.Model): """ Categories are used to specify the highes level structure. For example like 'wiki' or 'news' which we will use in our CMS. Categories need to be unique. """ prepopulated_fields = {"slug": ("name",)} id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) slug = models.SlugField(max_length=50) name = models.CharField(max_length=50, unique=True, verbose_name='categories') class Meta: ordering = ['name'] verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name class SubCategories(models.Model): """ Subcategories belong to the Categories. Subcategories shall be used as menu-items in navbars, etc. You can't delete a Category without deleting … -
Not able to affect look of html through external css
I have a static folder in it i have css folder inside of that i have .css file which link to my base page which is extended to all pages,when i select an element and try to affect its property i am unable to do so like putting the table in the home page in center.EArlier also i tied to increase cell's width and height in table but it did not affect it immediatley then suddenly after a day by itsel the height and width of cells got set.What do i need to do to affect my template through external css. Template the base.html page <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Base</title> <link rel="stylesheet" href="{% static "css/mystyle.css"%}"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> {%block Body_Block%} <table> HTML...code </table> {%endblock%} settings.py STATIC_DIR=os.path.join(BASE_DIR,"static") STATIC_URL = '/static/' STATICFILES_DIRS=[ STATIC_DIR, '/var/www/static/', ] css table{ margin: 0 auto; } -
cannot connect list page to detail page
I have been working on to make the website which people can post their review on restaurants. I finished creating urls.py, views.py, models.py and html file. I tried to connect the list page with the detailed page on each restaurants. Therefore, I used str:pk tag to connect list page with detail page. However it does't work and however times I check, I can't find why the error happens. settings and other settings are already done. I only have to adjust app files. My Goal: List of restaurants are already created. I want user to be able to go to the detail page by clicking the button below the "{{ list.outline}}" models.py from django.db import models from django.utils import timezone stars = [ (1,"☆"), (2,"☆☆"), (3,"☆☆☆"), (4,"☆☆☆☆"), (5,"☆☆☆☆☆") ] # Create your models here. class Tabelog(models.Model): store_name = models.CharField("店名",max_length = 124,primary_key=True) title = models.CharField("タイトル",max_length = 124,null=True,blank=True) evaluation = models.IntegerField("評価",choices = stars) comment = models.TextField("口コミ") create_date = models.DateField("口コミ投稿日",default=timezone.now) price = models.PositiveIntegerField("値段",help_text='円',default=0) def outline(self): return self.comment[:10] def __str__(self): return ("{},{},{}".format(self.store_name,self.evaluation,self.comment[:10])) urls.py from django.urls import path,include from Tabelog import views from Tabelog.views import ReviewList,ReviewDetail,ReviewForm,ReviewFix,ReviewDelete,ReviewContact,ReviewContactComplete app_name = "Tabelog" urlpatterns = [ path("lp/", views.lp,name="lp"), path("list/", ReviewList.as_view(),name="list"), path("detail/<str:pk>/",ReviewDetail.as_view(),name="detail"), path("form/",ReviewForm.as_view(),name="form"), path("form/fix/<str:pk>/",ReviewFix.as_view(),name="form_fix"), path("form/delete/<str:pk>/",ReviewDelete.as_view(),name="delete"), path("contact/",ReviewContact.as_view(),name="contact"), path("contact/complete/",ReviewContactComplete.as_view(),name="ContactComplete") ] forms.py from django.shortcuts … -
group rest api data by day and hour. Django rest framework
I'm super new to django and the rest API framework. I have a project that I am working on using both and vueJS for the front end. I need to serialize some data for a chart. For one of the API end points I am trying to group the data like so: "day_of_the_week": { "9am":[{"job":".."}], "10am":[{"job":"..."}], "11am": [{"job": ".."}], ... } I am using a Job class, for reference this is how the jobs end point looks like: jobs-api So instead of what i have on the picture I am creating a new endpoint where i will only show one object that contains the data for any given day. On the front end there is a chart with filters that let the user filter the jobs by the day they request. On load, when the user has given no day of the week, the end point will return the object of 'today'. Because I am new to this, I have no idea where to do this, my initial thought was to filter on the views.py, but for now I have done it in the serializer which gives me the error "Object of type Job is not JSON serializable". This is … -
How to easily create a single-page Web Application?
What is the easiest way to make a one-page web application, where there will be two input text, in which the variables a, b are entered and one button for accessing the python script to display the image at the received URL def get_pic(a,b): *magic* return *pic url* I've tried Django, but since I'm a beginner, I didn't understand how to assign a python function call to a button. Maybe there are ways as simple as possible and without unnecessary troubles, I need an elementary interface as in the attached picture P.S. Before that, I was engaged in creating desktop applications in PyQt and it was much easier there, you just drag-n-drop the necessary buttons, text blocks in the editor and then bind functions to them in Python, but with web applications, as I understand it, it will not work -
Access field from previous class model in Django
I am trying to use my entered email in my first class. This is my User class in my modes.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=100, unique=True) first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) home_address = models.CharField(max_length=500, blank=True, null=True) identification_card = models.FileField(upload_to='verify_id', default='verify_id/ID_card.png', help_text='Please upload a valid I.D (can be .jpeg or .pdf file).') This is my money request class class MoneyRequest(models.Model): email_user = models.ForeignKey(User) date_requested = models.DateTimeField(auto_now_add=True) withdraw_money = models.DecimalField(null=True, blank=True, max_digits=8, decimal_places=2, help_text='Minimum withdrawal is ₱300.00.', validators=[minimum_money]) I want my email_user to access my entered email in the User class. I am thinking that I should use something like self.objects to get my username. What should I put here? Thank you. -
Django: Passing kwargs into model method from template
I am trying to pass optional arguments from my template into a model method. The example, I am generating a Google Maps url, and want to pass different kwargs to set the size. class Map(models.Model): ... def get_google_static_url(self, size="800x800", scale="2", *args, **kwargs): From my template I am calling the method against the Map object: <img src="{{ object.get_google_static_url }}" alt=""> How can I pass the kwarg values within get_google_static_url()? -
Jinja template not rendering inline style correctly
I have an Python string that looks like this: patternBackground = 'background-color:#1CA2FF; background-image:url("data:image/svg+xml, ... that I'm trying to render in a Jinja template as an inline html style: style="{{patternBackground}}" The problem is that the style gets cut off by it's first quotation mark so all that renders is.. background-color:#1CA2FF; background-image:url( I've tried to escape the quotation marks in the Python string, this still doesn't work. Any ideas on how I can encode this or pass the style string through as one whole thing (that isn't prematurely cut off) Appreciate any help! Isaac