Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serch using queryset on Django
I have Topic model and Post model. I want to search using queryset. When q has string it work well, however when q = '' (which means All ) it doesn't show all post. How can I fix this? All code here models.py class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail',kwargs={'pk':self.pk}) views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context["topics"] = Topic.objects.all() return context def get_queryset(self): if self.request.GET.get('q') != None: q = self.request.GET.get('q') else: q = '' # q = self.request.GET.get('q') if self.request.GET.get('q') != None else '' return Post.objects.filter(topic__name__icontains=q).order_by('-date_posted') -
What is the most successful short-code in Django for creating a sign-in + register + email verification?
What is the best shortcode in Django for creating a sign-in + register + email verification? -
django context not rendering in html
Hi I have 'easy' problem with context in django ;/ I try to send context to render and show it in html page but it dosen't showing. urls path('', views.home, name='home'), path('viki/main', views.vikimain, name='vikimain'), views @login_required(login_url='login') def home(request): return render(request, 'project/home.html') @login_required(login_url='login') def vikimain(request): dict = {'test': 'test'} return render(request, 'project/main.html', dict) main.html {% extends 'project/base.html' %} {% block content %} <div>{{ dict }}</div> {% endblock %} -
How to improve performance of Django ORM already querying with prefetch_related? (many different tables involved)
I have a Django model which is linked by many other models in a reverse ForeignKey relationship, that is many-to-one. Illustration: class ModelA: photo_url = URLField(null=True) class AbstractModel: class Meta: abstract = True modelA_ref = ForeignKey(to=ModelA, on_delete=dj_models.CASCADE) class ModelB(AbstractModel): whatever = TextField(null=True) class ModelC(AbstractModel): whatever = TextField(null=True) class ModelD(AbstractModel): whatever = TextField(null=True) and so on for a dozen more. I have a serializer for ModelA, and a corresponding view for when I call the corresponding endpoint /api/v1/modela/<uuid:key>/ in Django REST Framework. Illustration: from rest_framework.generics import RetrieveAPIView class ModelASerializer: modelb_field = ListSerializer(source="modelb_set", child=ModelBSerializer()) modelc_field = ListSerializer(source="modelc_set", child=ModelCSerializer()) modeld_field = ListSerializer(source="modeld_set", child=ModelDSerializer()) class ModelAView(RetrieveAPIView): serializer_class = ModelASerializer lookup_field = "id" lookup_url_kwarg = "key" def get_queryset(self): key = self.kwargs["key"] return ModelA.objects.filter(id=key).prefetch_related( 'modelb_set', 'modelc_set', 'modeld_set' ) Of course, this optimization does not prevent Django from querying all the different tables when the /api/v1/modela/<uuid:key>/ endpoint is reached, as expected: in my situation, the accumulation of queries takes 60% of the 1000ms response time, which is way too long. Hence my question: is refactoring my database schema to make those models fit into one single table my only option? or is there something more elegant to be done? Thank you for your time. -
in django how can i access the tables of my sql database created with xampp
i have installed mysqlclient in my project virtual environment and also changed the setting.py in order to connect to mysql database(which is with xampp). image and then i have run the "python manage.py migrate" command. and now all looks okay. image so now i want to know how can i access the tables to retrieve data or to change(update, insert) through django. for example with django orm you have models of your database that can be used. but what can i do here? any ideas can help. ps: sorry for the way of telling the problem. i'm not english(and also i'm new to django). -
Django Query with and without comma
I have a .csv file with only one column (name) and multiple rows containing strings formatted like: "name, surname" "name surname" I loop through this file and check if they exist in my database the only problem is that in my database, everything is formatted like: "name, surname" so the query without a comma could not be found unless I do something like this: Model.objects.filter(name__search=row["name"]) But this takes a very long time to load.. is there any other way? -
NGINX GUNICORN FOR DJANGO APPLICATION COMPLETE SETUP ON DISTRIBUTED SYSYTEM [closed]
I HAVE ONE WEBSERVER WHICH IP IS XX.XX.XX.59 AND HAVE ANOTHER APPLICATION SERVER ON XX.XX.XX.27 I WANT T -
how to show show db. data for all template using base template
hello I m new in Django I m creating a Django ecommerce project nd I created I slider in base template I want to show slider in all the template ..first template its working properly but if I go for some other template like section then its not showing images nd product name which I extends from base template ..hope some one help us . base.html <div class="container bg"> <div id="demo" class="carousel slide my-3" data-ride="carousel"> <ul class="carousel-indicators"> <li data-target="#demo" data-slide-to="0" class="active"></li> <li data-target="#demo" data-slide-to="1"></li> <li data-target="#demo" data-slide-to="2"></li> </ul> <div class=" carousel-inner "> <div class="carousel-item active"> <div class="row"> <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src="/media/{{cake.0.images}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{cake.0.prodname|title}}</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src="/media/{{cake.1.images}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{cake.1.prodname|title}}</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src="/media/{{ic.0.images}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 … -
Django Deploy ElasticBeanstalk StaticFiles(JS/CSS) not loading
My Styles Are Not Loading: settings.py: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' STATICFILES_DIRS = [BASE_DIR / 'templates/static'] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' error eb logs: Apr 26 06:11:06 ip-172-31-46-75 web: Not Found: /static/assets/bootstrap/css/animate.css Apr 26 06:11:06 ip-172-31-46-75 web: Not Found: /static/assets/bootstrap/css/flex-slider.min.css Apr 26 06:11:06 ip-172-31-46-75 web: Not Found: /static/assets/bootstrap/css/slicknav.min.css Apr 26 06:11:06 ip-172-31-46-75 web: Not Found: /static/assets/custom/css/style.css ETC.......... I also did in my env python manage.py collectstatic and eb deploy , it still didnt load my css/js(html is perfectly loading) my .ebextensions: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: store.wsgi:application -
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'}) }