Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass django context data to frontend without inline script in template
I'm already passing django context data to my frontend part using inline scripts in my template file: <script> var variable = "{{ variable }}"; </script> But for security reasons I'm no longer able to do this. My Content Security Policy settings should be configured in a way to prevent inline scripts. Can you help me? Any ideas? -
How to check relation of one object in another models while deleting the object
When we delete object from dajngo admin side dashboard .it gives all the relation of the objects. Refer image.So how can we do this in coading ? Is there any method for that ? -
How to get template field values to Django class based view
Here is my class, I want to take values to this class from my template 'registeredUsers.html' class registeredusers(RegistrationView, PersonnelView): template_name = 'registeredUsers.html' def get_context_data(self, *args, **kwargs): context_dict = {} context_dict['employeeform']= RegistrationForm empDetails= Employee.object.all() return context_dict Template fields <input class="email" type="email" value="{{i.email}}"> <input class="email" type="email" value="{{i.email}}"> -
Django form not saving data to database with custom form
I trying to create a form for a parking lot for the user and the form will input their RFID card, their log history, license plate, name and active or not but I can't get Django form to save it to the database here is my models.py from django.db import models class data(models.Model): RFID = models.CharField(max_length=10) Name = models.CharField(max_length=10) Log = models.TextField() License_Plate = models.CharField(max_length=10) Active = models.BooleanField(default=True) My forms.py from django import forms from .models import data # import data from models.py class data_form(forms.ModelForm): class Meta: model = data fields = ['RFID', 'Name', 'Log', 'License_Plate', 'Active'] class data_custom_form(forms.Form): RFID = forms.CharField( widget=forms.TextInput(attrs={'id': 'user-rfid'}), ) Name = forms.CharField(widget=forms.TextInput( attrs={'id': 'user-name', 'cols': 40, 'rows': 1 })) Log = forms.CharField( widget=forms.TextInput(attrs={'id': 'user-log'}) License_Plate = forms.DecimalField() Active = forms.BooleanField() My views.py from django.shortcuts import render # Create your views here. from .models import data from .forms import data_custom_form def custom_form_view(request): custom_form = data_custom_form() if request.method == 'POST': custom_form = data_custom_form(request.POST) if custom_form.is_valid(): print(custom_form.cleaned_data) else: print(custom_form.errors) info = { 'form': custom_form } return render(request, 'parking.html', info) And my template <DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>parking</title> </head> <body> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="save"> … -
Heroku Redirect non-www to www on Django website
I currently have a website domain with Bluehost. Bluehost cannot redirect https://example.com to https://www.example.com using 301 redirects since I am not hosting with them. Now in my DNS settings, I have a CNAME (Alias) record that points @ to <string1>.herokudns.com and I have another CNAME (Alias) that points www to <string2>.herokudns.com. I have contacted Bluehost and they said one solution would be to point both www and @ to <string1>.herokudns.com but that does not seem to be a redirection to me. How can I manage to redirect the naked domain to www within Heroku on Python? I cannot test them a lot since Bluehost TTL is 4 hours and I cannot manage to change my configurations fast. Appreciate any help in advance! -
ImportError: cannot import name 'sysconfig' from 'distutils' (/usr/lib/python3.8/distutils/__init__.py)
I installed pip3 using sudo apt-get install python3-pip after that when I run the following command to install django sudo pip3 install django I get this error: Traceback (most recent call last): File "/usr/bin/pip3", line 9, in from pip import main File "/usr/lib/python3/dist-packages/pip/init.py", line 14, in from pip.utils import get_installed_distributions, get_prog File "/usr/lib/python3/dist-packages/pip/utils/init.py", line 23, in from pip.locations import ( File "/usr/lib/python3/dist-packages/pip/locations.py", line 9, in from distutils import sysconfig ImportError: cannot import name 'sysconfig' from 'distutils' (/usr/lib/python3.8/distutils/init.py) How do I fix this? -
Permission.objects.get() method is not working while creating the test database for Unit tests in Django
I Written the Django signals for creating the groups and assign permissions to theses groups for the different user roles but when I am running my test cases then I am getting permission error for creating test database. signal.py from django.contrib.auth.models import Permission, Group def create_group(): permission = Permission.objects.get(codename=codename, contant_type=contant_type) This is working fine for me when I run my migrations but when I am trying to run my test cases then I ma getting error for creating test database. django.contrib.auth.models.DoesNotExist: Permission matching query does not exist. -
Why am I not able to load youtube embed url in django template?
Currently I have been working on django templates with Angular js & I am binding data into django templates. I am facing difficulty when binding youtube video url using Angular js. My code as below. <div class="col-12 col-lg-6 col-xl-5 pb-3 pb-lg-0"><iframe class="agent-video-iframe border-0" height="326px" ng-src="{{agent.video_url }}" width="100%"></iframe></div> <!-- <div class="col-12 col-lg-6 col-xl-5 pb-3 pb-lg-0"><iframe class="agent-video-iframe border-0" height="326px" src="https://www.youtube.com/embed/KYPRQStfRWo" width="100%"></iframe></div>--> When I am loading page with static youtube url , I am able to successfully load youtube video url. When I am loading page with dynamic youtube url(binding using AngularJs), I am not able to load youtube video url. I am not also getting any error message. Please let me know if anyone has idea or solution. Thanks. -
How to retrieve values from the related table created by Django itself?
Recently I am developing a project where I have to create a table that contains 2 many to many fields and 1 foreign key. Through this table Django implicitly creates a related table (for mapping). Now my question is I need to fetch the values from the mapping table. This particular table has no existence in models.py but this is there in the database.How shall I query this one in views.py and what shall I import to make this table visible in views.py. p.s. I am a noob in Django. Any help would really be appreciable. -
Django Oauth Toolkit as SSO server
I want to know can we use Django oauth Toolkit (DOT) as SSO server? I am using Django Rest Framework in backend. Steps I need to achieve : On clicking the Login Button in the client server, it redirects to the server asking to authorise. If already logged in it will return the auth code. If not logged in open the log in prompt. On successful login step 2 will followed. Thanks. -
How to display python output to the page in django
Hey I am making a website with django, I already have the design of the website all that i need is to display a timer, history, different graphs, and other python backend code. I am confident i can write it in python I am just confused on how i can display the output from python to the page. Please help! -
How to genrate fingerprint using NAB Transact in django?
I am using NAB Transact with Python/Django. I found 2 documentation for Nab: Document 1 - https://sourdough.com/sites/default/files/PDF/DirectPostIntegrationGuide.pdf Document 2 - https://www.nab.com.au/content/dam/nabrwd/documents/forms/payment-andmerchants/nab-ecommerce-merchant-application-form.pdf I tried to generate a Fingerprint but couldn't get any response. <form action="https://transact.nab.com.au/test/directpost/genfingerprint" method="post" target="_blank"> <input type="hidden" name="EPS_MERCHANT" value="XYZ0010"> <input type="hidden" name=”EPS_PASSWORD” value=”txnpassword”> <input type="hidden" name="EPS_REFERENCEID" value="Test Reference"> <input type="hidden" name="EPS_AMOUNT" value="100.00"> <input type="hidden" name="EPS_TIMESTAMP" value="20140224221931"> <input type="hidden" name="EPS_RESULTURL" value="https://www.resulturl.com"> <input type="submit" value="OK"> </form> -
How to Upload Image in React js and Django?
I am trying to upload an image using react js on django backend but wheni try to upload pic and check it console.log() image FILE exist there and once i submit the form image file object shsows {} empty i don't why all the time when i submitted for its shows uploaded but all the time image shows null, Here is my code so far what i did. here is also a link of code sandbox link . https://codesandbox.io/s/thirsty-varahamihira-fnusu?file=/src/App.js:0-1494. Thanks. import React, { Component } from "react"; import "./styles.css"; class App extends Component { constructor(props) { super(props); this.state = { image: null }; } handleInputChange = async (event) => { await this.setState({ [event.target.name]: event.target.files[0] // image: event.target.files[0] }); }; handleSubmit = (e) => { e.preventDefault(); const formdata = new FormData(); formdata("image", this.state.image); fetch(`https://inback.herokuapp.com/api/1/blog/image/list/`, { method: "POST", headers: { "Content-Type": "multipart/form-data", Authorization: "Bearer 6tEg0RinS5rxyZ8TX84Vc6qXuR2Xxw" }, body: formdata }) .then((response) => { if (response.ok) { alert("Success"); } else { alert("error"); } }) .catch((err) => { console.log(err); }); }; render() { return ( <div id="other" className=""> <p className="mod" style={{ marginTop: "10px" }}> Uplaod </p> <hr></hr> <form onSubmit={this.handleSubmit}> <input type="file" name="image" onChange={this.handleInputChange} /> <button>Submit</button> </form> </div> ); } } export default App; -
Cannot send mail when close terminal AWS
I deployed a Django app on AWS and when I connect to AWS Linux terminal, it worked. But when close the terminal, the web server cannot send mail anymore. I use EmailMessage in Django. I run server with nginx and gunicorn. -
Django Hosting that has unlimited hosting apps for my Projects
Is there any website which gives unlimited apps to create for django hosting... Means I can upload as many django website as I want for my projects because heroku only gives 5 apps at max -
Django forms not adding textbox & not sending what user looked up
So the django file is not showing the form and at first, I got angry at that so I just used HTML code to create a form but I realized that when I submit it on the form it does not send it to where I want it to send. I was just wondering if you could help. I think the problem with the file is between the relationship between util.py file and the index.html file but I can't see it for some reason. Thank you!! util.py file class Form(forms.Form): searched = forms.CharField(max_length=128, help_text="Please enter the category name.") def get_name(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): searched = form.cleaned_data['searched'] return searched else: form = Form return render(request, "wiki/index.html", { "form" : form }) wiki.urls.py - main urls file from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include("encyclopedia.urls")), path('wiki/', include("encyclopedia.wurls")) ] encyclopedia.urls file from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] views.py file from django.shortcuts import render from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries(), "lookUp": util.get_name(request) }) def title(request, name): return render(request, "encyclopedia/titlePage.html", { "entries": util.list_entries(), "name": name, "entry": … -
add a field to a Django model
I am working on this project: https://github.com/mirumee/saleor I want to add a "user_id" column to the product table. So, I added the following code to line 248 https://github.com/mirumee/saleor/blob/master/saleor/product/models.py#L248 account_user = models.ForeignKey( Account_User, related_name="products", on_delete=models.CASCADE, ) However, Django says "NameError: name 'Account_User' is not defined". How could I solve this problem? Thanks -
Deploying a python app to heroku, struggling with gunicorn configuration
I've inherited a python django app and am trying to breathe new life in it. It's currently using python 2.7 and many old packages that I will eventually need to upgrade. But the first thing before upgrading is I want to have it running successfully on heroku. So far I have it running fine locally, but I'm running into issues with heroku and gunicorn. Here is the error I'm getting: 2020-09-10T03:48:27.212247+00:00 heroku[web.1]: Starting process with command `gunicorn spotlit_due_diligence.spotlit_due_diligence.wsgi:application` 2020-09-10T03:48:29.477479+00:00 heroku[web.1]: State changed from starting to up 2020-09-10T03:48:29.206728+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [4] [INFO] Starting gunicorn 19.10.0 2020-09-10T03:48:29.207159+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [4] [INFO] Listening at: http://0.0.0.0:45741 (4) 2020-09-10T03:48:29.207253+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [4] [INFO] Using worker: sync 2020-09-10T03:48:29.211268+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [11] [INFO] Booting worker with pid: 11 2020-09-10T03:48:29.250434+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [13] [INFO] Booting worker with pid: 13 2020-09-10T03:48:29.000000+00:00 app[api]: Build succeeded 2020-09-10T03:48:30.075238+00:00 app[web.1]: [2020-09-10 03:48:30 +0000] [11] [ERROR] Exception in worker process 2020-09-10T03:48:30.075250+00:00 app[web.1]: Traceback (most recent call last): 2020-09-10T03:48:30.075251+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 586, in spawn_worker 2020-09-10T03:48:30.075251+00:00 app[web.1]: worker.init_process() 2020-09-10T03:48:30.075251+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 135, in init_process 2020-09-10T03:48:30.075252+00:00 app[web.1]: self.load_wsgi() 2020-09-10T03:48:30.075252+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-09-10T03:48:30.075252+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-09-10T03:48:30.075253+00:00 app[web.1]: … -
Testing Graphene returns error JSONDecodeError: Expecting value: line 2 column 1 (char 1)
I am new to Unit Test on Graphene and DJango. I am trying to test my graphql query by graphene https://docs.graphene-python.org/projects/django/en/latest/testing/ But I have no idear why I am getting this error. Please help me. import json from graphene_django.utils.testing import GraphQLTestCase # Create your tests here. class CryptoBankQueryTestCase(GraphQLTestCase): def test_cryptobank_query(self): response = self.query( ''' query cryptoBank($id: Int!){ cryptoBank(cryptoBankId: $id) { id, name, phoneNumber, address } } ''', op_name="cryptoBank", variables={"cryptoBankId": 1} ) content = json.loads(response.content) # This validates the status code and if you get errors self.assertResponseNoErrors(response) # Add some more asserts if you like Error: ERROR: test_cryptobank_query (cryptobank.tests.test_cryptobank_query.CryptoBankQueryTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/cafafanscoders/Desktop/python/CryptoBankGraphQL/src/cryptobank/tests/test_cryptobank_query.py", line 22, in test_cryptobank_query content = json.loads(response.content) File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1) -
Django Oscar Dashboard link not accessible
I have developed oscar /django applications before but I am completely stumped by this issue: I can see the dashboard url in the supported urls list but I am not able to access it. 404 Page I have forked a few apps from oscar like voucher, shipping, checkout, reviews and customized them in various ways(None of these are dashboard related) . This is my INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'oscar.config.Shop', 'oscar.apps.analytics.apps.AnalyticsConfig', 'iirns.checkout.apps.CheckoutConfig', 'oscar.apps.address.apps.AddressConfig', 'iirns.shipping.apps.ShippingConfig', 'oscar.apps.catalogue.apps.CatalogueConfig', 'iirns.catalogue.reviews.apps.CatalogueReviewsConfig', 'oscar.apps.communication.apps.CommunicationConfig', 'oscar.apps.partner.apps.PartnerConfig', 'oscar.apps.basket.apps.BasketConfig', 'iirns.payment.apps.PaymentConfig', 'oscar.apps.offer.apps.OfferConfig', 'oscar.apps.order.apps.OrderConfig', 'oscar.apps.customer.apps.CustomerConfig', 'oscar.apps.search.apps.SearchConfig', 'iirns.voucher.apps.VoucherConfig', 'oscar.apps.wishlists.apps.WishlistsConfig', 'oscar.apps.dashboard.apps.DashboardConfig', 'oscar.apps.dashboard.reports.apps.ReportsDashboardConfig', 'oscar.apps.dashboard.users.apps.UsersDashboardConfig', 'oscar.apps.dashboard.orders.apps.OrdersDashboardConfig', 'oscar.apps.dashboard.catalogue.apps.CatalogueDashboardConfig', 'oscar.apps.dashboard.offers.apps.OffersDashboardConfig', 'oscar.apps.dashboard.partners.apps.PartnersDashboardConfig', 'oscar.apps.dashboard.pages.apps.PagesDashboardConfig', 'oscar.apps.dashboard.ranges.apps.RangesDashboardConfig', 'oscar.apps.dashboard.reviews.apps.ReviewsDashboardConfig', 'oscar.apps.dashboard.vouchers.apps.VouchersDashboardConfig', 'oscar.apps.dashboard.communications.apps.CommunicationsDashboardConfig', 'oscar.apps.dashboard.shipping.apps.ShippingDashboardConfig', # 3rd-party apps that oscar depends on 'widget_tweaks', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2', 'mailer', 'extra', ] and this is my root url file: from django.conf.urls import url from django.contrib import admin from django.apps import apps from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('extra.urls')), path('', include(apps.get_app_config('oscar').urls[0])), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to create a separeate log file for each user logged in using Django?
Am new to DJango, how to create a new logger or log file on each user logon? how to access this logger to log user specific actions? And also, Need to close the logger on the user logout. Please share any ideas or examples if any? -
django-pytest with user-agent cant find request.user-agent
thanks for your time. i've got a app thats getting tested with pytest-django. although i've been facing some issues for the request function o views.py. at my views i've got some statements based on the request.user_agent(app installed django-user-agents) to select if will be displayed a mobile or desktop template. And those are getting me errors on pytest-django. views.py: def curriculo_view(request): context = {} if request.user_agent.is_mobile: return render(request, 'amp/Curriculo-mobile.html', context) elif request.user_agent.is_pc: return render (request, 'admin/Curriculo.html', context) else: return render (request, 'admin/Curriculo.html', context) test_views.py: def test_curriculo_view(self): path = reverse('curriculo') request = RequestFactory().get(path) response = views.curriculo_view(request) assert response.status_code == 200 error: def curriculo_view(request): context = {} > if request.user_agent.is_mobile: E AttributeError: 'WSGIRequest' object has no attribute 'user_agent' accounts\views.py:98: AttributeError i've tried to set like when i want to set a user (ex:request.user = User.objects.get()), tried to set to the key of request.META['USER_AGENT'] and none is getting me trough this. -
Cannot assign "'value'": "model.attr" must be a "model" instance
I am new en django, I have the next models in models.py class Persona(models.Model): cedula_p= models.CharField(primary_key=True, max_length=10) Nombre_p= models.CharField(User, max_length=100) fecha_nacimiento_p= models.DateField() #11111, User1, 01/01/1991 #22222, User2, 02/02/1992 #Others 13998 items def __str__(self): return "{0},{1}".format(self.cedula_p, self.Nombre_p) class Producto(models.Model): Nombre_prod = models.CharField(max_length=100) precio = models.PositiveIntegerField() def __str__(self): return "{0}".format(self.Nombre_prod) class compra(models.Model): cedula_prod= models.ForeignKey(Persona, max_length=10, on_delete=models.CASCADE) producto = models.ForeignKey(Producto, on_delete=models.CASCADE) The forms.py is: class formulario_compra(forms.ModelForm): cedula_prod = forms.CharField() #I have 14.000 elements, for that reason i don't use select o choicefield class Meta: model = compra fields = '__all__' #input test cedula_prod: 11111 or 22222 and the views.py class crear_persona(CreateView): model = Persona form_class = formulario_persona template_name = 'web1.html' success_url = reverse_lazy('EjemploVista1') class crear_compra(CreateView): model = compra form_class = formulario_compra template_name = 'Web2.html' success_url = reverse_lazy('EjemploVista2') in the forms, in formulario_compra i don't use the default form for cedula_prod because would be a list with some values (14000), so, I use a charField. I need to verify that the input exists in the model Persona.cedula_p. At the moment to try to save appear: Cannot assign "11111": "compra.cedula_prod" must be a "Persona" instance. I try different things, but I can't solve this situation. -
How to check email is already in database or not in django?
I want to add a functionality in registration form that if email is already in database than display massage ie this email is already register. i am trying this with the following code but this is not working accounts/forms.py from django.contrib.auth import get_user_model from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserCreateForm(UserCreationForm): # email = forms.EmailField() class Meta: fields = ["username","email","password1","password2"] model = get_user_model() def clean_email(self): email = self.cleaned_data.get('email') if email in User.objects.all(): raise forms.ValidationError("Only .edu email addresses allowed") return email def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Display Name' # self.fields['email'].label = 'Email Address' -
How to get ManytoManyField's data from another model in Django?
I am here asking for guides on how to get ManyToManyField's data from another model. Let's say I have 3 models, Student, Course, and Attendance. Course model has a many to many relationship with Student. In CourseForm I set the widget of student to CheckBoxSelectMultiple so that user can check which student can get into that course in form. In another model called Attendance I also have a field which also has many to many relationship with Student. Now in my AttendanceForm on student field I want to display only the students who were selected when the Course was created. I think maybe we can do the queryset inside the AttendanceForm because right now the default queryset for student inside AttendanceForm is Student.objects.all() but I don't know how to do the queryset to get only the students who were selected when the Course was created. Can anyone help me please? models.py class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) class Course(models.Model): teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE) student = models.ManyToManyField(Student) random_code = ShortUUIDField(default=code, editable=False) class Attendance(models.Model): teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE) student = models.ManyToManyField(Student) course = models.ForeignKey(Course, on_delete=models.CASCADE) forms.py class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['student', 'random_code', ..] widgets = {'student': …