Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django bad escape \p at position 0
I copied a simple regex from here to remove accented letters but its giving an error. import re import unicodedata class Profile(models.Model): name = models.CharField(max_length=200, blank=False) def name_breakdown(self): newName = re.sub(r'\p{Mn}', '', unicodedata.normalize('NFKD', self.name.lower())) return newName the error: bad escape \p at position 0 What do I do to resolve this? -
I am new to django and still learning. Stuck here from quite long as the error message here is confusing. Any solutions?
These are the py files (error says unknown field(s) (model) specified for Post) views.py from django.db import models from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView from .models import Post from .forms import Post_form # Create your views here. #def home(request): # return render(request, 'home.html', {}) class HomeView(ListView): model = Post template_name = 'home.html' class ArticleDetailView(DetailView): model = Post template_name = 'article_details.html' class AddPostView(CreateView): model = Post form_class = Post_form template_name = 'add_post.html' #fields = '__all__' forms.py from django import forms from django.forms import widgets, ModelForm from django import forms from .models import Post class Post_form(forms.ModelForm): class Meta: model = Post fields = ('title','title_tag', 'model', 'body') widgets = { 'title' : forms.TextInput(attrs={'class':'form-control'}), 'title_tag' : forms.TextInput(attrs={'class':'form-control'}), 'author' : forms.Select(attrs={'class':'form-control'}), 'title' : forms.Textarea(attrs={'class':'form-control'}) } Error File "/urls.py", line 3, in <module> from .views import AddPostView, ArticleDetailView, HomeView File "/views.py", line 5, in <module> from .forms import Post_form File "/forms.py", line 6, in <module> class Post_form(forms.ModelForm): File "/models.py", line 276, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (model) specified for Post I am new to django and still learning. Stuck here from quite long as the error message here is confusing. Any solutions? -
How to Check box filter In Django?
I'm using Django as backend, Postgres SQL as DB, and HTML, CSS, and Javascript as frontend. I am stuck in the filtering option, where the user selects check one brand and shows the selected brand list in the template. So basically like this: I have multiple specifications for each category. Like Mobiles have: Brand RAM ROM etc. Till now, I have done list filtering but I want check-box filtering. The Codes goes here: views.py def product(request, data=None): product = Product.objects.all() if data == None: proc = Product.objects.filter(category = 1) elif data == 'OnePlus' or data == 'boAt' or data == 'Redmi' or data == 'realme': proc = Product.objects.filter(category = 1).filter(brand = data) return render(request, 'list/processor.html', {'product': product, 'proc':proc,}) product.html <ul class="list-group"> <a style="text-decoration:none" href="{% url 'main:product' %}"> <li class="list-group-item d-flex justify-content-between align-items-center"> All </li> </a> <a style="text-decoration:none" href="{% url 'main:productdata' 'OnePlus'%}"> <li class="list-group-item d-flex justify-content-between align-items-center"> OnePlus </li> ....... </ul> I have searched for Django-Filter but proper implementation of check-box filtering not there. How the Checkbox filtering will be done because this process takes too much time. Is there any easy way where all the particular columns get a filter, for ex. if brand name LG is repeated more than … -
How to pass 2 arguments to def get_queryset?
Good evening, I have a problem while learning Django. The point is that I am doing a training news site, and there is such an item as "public" - whether the news is published or not. And to display only published news, use "def get_queryset" But I need to display news only with public = True and by the date the news was created views.py class news(ListView): model = Post template_name = 'flatpages/new.html' context_object_name = 'news' # paginate_by = 6 ordering = '-data' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cate'] = Category.objects.all() return context def get_queryset(self): return Post.objects.filter(public=True) models.py class Category(models.Model): category_name = models.CharField(max_length=64, unique=True) subscribers = models.ManyToManyField(User, blank=True, null=True) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.category_name class Post(models.Model): PostAuthor = models.ForeignKey(Author, on_delete=models.CASCADE, verbose_name='Автор поста') PostNews = 'PN' PostArticle = 'PA' # «статья» или «новость» POSITIONS = [ (PostArticle, 'Статья'), (PostNews, 'Новость'), ] postCategory = models.ManyToManyField(Category, verbose_name='Категория поста', through='PostCategory') title = models.CharField(max_length=50, verbose_name='Название') positions = models.CharField(max_length=2, choices=POSITIONS, default=PostArticle, verbose_name='Тип поста') category_id = models.ForeignKey(Category, verbose_name='Категория', null=True, on_delete=models.CASCADE, related_name='category_id') data = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') data_update = models.DateTimeField(auto_now=True, verbose_name='Дата редактирования') photo = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name='Фото', blank=True, default='/photos/def/1.jpg/') previewName = models.CharField(max_length=128, verbose_name='Превью поста') text = models.TextField(verbose_name='Текст поста') rating = models.SmallIntegerField(default=0, … -
AssertionError: database connection isn't set to UTC
I have done server setup multiple times with the same settings but this time, I am seeing the error message. It is not even allowing to migrate the database. System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/core/management/base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations return {(migration.app, migration.name): migration for migration in self.migration_qs} File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/query.py", line 276, in __iter__ self._fetch_all() File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1170, in execute_sql return list(result) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1569, in cursor_iter for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1569, in <lambda> for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/utils.py", line 97, in inner return func(*args, **kwargs) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/backends/postgresql/utils.py", line 6, in utc_tzinfo_factory raise AssertionError("database connection isn't … -
Optimizing django rest framework API
I have created an API to get all the data from by database. There is a "deployment" table and a related table "sensors" which has a foreign key referencing the deployment, a one-many relationship. The serializer creates a nested JSON. Currently if I request all records it takes roughly 45 seconds to return the data (17,000 JSON lines). How do I profile my Django application to determine what is the bottleneck? Any suggestions on what can be improved to speed this up? Or is this is as good as it's going to get? models.py class deployment(models.Model): ADD_DATE = models.DateTimeField() #creation of record in db #...30 more fields.... class sensor(models.Model): DEPLOYMENT = models.ForeignKey(deployment, related_name='sensors', on_delete=models.CASCADE) ADD_DATE = models.DateTimeField() #creation of record in db SENSOR = models.ForeignKey(sensor_types, to_field="VALUE", max_length=50, on_delete=models.PROTECT) #...5 more foreign key fields... views.py class GetCrtMetadata(generics.ListAPIView): #Read only serializer_class = CurrentDeploymentSerializer queryset=deployment.objects.all().prefetch_related("sensors") filter_backends = [DjangoFilterBackend] filter_fields = [field.name for field in deployment._meta.fields] deployment app serializers.py class CurrentDeploymentSerializer(serializers.ModelSerializer): #Returns deployment with sensors sensors = SensorSerializer(many=True) class Meta: model = deployment fields = [field.name for field in deployment._meta.fields] fields.extend(['sensors']) read_only_fields = fields sensor app serializers.py class SensorSerializer(serializers.ModelSerializer): class Meta: model = sensor fields = [field.name for field in sensor._meta.fields] -
Html / jquery multiple forms submit
I am working on Django File Sharing Project and in file view on click on file preview div it will pop-up modal with description of file . I have problems in IDing multiple forms FileView.html <div class="parent"> <div class="child" onclick="document.getElementsByClass('form').submit();"> <form class="form" method="post" action="django-script.py"> <h5 > File.jpg</h5> <input type="hidden" name="file" value="file.jpg"> <h6 class="title">{{f.filename}}</h6> <img class="image" src="/images/icons/file.png" > </form> </div> <div class="child" onclick="document.getElementsByClass('form').submit();"> <form class="form" method="post" action="django-script.py"> <h5 > File.pdf</h5> <input type="hidden" name="file" value="file.pdf"> <h6 class="title">{{f.filename}}</h6> <img class="image" src="/images/icons/pdf.png" > </form> </div> <div class="child" onclick="document.getElementsByClass('form').submit();"> <form class="form" method="post" action="django-script.py"> <h5 > File.csv</h5> <input type="hidden" name="file" value="File.csv"> <h6 class="title">{{f.filename}}</h6> <img class="image" src="/images/icons/file.png" > </form> </div> If I use ID it works well only for 1 div I dont know how to make it for all div elements Original Django Code ViewFile.html <div class="parent"> {% for f in file %} <div class="child" onclick="document.getElementById('form').submit();"> <form id="form" method="post" action="{% url 'fileview' %}"> {% csrf_token %} <h5 >{{f.title}}</h5> <input type="hidden" name="file" value="{{f.filename}}"> <h6 class="title">{{f.filename}}</h6> <img class="image" src="{% static '/images/icons/file.png' %}" > </form> </div> {% endfor %} Views.py def fileview(request): global loginFlag,loginUser if request.method == 'POST': fil=request.POST['file'] about=Transaction.objects.filter(filename=fil) emp=about[0].userid aname=Employee.objects.filter(emp_id=emp)[0].name print(about) files=Transaction.objects.all() name=loginName context={'files':files,'name':name,'about':about,'aname':aname} return render(request,'detailedview.html',context) else: file=Transaction.objects.all() name=loginName context={'file':file,'name':name} return render(request, 'viewfile.html',context) I think the issue … -
Print a list in HTML file using Django
I want to print a list called formulario and I want to paste them into a html file using Django template language, although I'm not able to display that information in <li> tag. Is there sth am I missing? views.py from django.template import RequestContext from django.http import HttpResponse from django.shortcuts import render import pandas as pd formulario = ["Hola", "Hi"] def formulario(request): return render (request, "formulario/formulario.html",{ "formulario":formulario }) Html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Formulario !</h1> <ul> {% for formulario in formulario %} <li>{formulario}</li> {% endfor %} </ul> </body> </html> urls.py from django.urls import path from . import views urlpatterns = [ path("index.html",views.index, name="index"), path("financierofinanciamiento.html",views.financiamiento, name="financiamiento"), path("financierobeneficio.html",views.beneficio, name="beneficio"), path("tecnicoinfra.html",views.infra, name="infra"), path("tecnicoequipo.html",views.equipo, name="equipo"), path("tecnicoherramientas.html",views.herramientas, name="herramientas"), path("tecnicomateriaprima.html",views.materiaprima, name="materiaprima"), path("formulario.html",views.formulario, name="formulario"), ] -
Django Queryset Annotate value with latest related object
i have three models: Brand, Log and Abstract MWModel. class Log(models.Model): app = models.CharField(max_length=20, choices=get_modules()) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') method = models.CharField(max_length=8, choices=HTTP_METHODS) url = models.TextField() body = models.TextField(null=True) code = models.IntegerField() message = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.created_at.isoformat() class MWModel(models.Model): log = GenericRelation(Log) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Brand(MWModel): name = models.CharField(max_length=50) status = models.BooleanField(default=True) def __str__(self): return self.name How can get code field of last Log record created for each Brand? I have this Brand.objects.filter( merchant=account.merchant, identity__app=F('merchant__erp') ).annotate( log__last__created_at=Max('log__created_at'), log__last__code=Log.objects.filter( content_type__model=Brand._meta.model_name, object_id=OuterRef('pk') ).order_by('-created_at').values('code')[:1] ).values('pk', 'name', 'log__last__created_at', 'log__last__code') And i need something like this Brand.objects.filter( merchant=account.merchant, identity__app=F('merchant__erp') ).annotate( log__last__created_at=Max('log__created_at'), log__last__code=F('log__code', filter=Q('log__created_at'=F('log__last__created_at'))) ).values('pk', 'name', 'log__last__created_at', 'log__last__code') I would greatly appreciate your help. Thanks. -
want to do authentication using django rest framework, i want to setup the login route for mentors and other users and preserve some end points
Basically i want to authenticate the current user using user_details model and also to check if current user is a mentor and establish authorisation for the endpoints and preserve some endpoints from user But i am not able to understand how to achieve it my models.py from django.db import models # Create your models here. class LiveClass(models.Model): standard = models.IntegerField() no_of_students_registered = models.IntegerField(default=0) class Meta: verbose_name_plural = 'Class' class User_details(models.Model): name = models.CharField(max_length=30) standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) email = models.EmailField(max_length=30) mobile_number = models.IntegerField() class Meta: verbose_name_plural = 'User_details' class Mentor(models.Model): name = models.CharField(max_length=30) details = models.TextField() class Meta: verbose_name_plural = 'Mentors' class LiveClass_details(models.Model): standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) chapter_name = models.CharField(max_length=30) chapter_details = models.TextField() mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) class_time = models.DateTimeField() class Meta: verbose_name_plural = 'LiveClass_details' class LiveClass_registration(models.Model): class_details = models.OneToOneField(LiveClass_details, on_delete=models.CASCADE) name = models.OneToOneField(User_details, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'LiveClass_registration' my serializers.py from rest_framework import serializers from . import models class LiveClass_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass fields = '__all__' class User_details_serializer(serializers.ModelSerializer): class Meta: model = models.User_details fields = '__all__' class LiveClass_details_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass_details fields = '__all__' class Mentor_serializer(serializers.ModelSerializer): class Meta: model = models.Mentor fields = '__all__' class LiveClass_registration_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass_registration fields = … -
Order queryset using the number of related objects in Django
Let's say I have the following in models.py: class A(models.Model): ... class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) What I want to do is sort a queryset for A based on how many B objects they have, in descending order. What is the best approach to this issue? Thanks for any help. -
Get image file and fields in Django rest framework
I am trying to upload image via django restframe work and return a custom response views.py class Imageuploadviewset(viewsets.ModelViewSet): queryset = UploadModel.objects.all() serializer_class = UploadSerializer def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) return Response({'something': 'serializer'}) def list(self, request, *args, **kwargs): return Response({'Model': 'Skin Disease Diagnosis'}) models.py class UploadModel(models.Model): name=models.CharField(max_length=50) image=models.ImageField('images/') urls.py router = DefaultRouter() router.register(r'UploadModel', views.Imageuploadviewset) urlpatterns = [ path('',views.home,name='home'), path('api/', include(router.urls)), ] Serializer.py class UploadSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=UploadModel fields='__all__' Query is that how to play with name and image upload, run some functions on them and return a response. I am not sure how to get those. -
How to combine in one url both url not run on same time?
url(r'^(?P[\w]+)', views.myquestion.questions, name = 'questions'), url(r'^(?P[\w]+)', views.myquestion.mcqs, name = 'mcqs'), -
Django slow loading page due to lots of codes
I am implememting a small recommendation feature on my home page which will suggest jobs to candidates. To accomplish the latter, I have used CountVectorizer and Cosine Similarity. However, to perform this, I had to concatenate lots of fields from the candidate's profile and job description. This code is defined in the views.py. Every time I load the home page, this view gets executed and eventually, it takes time to load. Is there something I can do to improve the loading speed? Thank you guys ;) -
Django Channels - Websocket connection failed
I am currently trying to setup my Django Channels chat app, and I have followed the Docs to the best of my understanding - Obviously when something doesn't go right, there's always a solution, but I am just having difficulties working out where I've gone wrong with getting this to work. So far I have installed Django Channels, correctly configured my channel_layer within settings.py, I have referenced the docs and other online tutorials with creating my consumer.py file, utils.py, views.py and chat.html template file. I have also configured daphne and redis and I can confirm that both of these services are running. I have installed LetsEncrypt and have allowed the SSL port (443 for https connections). I am currently accessing my Django website on a live production server like this: https://:8001 and the direct link to my chat is configured as https://mydomain:8001/messenger Here are the status messages I am getting from the chat page: SUCCESS {response: "Successfully got the chat.", chatroom_id: 1}chatroom_id: 1response: "Successfully got the chat."__proto__: Object (index):303 setupWebSocket: 1 (index):371 ChatSocket connecting.. WebSocket connection to 'wss://www.<mydomain>.com:8001/messenger/1/' failed: setupWebSocket @ (index):317 success @ (index):389 c @ jquery.min.js fireWith @ jquery.min.js l @ jquery.min.js (anonymous) @ jquery.min.js ChatSocket error Event … -
How to filter against subclass's fields with Django InheritanceManager?
I am using InheritanceManager from django-model-utils library. Is there a way to filter against fields of a subclass? Something like this: from model_utils.managers import InheritanceManager class A(models.Model): objects = InheritanceManager() class B(A): flag = models.BooleanField() A.objects.select_subclasses().filter(flag=True) -
context_object_name doesnt work on CreateView (Django 2.2)
how are you? i have an issue. My form doesn't render on the html if i change the context_object_name from 'form' to 'recent_works' (only for my order). here is the code: models.py: class clientes_rfi(models.Model): fondo = models.TextField(null=True,blank=True) nombre_cliente = models.TextField(unique=True,null=True,blank=True) categoria = models.TextField(null=True,blank=True) pais = models.CharField(max_length=3,null=True,blank=True) activo = models.BooleanField(default=True,null=True,blank=True) prospecto = models.BooleanField(default=False,null=True,blank=True) trader_contraparte = models.TextField(null=True,blank=True) final = models.BooleanField(null=True,blank=True,default='t') views.py class CrearClienteCreateView(CreateView): context_object_name = 'recent_works' model = clientes_rfi template_name = "ordenes/ordenes-listar-clientes.html" fields = ['fondo','final','categoria','pais'] ordenes/ordenes-listar-clientes.html {% include 'index.html' %} {% block contenido %} <div class="container"> <div class="h1">Ingreso de trabajos nuevos</div> <form method="post">{% csrf_token %} {{ recent_works }} <input type="submit" value="Guardar"> </form> {% endblock contenido %} the render <form method="post"><input type="hidden" name="csrfmiddlewaretoken" value="lmq7NwolBOSGIy5vnIt8y3fZIUSdSPoC5icnHiNGFOgvWHAo"> <input type="submit" value="Guardar"> </form> Thanks in advance -
Foreign Key IntegrityError at /new_project null value in column "project_id" violates not-null constraint
I know this is probably a duplicate but I've tried every solution on other problems of this nature and I can't seem to solve this, here's my issue. Models class Project(models.Model): project_name = models.CharField(max_length=50) project_url = models.URLField() last_update = models.DateField(default=timezone.now) def __str__(self): return self.project_name class Commit(models.Model): project = models.ForeignKey(Project, on_delete = models.CASCADE, verbose_name="project") commit_id = models.CharField(max_length=40) author = models.CharField(max_length=200) date = models.DateTimeField(default=timezone.now) commit_msg = models.TextField() commit_info = models.TextField() regex_tags = models.TextField(null=True) def __str__(self): return self.commit_id + " - " + self.author + " - " I have these models and I need every commit to be associated with the project they come from. In my view, I do this: class new_project_view(View): def get(self, request): return render(request, 'new_project.html') def post(self,request): if 'create_project' in request.POST: project_name = request.POST['projectname'] project_url = request.POST['projecturl'] print("project url ", project_url) print("project name", project_name) generate_log_file(project_url) logfile = open("logfile.txt", "r") if not logfile.readlines() : print("Estou vazio") logfile.close() return render(request, 'new_project.html') else: print("Add log to DB") logfile.close() #Here I create the project model and send it to a function #that adds to the commits. project = Project.objects.create() project.project_name = project_name project.project_url = project_url project.save() add_log_to_db(project) print("Added") return render(request, 'new_project.html') The add_log_to_db function does a lot but it's working as intended … -
How to embed an HTML table from another domains webpage into my own using Python with Django framework via the backend?
I am trying to embed the HTML table from another domains webpage into my own. Obviously this is not possible using JavaScript via the front-end because of cross-origin policy. I saw a few suggestions to use the back-end, in my case Python on top of Django framework, to fetch the page and render it to the front-end so that it appears to be on the same domain and then use jQuery to extract only the element I am looking for. However, none of these suggestions really provided any working code that I could try and follow. I am a bit confused as to how to render an external domains webpage to my front-end using Django framework ? PS. The table in question does not have an id so I would need to use some sort of CSS selector to extract it. Ideally, I would like to keep the styling of the table the same as it is on the other site. Yes, I have permission to embed the table and I do reference the original site. Yes, I have tried an iFrame but I don't want the entire webpage and prefer not to "hack" the CSS. -
how do i store all loop variables in dictionary of python to use in django
PYTHON import requests import re import os import csv from bs4 import BeautifulSoup headers = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36', } searche=['note 8 pro','note 9 pro','boat','realme','poco'] for d in searche: truelink = d.replace(" ","-") truelinkk=('https://www.olx.in/hyderabad_g4058526/q-'+truelink+'?isSearchCall=true') r = requests.get(truelinkk,headers=headers).text soup=BeautifulSoup(r,'lxml') mobile=soup.find_all('li',class_='EIR5N') for note9maxpro in mobile: mobi= note9maxpro.find('span',class_='_2tW1I').text price= note9maxpro.find('span',class_='_89yzn').text date= note9maxpro.find('span',class_='zLvFQ').text link=note9maxpro.a.get('href') orglink='https://www.olx.in'+link price = price.replace("₹ ","") how to store all loop variables in dictionary of python to use in django later i want to use this data in django as. please give me solution to reduce lines of my code as well Thanks in advance for i in data: i.mobi i.price i.date -
is there anyway to use python for frontend development?
I am trying to find a way to develop a frontend using python As I don’t want to use any kind of javascript in my website, I am a Django developer from last 2 years but being a Django developer I feel that after learning python a lot we have to learn javascript too for the frontend, and I think this feels to the whole Django community that at the end of the day, they have to face JavaScript (by their will or forcibly). So, I want the whole community to spend some time to think and please let not down Python Developers to face JavaScript after learning a lot in Python. In my opinion, there should be a full-fledged frontend framework in Python -
How to select a declared variable from a script tag with JavaScript
Could you please help me? I have the four below declared variable inside a script tag ( in a html page. They are radomly generated by folium in python.I would like to select the last one from another js file without success. I tried this window.onload = function() { for (var name in this){ if(Object.keys({name})[0].includes("layer"){ alert (name) } } }; Here are the declared variables inside the script tag in the html page var circle_f3a483b3a7ba46748ac935d3995f4f6b = L.circle( [-16.0, 0.0] ).addTo(feature_group_1c28eff59e394734be54cf676a09eae1); var circle_a01d1791063145b18b439bd7687bc97f = L.circle( [-11.3137, 11.3137], ).addTo(feature_group_1c28eff59e394734be54cf676a09eae1); var layer_control_aec3ac6e0e424b74a19b4c9d1c78ffeb = { base_layers : { }, overlays : { "Roads" : geo_json_cae0ea33c63e4c438678d293e5c32c0d, "Intersections" : feature_group_1c28eff59e394734be54cf676a09eae1, }, }; -
How to replicate django authentication in several services
we have a web app using Django. We have the authentication system setup as described below. Now, we would like to take some part of the application to an independent service, but we would like to have the same valid token/authentication system. The new service will be using Django too, probably, so I would like to know if this is even possible or what options do I have to implement this behavior. In the case that we do not use Django in the new service, there would be a way to still use the same logic to authenticate requests on the two services? Authentication system Right now, we are authenticating the requests using the rest_framework module, more precisely, the TokenAuthentication class. This is the configuration: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', ... 'rest_framework', 'rest_framework.authtoken', ... } REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'module.authentications.AuthorizedAuthentication', ) } And the code we use to authorize the requests: import logging from rest_framework.authentication import TokenAuthentication from rest_framework.exceptions import AuthenticationFailed class AuthorizedAuthentication(TokenAuthentication): _logger = logging.getLogger(__name__) def authenticate(self, request): response = TokenAuthentication.authenticate(self, request) if response is None: return None return response To authenticate in the views, we do something like this: from rest_framework.permissions import … -
Limit number of objects of a self reference model with Prefetch Django
I have 2 models: Post and Comment. Like this: class Post(models.Model): content = models.TextField() class Comment(models.Model) content = models.TextField() owner = models.ForeignKey(User, null=False, on_delete=models.CASCADE) post_parent = models.ForeignKey( Post, on_delete=models.CASCADE, null=False, db_column='post_parent', related_name='comments', ) comment_ref = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True, related_name='children_comment' ) Suppose that comments can have sub-comments in 1 level. With a post's ID, I want to get 5 newest comments (not sub-comment), each of them is prefetched with their 3 newest sub-comments. My current implementation after searching is: sub_comments = Comment.objects.filter( comment_ref=OuterRef('pk'), post_parent=post_id ).order_by('-timestamp').values_list('id', flat=True)[:3] queryset = Comment.objects.filter( comment_ref=None,post_parent=post_id ).select_related('owner').prefetch_related( Prefetch('children_comment', queryset=Comment.objects.filter( id__in=Subquery(sub_comments) ), to_attr="cmt")) That does not work. It doesn't limit the number of prefetched sub-comments. Please help me :D -
Loading font in django templates
The structure of folders is as follow: --project |--myapp |--static |--fonts |--abs.ttf | |--templates |--report.html I load static files to report.html as follow: <!DOCTYPE html> <html> <head> <title> My Title</title> {% load static %} {% block style_base %} {% block layout_style %} <style type="text/css"> @font-face { font-family: 'abc'; src: url({% static 'fonts/abc.ttf' %}); {# src: url('file:///home/project/myapp/static/fonts/abc.ttf'); #} } ... When import font using url('file:///home/project/myapp/static/fonts/abc.ttf'); it's work fine but using url({% static 'fonts/abc.ttf' %}); doesn't work. settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Also I added urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)' to the urls.py` but no result found. Can anyone tell me where the problem is?