Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
which is the right way to import class in django?
code style 1: from ..service.user_service import UserService class UserView: user_service = UserService() user_service.get_all_users() # rest of code code style 2: from ..service.user_service import UserService as userService class UserView: userService.get_all_users() # rest of code service.user_service.py from .models.user import User # please class UserService: def get_all_users(self): return User.objects.all() both code works fine but which is the proper way? And also I want to know if this things may cause of the circular import error?. I have went through this question Circular (or cyclic) imports in Python. And what is the working mechanism of style 2 code? -
Boolean attribute or new table (Django + PostgreSQL)
Situation: I have a Books set. Book can be one of the types: "Test", "Premium" and "Common". Data proportional: 2%, 15%, 83%. Amount query per time unit (in percent): 40%, 20%, 40% I see some ways for resolve it in database: Boolean: is_test, is_premium. If we need only "Tests" book: Book.objects.filter(is_test=True). It is can be a proxy model, for example. Analogy for premium books; Separate Tables: books_test, books_premium, books_common. Choice field: string in ['Test', 'Premium', 'Common']; Combine 1 and 2: books_test table and books table with 'is_premium' attribute. And we need optimally querying this data! All three Book variants need in one page. Exist queryset combinations: only tests, only common, common + premium, only premium. If we use 1,3 variant: 1 endpoint with specific filter; If we use 2 variant: one of the tree endpoints without filters (frontend should know what kind endpoint use). Or we can create one endpoint with some conditions and check by backend. Anyway: need extend logic; Which way is more correct and why? -
Django - Return a file from Root folder via a URL
I purchased a SSL cert online and now ind the mid of verifying my host. How it works is: It gives me a file I have to make that file accessible through a specific URL on my host. If the content of the file matches, it's verified. Now I'm at step 2. I'm trying to return a file (static) from an URL, as required by Comodo to verify my server. So basically, I think if I access this link: http://your(sub)domain/.well-known/pki-validation/<filename.txt> The guide is here: https://helpdesk.ssls.com/hc/en-us/articles/206957109-How-can-I-complete-the-domain-control-validation-DCV-for-my-SSL-certificate- Can you guys help how I can return a file with this URL? Thanks! -
if condition is not working in python django when i compare template value with python value [on hold]
I wants to compare the request.POST.GET("entered",False)) to a = 0 but it is not working only the elif !=a and else condition is working. def code_check(request): print("=====Code check=====",request.POST.get("entered",False)) a = 0 if request.method =="POST": if a == request.POST.get("entered",False) and request.POST.get("entered",False) != False: return render(request, 'orders/success.html') elif request.POST.get("entered",False) != a: messages.error(request, f"Invalid Code! ") return render (request, "orders/code_verification.html" ) else: return render (request, "orders/code_verification.html" ) -
Source field in DRF serializer with multiple foreign keys to the same model
I have a Django model as follows: class Team(models.Model): name = models.CharField(max_length=100, unique=True) managers = models.ManyToManyField(User, through=MgrToTeam, related_name='mng') users = models.ManyToManyField(User, through=UsrToTeam,related_name='usr') I now have a serializer where i need to display all the users and managers associated with a team: class TeamDetailSerializer(serializers.ModelSerializer): managers = serializers.SlugRelatedField(queryset=User.objects.all(), slug_field='name') users = serializers.SlugRelatedField(queryset=Team.objects.all(), slug_field='name') class Meta: model = Team fields = ['id', 'name', 'managers', 'users'] However, this gives me the same output for both the users and managers.How do i fix this ? -
Django ordering by a foreign key field
I have two models as listed below : Class Project(models.Model) : name = models.TexField() Class Item(models.Model): project = models.ForeignKey(Project) name = models.TextFIeld() available = models.FloadField() So I need to fetch all Projects, however I want them such that, all those Projects which has Items that has available grater than 0, should come first. So I tried this list = Projects.objects.filter(**Some Fields**).order_by(available) How can I sort this list? -
How to solve 'localhost refused to connect' when using iFrame in Django template?
I have a Django app template that requires I use an iFrame to display a page local to the page I'm sourcing it from. In my template, I have: <iframe src="..." allowFullScreen="true" scrolling="auto"></iframe> and I want to src a page like: {% url 'my_view' %} but whatever I put in I always end up with the IFrame saying 'localhost refused to connect'. What's happening here? -
django automatic survey popup after some times of session
I want to show survey pop up automatically in my webpage sometimes after web session is started, How can I implement this using Django? -
Updating protected serve url path with patterns for django 1.11
How do you use this code in the current (1.11) version of Django? The code below uses patterns module but as I googled it was removed in 1.10. from django.conf.urls import patterns, include, url from django.contrib.auth.decorators import login_required from django.views.static import serve from django.conf import settings @login_required def protected_serve(request, path, document_root=None, show_indexes=False): return serve(request, path, document_root, show_indexes) urlpatterns = patterns('', url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL[1:], protected_serve, {'document_root': settings.MEDIA_ROOT}), ) Here's the source tutorial link -
How to use python script in django?
I'd like to use this at my homepage in django project(python 3.7.2 and django 2.1.7 installed). Input file will be uploaded different way. I only want to know how to use/where to paste script like this. Thanks for help! from csv import reader, writer name = input("Please input your file's name.") with open(name) as file: csv_reader = reader(file) search_input = input("Search by word?") for search in csv_reader: for rows in search: if search_input == rows: print(search) -
Django- empty string in url is not redirecting to the index page
I'm learning django and in my app, I have a urls.py which has 4 url patterns in it. if there is no string entered in the end of url then it must redirect to the index page as per the code but it is not happening. Rest url are working fine. MY urls.py from django.contrib import admin from django.urls import path from .views import index, about, news from django.conf import settings from mainsite import views urlpatterns = [ path(r'^$', views.index, name='index'), path(r'about/', views.about, name='about'), path(r'news/', views.news, name='news'), path(r'admin/', admin.site.urls), ] My views.py from django.shortcuts import render from datetime import datetime from .models import Article def index(request) : context = { 'current_date': datetime.now(), 'title': 'Home' } return render(request, 'index.html', context ) def about(request) : context = { 'current_date': datetime.now(), 'title': 'About' } return render(request, 'about.html', context ) def news(request) : populate_db() articles = get_articles() context = { 'articles': articles, 'current_date': datetime.now(), 'title': 'News' } return render(request, 'news.html', context ) def get_articles(): result = Article.objects.all() return result def populate_db(): if Article.objects.count() == 0: Article(title = 'first item', content = 'this is the first database item').save() Article(title = 'second item', content = 'this is the second database item').save() Article(title = 'third item', content … -
How to save frontend (react) JSON data in django particular table?
{ "question" :[ { "id": '0', "title":'Click to write the question text', "choice":['Click to write Choice 1','Click to write Choice 2','Click to write Choice 3'], "answerType":'singleAnswer', "answerStyle":'vertical', }, { "id": '1', "title":'Click to write the question text', "choice":['Click to write Choice 1','Click to write Choice 2','Click to write Choice 3'], "answerType":'singleAnswer', "answerStyle":'horizontal', }, { "id": '2', "title":'Click to write the question text', "choice":['Click to write Choice 1','Click to write Choice 2','Click to write Choice 3'], "answerType":'multipleAnswer', "answerStyle":'horizontal', }, ] } strong text Frondend(react) gives me this type of json data. I need to save it in my sqlite database in django. How i save the choice field?. if i make Question and Choice model separate how do i save the json choice one by one in choice table and how to give this data again in frontend. How i design my model and what should i need to write in my api view? -
Create and Update doesnt work in nested Serialzer Django
I have the following models: class Grade(models.Model): grade = models.CharField(max_length=255, primary_key=True) class Student(models.Model): class Meta: unique_together = ("rollno", "grade") name = models.CharField(max_length=255) grade = models.ForeignKey(Grade,related_name='StudentList', on_delete=models.CASCADE) rollno = models.BigIntegerField() And I have a nested serializer where I have written custom update and create. class Meta: model = Grade fields = ("grade", "StudentList") def create(self, validated_data): student_data = validated_data.pop('StudentList') grade = Grade.objects.create(**validated_data) for stds in student_data: Student.objects.create(grade=grade, **stds) return grade def update(self, instance, validated_data): students_data = validated_data.pop('StudentList') stds = (instance.StudentList).all() stds = list(stds) for student_data in students_data: student_update = stds.pop(0) student_update.name = student_data.get('name', student_update.name) student_update.grade = student_update.grade student_update.rollno = student_data.get('rollno', student_update.rollno) student_update.save() return instance I am trying to use put to create a new instance of Grade if it doesn't exist and update if it exists. While create does create a new instant but it cannot put any values in StudentList. Similarly when I do the update, even after I give new values in the StudentList, it doesn't update but doesn't gives an error. The view is below: class IndividualGrade(generics.RetrieveUpdateDestroyAPIView): ''' PUT/GET/DELETE grade/{grade:pk}/ ''' queryset = Grade.objects.all() serializer_class = GradeSerializer def put(self, request, *args, **kwargs): try: g1 = Grade.objects.get(grade=kwargs["pk"]) serializer = GradeSerializer(g1, data=request.data) serializer.update(g1, serializer.data ) except Grade.DoesNotExist: # Create a … -
Weird bug happening with Django and MySQL
I have two pieces of code, both doing the same thing but one takes 50 seconds and other takes less than 5 seconds. Models class Device(models.Model): device_uid = models.CharField(max_length=50, unique=True, null=False) class DeviceReadings(models.Model): device = models.ForeignKey(Device) value = models.FloatField(default=0) created_dt = models.DateTimeField() class Meta: unique_together = ('created_dt', 'device') The DeviceReadings table contains around 200 million rows. If i do this, mysql query won't use index and will scan 22 million rows and takes 40 seconds. #'D1,D2,D3' are comma separated device_uid's my_devices = "D1,D2,D3".split(",") devices = Device.objects.filter(device_uid__in=my_devices) readings = DeviceReadings.objects.filter(created_dt__gte=start_time, created_dt__lte=end_time, device__in=devices) However, if i do this, mysql query will use index and will only scan 1 million rows and takes around 4 seconds. my_devices = "D1,D2,D3".split(",") my_devices_ob = Device.objects.filter(device_uid__in=my_devices) devices = [] for device in my_devices_ob: devices.append(device) readings = DeviceReadings.objects.filter(created_dt__gte=start_time, created_dt__lte=end_time, device__in=devices) If i print the devices array, it is same in both the codes. Can someone explain what might be happening here ? -
Convert (and validate) file added in django admin
I'm working on a Django project that utilizes customized greetings (like in voicemail). The whole functionality is implemented, i have created a custom model: class Greeting(models.Model): audio_file = models.FileField(upload_to='greetings/') description = models.CharField(max_length=128) uploaded_at = models.DateTimeField(auto_now_add=True) The next thing that i wanted to do is to make sure that the uploaded file has all the expected properties (is a WAV file, has one channel, has low bitrate etc). But i don't even know where to start. These files will be only added via django admin. In regular FormView i would utilize server-sided validation in View, and only then add it to model. How to do it in django admin? To summarize what i expect my app to do: 1) Add file to a model in django admin 2) Server checks file properties, and if requirements are not met, tries to convert it to proper format 3) If the file is in proper format, only then it saves the object. -
Relation does not exist - Django & Postgres
I added some table to an existant model, but I got an error when i push my project to heroku : This happens to any models I add on this particular app ProgrammingError at /admin/dashboard/adressbook/ relation "dashboard_adressbook" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "dashboard_adressbook" My models.py class AdressBook(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Nom de l'utilisateur") text = models.CharField(max_length=200,verbose_name="Description") number = models.CharField(max_length=20,verbose_name="Numéro de téléphone") def __str__(self): return self.text def get_absolute_url(self): return reverse('dashboard-home') class Dashboard(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Nom de l'utilisateur") content = RichTextField(max_length=500,verbose_name="Description") text = models.TextField(verbose_name="Description supplémentaire",null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.content def get_absolute_url(self): return reverse('dashboard-home') class Links(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur") content = models.URLField(max_length=500, verbose_name="URL") name = models.CharField(max_length=500, verbose_name="Description") def __str__(self): return self.name def get_absolute_url(self): return reverse('dashboard-home') class Todo(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur") text = models.CharField(max_length=150, verbose_name="Nom de la Todo") content = RichTextField(verbose_name="Description supplémentaire",null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) complete = models.BooleanField(default=False, verbose_name="Statut de la Todo") urgence = models.BooleanField(default=False,verbose_name="Tâche urgente") def __str__(self): return self.text def get_absolute_url(self): return reverse('dashboard-home') class Phone(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Nom de l'utilisateur") text = models.CharField(max_length=200,verbose_name="Description") number = models.CharField(max_length=20,verbose_name="Numéro de téléphone") def __str__(self): return self.text def get_absolute_url(self): return reverse('dashboard-home') Traceback : Django Version: 2.1.7 Python … -
Display console output in django template in real time
I'm trying to create a web based user interface, where the user will press the button and start the script in the background. I would like to display console output in the browser in real time. What is the best and easiest way to do it? I only have experience with python, so I want to use a technology that will not take me a long time to understand it. -
django attach a csv to an email
I am currently attempting to attach a csv to an email but I keep getting errors, the code I have at the moment is this: error_list=[{'error_1': 0, 'error_2':1}, {'error_1': 2, 'error_2': 1}] with open('errors.csv', "w") as infile: writer = csv.DictWriter(infile, fieldnames=error_list[0].keys()) writer.writeheader() for data in error_list: writer.writerow(data) mail = EmailMessage(subject='Test', from_email=EMAIL_HOST_USER, to=['example@example.com',]) mail.attach('errors.csv', infile, 'text/csv') mail.send() I am not quite sure where I am going wrong - at the moment I am getting the error: 'Connection unexpectedly closed: [WinError 10054] An existing connection was forcibly closed by the remote host' -
Django. How to write a filter for the current user?
The listings application has a Listing table: class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риэлтор') region = models.CharField(default="Чуйская", max_length=100, verbose_name='Область') city = models.CharField(default="Бишкек", max_length=100, verbose_name='Город') district = models.CharField(blank=True, max_length=100, verbose_name='Район') title = models.CharField(max_length=200, verbose_name='Заголовок') address = models.CharField(blank=True, max_length=200, verbose_name='Адрес') description = models.TextField(blank=True, verbose_name='Описание') stage = models.IntegerField(blank=True, verbose_name='Этажность') rooms = models.IntegerField(blank=True, verbose_name='Количество комнат') garage = models.IntegerField(default=0, blank=True, verbose_name='Гараж') sqmt = models.IntegerField(blank=True, verbose_name='Площадь') price = models.IntegerField(blank=True, verbose_name='Цена') photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Основное фото') photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 1') photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 2') photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 3') photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 4') photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 5') photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 6') is_published = models.BooleanField(default=True, verbose_name='Публично') list_date = models.DateTimeField(default=datetime.now, blank=True, verbose_name='Дата публикации') def __str__(self): return self.title class Meta: verbose_name = 'Объявление' verbose_name_plural = 'Объявления' The listings application has a Listing table: class Realtor(models.Model): user_name = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Пользователь', related_name='realtor') name = models.CharField(max_length=20, verbose_name='Имя') photo = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name='Фото') description = models.TextField(blank=True, verbose_name='Описание') phone = models.CharField(max_length=20, verbose_name='Телефон') email = models.CharField(max_length=50, verbose_name='Email') is_mvp = models.BooleanField(default=False, verbose_name='Реэлтор месяца') hire_date = models.DateTimeField(default=datetime.now, blank=True, verbose_name='Дата приёма на работу') def __str__(self): return self.name class Meta: verbose_name = 'Риэлтор' verbose_name_plural = 'Риэлторы' In the accounts application, there is a function that in the personal … -
How to render OpenAPI 3.0 json schema with DRF including slashed urlpatterns?
I have a DRF DefaultRouter with some routes and I want to render a json OpenAPI schema: from rest_framework.schemas import get_schema_view from rest_framework.renderers import JSONOpenAPIRenderer router = routers.DefaultRouter() router.register(r'org/teams', org_viewsets.TeamViewSet, basename='team') router.register(r'structures', org_viewsets.StructureViewSet, basename='structure') urlpatterns = [path('', include(router.urls)),] schema_view = get_schema_view( url='http://localhost:8000/api/v2/', patterns=urlpatterns, renderer_classes=[JSONOpenAPIRenderer] ) urlpatterns += [path('schema.json', schema_view)] Routes with a intermediate slash like org/teams are not rendered. Routes like structures are rendered. Removing the slash solves the problem. How can I get all my routes rendered? Is this a bug or I am wrong? -
How to use django ORM to an API JSON result and perform calculation
I have thousands of attendance raw data (json) from a web tool that I extracted using their API. How can I get them into a table format / python object so I can use Django query and do calculations. Is there a better way to do this? -
Security concerns for serving files uploaded by admin
I want to use non-static images for my app. Meaning that Admin will be able to upload images (and create articles). Users will have read-only access to articles. Would in this case it be secure to use MEDIA_ROOT and MEDIA_URL on Production to store and serve images? Or still I should use only 3rd party resource (e.g. AWS S3) for storing/serving the images as this article recommends? -
How to Django Orm Left Join on two fields
I would like to join two tables by two fields with django ORM I got 4 tables class User: ... class VipUsers: library = ForeignKey(Library) user = ForeignKey(User) class Library: ... class Book: library = ForeignKey(Library) visible = BooleanField(default=None, null=True, blank=True) In SQL query looks like: SELECT b.id, user_id FROM project_book AS b LEFT JOIN project_vipusers AS v ON v.library_id=b.library_id AND v.user_id={user_id} WHERE CASE WHEN b.visible=True THEN v.user_id IS NOT NULL WHEN b.visible=False THEN v.user_id IS NULL ELSE true END; I try to make such solution but django generate no Join query my_user = {some_user_id} Book.objects.all().annotate( vip_users=Subquery(VipUsers.objects.filter(library=OuterRef('library'), user=my_user).values('user')[:1]), show=Case(When(visible=True, then=Q(vip_users__isnull=False)), When(visible=False, then=Q(vip_users__isnull=True)), default=Value(True), output_field=BooleanField() ) ).filter(show=True).distinct().values_list('id', flat=True) Is anyone now a good way to make such left join query? RawSql and raw() - I can't to use. -
I tried making a form of dynamic nature in django which change the number of fields in template as per user. screenshot of which is given below
I'm planning to make a dynamic forms in django which takes 3 basic fields one char type, one date type and one numeric integer value. I use basic django model forms and render method to save the form in daabase. But I'm unable to perform that operation in this dynamic form. Any type of help will be appreciated. -
How to convert JSON retrived from exist URL to view in REST Framework using Response
I want to receive JSON from specific URL display in View, Using Django Rest Framework. Combined view from CarViewSet and external json. You can see in my code that i want JSON from director_detail = requests.get('http://192.168.10.1/BASIC/GetEmployees/'+direct_id) combined with CarViewSet Here is my code View.py from django.shortcuts import render # Create your views here. from rest_framework import viewsets, filters from .models import getData from .serializers import CarSerializer import requests from rest_framework.response import Response class CarViewSet(viewsets.ModelViewSet): queryset = getData.objects.all() serializer_class = CarSerializer filter_backends = (filters.SearchFilter,) __basic_fields = ('plate_no',) search_fields = __basic_fields def list(self, request): queryset = getData.objects.all() serializer = CarSerializer(queryset, many=True) plateno = self.request.query_params.get('plate_no', None) if plateno is not None: queryset = queryset.filter(plate_no=plateno) serializer = CarSerializer(queryset, many=True) data = serializer.data empid= data[0]['empidlong'] requests.get('http://192.168.10.1/BASIC/GetEmployees/'+empid) direct_id =data[0]['director_emp_id'] director_detail = requests.get('http://192.168.10.1/BASIC/GetEmployees/'+direct_id) #director_detail.json() return Response(data,director_detail.json()) Thank in advance.