Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where to store database used in Django project?
I am developing a personal website using Django (to learn). I want to also save it on GitHub. Where to store the database [file] itself? Not on GitHub? If I want to make a save a copy of the database in case it vanishes, where does one typically upload their database? If my website is a "production" website with enough content, what would be the best practice? -
python framework for trading robot
I want to create a web application for trading. Front - React Backend - Python I can't decide which Python framework to choose. Backend should accept a request from the front, make a request to a third-party API and return its response to the front. Also, there is analytics module on the backend, which performs operations with data from API and front and sends requests to API too. A heavy load is assumed and the speed of work is critical for the application. I don't need a lot of models and admin panel. I choose between django, flask, FastApi, but if there are other frameworks for this task, I will be glad to hear. What would you recommend? Interested in the simplest solution to these problems. -
Got multiple values for argument 'Pattern' in Django
This is an 7 year old Django website and I'm trying to migrate it to the latest python version and got an error Error urls.py line 13, in urlpatterns = [ path('CyberHealth.views', TypeError: _path() got multiple values for argument 'Pattern' This is my urls.py urlpatterns = [ path('CyberHealth.views', path('', views.index, name='index'), #==== Role === path(r'^getorinsertroleAPI/$', views.getorinsertroleAPI, name='getorinsertroleAPI'), path(r'^updateordeleteroleAPI/(?P<pk>[0-9]+)/$', views.updateordeleteroleAPI, name='updateordeleteroleAPI'), #==== Register === path(r'^registerUser/$', views.registerUser, name='registerUser'), path(r'^registerFBUser/$', views.registerFBUser, name='registerFBUser'), path(r'^admin/registerCoach/$', views.reg -
Allow users to comment using their social media profiles
I am developing a personal blog using Django (to learn). I want to be the only user that is allowed to post there. However, I want to allow people to comment on my posts, when they do not register but (not sure of the correct terminology here) log in via their Google etc account to place a post. How is this functionality called? How can I achieve this in Django? Do I need to still save the user credentials etc into the database? Do I still need to have a Comment model (I think so)? -
Creating docker container with tensorflow giving libcublas.so error
I created a docker container with the Django app, celery, redis for database used Postgres. While we are importing tensorflow it is giving error of Libssl.so not found where as the file is exist in the docker container itself. Python = 3.6.12 Tensorflow-gpu=1.12.0 cuda = 9.0 cudnn = 7 The docker-compose.yml file which we are using are: version: '3' services: web: volumes: - static:/static - /usr/local/cuda/lib64/:/usr/local/cuda/lib64/ - /usr/lib/x86_64-linux-gnu/:/usr/lib/x86_64-linux-gnu/ - /usr/lib/nvidia-410/:/usr/lib/nvidia-410/ build: context: . ports: - "8000:8000" networks: - nginx_network hostname: "web" nginx: build: ./nginx volumes: - static:/static ports: - "3333:3333" networks: - nginx_network depends_on: - web hostname: "nginx" db: image: postgres:13.0-alpine container_name: ps01 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=AVL^&*() - POSTGRES_DB=xtract_prod networks: nginx_network: volumes: static: Docker File is: FROM alpine:latest FROM python:3.6.12 ENV LANG=C.UTF-8 RUN pip install --no-cache-dir --upgrade pip #LC_ALL=C.UTF-8 # FROM python:3.5.2 # RUN apt-get install libssl1.1 # RUN export LD_LIBRARY_PATH=/home/xaltgpu/miniconda3/lib RUN echo "/home/xaltgpu/miniconda3/lib" > /etc/ld.so.conf.d/openssl.conf RUN ldconfig RUN echo 'export LD_LIBRARY_PATH=/usr/local/cuda/extras/CUPTI/lib64:/usr/local/cuda/lib:/usr/local/cuda/lib64:/usr/lib/x86_64-linux-gnu:/usr/lib/nvidia-430' >> ~/.bashrc #RUN nvidia-smi RUN apt-get install libssl-dev libffi-dev -y RUN apt-get update RUN apt-get install libidn2-0 RUN apt-get install ffmpeg libsm6 libxext6 -y COPY temp_1 /app/temp_1 COPY entrypoint.sh app/entrypoint.sh COPY req.txt /app/req.txt WORKDIR /app RUN pip install -r req.txt RUN ls RUN pwd … -
Wagtail panel for self-referential many to many relationships with a through model
I am busy making something like a knowledge graph in wagtail. CurriculumContentItem is a node on that graph. It has a many-to-many relationship with itself, and the through model has important fields. I'm struggling to get this to be usable in the admin page. Please see the inline comments: class ContentItemOrder(models.Model): post = models.ForeignKey( "CurriculumContentItem", on_delete=models.PROTECT, related_name="pre_ordered_content" ) pre = models.ForeignKey( "CurriculumContentItem", on_delete=models.PROTECT, related_name="post_ordered_content" ) hard_requirement = models.BooleanField(default=True) class CurriculumContentItem(Page): body = RichTextField(blank=True) prerequisites = models.ManyToManyField( "CurriculumContentItem", related_name="unlocks", through="ContentItemOrder", symmetrical=False, ) content_panels = Page.content_panels + [ # FieldPanel("prerequisites") # FieldPanel just lets me select CurriculumContentItems, but I need to access fields in the through model # InlinePanel("prerequisites"), # This causes a recursion error FieldPanel('body', classname="full collapsible"), ] If I wanted to do this in the normal Django admin I would make use of an inlines to specify prerequisites. Something like: class ContentItemOrderPostAdmin(admin.TabularInline): model = models.ContentItem.prerequisites.through fk_name = "post" class ContentItemOrderPreAdmin(admin.TabularInline): model = models.ContentItem.unlocks.through fk_name = "pre" Is there a similar mechanism in Wagtail? It looks like I need to create a custom Panel for this. -
Is it possible to allow to create objects from the list_display view of the django admin site?
I have a model with fields name, roll_no, birth_date I am using the django admin's list display and list editable to have these fields displayed and edited in a list format in a single page. However, to add a new entry I have to go to the create_form page. Is it possible to simply add new objects from the list_display page itself? -
Populate selectbox after div show with columns from a pandas dataframe
So, I have a html form which, after submit, populates some selectboxes with rows values form a pandas dataframe. I have added a jquery script in order to hide the selectboxes before submit and show after submit , but the selectboxes are not being populated anymore as before. For sure something is missing but unfortunately I am pretty new to js and jquery. This is my script: $(document).ready(function(){ $("#myform").submit(function(e) { e.preventDefault(); $("#second").show(); }); This is my html: <form method = "POST" action ="dashboard" id="myform"> {% csrf_token %} <select name="line"> <option value=" 1" selected="selected"> 1</option> <option value=" 2">2</option> <option value=" 3">3</option> <option value="All">ALL</option> </select> Line <select name="data"> <option value="weekly" selected="selected">weekly</option> <option value="monthly">monthly</option> </select> Data <input type="submit" value="Select"> </form> </div> <div id = "second" style="display:none"> <br><br><br> <select class="position"> {% for pos in posnr %} <option value="{{ pos }}">{{ pos }}</option> {% endfor %} </select> <select class="x"> {% for pos in posnr %} <option value="{{ pos }}">{{ pos }}</option> {% endfor %} </select> <select class="y"> {% for pos in posnr %} <option value="{{ pos }}">{{ pos }}</option> {% endfor %} </select> </div> This is part of a django project , the view part is working well -
Other websockets does not work when a websocket is pending
I use Django Channels and I have multiple websocket addresses. When I connect to a websocket, it gets and computes somethings from database and this process may take 10 seconds. But during this 10 seconds all of my websockets does not respond to any user and it yields a 502 Bad Gateway to every user. It seems that all of my websockets are running by a single agent, and when it is pending, all other websockets does not respond anymore, until the agent becomes free. My code is some like the following code. How can I solve this problem? class SymbolConsumer(WebsocketConsumer): def connect(self): self.symbol_name = self.scope["url_route"]["kwargs"]["symbol_name"] async_to_sync(self.channel_layer.group_add)(self.symbol_name, self.channel_name) self.accept() self.send(time_consuming_function_1(self.symbol_name)) self.send(time_consuming_function_2(self.symbol_name)) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.symbol_name, self.channel_name ) def receive(self, text_data): pass -
AttributeError: module 'django.db.models' has no attribute 'Textfield'
am trying to run my python manage.py makemigrations in my terminal but it is giving me this error File "/home/collins/Dev/trydjango/src/products/models.py", line 5, in Product title = models.Textfield() AttributeError: module 'django.db.models' has no attribute 'Textfield' what could be the problem? -
How to concatenate string in django framework
I want to concatenate a string to get a product link in one of my django datatable columns. I want a result like this: https://www.aliexpress.com/item/1005003324927716.html The product id is stored in my mongodb database. This is what I tried to write in my datatable.html but i get an empty column: {% for product in products %} <tr> <td> {% with "https://www.aliexpress.com/item/"|add:{{product.productId}}|add:".html" as template %} {% endwith %} </td> </tr> {% endfor %} Then to make it as an href link as this syntax : <td><a href="{{product.Productlinks }}"> Click here</a></td> I am pretty new in using django and I will be so grateful if you help me in this isuue. Thank you ! -
[Driver Manager]Can't open lib '/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.9.so.1.1'
When I run $ python manage.py inspectdb --database=mssql_database I have the following error django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.9.so.1.1' : file not found (0) (SQLDriverConnect)") but the file libmsodbcsql-17.9.so.1.1 is there. $ cat /etc/odbcinst.ini [ODBC] Trace=Yes TraceFile=/tmp/odbc.log [FreeTDS] Description=TDS driver (Sybase/MS SQL) Driver=libtdsodbc.so Setup=libtdsS.so CPTimeout= CPReuse= UsageCount=2 [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server Driver=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.9.so.1.1 UsageCount=1 $ odbcinst -j unixODBC 2.3.7 odbcinst: symbol lookup error: odbcinst: undefined symbol: odbcinst_system_file_name -
Upload a file in a folder whose value is selected through a list of choices
I have the following Script model : from django.db import models import os def getListOfFiles(dirName): listOfFile = os.listdir(dirName) allFiles = list() for entry in listOfFile: fullPath = os.path.join(dirName, entry) if os.path.isdir(fullPath): allFiles.append((fullPath, entry)) return allFiles class Script(models.Model): script_name = models.CharField(max_length=200, blank=True) folder = models.CharField(choices=getListOfFiles('media/scripts'), max_length=200) file = models.FileField(upload_to=f'scripts/{folder}') def __str__(self): return self.script_name I want to upload the script to the value of the attribute folder selected by the user through a list of choices. With the upload_to=f'scripts/{folder}' it tries to upload it to media\scripts\<django.db.models.fields.CharField> which is obviously not what I want. I saw a bunch of people using a get_folder_display() function but is doesn't seem to work in models, or I did it wrong. How can I get the value of folder selected by the user ? -
code to fetch available seats after adding Passenger details(no_of_passengers) and update that in flight class .. I'm doing it at a very basic level
code to fetch available seats after adding Passenger details(no_of_passengers) and update that in flight class .. I'm doing it at a very basic level.code to fetch available seats after adding Passenger details(no_of_passengers) and update that in flight class .. I'm doing it at a very basic level. Here is My model.py using the Django-rest framework. I want to update aailable_seats(class Flight) after passenger details(No .of passengers) details added. import email from pyexpat import model from django.db import models GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) # Create your models here. class Airport(models.Model): Airport_name=models.CharField(max_length=100) country=models.CharField(max_length=100) def __str__(self): return self.Airport_name class Flight(models.Model): # f_id = models.UUIDField(primary_key=True) # a_id = models.UUIDField() flight_number = models.CharField(max_length=100,unique=True) depart_date_time = models.DateTimeField(auto_now_add=True) arrival_date_time = models.DateTimeField(auto_now_add=True) origin = models.CharField(max_length=100, blank=True, default='') destination = models.CharField(max_length=100, blank=True, default='') price = models.IntegerField() airline_name = models.CharField(max_length=100, blank=True, default='') total_seats = models.IntegerField() available_seats = models.IntegerField() #code = models.TextField() airport=models.ForeignKey(Airport,on_delete=models.CASCADE) def __str__(self): return str(self.flight_number) # def user_count(self): # return "Available Seats: " + self.available_seats.count + "Total Seats: " + self.total_seats.count class User(models.Model): name = models.CharField(max_length=100,blank=True, default='') contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100,blank=True, default='') email = models.EmailField(max_length=254) password = models.CharField(max_length=100,blank=True, default='') state=models.CharField(max_length=100,blank=True, default='') city=models.CharField(max_length=100,blank=True, default='') country=models.CharField(max_length=100,blank=True, default='') pincode= models.IntegerField() dob = models.DateField() … -
In GeoDjango, use GeoModelAdmin as a StackedInline in the Django Admin
I am trying to use the GeoModelAdmin as a StackedInline in the Django Admin panel. I have seen these two similar questions: GeoDjango: Can I use OSMGeoAdmin in an Inline in the User Admin? django admin inlines with GeoModelAdmin The answer that recommends inheriting from both GeoModelAdmin and StackedInline almost works. The following code: models.py: class SomeGeometry(gis_models.Model): geometry = gis_models.GeometryField(blank=False, null=False) some_model = models.ForeignKey("somemodel", blank=False, null=False, on_delete=models.CASCADE, related_name="geometries") class SomeModel(models.Model): name = models.CharField(max_length=255) admin.py: class SomeGeometryAdminInline(gis_admin.GeoModelAdmin, admin.StackedInline): model = SomeGeometry extra = 0 fields = ( "geometry", ) def __init__(self, parent_model, admin_site): # InlineModelAdmin.__init__ self.admin_site = admin_site self.parent_model = parent_model self.opts = self.model._meta self.has_registered_model = admin_site.is_registered(self.model) # BaseModelAdmin.__init__ overrides = copy.deepcopy(FORMFIELD_FOR_DBFIELD_DEFAULTS) for k, v in self.formfield_overrides.items(): overrides.setdefault(k, {}).update(v) self.formfield_overrides = overrides @admin.register(SomeModel) class SomeModelAdmin(admin.ModelAdmin): fields = ("name",) inlines = (SomeGeometryAdminInline, ) Correctly shows an editable geometry widget. But there is no "add another model" link at the bottom of the inline formset. Any hints as to how to get that link back? -
Django Rest Framework import OpenAPI spec from other service to generate Schema
My system consists of multiple services that generate their own OpenAPI specifications. For one endpoint in my Django service I want the input schema to be of a type that is specified at another service, is there somehow a way to retrieve/import/reference to a type that is part of another service? (Currently just using the schemas from DRF but thinking of using drf-spectacular) In the end I want the services to dynamically generate full OpenAPI specs (and sometimes those can be based on each other) -
CreateView show blank - Django
I did as "docs.djangoproject.com" says, add Templates in setting.py file, base.html file works ok, then created my accounts app then views, after that urls and main app urls.py file. everything works ok, without any errors, but the signup and login page doesn't show anything! could anyone help me? accounts[app] > models.py: accounts[app] > models.py accounts[app] > views.py: accounts[app] > views.py accounts[app] > urls.py: accounts[app] > urls.py accounts[app] > forms.py: accounts[app] > forms.py -
Iam Passing an value when iam redirecting the template in django
Iam New to Django.. I created Login Page and i submited that page it goes to another page i want that particular username in another page so iam passing that name when iam redirecting the page but it does'nt worked for me... urls.py from django.contrib import admin from django.urls import path from .import views urlpatterns = [ path('dash/',views.Dash,name='Dash'), ] Dash.html <div class="flex-grow-1"> <span class="fw-semibold d-block">{{name}}</span> </div> views.py def Login(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] user=auth.authenticate(username=username,password=password) if user is not None: request.session['user'] = username auth.login(request,user) return redirect('/dash',{name:user}) This is my code why iam not getting the name ? Please anyone help me -
django admin not displaying styles
i would like to deploy django in a kubernetes cluster but now i am struggling with the django admin static files. As you can see in the screenshot below, the browser receives the static files for the admin page correctly but not display it. What is a reason for this behavior and how can i fix it? I try it multiple times with debug on and off and in incognito window. -
Initial state in react redux are upadating after hard refresh instead on button click
I am trying to build a login page that uses simple JWT of django rest framework for authentication and react js as frontend and redux for state management. i am storing the user info in local storage and the initial state is updated from the local storage . I want to update the initial state on button click but it only updates after hard refresh . All the files used are below: UserReducer.js import axios from 'axios' import { USER_LOGIN_SUCCESS , USER_LOGIN_REQUEST , USER_LOGIN_FAIL , USER_LOGOUT , } from '../constants/userConstants' export const login = (email , password ) => async(dispatch) => { try{ dispatch({ type: USER_LOGIN_REQUEST }) const sdata = { headers: { 'Content-type': 'application/json' } } const {data} = await axios.post('/api/users/login/' , { 'username': email , 'password': password} , sdata ) localStorage.setItem('userInfo' , JSON.stringify(data)) dispatch({ type:USER_LOGIN_SUCCESS , payload:data }) dispatch({ type: USER_LOGOUT, payload: {} }) }catch(error){ dispatch({ type: USER_LOGIN_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }) } } Store.js import {createStore , combineReducers , applyMiddleware} from 'redux' import thunk from 'redux-thunk' import {composeWithDevTools} from 'redux-devtools-extension' import {productListReducer} from './reducers/productReducers' import { productDetailsReducer } from './reducers/productReducers' import { cartItemReducer} from './reducers/cartReducers' import { userLoginReducer } from './reducers/userReducers' const … -
django download a file filtered from a list of files
I'm working on a website where I have multiple excel files uploaded by users and stored in the DB, then a user chooses a file's name and date from a dropdown list and this specific file should be downloaded to him. right now I can get the File object that he requested but can't download it correctly. This is my Models.py class File(models.Model): file_name = models.TextField(max_length=1000, default='myFile') created_at = models.DateTimeField( default=datetime.datetime.now().replace(microsecond=0)) file = models.FileField() file_class = models.CharField( max_length=20, default='') def __str__(self): return self.file_name This is the part where I store the file in Views.py: modelFile = File() now = datetime.datetime.now().replace(microsecond=0) file_class = request.POST['select_course'] Fname = request.POST['file_name'] myFile = convertToBinaryData(uploaded_fileName) xlfile = ContentFile(myFile) modelFile.file.save(Fname, xlfile) modelFile.file_class = file_class modelFile.created_at = now modelFile.file_name = Fname modelFile.save() And here is where I retrieve and download the file in Views.py : def viewTrial(request): if request.method == "POST": chosen_filename = request.POST['select_trial'] chosen_date = request.POST['select_trial2'] date = pd.to_datetime( chosen_date, infer_datetime_format=True).strftime('%Y-%m-%d %H:%M') FileToView = File.objects.filter(created_at__contains=date).filter( file_name__contains=chosen_filename) response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename=%s' % chosen_filename+".xls" return response else: return render(request, "model/trials.html", {}) this code downloads an excel file with only the file name written in it, I've seen multiple questions here regarding this issue and the downloading, … -
Adding Legacy sqlite3 db to Django model with no primary key
I am adding a legacy sqlite3 db with 6 tables. 3 of those tables have a primary key field and I am able to access the data via the admin panel... all good However, the other 3 do not have a primary key column which is giving me an error no such column: table1.id when i try to access the table via the admin panel. I have found the sqlite3 adds a hidden rowid to all tables so I am able to access the rowid by using select rowid * from table1 So I tried adding the rowid as a field in the table1 Model like this: class table1(models.Model): rowid = models.IntegerField(primary_key=True, editable=False) order_id = models.ForeignKey(Demand, null=True, on_delete= models.SET_NULL) product_id = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) quantity = models.IntegerField(default=1) Now when i try running ./manage.py makemigrations I run into an issue saying: It is impossible to add a non-nullable field 'rowid' to table1 without specifying a default. This is because the database needs something to populate existing rows But from my understanding, the database already has the rows populated.. so i'm not sure whats happening. Any help is appreciated! The only thing i've found online that relates to this is a … -
In Django, how can I select multiple list_filter elements
I have one model called CLUB, and another called DIVISION. Club has a manytomany field with division. The point is that I want in the admin panel where I see the clubs to be able to filter by more than one division. I have been looking for but nothing seems to work, there is a old library but is deprecated. Thanks! -
How to get always get last record
class PettyCashListAPIView(ListAPIView): pagination_class = CustomPagination permission_classes = [IsAuthenticated,] serializer_class = serializers.PettyCashSerializer def get_queryset(self): data = center_models.PettyCash.objects.filter(allowance_to=self.request.user.paneluser) return data Lenght of data has more than one. But I want to return only the latest record. PettyCash model has created_at DateTimeField. I tried latest('created_at), last() but getting PettyCash has not len() error. Any Help. Thank you !! -
How to change swagger logo and text in the top bar in django app?
I have included swagger the following way in the Django app schema_view = get_schema_view( openapi.Info( title="Calculate", default_version="v1", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path("", schema_view.with_ui("swagger", cache_timeout=0), name="swagger"), How can I change the top bar logo and text? from "Swagger - supported by SMARTBEAR" to "Smart Calculator"