Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my Django form is showing an error when i tried creating an user object
In my Sign up form I tried to create an object called myuser from Django.contrib.auth.models this is the image It's showing an error from django.contrib.auth.models import User def signup(request): if request.method == "POST": fname = request.POST['fname'] lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] myuser = User.objects.create_user( fname , email , pass1) myuser.first_name = fname myuser.last_name = lname context = {} return render(request, '/Users/tanajkhanuja/Desktop/bee/main/templates/main/Signup.html', context) -
django 4.0.4 ./manage working, however when using the management command 'runserver', an error is returned
A peculiar thing is happening with my Django Manage script. No changes have been made since yesterday, however 'runserver' stopped working, and returns: ValueError: illegal environment variable name If I run other management functions that script works fine, so I get no errors, unless I use the 'runserver' If I run ./manage on it's own, I get the management command list: Type 'manage.py help ' for help on a specific subcommand. Available subcommands: [auth] changepassword createsuperuser [contenttypes] remove_stale_contenttypes [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver [sessions] clearsessions [staticfiles] collectstatic findstatic runserver -
authenticate django using oAuth2 for integration with elasticsearch
I have worked on a django app with elasticsearch as backend. During development I have used a local elasticsearch instance running in docker and connected to it using username and password as below. Now I need to change authentication to Oauth2 using azure AD. Cant find any good documentation on how to do it. from django settings.py: user_name = "elastic" host_ip = "127.0.0.1" host_ports = 9200 elk_url = f'https://{user_name}:{ESPASSWORD}@{host_ip}:{host_ports}' ELASTICSEARCH_DSL = { 'default': { 'hosts': elk_url, 'ca_certs': False, 'verify_certs': False, } } Help is appreciated -
How to send pictures from React-Native app to the Django server using Expo ImagePicker?
I study React Native and Django and create an iOS app, which recognize text in pictures. I need to upload images to the Django Server but I have error from server: [26/Apr/2022 12:10:51] "POST /api/textocr/ HTTP/1.1" 400 519 error {'title': [ErrorDetail(string='Обязательное поле.', code='required')], 'image': [ErrorDetail(string='Расширение файлов “” не поддерживается. Разрешенные расширения: bmp, dib, gif , tif, tiff, jfif, jpe, jpg, jpeg, pbm, pgm, ppm, pnm, png, apng, blp, bufr, cur, pcx, dcx, dds, ps, eps, fit, fits, fli, flc, ftc, ftu, gbr, grib, h5, hdf, jp2, j2k, jpc, jpf, jpx, j2 c, icns, ico, im, iim, mpg, mpeg, mpo, msp, palm, pcd, pdf, pxr, psd, bw, rgb, rgba, sgi, ras, tga, icb, vda, vst, webp, wmf, emf, xbm, xpm.', code='invalid_extension')]} Bad Request: /api/textocr/ What I did: Django Server: models.py from django.db import models # Create your models here. class Ocr(models.Model): title = models.CharField(max_length=100, blank=False, null=False) image = models.ImageField(upload_to='images/', null=True, blank=True) def __str__(self): return self.title serializers.py: from rest_framework import serializers from .models import Ocr class PostSerializer(serializers.ModelSerializer): class Meta: model = Ocr fields = '__all__' views.py: from django.shortcuts import render from .serializers import PostSerializer from .models import Ocr from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from … -
How can I do a query with multiple distinct Q objects?
I have a preference model in my Django app, and I am trying to write a query that filters to items that have two preferences set in a certain way. The preferences are stored many-to-many, so each object has multiple preferences linked to it. For preference 1, I can check with: Team.objects.filter(teampreferencemodel__name='remind_morning', teampreferencemodel__raw_value='a') For preference 2, I can check with: Team.objects.filter(teampreferencemodel__name='remind_days_before', teampreferencemodel__raw_value='5') My goal is to get the intersection of those two queries. I thought I could do something like: Team.objects.filter(Q(teampreferencemodel__name='remind_morning', teampreferencemodel__raw_value='a')), Q(teampreferencemodel__name='remind_days_before', teampreferencemodel__raw_value='5')) but it appears (I think) that Django is trying to satisfy both Qs with the same teampreferencemodel, rather than finding one that has one of each. Is there any way to optimize this query, via Q or something else, or do I need to just resort to: Team.objects.filter(teampreferencemodel__name='remind_morning', teampreferencemodel__raw_value='a').intersection( Team.objects.filter(teampreferencemodel__name='remind_days_before', teampreferencemodel__raw_value='5')) or slightly better: Team.objects.filter(teampreferencemodel__name='remind_morning', teampreferencemodel__raw_value='a').filter( teampreferencemodel__name='remind_days_before', teampreferencemodel__raw_value='5')) It just feels like there should be a better way... -
Sharing models between two Dockerizable Django projects and ForeignKey to a model
I want to create three Django projects. The projects sharing models between them on the same database like modular monolith structure. How Can I access a model from the other project for ForeignKey to a model. I've been doing research and application on the subject, but I still haven't found how to set up a structure. -
Submitting SUMMARY Data from Django to React using DRF
I'm starting to test some API data between django and React using Rest API. I'm able to submit this data between Djnago model and React front end. [ { "id": 1, "gender": "Male", "age": 40, "updated": "2022-04-25T18:55:23.304456Z", "created": "2022-04-25T14:07:48.282139Z" }, { "id": 2, "gender": "Male", "age": 33, "updated": "2022-04-25T18:55:23.304456Z", "created": "2022-04-25T14:07:48.282139Z" }, { "id": 3, "gender": "Female", "age": 22, "updated": "2022-04-25T18:55:23.304456Z", "created": "2022-04-25T14:07:48.282139Z" }, { "id": 4, "gender": "Female", "age": 33, "updated": "2022-04-25T18:55:23.304456Z", "created": "2022-04-25T14:07:48.282139Z" }, ] My goal is not to submit this raw data, but instead to submit summary data (data analysis) that calculates the average age for males and females, so I should be getting something like this: [ { "gender": "Male", "average_age": 36.5, }, { "gender": "Male", "average_age": 27.5, } ] Where should I be making these cross tabulations? on the backend or front end? if on the backend should I be creating new models for the summary data? I tried looking online for advice on this but I was unlucky! -
Reduce excel sheet generation time in Django
I have a huge code written in python(Django framework) which generates an excel sheet and it takes more than 5-10 mins to do so. The code generates multiple tabs in the sheet and it does it one after another (sequential function calls).The first 5-6 tabs take less time and the remaining tabs(network tabs) use the same logic in a single for loop to generate independent network tabs. Is there any way I can generate these network tabs simultaneously to reduce the excel sheet generation time? -
Error validating in instagram api login with django
hi i have a problem in instagram api login im doing all that right as doc said but i have this error : Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request its redirect once but when i want to make a post request it didnt work : @api_view(["GET"]) def insta_call_back(request): code = request.query_params.get("code") user_id = request.query_params.get("state") data = { "client_id": settings.INSTAGRAM.get("client_id"), "client_secret": settings.INSTAGRAM.get("client_secret"), "grant_type": "authorization_code", "redirect_uri": f"{settings.ONLINE_URL}api/insta_call_back", "code": code } resp = requests.post("https://api.instagram.com/oauth/access_token/", data=data) return Response({ "resp": resp.text }) i write this code in python django -
Facing AttributeError: 'bytes' object has no attribute 'read'
cursor = connection.cursor() Fetchstepseven = cursor.execute( "SELECT t.profile_photo, t.id_option, t.id_proof, t.id_proof_number, t.signature FROM trainee t WHERE t.user_id=%s", [payload["id"]], ) records = cursor.fetchall() payload = [] content = {} for result in records: # profile_photo= base64.b64encode(urlopen("https://jrf-recruitment.iirs.gov.in/encodeimage/"+result[0]).read()) gcontext = ssl.SSLContext() profile_photo = JSONParser().parse( base64.b64encode( urlopen( " https://jrf-recruitment.iirs.gov.in/encodeimage/" + result[0], context=gcontext ).read() ) ) jsonResponse = json.loads(profile_photo.decode("utf-8")) content = { "profile_photo": jsonResponse, "id_option": result[1], "id_proof": "encodeimage/" + result[2], "id_proof_number": result[3], "signature": "encodeimage/" + result[4], } # https://jrf-recruitment.iirs.gov.in/encodeimage/"+result[0] payload.append(content) content = {} # Get step seven data code end return JsonResponse( { "success": True, "message": "Step Six successfully done.", "token": token, "data": jrf_serializer.data, "step7": payload, } ) -
I need to execute specific functions in django backend when I click specific buttons in react frontend
Register.js import React, { useState } from 'react'; import './Register.css'; import axios from 'axios' import {RegionDropdown} from 'react-country-region-selector'; function Register() { const [fname,SetFname]=useState(''); const [Lname,SetLname]=useState(''); const [Country,SetCountry]=useState(''); const [des,SetDes]=useState(''); const [file,setFile] = useState(null) const imagehandle =(e)=>{ const datas = e.currentTarget.files[0] setFile(datas) } const handleSubmit= e =>{ e.preventDefault() console.log(file) let form_data = new FormData(); form_data.append('firstname',fname); form_data.append('lastname',Lname); form_data.append('image', file); form_data.append('country', Country); form_data.append('description', des); axios.post('register/', form_data, { headers: { 'content-type': 'multipart/form-data' } }) .then((res)=>{ console.log(res.data) }) .catch((err)=>console.log(err)) } return ( <div class="container"> <h1>Register New case</h1> <form onSubmit={handleSubmit} autoComplete='off'> <div class="row"> <div class="col-25"> <label for="fname">First Name</label> </div> <div class="col-75"> <input type="text" value={fname} onChange={e=> SetFname(e.currentTarget.value)} id="fname" name="firstname" placeholder="Your name.." /> </div> </div> <div class="row"> <div class="col-25"> <label for="lname">Last Name</label> </div> <div class="col-75"> <input type="text" value={Lname} onChange={e=> SetLname(e.currentTarget.value)} id="lname" name="lastname" placeholder="Your last name.."/> </div> </div> <div class="row"> <div class="col-25"> <label for="country">Last Seen</label> </div> <div class="col-75"> <RegionDropdown country="India" value={Country} name="place" onChange={e=> SetCountry(e)}/> </div> </div> <div class="row"> <div class="col-25"> <label for="description">Description</label> </div> <div class="col-75"> <textarea id="des" value={des} onChange={e=> SetDes(e.currentTarget.value)} name="description" placeholder="Write something.."></textarea> </div> <div class="col-25"> <label for="Image">ImageUpload</label> </div> <div class="col-75"> <input type="file" name='img' src={file} onChange={imagehandle} multiple accept="image/*"/> </div> </div> <div class="row"> <input type="submit" value="Submit"/> </div> </form> </div> ); } export default Register; views.py class PostView(APIView): parser_classes = (MultiPartParser, … -
Django form with third party API
I am new in django and web developing. I have something in trouble of django working with third party API and would like some helps. What I want to do is to tell django to send an API simultaneously to store the information at the time the form is submit. (meanwhile save data in both django and other place). Is it possible to do so? Also in UpdateView? Below is my current code, it works well with django about creating data, however I am not sure where to place third party API in them. models.py class DocumentingJob(models.Model): class TaskType(models.TextChoices): MACHINE_LEARNING = ("machine_learning_task", "ml_task") RULE = ("rule_task", "r_task") name = models.CharField(max_length=100, verbose_name="document_task", default="Job") description = models.TextField(verbose_name="description of task") is_multi_label = models.BooleanField(default=False) job_type = models.CharField(max_length=100, choices=TaskType.choices, default=TaskType.RULE) create_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now=True) task_id = models.UUIDField(default=uuid.uuid1, unique=True, editable=False) create_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def __str__(self): return f"{self.name} ({self.get_job_type_display()})" def get_absolute_url(self): return reverse('documenting_jobs:job-detail', kwargs={'pk': self.pk}) views.py class IndexAndCreateView(LoginRequiredMixin, generic.CreateView): model = DocumentingJob template_name = "documenting_jobs/index.html" form_class = DocumentingJobForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['documenting_jobs'] = self.model.objects.order_by('-create_time') return context def form_valid(self, form): form.instance.create_time = self.request.user return super().form_valid(form) forms.py class DocumentingJobForm(forms.ModelForm): class Meta: model = DocumentingJob fields = '__all__' exclude = ['create_by', 'is_multi_label'] widgets … -
How to invalidate django rest framework cache on cloudwatch when doing PUT or POST call
I have a Django rest framework application running behind AWS Cloudfront. I then have an api endpoint /api/user/ which has a GET, POST, and PUT enabled. When I do a POST call to the api endpoint, the GET call shows cache results for about a minute. How do I remove the cache when a POST or PUT is ran? -
store users data django python
Could you please clarify, where users data store when user register in django. F.ex according to this link in github: enter link description here When I login to admin page I can see all users, but can not understand where data stores. -
Responsive CSS not working in Django project
I am using Django for my project. I have given CSS links in my html files like , <link rel="stylesheet" type="text/css" href="{% static 'css/sideCart.css' %}"> My normal CSS are being rendered , but my responsive CSS are not being rendered in , " Device Toolbar " mode. It renders in just inspecting site normally. I have given responsive CSS code as follows: @media (max-width : 920px){ .sideBar{ display : none ; } } -
How to update an item in django without creating a new item?
I'm trying to update an item(book) present in the database, Even though I've added instance so that a new item is not created but instead the item is only updated, but unfortunately it's not working as it is supposed to, Instead of updating the item, a new item is being created, am I missing something in here? models.py class Book(models.Model): book_name = models.CharField(max_length= 100) author_name = models.CharField(max_length=100) publisher = models.CharField(max_length=100) published_on = models.DateTimeField(blank=True, null=True) Language = models.CharField(max_length=100) image = models.ImageField(blank = True, upload_to='images/') created = models.DateTimeField(auto_now_add = True) def __str__(self): return self.book_name @property def imageURL(self): try: url = self.image.url except: url = " " return url views.py def book_register(request): if request.method == 'POST': form = BookForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/') else : return render(request, 'crud_operation/book_form.html', {'form': form}) else: form = BookForm() context = {'form':form} return render(request,'crud_operation/book_form.html',context) def book_update(request,pk): book = Book.objects.get(id=pk) form = BookForm(instance = book) if request.method == 'POST': form = BookForm(request.POST, request.FILES, instance=book) if form.is_valid(): form.update() return redirect('/') context = {'form':form} return render(request, 'crud_operation/book_form.html',context) urls.py urlpatterns = [ path('create-book/',views.book_register, name = 'books'), path('update-book/<int:pk>/',views.book_update, name = 'book_update'), ] forms.py class BookForm(ModelForm): class Meta: model = Book fields = '__all__' widgets = { 'published_on': DateInput(attrs={'type': 'date'}) } -
How to handle 404 request in Django?
I am trying to handle 404 requests when the page is not found. I am getting an error as Server Error (500). Here is the code : In settings.py DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1'] In myapp.views: def handle_not_found(request, exception): return render(request, "404.html") In project urls.py : handler404 = "myapp.views.handle_not_found" -
Throwing error when tried to sent javascript object to views in Django
I need to send data that I have as a Javascript object in a javascript file to views in Django. Tried as below but throws error as : Not Found: /postendpoint/$ **main.js** #data from the HTML form stored as JS object formdata={ surname:sur_name, firstname:first_name, login:login_id, assignee:assignee, phonenumber:phone_no, groupname:group, email:email, segment:acsp }; function validation(){ var valid=checkValidity(); console.log(valid); if(valid){ **#sending formdata** $.ajax({ url:'/postendpoint/$', type: "POST", data: formdata, success:function(response){ console.log("formdata sent") }, error:function (xhr, textStatus, thrownError){ console.log("formdata not sent") } }); displayTable(); } } **views.py** def YourViewsHere(request): if request.method == 'POST': formdata=request.POST.get('data') print(formdata) **urls.py** from django import URLs from django.urls import path,re_path from smgusersearch import views urlpatterns = [ path("", views.index,name="index"), path("postendpoint/", views.YourViewsHere,name="YourViewsHere"), ] Need to send the form data in JS file to views -
Google-distancematrix-api not calculating distance for my country
I'm using google-distance_matrix in my web app to calculate distance and prices. The code seems to be working fine if I'm using counties other than my own country (Zimbabwe ). For example from Brooklyn Bridge to Madison Square Gardens the API is able to get the coordinates and provide results first attachment but for any locations within Zimbabwe, the API is unable to produce results second attachment. What might be the problem? first attachment second attachment -
Checksums Sha256
Would love it if some one can I guess have technical knowledge of Checksums sha256 an would like to talk about VMWARE IoT Smartcontracts an about the unruly Oracle problem -
How to solve django and angular cors errors
I'm developing application and got this error: Access to XMLHttpRequest at 'https://subdomain.domain.org/api/parks/?page_size=6&page_number=1' from origin ''https://subdomain.domain.org' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Django Config setting.py: INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] ALLOWED_HOSTS = ['app_name-backend.herokuapp.com'] CORS_ALLOWED_ORIGINS = [ 'https://app_name-frontend.herokuapp.com', 'https://subdomain.domain.org', ] CORS_ALLOW_ALL_ORIGINS = False Angular Requests service.ts: getParks(filters: any=null, parameters:any=null): Observable<any> { ... var httpHeaders = new HttpHeaders(); httpHeaders.set('Content-Type', 'application/json'); httpHeaders.set('Access-Control-Allow-Origin', '*'); var requestUrl = this.baseServiceUrl + this.serviceUrl; return this.httpClient.get<any>(requestUrl, { params: httpParams, headers: this.httpHeaders }) .pipe( ... ), catchError(this.handleError<Park[]>('Park getParks', [])) ); } The front and back are hosted on heroku Any idea how to fix it ? Thanks in advance. -
Cann't install django with error 'Non-zero exit code (2)'
When i create new django project in pycharm i have error enter image description here Help me please -
how do I update cart with AJAX
I'm trying to use ajax to update the {{cartItems}} on nav when someone hits the add-to-cart button on shop.html without reloading the page, so far this is what I was able to work on. So how do I make this work? also if u have any other suggestion please lemme knw! would really appreciate your help, thx!! rest of the important code is here: https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352 urls.py path('ajax_update/', views.ajax_update, name="ajax_update"), nav.html <span class="bag-icon"> {% url 'store:cart' as url %} <a id="icons-account" href="{% url 'store:cart' %}"><i class="fas fa-shopping-bag {% if request.path == url %}change{% endif %}"></i><a id="lil-icon-two">{{cartItems}}</a></a> </span> cart.js var updateBtns = document.getElementsByClassName('update-cart') for(var i=0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) console.log('USER:', user) if(user === 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log('User is not authenticated') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Item should be deleted') delete cart[productId]; } } console.log('CART:', cart) document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" /*replacing location.reload() with ajax*/ function updating_cart_ajax(){ $.ajax({ url: 'ajax_update/', success: function (result) { $('.shop').reload(result) }, … -
Is it okay to use WordPress HTML for Django?
I have a client asking me to build a static HTML website. He wants to integrate it with Django for backend. The first initial design was not very good and he wants me to build another one with specific feature. I was looking to build the site using WordPress and then convert the WordPress site into a static HTML website using a plugin called Simply Static. My only concern is will it be okay if I use such method to build a static site? I've never use Django, so I don't really know whether it would a problem to integrate their backend or not. The reason why I'm using WordPress is because I think it would be a lot faster for me to do the job. I already generate one Wordpress page into a static HTML and it runs okay without any problem. But, as I said, I don't know if it's gonna be a problem for backend team to integrate Django. Thank you -
react.js & django, useParams unable to navigate to the page
I am current building a react app with django, I am trying to navigate from the HomePage to the DataPage with corrsponding id. However, it return Page not found error. I am using react-router-dom v6. Using the URLconf defined in robot.urls, Django tried these URL patterns, in this order: admin/ api/ api-auth/ homepage homepage/data The current path, homepage/data/54, didn’t match any of these. Here is my App.js export default class App extends Component { constructor(props) { super(props); } renderHomePage() { return ( <HomePage /> ); } render() { return ( <BrowserRouter> <Routes> <Route exact path='homepage/' element={this.renderHomePage()} /> <Route path='homepage/data/:id' element={<DataPage />} /> </Routes> </BrowserRouter> ) } } const appDiv = document.getElementById("app"); render(<App />, appDiv); And I want to navigate to the DataPage below: const EmtpyGrid = theme => ({ Grid: { ... } }); function DataPage(props) { const { classes } = props; const { id } = useParams(); return ( <div> ... some material ui components ... <div/> ) }; DataPage.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(EmtpyGrid)(DataPage); I was thinking whether I need configure my url.py in frontend as well, and I need to define a designated value for {id} returned from the materialui component first. Perhaps …