Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django mpld3 show json serializable error
hi i am trying to display a multi dimensional bar chart using mpld3 and django framework when i run following cord it produce **Object of type 'ndarray' is not JSON serializable ** error at fig_to_html() function line -
How to save a django variable in Template after refreshing?
I have a Django template that contains a button. If clicked, it will display the current time. My intention is to view this time even after a user refreshes the page. However, the data gets deleted after refreshing. How can I do this? Currently, the time is calculated using an external script in my Django root project. After execution, I used a HttpResponse in my views module and place this data in my HTML file using an AJAX call. This is my current code so far: time.py (external script): from datetime import datetime def time(): current_time = datetime.now() datetime = current_time.strftime("%d/%m/%Y %H:%M:%S") return datetime views.py: from time import time #importing external script #calling the time() method that calculates current time def time(request): current_time = time() return HttpResponse(current_time) urls.py: from users import views as users_views #app that stores views.py module urlpatterns = [ path('current_time/', users_views.time, name = 'current_time'), ] home.js: $('#button').click(function () { $.ajax({ cache: false, url: "/current_time/", success: function(data) { $('#button').html(data) //display time after user clicks on button } }); }); home.html: ..... #all HTML layout stuff <div> <p> Last seen: <button type="button" id='button'> {{current_time}} </button> #time accessed from views.py } </p> </div> How to save the time variable after … -
Can someone please help me to built a simple music player webpage using django?
I want to create a webpage where admin can add music from backend and users can play the song and add to fevorite using Django. Thats all i want please someone help me -
How to check if an array of objects belongs to the user or not in Django Rest Framework
I have a question that is how to check the passed array of objects to DRF belongs to the user or not. consider the below array of objects that will be passed from the client-side. const array_of_objects = [ {id:1, title: "some title", body: "some body"}, {id:2, title: "some title", body: "some body"}, {id:3, title: "some title", body: "some body"}, {id:4, title: "some title", body: "some body"}, {id:5, title: "some title", body: "some body"}, ] Consider id 1,2,3,4 belongs to the logged in user and 5 doesn't. So in this case I have to send method not permitted error to the client. Currently what I'm doing is in the DRF view, loop through the array of objects and get the id (primary key) and get the instance of that id from the model and compare the logged in user and the instance user. If it's equal then proceed to the next code. If not, send not permitted error response to the user. There is like 10-20 lines of code. Since we can extend BasePermission class and write our own permission class. Is it possible to simplify the code in there or else we have to again loop through the the … -
get_or_create() creating a new object everytime I run the test case
I am testing my api and everytime am running the test case using python manage.py test api.users.tests --keepdb it is creating a new Language object everytime, instead it should fetch the existing Language object itself as I am not destroying the database. class ProfileTest(TestCase): @classmethod @override_settings(DEBUG=True) def setUpTestData(cls): instance, is_created = Language.objects.get_or_create(value='English', locale='en') url = '/api/v1/auth/login/' data = {'mobile_number': '9899137678', 'country_code': '91', 'device_id': '123'} response = Client().post(path=url, data=data) json_response = response.json() url = '/api/v1/auth/verify/' data = {'code': json_response['otp'], 'verification_id': json_response['verification_id'], 'language': instance.id, 'registration_id': '123', 'type': '1', 'device_id': json_response['device_id']} response = Client().post(path=url, data=data) json_response = response.json() token = json_response['token']['access'] token = 'Token ' + token cls.headers = { 'HTTP_AUTHORIZATION': token, } def test_get_user_profile(self): url = '/api/v1/users/profile/' response = self.client.get(path=url, **self.headers) print('\n', response.content, '\n') self.assertEquals(response.status_code, status.HTTP_200_OK, 'Couldn\'t fetch profile data.') -
how to hash password in views for registering a user in custom user model
this is my code snippet where i am registering a new user based on custom user model. i need to hash the password before storing user. having no idea how to do this. any help would be appreciated. class UserCreate(APIView): # User Creation-> def post(self, request, format='json'): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: token = Token.objects.create(user=user) json = serializer.data json['token'] = token.key return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) the problem is that it is creating user without hashing the password and when i am trying to log in with the credentials i am getting the issue "non_field_errors": [ "Unable to log in with provided credentials." ] -
Django admin filters in custom template
I want to implement django admin filters in my custom template can any body from you help me in resolving this issue i will appreciate. -
Intercepting an invalid step submission in a django-formtools WizardView?
If I have a django-formtools WiazrdView, and I want to intercept a step form submission that did not pass the step's Form's validation, how could I do that? -
Django fixtures: create relationships using relation set instead of foreign key
Let's say I have the following database models: class Team(models.Model): name = models.CharField(max_length=50, unique=True) class Player(models.Model): name = models.CharField(max_length=50, unique=True) team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, blank=True) I'm creating a fixture to load initial data into these tables, which looks like this: # TEAMS - model: demo.team fields: id: 1 name: Raiders # PLAYERS - model: demo.player fields: team: 1 name: Derek Carr - model: demo.player fields: team: 1 name: Darren Waller This works fine, but I'd like to create the player objects first and then attach them to a team when I create the team objects (which is more human readable IMO): # PLAYERS - model: demo.player fields: id: 1 name: Derek Carr - model: demo.player fields: id: 2 name: Darren Waller # TEAMS - model: demo.team fields: name: Raiders player_set: - 1 - 2 Attempting to load in this data results in the following error: django.core.exceptions.FieldDoesNotExist: Team has no field named 'player_set'. Am I doing something wrong or is this approach not possible? -
Django Stripe SCA Bug That Allows Customers To Bypass SCA and Gain Access To Paid Subscription Service
I have a bug in my code that allows customers to subscribe to a paid membership for my service without authenticating their SCA card by clicking the back button and then trying the SCA card again. This is very bad because a customer can get a paid membership subscription without paying. I would either like to redirect the user back to 3d-secure-checkout.html to re-authenticate them or to not create the subscription in the database or stripe unless the customer successfully authenticates their card. Code: https://dpaste.de/AHKr Video: https://streamable.com/mm0jy Seems like the subscription is being created and is being considered active in the database even though the payment was not authenticated. After the redirect where it fails, it is not checking if payment succeeded or not. What I have tried for debugging: (printing out as many variables as possible) https://dpaste.de/oWV2 I have been stuck for a while and am not sure what to do. Please help. -
JOIN on django orm
1. 1.1. query: QuestionRequestAnswerModel.objects.filter(request_no__exact=index['id']).select_related('answer_user').values('answer_user', 'amount', 'select_yn') 2. 2.1. query: description I want to get answer_user's last_name. but when I use django orm by select_realated('answer_user'), the result give me the answer_user's id only. how can I get another column, except id, on ORM join? -
Django: Getting NoReverseMatch Error While Attempting to Use Slug in URLs
I am a beginner learning Django through building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews. I have already created models, views and the template files. Right now, I am facing a problem. While attempting to use slug, I am getting NoReverseMatch Error. It looks like this: NoReverseMatch at /index Reverse for 'modellist' with arguments '('',)' not found. 1 pattern(s) tried: ['phonemodel/(?P<slug>[-a-zA-Z0-9_]+)$'] However, I didn't face any problem with while using primary key in urls.py. The problem is occurring when I attempt to use slug in the URLs. Here are my codes of models.py located inside PhoneReview folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Brand(models.Model): brand_name = models.CharField(max_length=100) origin = models.CharField(max_length=100) manufacturing_since = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(max_length=150, null=True, blank=True) def __str__(self): return self.brand_name def save(self, *args, **kwargs): self.slug = slugify(self.brand_name) super().save(*args, **kwargs) class PhoneModel(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) model_name = models.CharField(max_length=100) launch_date = models.CharField(max_length=100) platform = models.CharField(max_length=100) slug = models.SlugField(max_length=150, null=True, blank=True) def __str__(self): return self.model_name def save(self, *args, **kwargs): self.slug = slugify(self.model_name) super().save(*args, **kwargs) class Review(models.Model): phone_model = … -
Exporting the fields of non-related with the model (Django Import-Export)
I am using Django-import-export on django admin. I want to export the fields that are not related or are related over 2~3 relationship with the current model. For example Model Classes class A(models.Model): name = models.CharField(default=False) category= models.CharField(default=True) class B(models.Model): title = models.CharField(default=False) category = models.CharField(default=False) Resource class ResourceA(resources.ModelResource): class Meta: model = A How can I get the fields on ResourceA, so that I can export the them to excel? -
How to dynamically add Docker Container's IP to the Django's ALLOWED_HOST
I have planned to deploy my Django application in Docker. For host validation, we need to set the ALLOWED_HOST variable to a domain name or IP address. How can I add the IP address of the container where my application is being served, to the allowed host? I don't want to use wildcards or IP range for security reasons. What can I do? -
How could I make the Edit button work from a modal to update its content
What I wanted to occur is that when I click the update button I could edit the contents of the modal also in the database. And for now i could not do that. And my modal is inside my index.html Here are my ........ Code from Modal and index.html: <!-- Modal --> <div class="modal fade" id="employee.employee_id_{{ employee.employee_id }}" tabindex="-1" role="dialog" style="display: none; overflow: auto;" aria-hidden="true" data-backdrop="static"> <div class="modal-dialog" role="document"> <div class="modal-content"> <h5 class="modal-title" id="employee.employee_id_{{ employee.employee_id }}" </h5> </div> <div class="modal-body" style="overflow: auto"> <div class="container-fluid"> <div class="row"> <div class="col-xl-12"> <div class="card"> <div class="card-header-success" > <h4 align="center" class="card-title">EMPLOYEE PROFILE</h4> </div> <form class="form" id="edit_employee_form" name="edit_employee_form" method="post" action="/edit_employee_form"> <div class="card"> <div class="card-body"> <div class="text-center"> <img src="{% static 'img/faces/marc.jpg' %}" class="rounded" height="150" width="150"> </div> <br> <div class="row"> <div class="col-md-6"> <input type="text" class="form-control" name="emp_id" value="{{employee.employee_id}}" hidden> </div> </div> <div class="form-row"> <div class="col-md-4 mb-3"> <div class="form-group bmd-form-group is-focused"> <label class="bmd-label-floating" for="first_name">First Name</label> <input type="text" class="form-control" id="first_name" name="val_first_name" value=" {{ employee.first_name }}" > </div> </div> <div class="col-md-4 mb-3"> <div class="form-group bmd-form-group is-focused"> <label class="bmd-label-floating" for="first_name">Middle Name</label> <input type="text" class="form-control" id="middle_name" name="val_middle_name" value=" {{ employee.middle_name }}" > </div> </div> <div class="col-md-4 mb-3"> <div class="form-group bmd-form-group is-focused"> <label class="bmd-label-floating" for="last_name">Last Name</label> <input type="text" class="form-control" id="last_name" name="val_first_name" value=" {{ employee.last_name }}" … -
I'm new to django and i'm trying to get a template to work, i've adapted all the other script tags and css but this one, what should i change?
\u003Ch2\u003E\u003Cstrong\u003E\u003Cu\u003EA propos des cookies \u003C\/u\u003E\u003C\/strong\u003E\u003C\/h2\u003E\n\u003Cp\u003EEn poursuivant votre navigation sur ce site, vous acceptez que des Cookies soient utilis\u00e9s afin de r\u00e9aliser des statistiques d\u2019audience, d\u2019am\u00e9liorer votre exp\u00e9rience d\u2019utilisateur et de vous offrir des contenus personnalis\u00e9s.\u003C\/p\u003E\n\u003Cp\u003E\u00a0\u003C\/p\u003E\n \u003Cbutton type=\u0022button\u0022 class=\u0022find-more-button eu-cookie-compliance-more-button\u0022\u003ENon, plus d\u0027informations\u003C\/button\u003E\n \u003C\/div\u003E\n \n \u003Cdiv id=\u0022popup-buttons\u0022 class=\u0022\u0022\u003E\n \u003Cbutton type=\u0022button\u0022 class=\u0022agree-button eu-cookie-compliance-secondary-button\u0022\u003EJe suis d\u0027accord\u003C\/button\u003E\n \u003Cbutton type=\u0022button\u0022 class=\u0022decline-button eu-cookie-compliance-default-button\u0022 \u003ENon, merci\u003C\/button\u003E\n \u003C\/div\u003E\n \u003C\/div\u003E\n\u003C\/div\u003E","use_mobile_message":false,"mobile_popup_html_info":"\u003Cdiv class=\u0022eu-cookie-compliance-banner eu-cookie-compliance-banner-info eu-cookie-compliance-banner--opt-in\u0022\u003E\n \u003Cdiv class=\u0022popup-content info\u0022\u003E\n \u003Cdiv id=\u0022popup-text\u0022\u003E\n \u003Cbutton type=\u0022button\u0022 class=\u0022find-more-button eu-cookie-compliance-more-button\u0022\u003ENon, plus d\u0027informations\u003C\/button\u003E\n \u003C\/div\u003E\n \n \u003Cdiv id=\u0022popup-buttons\u0022 class=\u0022\u0022\u003E\n \u003Cbutton type=\u0022button\u0022 class=\u0022agree-button eu-cookie-compliance-secondary-button\u0022\u003EJe suis d\u0027accord\u003C\/button\u003E\n \u003Cbutton type=\u0022button\u0022 class=\u0022decline-button eu-cookie-compliance-default-button\u0022 \u003ENon, merci\u003C\/button\u003E\n \u003C\/div\u003E\n \u003C\/div\u003E\n\u003C\/div\u003E\n","mobile_breakpoint":"768","popup_html_agreed":"\u003Cdiv\u003E\n \u003Cdiv class=\u0022popup-content agreed\u0022\u003E\n \u003Cdiv id=\u0022popup-text\u0022\u003E\n \u003Ch2\u003EThank you for accepting cookies\u003C\/h2\u003E\n\u003Cp\u003EYou can now hide this message or find out more about cookies.\u003C\/p\u003E\n \u003C\/div\u003E\n \u003Cdiv id=\u0022popup-buttons\u0022\u003E\n \u003Cbutton type=\u0022button\u0022 class=\u0022hide-popup-button eu-cookie-compliance-hide-button\u0022\u003EMasquer\u003C\/button\u003E\n \u003Cbutton type=\u0022button\u0022 class=\u0022find-more-button eu-cookie-compliance-more-button-thank-you\u0022 \u003EMore info\u003C\/button\u003E\n \u003C\/div\u003E\n \u003C\/div\u003E\n\u003C\/div\u003E","popup_use_bare_css":false,"popup_height":"auto","popup_width":"100%","popup_delay":1000,"popup_link":"\/fr\/innovinsa-may-june-terms-and-conditions","popup_link_new_window":1,"popup_position":null,"popup_language":"fr","store_consent":false,"better_support_for_screen_readers":0,"reload_page":0,"domain":"","popup_eu_only_js":0,"cookie_lifetime":"100","cookie_session":false,"disagree_do_not_show_popup":0,"method":"opt_in","whitelisted_cookies":"","withdraw_markup":"\u003Cbutton type=\u0022button\u0022 class=\u0022eu-cookie-withdraw-tab\u0022\u003EPrivacy settings\u003C\/button\u003E\n\u003Cdiv class=\u0022eu-cookie-withdraw-banner\u0022\u003E\n \u003Cdiv class=\u0022popup-content info\u0022\u003E\n \u003Cdiv id=\u0022popup-text\u0022\u003E\n \u003Ch2\u003EWe use cookies on this site to enhance your user experience\u003C\/h2\u003E\n\u003Cp\u003EYou have given your consent for us to set cookies.\u003C\/p\u003E\n \u003C\/div\u003E\n \u003Cdiv id=\u0022popup-buttons\u0022\u003E\n \u003Cbutton type=\u0022button\u0022 class=\u0022eu-cookie-withdraw-button\u0022\u003EWithdraw consent\u003C\/button\u003E\n \u003C\/div\u003E\n \u003C\/div\u003E\n\u003C\/div\u003E\n","withdraw_enabled":false,"withdraw_button_on_info_popup":0,"cookie_categories":[],"enable_save_preferences_button":1,"fix_first_cookie_category":1,"select_all_categories_by_default":0},"urlIsAjaxTrusted":{"\/fr\/search\/node":true,"\/fr":true}}); //--> -
Django: Problem with Getting The Right Objects
I am a beginner learning Django through a building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews. Right now, I am facing a problem. I have added two phone brands, Samsung and Apple, through Django admin. They are being displayed at http://127.0.0.1:8000/index. When I click on Samsung, I see three phone models, Galaxy S10, Galaxy Note 10 and iPhone 11, which have already been added through Django admin. However, iPhone 11 is not supposed to be displayed here, as its brand is Apple, not Samsung. So, basically, when I click on Samsung, only Galaxy S10 and Galaxy Note 10 are supposed to be displayed, not iPhone 11. How can I fix the issue? Here are my codes of models.py located inside PhoneReview folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Brand(models.Model): brand_name = models.CharField(max_length=100) origin = models.CharField(max_length=100) manufacturing_since = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.brand_name def save(self, *args, **kwargs): self.slug = slugify(self.brand_name) super().save(*args, **kwargs) class PhoneModel(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) model_name = models.CharField(max_length=100) launch_date = models.CharField(max_length=100) platform = models.CharField(max_length=100) def __str__(self): … -
SQL to django ORM
I have the model: class DeviceVals(Model): id = UUIDField() dt = DateTimeField() value = FloatField() I need calculate sum of changes from this table, here is sql which works fine: SELECT dt, SUM(cons) FROM (SELECT id, dt, value, ("value" - LAG("value", 1) OVER (PARTITION BY "id" ORDER BY "dt" ASC)) AS "cons" FROM "devicevals") AS ss GROUP BY "dt" ORDER BY "dt"; I need to convert this sql to django ORM. How can I do that? -
Adding data to many-to-many relation in Django database
I am using django 2.2, python 3.6.8 on ubuntu 18.04 with mysql server. I have courses, student and courses_student tables. There is a many-to-many relation between courses and students. In Courses model : student = models.ManyToManyField(Student, blank=True, verbose_name=_("Öğrenci")) I manually created a form in a template and making data insertions manually. studentnamesuuidlist = request.POST.getlist('ogrenci_isimleri') #list student1 = Student.objects.filter(uuid=studentnamesuuidlist[0]) coursesobject.student.set(student1) student2 = Student.objects.filter(uuid=studentnamesuuidlist[1]) coursesobject.student.set(student2) There are 2 students for this course. Student uuid's are coming from template form post. When i run above lines, student2 record is created in courses_student joint table. But student1 is not created. It should create 2 record but it is creating 1 record in joint table. -
Django ouath token returns 403 error while token is valid
I am using django oauth toolkit for a while but in my new project when I use generated token to access protected url it return 403 forbidden while token is correct. I use o/token/ to get a token, then I use ad the token in Bearer tab of insomnia and 403 returns I have this in my settings: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } -
'AnonymousUser' object has no attribute '_meta' - [ For when i try to login with username and password which are not exist. ]
I have written a login function that almost works except when I am trying to login with an invalid username and password it gives me an error. Which is: AttributeError at /account/login 'AnonymousUser' object has no attribute '_meta' My login function: def sign_in(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: auth.login(request,user) return redirect('addproducts') else: print("user not exist") return redirect('login') else: return render(request,'accounts/login.html') What I did wrong? Help me, please! -Thank You -
Is there a way to trigger a React update through Django?
I am working on an application with a Django backend and React frontend. The Django backend currently receives text messages as they are received (no polling). I would like to know how to update my React application with the post data from the text message request as the texts are received (no polling), all while using the Django Rest Framework? I've looked online but I haven't found much information specific to this problem. From what I've read it seems Redux might be the answer, but I'm very new to React and have only briefly looked into Redux so I'm not sure. Also from what I've read online, people have said only use Redux if you have to due to the steep learning curve so I'm wondering if anyone with more experience can point me in the right direction! -
How do I work with Static CSS files in Django?
In my project when working with CSS files, I add a link from my html document pointing to a static file. Every-time I want to make a change to the CSS file, I go into the static folder which I specified in STATICFILES_DIR, and then I run the collectstatic command to see the change in the browser. Is there a more efficient and quicker way of working with CSS files in Django. I am a newbie to Django so I apologise if the question is simple, however I couldn't find an answer on the web. Thank you. -
Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'
I am using a sklearn MLPClassifier class and am getting the error: Cannot cast array data from dtype('float64') to dtype(' I have a function that converts the string entry to a list Function: def listinha_da_amanda(entrada): listinha = [] auxiliar_lista = '' for i in range(len(entrada)): if (entrada[i] != ','): auxiliar_lista += entrada[i] elif (entrada[i] == ','): listinha.append(auxiliar_lista) auxiliar_lista = '' return listinha def rna(entrada): import pandas as pd import numpy as np base = pd.read_csv('app/sonotas.csv') previsores = base.iloc[:, 1:10].values classe = base.iloc[:, 10].values from sklearn.preprocessing import StandardScaler scaler = StandardScaler() previsores = scaler.fit_transform(previsores) from sklearn.neural_network import MLPClassifier classificador = MLPClassifier(verbose=True, max_iter=1000, solver='adam', hidden_layer_sizes=(12), activation='relu') classificador.fit(previsores, classe) resolv = listinha_da_amanda(entrada) resolv2 = [] resolv2.append(resolv) resultado = classificador.predict(resolv2) return resultado Input Example: 9,8.6,6,7.6,8.1,7.8,8.3,9.4,8.9, I am using the Django framework. -
django works perfectly with socket io when I python manage.py runserver but how to do with gunicorn?
I have taken some help from django example with socket.io I found some issue that if I run this code it will only run my socket(5000) but not my main website(at 8000) so I modified it a little bit and it looked like something this socketio_app/views.py from django.shortcuts import render # Create your views here. import socketio sio = socketio.Server(async_mode='eventlet', always_connect=True) @sio.event def connect(sid, environ): print('connected to ', sid) return True @sio.event def disconnect(sid): print("disconnected", sid) @sio.on('chat') def on_message(sid, data): print('I received a message!', data) sio.emit("chat", "received your msg"+str(data)) Similarly as in the github repo they overrided runserver command I made some changes to it to make it look like I also called super to run main website coded along with threaded socket io at port 5000 socketio_app/management/commands/runserver.py from django.core.management.commands.runserver import Command as RunCommand from socketio_app.views import sio import os class Command(RunCommand): help = 'Run the Socket.IO server' def handle(self, *args, **options): if sio.async_mode == 'threading': super(Command, self).handle(*args, **options) elif sio.async_mode == 'eventlet': import eventlet import eventlet.wsgi from ProLogger.wsgi import application import threading def fun(): print(os.system("sudo kill -9 `sudo lsof -t -i:5000`")) eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 5000)), application) t = threading.Thread(target=fun) t.start() import time time.sleep(3.5) super(Command, self).handle(*args, **options) wsgi.py import os from django.core.wsgi …