Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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" -
how to access django bash in portainer?
I am able to access the django docker using the following in the cloud console docker exec -it backend bash How can I do the equivalent in Portainer GUI? It is just stuck in Exec into container as default user using command bash -
Check cell value, recalculate and overwrite xlwt
Trying to achieve the following: Loop through a list with this type of objects: #1 Cost: 12 Unit: per month Amount: 3 users #2 Cost: 32 Unit: per quarter Amount: 2 users etc And make a forecast xls export based on this for each month: Jan - 100 (312 + 322) Feb - 36 (312) March - 36 (312) Apr - 100 (312 + 322) etc My implementation of this was as follows: for po in queryset.select_related( 'quote__relatie', 'entity', 'delivery_address', 'requester', 'approver',): row_num += 1 ws.write(row_num, 0, str(po.costcode), font_style) ws.write(row_num, 1, str(po), font_style) ws.write(row_num, 2, str(po.quote.relatie), font_style) ws.write(row_num, 2, str(po.project), font_style) for cl in po.inkooppost_set.all(): data = {} if cl.eenheid.recurrent: for pc in range(cl.aantal): if cl.invoice_date: invoice_date = (cl.invoice_date + datetime.timedelta( days=(pc * cl.eenheid.frequency))) #find columnnumber r = relativedelta(invoice_date, month.order_date) col_num = (r.years*12) + r.months + 3 #check whether another cost has been inferred and update cell print(col_num) if data.get(col_num): data.update({col_num: data.get(col_num) + cl.eenheidprijs}) else: data.update({col_num: cl.eenheidprijs}) ws.write(row_num, col_num, data[col_num], font_style) else: invoice_date = cl.invoice_date r = relativedelta(invoice_date, month.order_date) print(r) col_num = (r.years *12) + r.months + 3 print(data.get(col_num)) if data.get(col_num): data.update({col_num: data.get(col_num)+ cl.eenheidprijs}) else: data.update({col_num: cl.eenheidprijs * cl.aantal}) ws.write(row_num, col_num, (cl.eenheidprijs * cl.aantal), font_style) Using a dict to build … -
Error while generating FCM token using django
This is error that i am getting in my javascript console An error occurred while retrieving token. DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded. at https://www.gstatic.com/firebasejs/8.6.3/firebase-messaging.js:1:25606 I am trying to send push notification from firebase but getting error. any one plz help me. i am trying to generate FCM token in javascript console but getting error here is my index.html file where i am getting import error index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://www.gstatic.com/firebasejs/8.6.3/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.6.3/firebase-analytics.js"></script> <script src="https://www.gstatic.com/firebasejs/8.6.3/firebase-messaging.js"></script> {% comment %} <script src="/static/js/firebase-messaging-sw.js"> {% endcomment %} <script> var firebaseConfig = { apiKey: "AIzaSyAcV-zkELH2kC2ylNcqfxcAF9LLmyJW3n8", authDomain: "fir-push-notification-ca088.firebaseapp.com", databaseURL: "https://fir-push-notification-ca088-default-rtdb.firebaseio.com", projectId: "fir-push-notification-ca088", storageBucket: "fir-push-notification-ca088.appspot.com", messagingSenderId: "123105123891", appId: "1:123105123891:web:59c426864dd7b8c35ecd46", measurementId: "G-NEZ3NC2GYL" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); firebase.analytics(); const messaging = firebase.messaging(); console.log(messaging.getToken()) messaging.getToken({ vapidKey: 'AAAAHKmjHjM:APA91bEWX1Mrp6HIfjx6Y4n2chW2GpfB3GzrwQp1T1KQ3i5a_4mVnEhEa_hd95c-N9ZADi8fTUobdhlvs5d0b1JMrYWE_sJ1KjsdnXLMg4rxOAFPem4nxpazNtimZEb2PGKtHZAB9sKX' }).then((currentToken) => { if (currentToken) { console.log(currentToken) } else { console.log('No registration token available. Request permission to generate one.'); } }).catch((err) => { console.log('An error occurred while retrieving token. ', err); }); messaging .requestPermission() .then(function () { console.log("Notification permission granted."); return messaging.getToken() }) .catch(function (err) { console.log("Unable to get permission to notify.", err); }); messaging.onMessage((payload) => { console.log('Message received. … -
Get sub One To Many relation from specific model in django
I have two models User and Sale, each sale has a buyer and a seller. I would like to get all buyers (also Users) from a specific user my_user. class User(models.Model): name = models.CharField(max_length=250, default='', blank=True) # more fields.... class Sale (models.Model): buyer = models.ForeignKey( User, blank=False, null=False, related_name='purchases', on_delete=models.CASCADE, ) seller = models.ForeignKey( User, blank=False, null=False, related_name='sales', on_delete=models.CASCADE, ) # more fields.... This works fine: User.objects.filter(purchases__seller = my_user) But I would like to know if there is a way to do it by using the my_user object directly. Something like this my_user.sales.buyer Thanks in advance guys -
What should i do to learn django-ninja
I am a beginner in programming, I'm trying to learn Django-ninja but I'm confused, what should I learn first, I know some basics of python. Will I need to learn Django first? I will be thankful if anyone have a map learn that leads to Django-ninja -
How to backup user files before pulling repository in jenkins
I have a django project which is deployed in a docker container. I created a pipeline in jenkins triggered via github webhooks. Everyting works fine but I have some user files in project directory which I want to backup before jenkins pull the repository. Is there a way to add a pre build step to my pipeline script or avoid deleting files when running git pull command ? -
django redirect to form view and autofill with previously entered values
I have following scenario. User fills out a form If the user clicks the "continue" button and the form is valid the user will be redirected to a summary view In the summary view the user checks the input again. He can either continue or go back. If he continues the data will be saved in the database, if he goes back he can edit the form. Since in step 4 the user is at the view summary I have to redirect him to the home view. I don´t want the user to fill out the entire form again, the previously entered data should be autofilled if he goes back. Something special: I am using django-tagify2 for one input in the form to get tags rather then text. If the user goes back the tags should be rendered correctly in the tagify specific form. So here are my files: home.html {% extends "messenger/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="message-container"> <form method="POST" autocomplete="off"> {% csrf_token %} {{ form|crispy }} <button name="sendmessage" class="btn btn-outline-info" type="submit">Continue</button> </form> </div> {% endblock content %} summary.html {% extends "messenger/base.html" %} {% block content %} <h4>Zusammenfassung</h4> <p><b>Empfänger: </b>{{ receiver }}</p> <br> <p><b>Betreff: … -
Upload file to server temporarily to process it from django
I am developing a website in django which will convert one file type to another. Main core logic of conversion is done in python, but now as for website, the file needs to be uploaded temporarily on the server, so that server can do the conversion and produce new file to be downloaded. How is this to be accomplished? -
How can I serialize one to many models in Django Rest?
So I have two models Invoice and Items. Invoices can have many Items. Here's how they are defined: class Invoice(models.Model): customer_name = models.CharField(max_length = 200, verbose_name='Customer Name') customer_phone = models.IntegerField(null = True, blank = True, verbose_name='Customer Phone') customer_address = models.TextField(null = True, blank = True, verbose_name='Customer Address') invoice_id = models.UUIDField(primary_key = True, unique = True, default=uuid.uuid4, verbose_name='Invoice ID') invoice_date = models.DateField(auto_now_add=True, verbose_name='Invoice Date') def __str__(self): return self.customer_name + ' - ' + str(self.invoice_id) class Meta: verbose_name = 'Invoice' verbose_name_plural = 'Invoices' class Items(models.Model): invoice = models.ForeignKey(Invoice, on_delete = models.CASCADE, related_name='invoice') item_name = models.CharField(max_length = 200, null = False) item_quantity = models.IntegerField() item_price = models.IntegerField() item_id = models.AutoField(primary_key=True) def __str__(self): return self.item_name class Meta: verbose_name = 'Items' verbose_name_plural = 'Items' I want to implement two API endpoints, one to get the list of invoices, and another to get a specific invoice with its items. For example, /api/ will return all invoices [ { "customer_name": "John Doe", "customer_phone": 111666, "customer_address": "Palo Alto, California", "invoice_id": "a8aeb5a8-5498-40fd-9b4f-bb09a7057c71", "invoice_date": "2022-05-04" }, { "customer_name": "Cassian Green", "customer_phone": 111000, "customer_address": "2112 Illinois Avenue", "invoice_id": "7d7b7878-3ffc-4dd2-a60a-fa207c147860", "invoice_date": "2022-05-04" }, { "customer_name": "Chelsea Davis", "customer_phone": 666777, "customer_address": "2260 Coplin Avenue", "invoice_id": "3dda2054-49d7-49dc-9eba-ddc0fdacfd3b", "invoice_date": "2022-05-04" }, { "customer_name": "Derek Elliott", … -
access variable in template from views.py - Django
This is my first time messing with django and I am having trouble passing variables from a view function to a template html file. views.py def index(request): try: ms_identity_web.acquire_token_silently() authZ = f'Bearer {ms_identity_web.id_data._access_token}' graph_user_picture = requests.get(settings.USERPHOTO, headers={"Authorization": authZ}) file = open("Sample/static/user_iamge"+str(ms_identity_web.id_data.username).split(" ")[0]+".png", "wb") file.write(graph_user_picture.content) file.close() clamdata = context_processors.context(request) print(clamdata["claims_to_display"]["preferred_username"]) userdata = requests.get(settings.ENDPOINT+"/"+clamdata["claims_to_display"]["preferred_username"], headers={"Authorization": authZ}).json() print(userdata) return render(request, "flow/index.html", userdata) except Exception as e: print(e) return render(request, "flow/start.html") and I am trying to send userdata over to index.html like so: <div class="ms-Persona-details"> <div class="ms-Persona-primaryText">{{ userdata["displayName"] }}</div> <div class="ms-Persona-secondaryText">{{ userdata["jobTitle"] }}</div> <div class="ms-Persona-tertiaryText">{{ userdata["businessPhones"][0] }}</div> <div class="ms-Persona-tertiaryText">{{ userdata["userPrincipalName"] }}</div> </div> However, I am getting either no variables showing up on the screen or I get an error like this: Could not parse the remainder: '["displayName"]' from 'userdata["displayName"]' I assume I am missing something basic in index.html to pass variables from the views.py to the index.html file -
I use Django with PostgreSQL on docker compose, but django-test can't access database
I practice Writing your first Django app, part 5, it's django test section. And my environment is: Django 4.0 Python 3.9 Database PostgreSQL 14.2 Docker compose In addition, the connection to PostgreSQL is configured via .pg_service.conf and .pgpass. docker-compose.yml version: "3.9" services: web: build: context: . container_name: web restart: unless-stopped tty: true working_dir: /opt/apps volumes: - .:/opt/apps/ - .pgpass:/root/.pgpass - .pg_service.conf:/root/.pg_service.conf entrypoint: "./entrypoint.sh" command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" depends_on: - db db: image: postgres container_name: db environment: POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} ports: - ${DB_PORT}:5432 volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data: networks: django-tutorial: compose .env file DB_USER=postgres DB_PASSWORD=postgres DB_HOST=db DB_PORT=5432 .pg_service.conf [DB] host=db user=postgres dbname=django_tutorial port=5432 .pgpass db:5432:postgres:postgres:postgres When docker-compose up -d is executed with the above configuration and python manage.py migrate is executed, the migration is performed no problems and the database is accessible. However, when I try to run the test as in python manage.py test polls, I get the following error. (The test is the same as the code in the link at the beginning of this article.) Do I need any additional configuration for the test DB? docker compose exec web python manage.py test polls ✔ 15:20:03 Found 1 test(s). Creating test … -
Is there any article or book which guide reverse engineering for the django framework?
I want to learn how to reverse engineering the django framework. If there is some article or book available for it then please suggest me. -
Django giving "Reverse for 'view' not found" error when view is defined
While using django 4.0.4 I have encountered the error "Reverse for 'upload' not found. 'upload' is not a valid view function or pattern name". It was working earlier in the day, and I can't figure out the problem for the life of me. I'll include my views.py, urls.py, and the relevant section of my html file, all three of which are in the same folder of the project. If anyone has any advice I would greatly appreciate it. Views.py def welcome(request): return render(request, 'welcome.html') def contact(request): return render(request, 'contact-us.html') def how(request): return render(request, 'How-to-use.html') def upload(request): if request.method == 'POST': if 'scatter_plot' in request.POST: form = UploadFileForm(request.POST.get, request.FILES) file=request.FILES['document'] csv = CSV.objects.create(doc=file) os.system('python ../scatter_plot.py') if 'line_plot' in request.POST: form = UploadFileForm(request.POST.get, request.FILES) file=request.FILES['document'] csv = CSV.objects.create(doc=file) os.system('python ../line_plot.py') return render(request, 'uploaded.html') else: form = UploadFileForm Urls.py urlpatterns = [ path('', views.welcome), path('admin/', admin.site.urls), path('contact-us/', views.contact), path('upload.html', views.upload), path('upload/', views.upload), path('welcome/', views.welcome), path('How-to-use/', views.how), path('contact-us.html', views.contact), path('welcome.html', views.welcome), path('How-to-use.html', views.how) ] Welcome.html <form method="POST" enctype="multipart/form-data" action="{% url 'upload' %}"> {% csrf_token %} <input type='file' name='document' accept='.csv'> <button type='submit' name='line_plot'>Graph as a line Graph</button> <button type='submit' name='scatter_plot'>Graph as a Scatter Plot</button> </form> -
How to test correctly this func in Django?
I have a test which check user can create a news or not. But my test doesn't work. I suppose I do something wrong with 'category' and 'author', but I don't know how to change it correctly. When I create a news in site by myself, everything work right. Test: @classmethod def setUpTestData(cls): user = User.objects.create(username='test1') user.set_password('test1') user.save() Profile.objects.create(user=user) NewsCategory.objects.create(category='Sport') def test_if_user_can_create_news(self): user = self.client.login(username='test1', password='test1') self.client.post(reverse('create_news'), { 'title': 'News 1', 'description': 'Description news 1', 'category': NewsCategory.objects.get(category='Sport'), 'author': user }) self.assertTrue(News.objects.filter(title='News 1').exists()) Models: class News(models.Model): title = models.CharField(max_length=200, verbose_name='Title') description = models.TextField(verbose_name='Description') category = models.ForeignKey(NewsCategory, on_delete=models.CASCADE, verbose_name='Category') author = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name='Author') class NewsCategory(models.Model): category = models.CharField(max_length=100, verbose_name='Category') Form: class NewsForm(forms.ModelForm): class Meta: model = News fields = 'title', 'description', 'category' -
how to implement raw sql query in DRF with paramters
Hi Everyone i am trying to implement raw sql query to create api in django framework and input paramter is team_id, start_date and end_date. like team_id=1 and start=2022-04-25 and end_date=2022-05-01, and temp1 query date like 7 date from 2022-04-25 to 2022-05-01. how will do this,please help me out. SELECT temp1.car_number,temp1.trips,temp1.status, case when temp1.date= %s then temp1.trip else 0 end as day1_trips, case when temp1.date= %s then temp1.trip else 0 end as day2_trips, case when temp1.date= %s then temp1.trip else 0 end as day3_trips, case when temp1.date= %s then temp1.trip else 0 end as day4_trips, case when temp1.date= %s then temp1.trip else 0 end as day5_trips, case when temp1.date= %s then temp1.trip else 0 end as day6_trips, case when temp1.date= %s then temp1.trip else 0 end as day7_trips from (SELECT date, car_number,driver_id,trips,car_status,status, case when trips=0 THEN else trips end as trip FROM fleet_car_dash_daily /this is input paramter/ WHERE team_id= %s and (date BETWEEN %s and %s))as temp1 group by temp1.date -
RuntimeError: __class__ not set defining 'AbstractBaseUser'
Django app works fine local, but when pushed to heroku build works, but deploy fails: RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagated to type.__new__? reading older posts this has been attributed to Django version / python version incompatibilities. This is a recent version: Django 3.2.13 and Python 3.9.12. This is confirmed to work together. Tried downgrading / upgrading, but without succes. Any one has an idea how to resolve?