Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I try to install spacy in django
when i try to install spaCy in django in cmd it give me this error enter image description here enter image description here enter image description here -
Writing correct views to display restaurant food menus
I am creating a webapp for a new restaurant and want to display the different food menus for people to view and owner to be able to update and delete items from the menu when appropriate. I have a model for the menus and the items on the menu """ A Menu represents a collection of categories of food items. For example, a restaurant may have a Lunch menu, and a Dinner menu. """ class Menu(models.Model): name = models.CharField(max_length=246, unique=True,) slug = models.SlugField(max_length=24, unique=True, help_text='The slug is the URL friendly version of the menu name, so that this can be accessed at a URL like mysite.com/menus/dinner/.') additional_text = models.CharField(max_length=128, null=True, blank=True, help_text='Any additional text that the menu might need, i.e. Served between 11:00am and 4:00pm.') order = models.PositiveSmallIntegerField(default=0, help_text='The order of the menu determines where this menu appears alongside other menus.') class Meta: verbose_name = 'menu name' def __str__(self): return self.name """ A Menu Category represents a grouping of items within a specific Menu. An example of a Menu Category would be Appetizers, or Pasta. """ class MenuCategory(models.Model): menu = models.ForeignKey(Menu, null=True, help_text='The menus that this category belongs to, i.e. \'Lunch\'.', on_delete=models.SET_NULL) name = models.CharField(max_length=32, verbose_name='menu category name') additional_text = … -
django-filters: Preclean filterset field
I have django model and django-filters FilterSet: class MyModel(models.Model): name = models.CharField() class MyFilterSet(FilterSet): name = filters.CharFilter(lookup_expr='icontains', min_length=3) class Meta: model = MyModel fields = 'name', In name can be passed bad symbols such as [-()\"#/@;:<>{}`+=~|.!?,]. I need to remove them from name before validators are being ran. How can preclean name field in filterset class? -
Deployed Django project does not load static files
I have just deployed (first time ever) a Django project to a web server. Everything (including postgres) works flawlessly, except that static images won't load. Here is the relevant part of the settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") #STATICFILES_DIRS = [ # os.path.join(BASE_DIR, "static"), #] # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' LOGIN_REDIRECT_URL = 'home' LOGIN_URL = 'login' LOGOUT_URL = 'logout' AUTH_USER_MODEL = 'account.CustomUser' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') The error message I get is the following in the console: "GET /static/images/logo.png HTTP/1.1" 404 1808 However, when checking the file path in the console I have the following: root@melius:/django/melius/static/images# In this folder the files are present. Where is my mistake? -
How do I check if there are items in the database Django
Disclaimer, I've just started with Django a couple of days ago so I'm still quite new to it, patiance please. Alright so I have two different models in my models file. One of them is the Order with certain order attributes and the other one is Counter, an assistant model so to say. The idea is that I need to check the database if an order exists, if it doesn't, i need to give Counter the value of 1 as this will be the first order, then the value needs to be assigned to the code of the Order model. On the other hand, if an order does exist, then increment a counter by 1. Here's my approach and it's getting me this error as the value of code: <django.db.models.query_utils.DeferredAttribute object at 0x04996280> Here is the simplified version of the models. Also quick question, am I right to do this part on the models file? Should I do it on the serializer or views or it doesn't really change anything. Thanks in advance. class Counter(models.Model): def count(self): self.value = 0 for order in Order.objects.all(): self.value += 1 return self.value @property def names(self): return "P+ %s + %s" % (self.value, Order.code_year) … -
Django Remote User Authentication
I am using Django to build a data analysis webpage for our corporate. Currently, I am using the default Django server as the domain of my webpage. However, I am new to Django. In the webpage I want to do two things: In the navigation bar on the website, I want the username shown. Anyone using the corporate network or in the Active Directory of the corporate is authenticated to use the webpage, and once they visit it, their username is shown at the top of the page. I want to embed a Spotfire file in the webpage. However, I don't want the embedded Spotfire to ask for login, I want it directly shown to the user. I hope you can help me. -
How to add an image editor (cropper plugin) to my python project?
trying tot follow: https://medium.com/geekculture/implement-cropping-feature-on-your-website-in-under-10-min-cropper-js-46b90d860748 trying to implement a cropping feature to my beginner app, user is asked to upload an image and will be given the option to crop the image, having a hard time understanding how forms work with django, Specially with crispy forms. app Idea: soccer cards collector aapp, where user adds teams and each team page will have list of players with pics,etc... difference from medium article code: I am implementing a one to many relationship with the teams model where each team can have more than one pic uploaded URLS.py path('', views.home, name="home"), path('about/', views.about, name="about"), path('teams/', views.teams_index, name="teams_index"), path('teams/<int:team_id>/add_fixture/', views.add_fixture, name='add_fixture' ), path('teams/create', views.TeamCreate.as_view(), name="teams_create"), path('teams/<int:team_id>', views.teams_detail, name="teams_detail"), path('teams/<int:pk>/update', views.TeamUpdate.as_view(), name="teams_update"), path('teams/<int:pk>/delete', views.TeamDelete.as_view(), name="teams_delete"), path('teams/<int:team_id>/assoc_card/<int:card_id>/', views.assoc_card, name="assoc_card"), path('cards/', views.cards_index, name="index"), path('cards/<int:card_id>/', views.cards_detail, name="detail"), path('cards/create/', views.CardCreate.as_view(), name="cats_create"), path('cards/<int:pk>/update/', views.CardUpdate.as_view(), name="cards_update"), path('cards/<int:pk>/delete/', views.CardDelete.as_view(), name="cards_delete"), path('teams/<int:team_id>/crop', views.crop, name="crop"), views.py def crop(request, team_id): team = Team.objects.get(id=team_id) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) # Gets the uploaded data and maps it to the ProfileForm object if form.is_valid(): # Checks if the uploaded data is valid or not new_crop = form.save(commit=False) new_crop.team_id = team_id new_crop.save() form.save() # Saves the uploaded data into our Database model return redirect('details') # Makes … -
Django NoReverseMatch Error. Please guys, kindly assist with this django error on keyword arguments '{'slug': ''}' not found
please I need help with this Django error. I have searched and done things I learnt, yet, I couldn't decipher the problem Model.py from django.db import models from django.urls import reverse # Create your models here. class Notes(models.Model): note_topic = models.CharField(max_length=200, blank=False) note_body = models.TextField(null=True, blank=True) slug = models.SlugField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.note_topic def get_absolute_url(self): return reverse('notebooks:note-detail', kwargs={'slug' : self.slug}) ``` view.py from django.utils import timezone from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Notes class NotesView(ListView): model = Notes template_name = 'notes.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['notes'] = Notes.objects.all() return context class NotesDetailView(DetailView): model = Notes template_name = 'note-detail.html' context_object_name = 'note' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['time'] = timezone.now() return context ``` urls.py for the app from django.contrib import admin from django.urls import path, include urlpatterns = [ path('notes/', include('notebooks.urls', namespace='notes')), path('admin/', admin.site.urls), ] note.html the notebook app home page {% extends 'base.html' %} {% block title %} List of Notebooks {% endblock title %} {% block content %} <div class="col-7 mt-4"> <div class="list-group"> <button type="button" class="list-group-item list-group-item-action active" aria- current="true"> List Of Notebooks </button> {% for item in object_list … -
How to download zip file coming as django response through ajax post request?
so ,after my ajax post request my Django view return a zip file as response.I want to download that zip file as soon as response came . But i don't know what to do . I go through many answer but not worked for me. Right now zip file downloading but when i open it's corrupted. My django response zip file type is <class '_io.BufferedReader'>. Ajax Code of Post request function upload(url) { let pdf_file = $('#file_input').get(0).files[0]; let form_data = new FormData(); form_data.append("file", pdf_file); jQuery.ajax({ url: url, type: "POST", data: form_data, enctype: 'multipart/form-data', contentType: false, processData: false, success: function (response) { var binaryData = []; binaryData.push(response); var link = document.createElement('a'); link.href = window.URL.createObjectURL(new Blob(binaryData, {type: "application/zip"})) link.download = 'sample.zip'; document.body.appendChild(link); link.click(); }, error: function (response) { loading_btn.classList.add("d-none"); upload_btn.classList.remove("d-none"); } }); } ajax Response ** Django View ** @csrf_exempt def upload_file(request): if request.is_ajax() and request.method == 'POST': zip_file = open('/home/deftbox/PycharmProjects/pdf_data_Extractor/test.zip', 'rb') return FileResponse(zip_file) -
How can i solve this error that i enccountered while deploying django on iis
I am getting the error below. Could someone tell me why. Running python 3.8 Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\Users\biu\AppData\Local\Programs\Python\Python38\Lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\Users\biu\AppData\Local\Programs\Python\Python38\Lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\Users\biu\AppData\Local\Programs\Python\Python38\Lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler handler = import(module_name, fromlist=[name_list[0][0]]) File ".\analytics_suite\wsgi.py", line 16, in application = get_wsgi_application() File "C:\Users\biu\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\Users\biu\AppData\Local\Programs\Python\Python38\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\biu\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 81, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant StdOut: StdErr: -
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.