Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Typing warnings on Django HttpRequest GET param retrieval in PyCharm
I currently encounter a warning in PyCharm when I try to retrieve a value from the GET dictionary of the Django HttpRequest object. I have always used the code below but I am trying to add type checks in my source code. from django.http import HttpRequest def parse_request(request: HttpRequest): request.GET.get('mykey') Warning: Parameter 'key' unfilled I am using Python 3.9.6 Django 3.2.4 PyCharm 2021.1 -
Not a valid origin for the client for google auth
I am making django, react and google auth with this introduction https://iamashutoshpanda.medium.com/google-login-with-django-react-part-1-c189bc69a999 my App.js import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import Grid from "@material-ui/core/Grid"; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import GoogleLogin from "react-google-login"; import axios from "axios"; // get env vars const googleClientId = process.env.REACT_APP_GOOGLE_CLIENT_ID; const drfClientId = process.env.REACT_APP_DRF_CLIENT_ID; const drfClientSecret = process.env.REACT_APP_DRF_CLIENT_SECRET; console.log("googleClientId:" + googleClientId); //correct console.log("drfClientSecret:" + drfClientSecret); //correct console.log("drfClientId:" + drfClientId); //correct const baseURL = "http://localhost:8008"; const handleGoogleLogin = (response) => { axios .post(`${baseURL}/auth/convert-token`, { token: response.accessToken, backend: "google-oauth2", grant_type: "convert_token", client_id: drfClientId, client_secret: drfClientSecret, }) .then((res) => { const { access_token, refresh_token } = res.data; console.log({ access_token, refresh_token }); localStorage.setItem("access_token", access_token); localStorage.setItem("refresh_token", refresh_token); }) .catch((err) => { console.log("Error Google login", err); }); }; const App = () => { return ( <div className="App"> <GoogleLogin clientId={googleClientId} buttonText="LOGIN WITH GOOGLE" onSuccess={(response) => handleGoogleLogin(response)} render={(renderProps) => ( <button onClick={renderProps.onClick} disabled={renderProps.disabled} type="button" class="login-with-google-btn" > Sign in with Google </button> )} onFailure={(err) => console.log("Google Login failed", err)} /> </div> ); }; export default App; Now I have this error, when loading the browser Not a valid origin for the client: http://localhost:3000 has … -
django session data not being saved
Little explanation of what i'm doing: I've a simple telegram bot that sends a link to the user, the link is a twitch login page to authentificate the user and giving me permission to do some twitch stuffs. More in details the user click the link, do the twitch login and then is redirected to mysite.com/verify where all the oidc authentification things are made, then if everything is correct i want to add both twitch id and telegram id of the user to an external database. views.py @csrf_exempt def telegramBot(request): #function to handle telegram webhook print("telegramBot request.session", request.session) for key, value in request.session.items(): #printing all value in session print('{} => {}'.format(key, value)) request.session['telegramid'] = "12345" #trying to add data for key, value in request.session.items(): #checking if there is the new value print('{} => {}'.format(key, value)) #here it correctly prints telegramid => 12345 request.session.modified = True if request.method == 'POST': [code to handle telegram messages] return HttpResponse(status=200) else: return HttpResponse('get',status=200) #mysite.it/verify/ #the user is redirected here after login with twitch def verify(request): print("verify request.session", request.session) for key, value in request.session.items(): #PROBLEM! It prints nothing, print('{} => {}'.format(key, value)) #where is the telegram id previously set? request.session['twitchid'] = "twitchid" #trying to add … -
Django Error on Form instead of raising a ValidationError
I was wondering how I could show an error on the form instead of raising a validation error page. I mean when on the form itself the errorlist is generated, I will attach a screen shot of a different form because my explanation isn't the best haha. Right now in my view I raise a ValidationError instead of the form just adding the error itself. How can I go about adding the form error instead of raising an actual validation error? I would like the normal behavior of errorlist appearing on my form. Any help is greatly appreciated! my view is as follows: class EditProfileInformationView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): form = UserEditForm(initial={ 'first_name': self.request.user.first_name, 'last_name': self.request.user.last_name, 'email': self.request.user.email }) context = { 'form':form } return render(request, 'accounts/update.html', context) def post(self, request, *args, **kwargs): form = UserEditForm(instance=request.user, data=request.POST) context = { 'form': form } if form.is_valid(): initial_email = self.request.user.email form.save(commit=False) email = form.cleaned_data['email'] if User.objects.filter(email=email).exists() and email != initial_email: raise ValidationError('This email already exists') else: form.save() messages.success(request,'Profile Successfully Updated') return redirect('/') else: return render(request, 'accounts/update.html', context) -
How to get the nth record of a model with Python - Django?
I'm currently working on a command that deletes old records for some models that grow a lot in the database. The idea behind is receiving a parameter that indicates from which record number (not id) we have to delete backwards. For doing this i came up with this solution: reference_record = WarmUpCache.objects.filter(company_id=company).values_list('id', flat=True).order_by('-id')[_number_of_records] records_to_delete = WarmUpCache.objects.filter(company_id=company,id__lt=reference_record) if records_to_delete: records_to_delete.delete() For example, for a given company_id=118 I get the ids of the records associated to that Company. Having this, I try to get the nTh record and then, calculate how many records are with an id lower than the given one. After that, delete all of them. Currently this solution is working, but I'm managing to improve it somehow. I have checked stackoverflow to find any answers but I only found old answers that explain almost the same solution I made: django query get last n records django queryset runtime - get nth entry in constant time So, the question itself is ¿Is there any way to improve this query by obtaining just the nth record of a model? Thanks a lot. -
Uncaught TypeError: Cannot read property 'bind' of undefined?
Uncaught TypeError: Cannot read property 'bind' of undefined? This error occurs and also page did not render. I also search on this error but I didn't get any detail or solution. If someone knows the problem and has a solution kindly explain a little bit because I am a beginner. Thanks. Code Leads.js import React, { Component, Fragment } from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { getLeads, deleteLead } from "../../actions/leads"; export class Leads extends Component { constructor(props) { super(props); this.delete = this.deleteLead.bind(this, lead.id); //This line use keyword Bind } static propTypes = { leads: PropTypes.array.isRequired, }; componentDidMount() { this.props.getLeads(); } render() { return ( <Fragment> <h2>Leads</h2> <table className="table table-striped"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Message</th> <th>Delete</th> </tr> </thead> <tbody> {this.props.leads.map((lead) => ( <tr key={lead.id}> <td>{lead.id}</td> <td>{lead.name}</td> <td>{lead.email}</td> <td>{lead.message}</td> <td> <button onClick={this.delete} //Here I want to use it className="btn btn-danger btn-sm" > {" "} Delete </button> </td> </tr> ))} </tbody> </table> </Fragment> ); } } const mapStateToProp = (state) => ({ leads: state.leads.leads, }); export default connect(mapStateToProp, { getLeads })(Leads);``` [![error screenshot][1]][1] [1]: https://i.stack.imgur.com/uoewu.png -
Launch login modal on page load
I'm creating a Django based site and want to launch a login modal if a user tries to access a restricted page while unauthenticated. I started with https://github.com/trco/django-bootstrap-modal-forms and am able to create a functioning login button that launches a login modal but I want the modal to show by itself if the user is unauthenticated. I don't know Javascript so am struggling with this step but is there some way to modify the second script tag to show the modalForm on window load like the first script? {% if user.is_authenticated %} <!-- show something --> {% else %} <div class="modal fade" tabindex="-1" role="dialog" id="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"></div> </div> </div> <!-- <button id="login-btn" class="btn btn-primary" type="button" name="button">LogIn</button> --> <script type="text/javascript"> $(window).on('load',function(){ $('#modal').modal('show'); }); </script> <script type="text/javascript"> $(function () { // Log in button $("#login-btn").modalForm({ formURL: "{% url 'login' %}" }); }); </script> {% endif %} urls.py app_name = 'accounts' urlpatterns = [ path('login/', views.CustomLoginView.as_view(), name='login') ] views.py class CustomLoginView(BSModalLoginView): authentication_form = CustomAuthenticationForm template_name = 'accounts/login.html' success_message = 'Success: You were successfully logged in.' #extra_context = dict(success_url=reverse_lazy('index')) forms.py class CustomAuthenticationForm(AuthenticationForm): class Meta: model = User fields = ['username', 'password'] -
DRY principal in django for needing to use the same query in every function
I have a question. I have a django project where I inherit a navigation bar in all my rendered html views. I want to pass a variable that records how many of certain instance exisits within my DB. Okay so this is extremely simple if I write a query in every single function that renders an html page that {%include 'partials/navbar.html'%}, and every function does because I extend my index file which includes my navbar So like I said it super simple to write a query within every single function and then pass this value in the context. But is there a way that is less tedious almost like an injector in angular?enter image description here -
unable to fetch item from selected categories in django
i want to fetch the item of related subcategories but i am unable to fetch the items from that subcategories it is showing me the error AttributeError: 'Subcategories' object has no attribute 'item' so here is my code my models class Subcategories(models.Model): categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='our_categories') name = models.CharField(max_length=200, blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Item(models.Model): categories = models.ForeignKey(Categories, on_delete=models.CASCADE,) subcategories = models.ForeignKey(Subcategories, on_delete=models.CASCADE, related_name='products') can_buy = models.ForeignKey(For, on_delete=models.CASCADE,) name = models.CharField(max_length=200, blank=False) contain_size = models.CharField(max_length=10, blank=True) first = models.ImageField(upload_to='items', blank=False) second = models.ImageField(upload_to='items', blank=True) third = models.ImageField(upload_to='items', blank=True) fourth = models.ImageField(upload_to='items', blank=True) fifth = models.ImageField(upload_to='items', blank=True) item_vedio = models.FileField(upload_to='item_vedio', blank=True) offered_price = models.FloatField(blank=False,) actual_price = models.FloatField(blank=False) about = models.TextField(blank=False, default="about" ) offer = models.CharField(max_length=4, blank=True) def __str__(self): return self.name my urls.py urlpatterns = [ path('<int:subcategory_id>/products/',Product.as_view(),name='product' ), ] my views.py class Product(View): def get(self, request,): category_list = Categories.objects.all() return render (request, 'product.html', {'category_list': category_list }) def get(self, request, subcategory_id): subcategory = get_object_or_404(Subcategories, pk=subcategory_id) products = subcategory.item.all() return render (request, 'products.html',{"subcategory_list" : products }) any idea what causing the issue and thank you for your time -
How do I use checkboxes to pass value to views django?
I am trying to use checkboxes to get the selected options from the user and pass it onto the views to create a new instance using the value, however, I am finding it difficult to get the input value as it keeps showing None the I try getting the value using the input name within the tag. template <form action='/print_from_button' method='GET'> <table id="id_list_table" class="table table-condensed"> <thead> <tr> <th id="input">Input</th> </tr> </thead> <tbody id="fbody"> {%for m in matches%} <tr> <td><br>{{ m.match }}</br> ({{m.datespent}})</td> <td> <input type="checkbox" name="inputs" class="checkvalue" value={{m.match}} /> </td> </tr> {%endfor%} </tbody> </table> <input type="text" name="checkval" id="checkallvalues" size="50"> <button type='submit'> Confirm </button> </form> urls.py from django.urls import path from . import views from .views import matchpaymentsoverview from django.contrib.auth.decorators import login_required urlpatterns = [ path('matchpayment/overview/',views.matchpaymentsoverview, name="matchpaymentsoverview"), path('print_from_button', views.print_from_button) ] views.py def print_from_button(request): print("button clicked") if request.POST.get('checkval'): vi = request.POST.get('checkval') print(vi) vi1 = request.GET.get('checkval') print(vi1) list_of_input_ids=request.POST.getlist('inputs') print(list_of_input_ids) return HttpResponse("""<html><script>window.location.replace('/');</script></html>""") I keep getting none when I print the above name tags, would I need the button to trigger the function, or I can just create a function and use the get to get the values. Hope it makes sense. Thanks -
Is there a way to add actual HTML to a template from strings containing HTML markup in Django?
So, I want to convert a string I have containing HTML tags converted from a Markdown file into actual HTML. Then inserting the HTML afterwards into a template via Django (this is my first time ever using Django). What my current output looks like: Instead of getting plain text, I want the HTML shown in the screenshot to be executed like normal HTML. Code from my views.py file: from django.http.response import HttpResponse from django.shortcuts import render from markdown2 import Markdown, markdown import random from . import util import html.parser # index output def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) # function to render wiki entries def page_render(request, title): entry = util.get_entry(title) if entry != None: markdowner = Markdown() content = markdowner.convert(entry) return render(request, "encyclopedia/display.html", { "title": title, "content": content }) else: return render(request, "encyclopedia/error.html") Code from my HTML template: {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} {{ content }} {% endblock %} Thanks in advance for the help! Kind Regards PrimeBeat -
Stuck in DJango
Hi im new in django and programming and when I write django-admin startproject to create a new project A commandERROR appears and it's says CommandError: Destination directory 'C:\WINDOWS\system32\3' does not exist, please create it first. -
How to create DRF Reverse Deep Nested (indepth : 4) Json Object?
How to achieve ProjectEmployee, Employee, EmployeeSpecialization, AvailableWorkField through Project single API? All are connected by ManyToMany RelationShip. Here I am showing a short model code: class Project(models.Model): title = models.CharField(max_length=300, primary_key=True, unique=True) class Employee(models.Model): name = models.CharField(max_length=300, blank=True, null=True) class AvailableWorkField(models.Model): available_field_position = models.CharField(max_length=100) class EmployeeSpecialization(models.Model): employee = models.ForeignKey(Employee, related_name='employee_specialization_employee', on_delete=models.CASCADE) preferred_field = models.ForeignKey(AvailableWorkField, related_name='employee_specialization_available_work_field', on_delete=models.CASCADE) class ProjectEmployee(models.Model): project = models.ForeignKey(Project, related_name='project_employee_project', on_delete=models.CASCADE) employee = models.ForeignKey(Employee, related_name='project_employee_employee', on_delete=models.CASCADE) project_position = models.CharField(max_length=100) Here is my serializer: class AvailableWorkFieldSerializers(serializers.ModelSerializer): class Meta: model = AvailableWorkField fields = '__all__' class EmployeeSpecializationSerializers(serializers.ModelSerializer): employee_specialization_available_work_field = AvailableWorkFieldSerializers(many=True, read_only=True) class Meta: model = EmployeeSpecialization fields = '__all__' class EmployeeSerializers(serializers.ModelSerializer): employee_specialization_employee = EmployeeSpecializationSerializers(many=True, read_only=True) class Meta: model = Employee fields = '__all__' class ProjectEmployeeSerializers(serializers.ModelSerializer): project_employee_employee = EmployeeSerializers(many=True, read_only=True) class Meta: model = ProjectEmployee fields = '__all__' class ProjectSerializers(serializers.ModelSerializer): project_employee_project = ProjectEmployeeSerializers(many=True, read_only=True) class Meta: model = Project fields = '__all__' I want a complex nested JSON object like this for project rest API: [ { "title": "RevSurvey", "project_employee_project": [ { "id": 2, "project_position": "Django", "project": "RevSurvey", "employee": { "id": 1, "name": "david", "preferred_field": [ { "id": 1, "available_field_position": "Laravel" } ] } } ] } ] But I was expecting to get: [ { "title": "RevSurvey", "project_employee_project": [ { … -
How to load jquery provided by django into your template
How do I load jquery provided Django admin instead of downloading it again. {% load admin/static %} <script src="{% static 'js/jquery.js' %}"></script> instead of: <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> -
Received not compatible Decimal
I am trying to add data to the Loan model using django-graphene mutations but I am receiving this error as mentioned below. My code is as follows. models.py class Loan(models.Model): principle = models.DecimalField(max_digits=8, decimal_places=2) tenure = models.PositiveSmallIntegerField(help_text="Duration in months ") mutation.py # making a DjangoObjectType of Loan Model class LoanType(DjangoObjectType): class Meta: model = loan_model # create new Loan class LoanMutation(graphene.Mutation): class Arguments: # The input arguments for this mutation principle = graphene.DecimalField() tenure = graphene.Int() # loan endpoint loan = graphene.Field(LoanType) @classmethod def mutate(cls, root, info, principle, tenure): loan = loan_model(principle=principle, tenure=tenure) loan.save() # Notice we return an instance of this mutation return LoanMutation(loan=loan) class Mutation(graphene.ObjectType): new_loan = LoanMutation.Field() schema = graphene.Schema(query=Query, mutation=Mutation) GraphiQL mutation i tried to execute mutation CreateLoan { newLoan(principle: 300.50, tenure: 12) { loan { id principle tenure } } } response i received { "errors": [ { "message": "Received not compatible Decimal \"300.5\"" } ], "data": { "newLoan": { "loan": null } } } I have tried to use principle = models.FloatField() and principle = graphene.FloatField() i do not receive this error. -
FileNotFoundError at /admin/ [Errno 2] No such file or directory: '//m2n_project/messages.json'
I am facing an issue, like with my local server, it is able to login with admin credentials. But on a live server, it is showing the error "FileNotFoundError". I don't know what is wrong with the code. This is the view of admin login- if user is not None: if user.is_superuser or user.is_staff: user.login(request,user) request.session['user_id'] = id messages.success(request, "Welcome " + str(request.user.username) + "! to the administration.") return redirect('homepage') else: # print("status else") messages.error(request, json.loads(open(os.path.join(os.getcwd() + '/m2n_project/messages.json')).read())[ … "login_denied"]) return render(request, 'admin_app/admin_login.html') else: messages.error(request, json.loads(open(os.path.join(os.getcwd() + '/m2n_project/messages.json')).read())[ -
Intermediate model form django
I'm having trouble creating a form. My models: class Subject(models.Model): name = models.CharField(max_length=30) duration = models.IntegerField() price = models.IntegerField() class Student(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) subject = models.ManyToManyField(Subject,through="StudentSubject") class StudentSubject(models.Model) student = models.ForeignKey(Student,on_delete=models.CASCADE) subject = models.ForeignKey(Subject,on_delete=models.CASCADE) discount = models.IntegerField() I'm using the intermediate model StudentSubject to add the discount of each subject however I can't think of how to create the form and how to render it in a template. The form I want to create, is having each subject listed(and a checkbox to select them) and a discount field next to each subject as follows: [] Math DiscountField1 [X] Physics DiscountField2 [X] CompSci DiscountField3 -
Adding custom HTML elements around UserCreationForm's default elements
I am using widget_tweaks to add custom classes to input forms. But how do I add entire HTML elements like this to beautify the username ? <label for="basic-url" class="form-label">Your vanity URL</label> <div class="input-group mb-3"> <span class="input-group-text" id="basic-addon3">https://example.com/users/</span> <input type="text" class="form-control" id="basic-url" /> </div> I am using a basic signup form but want to include custom HTML around it. {% load widget_tweaks %} {% for field in form %} <div class="form-group mt-3 {% if field.errors %}alert alert-danger{% endif %}"> {{ field.errors }} {{ field.label_tag }} {% render_field field class="form-control" %} {% if field.help_text %}<small class="text-muted">{{ field.help_text|safe }}</small>{% endif %} </div> {% endfor %} -
Relay-style pagination with Django
I'm working on a Django 3.x app and I need to expose a REST API that will then be consumed by a GraphQL server in order to provide a GraphQL endpoint to a client. The cursor based pagination provided by Django out of the box only provides a next and previous cursors for each request, but Relay requires one opaque cursor for each returned edge/item. How can I ask Django to generate a cursor for each item? -
Prevent django empty lines in docker console
Hi I'm new to Docker and Django and I wanted to clean up the logging output in the console but I found empty lines with timestamps that are not related to basicConfig of logging(python language) in my app. I don't know if they are generated automatically by Django or docker container. [logging in output console][1] I want to remove these empty lines which only contain a timestamp and no info after [-] [1]: https://i.stack.imgur.com/evlKs.png -
Django get rid of duplicated queries in nested models
I have models as shown below, class Manufacturer(models.Model): name = models.CharField(max_length=100) class Car(models.Model): manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) name = models.CharField(max_length=300) @property def latest_variant(self): return self.carvariant_set.last() class CarVariant(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) name = models.CharField(max_length=300) and I am making a query to get the latest variant of all cars, I am getting much duplicated queries. I couldn't eliminate it work with prefetch_related Car.objects.all().prefetch_related('carvariant_set') How can I eliminate the duplicated queries? -
How can I use process_request in Django for checking if the request contains the header I require?
I am have a Django app with a decent amount of views. What I wish to do is that whenever a request is sent to the app, it gets checked for headers, and if the header SECRET has the value $ecret$tring, only then the request is matched with my urlpatterns and sent to the view. Else, it should return the following- {'MESSAGE': 'UNAUTHORIZED'} with a 401 status. Here is the middleware class that I have written- from django.http import JsonResponse from django.utils.deprecation import MiddlewareMixin class AuthCheck(MiddlewareMixin): def process_request(self, request): if 'SECRET' in request.headers: if request.headers['SECRET'] != '$ecret$tring': return JsonResponse({'MESSAGE': 'UNAUTHORIZED'}, status=401) else: return JsonResponse({'MESSAGE': 'UNAUTHORIZED'}, status=401) However, when I send a request without the header, it still gets sent to the view. What's going wrong? -
django- host a website without python app on cpanel?
I am going to host a website build on the Django framework. There are tutorials on youtube on how to host but they all are using the python app already on Cpanel. But my hosting provider Hostgator does not give the python app in Cpanel. is there any other way to host the Django website without the python app on Cpanel? -
Difference between content_type=application/json and format=json in DRF APIClient
I'm using rest_framework.test.APIClient for unit tests in my project. I used a dictionary as a request data, so None values there are not parsed properly as it doesn't understand the format. I added format="json" as a parameter to client.post() and it worked fine. However adding content_type="application/json" solved the problem as well and I want to know what's the difference. -
How do I implement JavaScript and Django?
I've been learning Django as a backend framework, and now I am starting to have to deal with API and JavaScript. I've been trying to understand how a normal application would be built, but this just confuses me so much. Is Django just used to build the database and API at the end of the day so that you can communicate with it from the front-end? Anything that would clarify this workflow would be appreciated. As of now, it seems like what I learned about injecting data in templates with Django etc, is supposed to be replaced with JavaScript