Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing forms values/strings into views.py and back to template
I know that there's a lot of topics with this matter, but I just can't get my code working. Can you please help me what is wrong with my Django website school project. So the problem gets easier to understand lets assume that I want to make a basic search bar to my site, where: user can submit a word the word goes into views.py file where from views.py file it will get back to template with render function My current code looks like this: HOME.HTML CODE <!-- Submit hashtag search --> <form action="/search/" method="get" > <input type="text" name = "q"> <input type="submit"value="Search"/> </form> <h1> hashtag </h1> VIEWS.PY CODE from django.shortcuts import render import tweepy, csv, sys, re from website import twitterAPI # This is supposed to make the homescreen blank before submitting any word to the search box def home(request): return render(request, 'website/home.html') def about(request): return render(request, 'website/about.html') # When submitting a word to the search box this function should # return the word back to home.html as a 'context' def search(request): hashtag = 'You submitted: %r' % request.GET['q'] context = {'hashtag': hashtag} return render(request, 'website/home.html', context) Currently, the website opens like it should (blank page with a search … -
python project is not running in visual studio
hi i made this simple project https://github.com/dharmendrak603/myfirstproject and it was running properly earlier and i moved out to some other project, but now when i want to run this project it gives me error below. actually i don not remember the virtual envirment name aslo but i remember that it should be one of denvx or 111 . i am new to django and python. please help. django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Generate access token using user instance (not username, password and grant_type)
I'm using Django REST Framework and using this library to provide token based authentication to the frontend applications. There is Login with Google implementation using django-allauth plugin. I want to generate access token when user login using social account. For handling social login and generating social account, I have created this view. class GoogleLoginView(LoginView): """ Enable login using google """ adapter_class = GoogleOAuth2Adapter serializer_class = CustomSocialLoginSerializer def login(self): self.user = self.serializer.validated_data['user'] self.token = TokenView().create_token_response(self.request) return self.token def post(self, request, *args, **kwargs): self.request = request self.serializer = self.get_serializer( data=self.request.data, context={'request': request} ) self.serializer.is_valid(raise_exception=True) url, header, body, status_ = self.login() return Response(json.loads(body), status=status_) The request data has user instance along with client_id and client_secret of the application. But this gives error '{"error": "unsupported_grant_type"}' Version django-oauth-toolkit==1.3.0 -
include credentials in ajax request (Django REST)
my server packages are: Django==3.0 django-cors-headers==3.2.1 djangorestframework==3.11.0 djangorestframework-simplejwt==4.4.0 and i configured CORS as mentioned here CORS config in settings.py is: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = None my api login view: class BaseLogin(APIView): renderer_classes = [JSONRenderer] permission_classes = [IsAnonymous] def post(self, request): ... ... response = Response('Logged in', status=status.HTTP_200_OK) response.set_cookie(key='access', value=f'Bearer {str(access)}', expires=datetime.fromtimestamp(access['exp'])) response.set_cookie(key='refresh', value=str(refresh), expires=datetime.fromtimestamp(refresh['exp'])) # login login(request, user, backend='django.contrib.auth.backends.ModelBackend') return response In frontend we use Vue CLI jquery ajax for Login: $.ajax({ url: "https://something.ngrok.io/api/v1/accounts/login/student/", crossDomain: true, data: { eu: "username", password: "pass" }, xhrFields: { withCredentials: true }, type: "POST", success: function(data, textStatus, request) { console.log(request); }, error: function(request, textStatus, errorThrown) { console.log("error"); } }); and here is ajax for an endpoint that needs Authorization header: $.ajax({ url: "https://something.ngrok.io/api/v1/accounts/vc/user-email/", crossDomain: true, xhrFields: { withCredentials: true }, type: "GET" }).done(function(data, status, xhr) { }); after login we have access and refresh tokens in browser -> storage -> cookies. as we know, can not access cookies that been set by server in js code. The problem is we get 401 unauthorized in protected views and reason is we don't have 'Authorization: Bearer Token here' in request headers. do we need extra config in server or ajax requests? Thank … -
Inserting the same values of string (as a key ) in the dictionary
I was writing the python code in Django. I was facing a problem, wherein I have three fields which are optional: Contact Name Contact Number Contact Email Ram 9888812345 *Blank*(Meaning not present) Ram *Blank(Meaning not present)* ram@gmail.com Shyam 8776532211 shyam@hotmail.com Shyam 7862126121 radhe@gmail.com For this, I had written code as follows: contact_validation = {} for row in df: if not row['Contact Name']: row['Contact Name'] = 'Name' if not row['Contact Number']: row['Contact Number'] = 'Number' if not row['Contact Email']: row['Contact Email'] = 'Email' if (row['Contact Name']+ "-" + row['Contact Number']+ "-" + row['Contact Email']) not in contact_validation.keys(): contact_validation[(row['Contact Name']+ "-" + row['Contact Number']+ "-" + row['Contact Email']).strip()] = [] contact_validation[(row['Contact Name']+ "-" + row['Contact Number']+ "-" + row['Contact Email']).strip()].append(row['Name']) else: contact_validation[(row['Contact Name']+ "-" + row['Contact Number']+ "-" + row['Contact Email']).strip()].append(row['Name']) For this, Currently I have an output as below: {'Ram-9888812345-Email': ['CRM_TestVenue_26_March_23'], 'Ram-Number-ram@gmail.com': ['CRM_TestVenue_26_March_2'] 'Shyam-8776532211-shyam@hotmail.com':[Test2], 'Shyam-7862126121-radhe@gmail.com':[Test3]} But I required the Output as follows: {'Ram-9888812345-ram@gmail.com': ['CRM_TestVenue_26_March_23','CRM_TestVenue_26_March_2'], 'Shyam-8776532211-shyam@hotmail.com':[Test2], 'Shyam-7862126121-radhe@gmail.com':[Test3]} Can anyone please suggest some piece of code or advice.? What needs to be changed? -
How to acheive a forward assignment of m2m object in django?
I know this is a weird question and also aware that django doesn't allow forward creation of m2m objects. Firstly my models.py is: class Option(models.Model): option = m.CharF(...) class Question(models.Model): question = m.CharF(...) answer = m.CharF(...) option = m.m2m(Option) class Test(models.Model): name = m.CF(...) question = m.m2m(Question) As you can see my model, it is a structure for online question paper. I know that only existing questions and options can be added while creating a new test object. How can i achieve my objective of creating the Test, Question and Option objects at the same time. After searching around stackoverflow and some googling, i came to know about .add() but that didn't suite my goal. Any solutions? If you can, please do add a views.py for it. That would be of great help. -
Why does floatformat prevent value from showing on django template
I am trying to format my float values on django template as follows. {{ product.invoicePrice|floatformat:2 }} without the |floatformat:2 part, the invoicePrice shows on the template but once I add the |floatformat:2, nothing is displayed. Any ideas why? -
Ajax connection error between views.py and html Template
I using ajax to loading speed better. But the ajax connection is not working properly. This is the template code that without Jquery document.getElementById('{{ key }}_execute').addEventListener('click', function (event) { var xhr = new XMLHttpRequest(); xhr.open('POST', './more', true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById('{{ key }}_more').innerHTML = xhr.responseText; } } xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var data = 'sample'; xhr.send(data); }); and this is view.py def more(request): if request.method == 'POST': adfd = request.POST.get('data') return render(request, 'score/more.html', {'a' : adfd}); if this code is right, the result have to be "test". but it print "None" i think this code can't give a parameter well. But it's working well without error. Is any advise to give and take a information well? -
Difference between resolve(path).url_name & resolve(path).view_name in Django
Can anyone tell me the difference between resolve(path).url_name and resolve(path).view_name in Django? resolve is a method in django.urls module. Please see this link : https://docs.djangoproject.com/en/3.0/ref/urlresolvers/#resolve I went through the description in link but could not understand it. It seems similar to me. -
Django: is_valid() method is always return false when use with ModelForm
is_valid() method is always returning false when i use forms.ModelForm in forms.py to create form,so that i can save all values getting from form which is input by user.This code works fine with forms.Form but not with forms.ModelForm forms.py from django import forms from .models import student class student_data(forms.ModelForm): name=forms.CharField(widget=forms.TextInput,max_length=20) id=forms.IntegerField() address=forms.CharField(widget=forms.TextInput,max_length=50) class Meta(): model=student fields=['name','stu_id','address'] here is models.py from django.db import models # Create your models here. class student(models.Model): name=models.CharField(max_length=20) stu_id=models.IntegerField() address=models.CharField(max_length=60) class Meta: db_table='student' here is views.py from django.shortcuts import render from django.http import HttpResponse from .models import student from .forms import student_data def my_data(request): stu1_name='' stu2_name='' stu_name='' myform=student_data(request.POST) if (request.method=="POST" and myform.is_valid()): stu_name=myform.cleaned_data['name'] stu1_name=myform.cleaned_data['id'] stu2_name=myform.cleaned_data['address'] myform.save() else: myform=student_data return render(request,'show.html',{'student':stu_name,'id':stu1_name,'address':stu2_name}) html file for form <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div> <form name="form" action="/payment/show/" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Add Me</button> </form> </div> </body> </html> -
How to interact with web site urls ? I have Djoser installed with Django rest framework
I have Djoser installed in Django Rest framwork. I could login using '/token/login/' command by providing {email:'',password:''} field through Postman (it is POST command and I enter through Postman body section as raw data) Djoser documents says that in order to access user info,I need to provide below details in post command $ curl -LX GET http://127.0.0.1:8088/auth/users/me/ -H 'Authorization: Token b704c9fc3655635646356ac2950269f352ea1139' {"email": "", "username": "djoser", "id": 1} Please advice how to send GET request to Django server using postman or browser url, I am a newbie so I dont know to interace with urls Thanks in advance -
Python Django: Pillow installation works but django doesn't recognise it
I am learning to write a basic online shop webapp with Django. I am follow instructions from https://www.youtube.com/watch?v=jZ3DhppbUnM&t=269s, all seems to be fine but I found myself in a loop. When running C:\Users\Llewellyn\myshop>python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: shop.Product.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". C:\Users\Llewellyn\myshop> Then after installation in PyCharm project terminal (myshop) C:\Users\Llewellyn\myshop>pip install Pillow Collecting Pillow Downloading Pillow-7.0.0-cp38-cp38-win_amd64.whl (2.0 MB) |████████████████████████████████| 2.0 MB 1.7 MB/s Installing collected packages: Pillow Successfully installed Pillow-7.0.0 (myshop) C:\Users\Llewellyn\myshop> and rerunning python manage.py makemigrations in commandprompt I get the same error? Which is confusing because I just installed the package? The complete problem..' C:\Users\Llewellyn\myshop>python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: shop.Product.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". C:\Users\Llewellyn\myshop>python -m pip install Pillow Requirement already satisfied: Pillow in c:\python36\lib\site-packages (7.0.0) C:\Users\Llewellyn\myshop>python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: shop.Product.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". C:\Users\Llewellyn\myshop> … -
Django MultiValueDictKeyError when sending multiple select data
I want to render a multivalueDict in the template for iteration. How is that possible?I get MultiValueDictKeyError with the below code @require_POST def mail_forward_dynamicForm(request): receivers = request.POST['receivers'] return render(request, 'mail_forward/dynamic_form.html', {'receivers':receivers }) -
Forbidden(403) permission access error on Apache2.4 on windows machine
I am running my Django app on Apache2.4.38. I have given all the necessary parameters and access to the Apache server. Still, I am receiving a 403 error when I try to access the Application URL. httpd-vhosts.conf: Listen 8084 WSGIPythonPath "D:/WebAttendance/" <VirtualHost *:8084> SSLEngine on SSLCertificateFile "D:/Desktop/Python/WebAttendance/certs/development.crt" SSLCertificateKeyFile "D:/Desktop/Python/WebAttendance/certs/development.key" WSGIScriptAlias / "D:/Desktop/Python/WebAttendance/WebAttendance/wsgi.py" DocumentRoot "D:/Desktop/Python/WebAttendance" <Directory "D:/Desktop/Python/WebAttendance/"> <Files wsgi.py> AllowOverride All Require all granted </Files> </Directory> <Directory "D:/Desktop/Python/WebAttendance/home/static/"> Require all granted </Directory> Alias /static "D:/Desktop/Python/WebAttendance/home/static" ErrorLog "D:/Desktop/Python/WebAttendance/log/error.log" CustomLog "D:/Desktop/Python/WebAttendance/log/access.log" common </VirtualHost> Error: Forbidden You don't have permission to access / on this server. -
python-celery docker container not able to read images and files passed by python-model docker container
docker-compose.yml version: "3" networks: app-tier: driver: bridge services: python-api-celery: &python-api-celery build: context: /Users/AjayB/Desktop/python-api/ networks: - app-tier volumes: - .:/python_api/ - .:/python_model/ environment: - PYTHON_API_ENV=development command: > sh -c "python manage.py makemigrations && python manage.py migrate" python-api: &python-api <<: *python-api-celery ports: - "8000:8000" command: > sh -c "python manage.py runserver 0.0.0.0:8000" python-model: &python-model build: context: /Users/AjayB/Desktop/Python/python/ ports: - "8001:8001" networks: - app-tier environment: - PYTHON_API_ENV=development volumes: - .:/python_model/ - .:/python_api/ depends_on: - python-api command: > sh -c "cd /python-model/server/ && python manage.py migrate && python manage.py runserver 0.0.0.0:8001" python-celery: &python-celery <<: *python-api-celery depends_on: - redis command: > sh -c "celery -A server worker -l info" redis: image: redis:5.0.8-alpine hostname: redis networks: - app-tier expose: - "6379" ports: - "6379:6379" command: ["redis-server"] Application workflow: I hit APIs passing image to python-api on port 8000., python-api then calls python-model at port 8001 to predict the outcome of an image., which is then passed to python-celery to display images and results in mail. The docker-compose build went smooth, I'm able to run all the 5 containers.., output of docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES xxxxxxxxxxxx integrated_python-celery "sh -c 'celery -A se…" 13 minutes ago Up 5 seconds 8000/tcp integrated_python-celery_1 … -
django model from create a new record instead of updating old one
I am newbie in django. Now my issue is that I updating my record but it's adding a new record instead of updating old one. Where I'm wrong? views.py class EditProduct(TemplateView): template_name = 'stock/editproduct.html' def get(self, request, product_id): productedit = get_object_or_404(Product, pk=product_id) data=Product.objects.get(id=product_id) form = EditProductForm(instance=data) args = {'form':form, 'productedit':productedit} return render(request, self.template_name, args) def post(self, request, product_id): form = EditProductForm(request.POST, request.FILES) if form.is_valid(): productadded = form.save(commit=False) productadded.saler = request.user productadded.pub_date = timezone.datetime.now() productadded.save() return redirect('stock') else: args = {'form': form} return render(request, self.template_name, args) Your help will be appreciated. Thank You -
How can i create a re-usable Template
im new to Django and im in this Stage where you try to build some bigger stuff. So i have my Template "Create User" and a Function with Template where i can delete and edit. Delete works fine. But when i Press Edit, i return my CreateUser Template where i load data in the field and the user can edit it. So if i press edit, my CreateUser Page will be loaded, the fields are filled but when i press save it doesnt work. It returns my Edit Page. Can anyone help me a bit? Would be really nice bc im really hardstuck atm. Btw, you can also give me some advice to my lil code if you want!:) Its not finished right now i know, just want to solve the view first Template: <form action="." method='POST'> {%csrf_token%} <div class="container"> <form> <div class="form-group"> <label for="usr">First Name</label> <input type="text" name="first_name" class="form-control" value="{{user.first_name}}" id="usr"> </div> <div class="form-group"> <label for="pwd">Last Name</label> <input type="text" name="last_name" class="form-control" value="{{user.last_name}}" id="pwd"> </div> <div class="form-group"> <label for="usr">Email</label> <input type="text" class="form-control" id="usr" value="{{user.email}}"> </div> My view: if request.user.has_perm('auth.edit_user'): users = Employee.objects.all() if request.method == "POST": if request.POST.get('delete'): selected_item = request.POST.get("delete") todel = Employee.objects.get(id=selected_item) todel.delete() messages.success(request, "User wurde erfolgreich gelöscht") … -
Django REST Framework: definiting parser and renderer classes on a viewsets.ViewSet @action by @action basis
I was wondering ... what is the best practise way to define custom / bespoke parser and renderer classes on an action by action basis for a rest_framework.viewsets.ViewSet class? Say I wrap a method handler with the following @action decorator: class SomeViewSet(viewsets.Viewset): @action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf]) def process(self, request, *args, **kwargs): ... Is it as simple as adding something like: class SomeViewSet(viewsets.Viewset): @action( detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf], renderer_classes=(PlainTextRenderer,), parser_classes=(MultiPartParser,) ) def process(self, request, *args, **kwargs): ... -
Django Initial value for date picker
Is there a way to set initial value for date picker? I would like to get today's date. My code: class DateInput(forms.DateInput): input_type = 'date' value = date.today() class testerForm(forms.ModelForm): class Meta: model = Tester fields = ('phandlowy', 'data_wypozyczenia') widgets = {'data_wypozyczenia': DateInput(),} -
Django - Modify a foreign key field when updating primary field
I have a question. I have a relation (many-to-many) between two class and I would like when there is a relation created, update a field. class Question(models.Model): intitule = models.TextField(verbose_name="name") matched = models.BooleanField(verbose_name="matched", default=True) asked = models.IntegerField(verbose_name="was asked", default=1) class Meta: ordering = ['intitule'] def __str__(self): return str(self.matched) + " [" + str(self.asked) + "]" + " - " + self.intitule class Reponse(models.Model): reponse = RichTextField() question = models.ManyToManyField(Question) def __str__(self): return self.reponse Here is my question: When I create an object "Response" in the admin interface and I choose a question, I would like to update the attribute "matched" in question automatically. How can I do that ? Thank you very much. -
Django - What if there are more than 100 models in single app
I'm working on Django project that uses more than 200 models. Is it good to have more than 100 models in single models.py?. -
Prevent Force Download of AWS S3 Files Django
I am using storages.backends.s3boto3.S3Boto3Storage storage backend to upload files in my django project. field declaration in model: document = models.FileField(upload_to=s3_directory_path.user_directory_path) user_directory_path def user_directory_path(instance, filename): # TODO: Try to include this along with check filetype on the request object document = instance.document mime = magic.from_buffer(document.read(), mime=True) extension = mimetypes.guess_extension(mime, strict=False) file_name = str(uuid.uuid4()) + extension document.seek(0) return os.path.join("users", str(instance.user.id), file_name) The saving of the document works perfectly fine, but the link which is generated force downloads the file. How can i avoid that? -
PasswordResetForm doesn't send email
I'm working on a user system on an app. Everything works fine except one thing. When I create a user, I generate a password to keep in database and send an email to the new created user to set his own password. So the password is in the database and I use PasswordResetForm to send an email of password reseting. Here is the code I use: reset_password_form = PasswordResetForm(data={'email': user.email}) if reset_password_form.is_valid(): reset_password_form.save(request=request, use_https=True, from_email="Webmaster@mysite.com", html_email_template_name='main/password_reset/password_reset_email.html', subject_template_name="main/password_reset/password_reset_subject.txt") And here is the problem, no email is sent. So to clarify, I already use this Form in case we click on "I forgot my password" and it works very well. So There is no problems of settings for the email server. As well the reset_password_form.is_valid() is true I can breakpoint in the if. The user.email exists and contain a real and correct email adress. I have the feeling that when I call save() on my form it doesn't send the message, did I do a mistake thinking it will do? -
how do I dynamically(?) add fields in Django model?
So I'm a newbie in Django, and having trouble with model. I'm wondering if creating additional field every time a user does certain action (e.g., click (+) button) is possible. So below is the field that I want the user to add as many as he/she wants. models.py class SimpleInput(models.Model): each_input = models.CharField(max_length=200) I have the (+) button in my html file, as well as JavaScript code that enables the function--adding fields with id's increasing by +1. But I'm not sure how I can connect this with model. I very much appreciate your help. Thanks :) For your information, I'm attaching the JS code. $(document).ready(function(){ var addNum = 0; $("#addButton").click(function(){ var currentId = $("#simple_input"+addNum.toString()); var newId = currentId.clone(); newId.attr('value', ''); newId.attr('class', "addedLine"); newId.attr('id', "simple_input"+(addNum+1).toString()).prependTo(".ED_addedHere"); addNum = addNum +1; }); }); -
How to run Django and Spark application
I am working on a Spark Application and I want to create a rest API in Django, below is my code from django.shortcuts import render from django.http import Http404 from rest_framework.views import APIView from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from django.http import JsonResponse from django.core import serializers from django.conf import settings import json from pyspark import SparkContext, SparkConf, SQLContext sc = SparkContext() sql = SQLContext(sc) df = Sql.read.format("jdbc").options( url = "jdbc:mysql://127.0.0.1:3306/demo", driver = "com.mysql.cj.jdbc.Driver", dbtable = "tablename", user = "xyz", password = "abc" ).load() totalrecords = df.count() # Create your views here. @api_view(["GET"]) def Demo(self): try: a = str(totalrecords) return JsonResponse(a,safe=False) except ValueError as e: return Response(e.args[0],status.HTTP_400_BAD_REQUEST) I want to know how will I run this code, as I have directly tried "python manage.py runserver" which is not working, so how to run this spark and django with django api and spark-submit with all required spark jar file?