Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to incorporate chat feature in django app [closed]
I have a django app for university alumni where they can make accounts. I want to incorporate chat functionality in it so the registered users can chat with each other just like facebook. Any ideas how I can do this. Should I learn django channels or use some third-party library? It is urgent. -
How to show extra dynamic field along with all model fields inside StackedInline Django
I want to display a dynamic link inside StackedInline admin class. How can I do this if the dynamic field is not part of the model. This is my code - class HistoryInline(admin.StackedInline): verbose_name_plural = 'History' model = Import fields = ('link',) extra = 0 readonly_fields = ['link'] def link(self, obj): url = ... return mark_safe("<a href='%s'>click here</a>" % url) class CatalogAdmin(admin.ModelAdmin): list_display = ('__str__', 'created_at', 'updated_at') inlines = [ImportInline, HistoryInline] exclude = ('app') I tried adding the function name inside fields but it didn't work. Also tried list_display but it seems to be not available for StackedInline How can I make it show me all the model fields as well as the extra dynamic link ? -
How to optimize django-rest-framework serializers with multiple queryset at SerializerMethodField()
I am new to django-rest-framework, and I have a project where I have to optimize the response time of an existing API endpoint. Using django-debug-toolbar, found some ways to use prefetch_related() to lessen the SQL queries. The problem is I found that the design of the serializer is to have multiple SerializerMethodField to get its statistics values and using prefetch_related only works on all() but on the second serializer method field with filter() is still being queried for every Class loop. You may see sample code below(this is not the specific code but something like this). serializer.py: class ClassStatisticsSerializer(ModelBaseSerializer): total_sessions = serializers.SerializerMethodField() activity_count = serializers.SerializerMethodField() def get_total_sessions(self, instance): sessions = instance.classactivity_set.all() date = self.context.get('date') if date: sessions = sessions.filter(date=date) if len(sessions) == 0: return None return sessions.count() def get_activity_count(self, instance): activities = instance.classactivity_set.filter(is_present=False) date = self.context.get('date') if date: activities = activities.filter(date=date) if len(activities) == 0: return None return activities.count() class Meta: model = Class fields = ( 'id', 'batch', 'type, 'total_sessions' 'activity_count' ) views.py: class ClassStatisticsList(APIView): def get(self, request, *args, **kwargs): queryset = Class.objects.all().prefetch_related('classactivity_set') serializer = ClassStatisticsSerializer() return Response(serializer, status=status.HTTP_200_OK) In here, when I check the SQL queries on the django debug toolbar, get_total_sessions was being queried once on the … -
{{ self.article_title }} tag did not show up webapplications on wagtail
what I want I will build up one web application by wegtail like News distribution app. I made class on Blocks.py, inherited into models.py and coded on html to show them up. This class means to input article information like title and url and to list them up. although I coded html and it was recognzed, however it doesn't show up on display. error messages I've not got some error messages. pls see this photo, I coded {{ self }} and show them up. We can see article title and more information. In detail Project tree this is the constitution of my project. project tree coding #streams/blocks.py #python file #block model to input article info class ArticleIndexBlock(blocks.StructBlock): articles = blocks.ListBlock( blocks.StructBlock( [ ("article_image", ImageChooserBlock(required=True)), ("article_title", blocks.CharBlock(required=True, max_length=40)), ("article_text", blocks.TextBlock(required=True, max_length=200)), ("article_url", blocks.URLBlock(required=False)), ] ) ) class Meta: template = "streams/article_index_block.html" icon = "edit" label = "Article" #articles/models.py #python file #models inherited from Streams/blocks.py class ArticleIndexPage(Page): template = "articles/article_index.html" content = StreamField( [ ("article_index_block", blocks.ArticleIndexBlock()), ], null=True, blank=True, ) content_panels = Page.content_panels + [ StreamFieldPanel("content"), ] def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) context["posts"] = ArticleIndexPage.objects.live().public() return context class Meta: verbose_name = "Article index Page" verbose_name_plural = "Article … -
Image not converting to base 64 in Django
I am trying to convert the HTML web pages to PDF I am using Xhtml2pdf library for this, this does not display images on the PDF therefore, its needed to convert the images in base 64 which can be displayed on the PDF, I have wrote the base 64 and applying the my custom filter on the image and its not converting it in the base 64 because image is not visible in the generated PDF. What am I doing wrong following is my code: view.py class Instagram_Report_View(TemplateView): template_name = "Target_Management_System/InstagramPerson_Target_Report.html" def get(self, request, *args, **kwargs): object_gtr_id = kwargs['object_gtr_id'] profile = acq.get_data_response_object_by_gtr_id(ObjectId(object_gtr_id)) print(profile.to_mongo()) #return render(request, 'Reports_Management_Unit/pdf_file.html',{'profile':profile}) pdf=render_to_pdf('Reports_Management_Unit/pdf_file.html') return pdf custom_filter.py (in this file the code for image to base 64 is written) from django import template import base64 from io import StringIO import urllib.request import requests register=template.Library() @register.filter def convert_to_base64(url): return base64.b64encode(requests.get(url).content) pdf_file.html {% load staticfiles %} {% load custom_filter %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <img src="{% static 'Reports_Management_Unit/img/profile_pic.jpg' | convert_to_base64 %}"> </body> </html> -
During fullcalendar update, invalid date is taken
This is my add_event. def add_event(request): title = request.GET.get("title", None) start = request.GET.get("start", None) end = request.GET.get("end", None) event = Events(title=str(title), start=start, end=end) event.save() data = {} return JsonResponse(data) Date is taken like this 2020-08-07T15:00:00 2020-08-07T16:00:00 However, when data wants to update, it says invalid date when I try to print the updated start date and end date. def update(request): start_date = request.GET.get("start", None) end_date = request.GET.get("end", None) title = request.GET.get("title", None) id = request.GET.get("id", None) event = Events.objects.get(id=id) print (start_date) print (end_date) data = {} return JsonResponse(data) I can't update fullcalendar currently due to formatting problem. Does anyone has any idea why the update doesn't work properly? my html looks like this <script> $(document).ready(function () { $('#calendar').fullCalendar({ height: 550, lang: "ja", header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, // timeZone: 'Asia/Tokyo', navLinks: true, timeFormat: 'HH:mm', events: [ {% for event in events %} { title: "{{ event.title}}", start: '{{ event.start|date:"Y-m-d\TH:i:s\Z" }}', end: '{{ event.end|date:"Y-m-d\TH:i:s\Z" }}', id: "{{ event.id}}", allDay: "{{ event.allDay}}", }, {% endfor %} ], displayEventTime: true, displayEventEnd: { month: true, basicWeek: true, "default": true }, selectable: true, selectHelper: true, select: function(start, end, resource) { // 日付選択された際のイベント // ダイアログタイトル設定 $("#dialogTitle").text("スケジュール登録"); // タイトル初期化 $("#inputTitle").val(""); // 備考初期化 … -
Comparing choice field from model in django template
models.py class Skill(models.Model): title_choice = [ ('LANGUAGE', 'Language'), ('FRAMEWORK', 'Framework') ] title = models.CharField(max_length=15, choices=title_choice, default='LANGUAGE') name = models.CharField(max_length=50) And the template(when compare with title) is <h2 class="mb-5">Skills</h2> {% for item in Skill %} {% if item.title == "LANGUAGE" %} <h3 class="mb-0">Programming Languages</h3> <ul class="subheading mb-3"> <li class="list-inline-item">{{ item.name }}</li> </ul> {% elif item.title == "FRAMEWORK" %} <div class="subheading mb-3">Frameworks</div> <ul class="list-inline dev-icons"> <li class="list-inline-item">{{ item.name }}</li> </ul> {% endif %} {% endfor %} OUTPUT: output when I compare with title When I try to compare the title from my model it doesn't show any data But when I compare the "name" with the database value it shows the correct output. template(when I compare with name) <h2 class="mb-5">Skills</h2> {% for item in Skill %} {% if item.name == "Python" %} <h3 class="mb-0">Programming Languages</h3> <ul class="subheading mb-3"> <li class="list-inline-item">{{ item.name }}</li> </ul> {% elif item.name == "React" %} <h3 class="mb-0">Frameworks</h3> <ul class="subheading mb-3"> <li class="list-inline-item">{{ item.name }}</li> </ul> {% endif %} {% endfor %} OUTPUT:when I compare with name I want to compare the value with title and show the results -
If there are no Posts displayed, how can I put a message?
In this situation I'm creating a blog, and in this blog I'm creating a "My Posts" page, and the thing is that if a user hasn't created a post, I want it to say the message "You have not written any posts yet", I'm having problems with the logic in the html, I was trying to use {% if post %}, but it's not working, here's the code: my_posts.html {% extends "app1/base.html" %} {% block body_block %} <div class="container"> <h1>Post</h1> {% for post in object_list %} {% if user.is_authenticated %} {% if user.id == post.author.id %} {% if post %} <li><a href="{% url 'app1:article-detail' post.pk %}">{{post.title}}</a> - {{post.author}} - <small>{{post.post_date}}</small> - <small> category : <a href="{% url 'app1:category' post.category|slugify %}">{{post.category}}</a> - </small> <small><a href="{% url 'app1:updatepost' post.pk %}">Edit</a></small><small> <a href="{% url 'app1:deletepost' post.pk %}">- Delete</a> </small></li> {{post.snippet}} {% else %} <h1>You have not written any posts yet!</h1> {% endif %} {% endif %} {% endif %} {% endfor %} </div> {% endblock %} views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth import authenticate, login, logout from django.urls import reverse, reverse_lazy from .forms import PostForm, PostUpdateForm from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category from django.http … -
Deploy Django app and React app on same domain?
I'm trying to host django website and react frontend on same domain. for example my django app server is serving all the data on this endpoint. abc.com/api/v1/...... Now I want to host react app on abc.com so that my react app should be available on aba.com. Here I'm using nginx. -
Django select_related field alters filter result
I have the following Django ORM model. Video has a FK to Person, and Person has PK to Position. class Video(models.Model): title = models.CharField(max_length=35) url = models.URLField() person = models.ForeignKey('Person', on_delete=models.SET_DEFAULT, default=1, null=False, blank=False) class Person(models.Model): firstName = models.CharField(max_length=100, null=False) lastName = models.CharField(max_length=100) linkedIn = models.URLField(blank=True) position = models.ForeignKey('Position', on_delete=models.SET_DEFAULT, default=1) picture = models.FileField(upload_to=getFilePath) class Position(models.Model): title = models.CharField(max_length=100, null=False, blank=False) company = models.ForeignKey('Company', on_delete=models.SET_DEFAULT, default=1, null=False) location = models.ForeignKey('Location', on_delete=models.SET_DEFAULT, default=1, null=False) If I query without select_related, I got the following: (Pdb) videoModel.objects.filter(Q(**{'position__department':''})) <QuerySet [<Video: titleGeneral @ General @ companyA Fulltime Fulltime>]> If I add select_related, it returns null. (Pdb) videoModel.objects.filter(Q(**{'position__department':''})).select_related('person__position') <QuerySet []> The person and position PK are all set correctly in this Video object. (Pdb) videoModel.objects.filter(Q(**{'position__department':''}))[0].natural_key() {'title': 'titleGeneral', 'url': 'urlGeneral', 'person': {'firstName': 'fnA', 'lastName': 'lnA', 'linkedIn': 'lkinA', 'position': 'titleA @ companyA', 'picture': ''}} I am using Django 2.2.13 with Djongo/Mongodb backend. -
How to execute query two many to many field in Django?
#I am new in python web framework Django. #models.py class User(AbstractUser): is_employeer = models.BooleanField(default=False) is_jobseeker = models.BooleanField(default=False) class allskill(models.Model): skills = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.skills def get_absolute_url(self): return reverse('employee:post_job') class jobseeker(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) phone_number = models.CharField(max_length=20) location = models.CharField(max_length=100) gender = models.CharField(max_length=20, choices=GENDER_CHOICE, default=GENDER_MALE) email = models.EmailField(default='ajay@gmail.com') jobseeker_skill = models.ManyToManyField(allskill) def __str__(self): return self.user.username class Employeer(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) company_name = models.CharField(max_length=50, default='company name') company_tel = models.CharField(max_length=20, default='01-56559565') phone_number = models.CharField(max_length=20) location = models.CharField(max_length=100) company_website = models.URLField(default="company.com") company_email = models.EmailField(default='company@gmail.com') conpany_type = models.CharField(max_length=200, choices=COMPANY_TYPE, default=TE) def __str__(self): return self.user.username class Job_Post(models.Model): job_title = models.CharField(max_length=200) job_descreption = models.TextField() user = models.ForeignKey(User, on_delete = models.CASCADE) job_post_date = models.DateField(default=timezone.now) required_skill = models.ManyToManyField(allskill) time = models.CharField(max_length=200, choices=time, default=FT) def __str__(self): return f"{self.user.username}'s {self.job_title}" def get_absolute_url(self): return reverse('employee:job_list', kwargs={'username':self.user}) #views.py class joblist(ListView): model = Job_Post template_name = 'my_skill.html' context_object_name = 'jobsforjobseekerskill' def get_queryset(self): jobseeker = self.request.user.is_jobseeker jobseeker_skills = Job_Post.objects.filter(required_skill__pk__in = jobseeker.jobseeker_skill.values_list('pk', flat = True)) print(jobseeker_skills) return jobseeker_skills #got this error enter image description here question Is it good way to write a code in good way? How to after login as jobseeker, jobseeker can shows jobs only related their … -
Django Rest Framework present serializer fields in specific order
regarding DRF Serializers, I know that fields are returned as OrderedDict but I have below issue because of inheritance from other serializer class. class SerializerA(serializers.Serializer): id = serializers.CharField() name = serializers.CharField() class SerializerB(SerializerA): surname = serializers.CharField() age = serializers.IntegerField() So, serializer A will return things in below order. { "id": 1, "name": "Foo" } and serializer B will return this. { "id": 1, "name": "Foo", "surname: "Bar", "age": 15 } However, what I want is that to return Serializer B as written below (or a different order) { "name": "Foo", "surname: "Bar", "age": 15 "id": 1, } What do you think about best way to do this? -
How to make on_conflict_replace work in Django batch_create?
I'm tring to batch_insert db data with bulk_create with Django. And the field account and month are unique togather. # db table class MSpendForMonth(models.Model): created_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) system_value = models.DecimalField(max_digits=16, decimal_places=2) checked_value = models.DecimalField(max_digits=16, decimal_places=2, null=True) account = models.ForeignKey(MAccount, models.DO_NOTHING, related_query_name="account_month", related_name="account_month" ) month = models.IntegerField(blank=True, null=True) class Meta: db_table = 'spend_for_month' unique_together = (('account', 'month'),) The system_value sometimes changed, so I want to replace with a new value. And I try to use bulk_create to speed up my db operation. bulk_data = [] try: with transaction.atomic(): for spend_data in spend_month_date_sum_queryset: bulk_data.append( MSpendForMonth( account_id=spend_data["account_id"], month=month, system_value=spend_data["sum_value"], ) ) MSpendForMonth.objects.bulk_create(bulk_data, ignore_conflicts=True ) # MSpendForMonth.objects.bulk_update(bulk_data, fields="system_value") except: import traceback as tb tb.print_exc() My question is how can I bulk_create data and replace with new value of system_value if there is a conflict on unique key account-month. It should be something like insert_many().on_conflict_replace() -- peewee I think Thanks -
Extracting data with all fields from a postgresql database and creating a new model with some new fields in django
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '*****', 'USER': '******', 'PASSWORD': '*****', 'HOST': '******', 'PORT': '***', } } I am using a postgresql sql database hosted online .The thing is I want to create a new model with all common fields and some additional fields.Can anyone help me with how should i proceed?.Also im using django-mailbox to import the messages and attachments. -
Is it possible to serve a (dynamically generated) canvas as a png file with Django?
I know this is possible with Node.JS but for this project, I'm constrained to Python/Django. I have an endpoint that accepts parameters then adds elements to a div using js. My problem now is I want to turn that div into a png file and serve it as such. I.e. accessing the following link would just yield an image. https://myserver.com/generate.png?foo=true&bar=false Is this possible with Django/Python? If not, is there another way to achieve this result similarly such as making a GET request to this end point then converting the div into a png? -
How to pass a session variable in filters.py (Django-filters)?
I'm trying to filter my 'Choice Filter' according to employer_id which is a foreign key on my 'Application' model. The primary key is from my 'Employer' model. I need to somehow pass a session variable with the employer that is currently logged in - like request.session["current_employer"]. I have the required session that works perfectly in my views, but I just need to find a way to pass it through here to - filters.py (for my select field). I'd appreciate any help. My code at the moment: class ApplicationFilter(django_filters.FilterSet): class Meta: model = Application fields = [ "job_title", ] job_title = django_filters.ChoiceFilter( widget=forms.Select(attrs={'class': 'form-control'}), choices=(list(Application.objects.values_list('job_title', 'job_title')))) I am trying to get something like this. class ApplicationFilter(django_filters.FilterSet): class Meta: model = Application fields = [ "job_title", ] job_title = django_filters.ChoiceFilter( widget=forms.Select(attrs={'class': 'form-control'}), choices=(list(Application.objects.values_list('job_title', 'job_title').filter(employer_id=???)))) -
how to print data on webpage by their district name and active, confirmed etc data
I am using Below Api: https://api.covid19india.org/v2/state_district_wise.json i am using django framework i wanted to print data shown below, [ "state": "Gujarat", "statecode": "GJ", "districtData": [{"district": "Other State", "notes": "", "active": 35, "confirmed": 119, "deceased": 1, "recovered": 83, "delta": {"confirmed": 0, "deceased": 0, "recovered": 0}}] ] -
django media files are not loading with nginx
I have this configuration in nginx for my django application. But, my media files not working. server { listen 8000; server_name 104.155.134.205; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/fractaluser/taswira; } location /media/ { root /home/fractaluser/taswira; } location / { include proxy_params; proxy_pass http://unix:/home/fractaluser/taswira/taswira.sock; } } fractaluser@taswira-instance-1:~/taswira$ ls README.md dataset mail-template.html member profiling-requirements.txt requirements.txt scheduler.py taswira.sock amchart.notes env manage.py pdfs registration.html reset.html settings test.py approved.html invite.html media profiling rejected.html rough.py subscribe.html user fractaluser@taswira-instance-1:~/taswira$ My media folder is inside in my root directory. It was working earlier but, after adding domain name to api.taswira.ai the media files are not loading. In nginx it says not found. Please have a look -
Equvalent code for "transaction.commit_unless_managed()" which was removed from django 1.8
I have the script file which was using "transaction.commit_unless_managed()" code. Now it's not running because this module has removed from Django 1.8. is there any option to fix it? Thanks in advance! -
Django, keep both global and local STATIC folders
I'm quite new in Django, coming from PHP and node mostly. By default, I understand that every app needs to have its own static folder, which is ok for me but I also need to have a global static folder to serve resources that are common to all apps. The problem is if I add to settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "staticfiles"), ] I achieve the result of having a common global folder, but then the app-level static folders do not work anymore. Is there a way to keep both approaches? Thanks -
Track Applications and Website usage in python [closed]
I have a code to track Windows app usage using uiautomation and win32gui. I want to add this feature for my users in a Django web app. How can I add this offline feature in Django? -
On a django site I ma getting socket cluster error
Not Found: /socketcluster/ [06/Aug/2020 21:45:44] "GET /socketcluster/ HTTP/1.1" 404 3181 this happens every 61 secounds while I am running the django webserver, using "python3 manage.py runserver". I am very new to web development and have no clue what this is or means, any help is appreciated. P.S. Do I need a db to handle requests for the web server -
AssertionError occurs when posting using django rest framework
AssertionError occurs when posting using django rest framework The process before an error occurs is this I set the url pattern, view and serializer class from django.urls import include, path from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register('post' , views.PostViewSet) # print("router.urls : " , router.urls) urlpatterns = [ path('public/' , views.PublicPostListAPIView.as_view()), path('', include(router.urls)), ] view from rest_framework import generics from rest_framework.viewsets import ModelViewSet from .serializers import PostSerializer from .models import Post class PublicPostListAPIView(generics.ListAPIView): queryset = Post.objects.filter(is_public=True) serializer_class = PostSerializer class PostViewSet(ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer serializers.py from django.contrib.auth import get_user_model from rest_framework import serializers from rest_framework.serializers import ModelSerializer from instagram.models import Post class AuthorSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ['username','email'] class PostSerializer(ModelSerializer): author = AuthorSerializer() class Meta: model = Post fields = [ 'pk', 'author', 'message', 'created_at', 'updated_at', 'is_public', ] Request to the address below http://127.0.0.1:8000/post/ 3.posting 4.error occured like below thanks for let me know how to fix it -
Uncaught TypeError: $.ajax is not a function. Error even after not using the slim version
I'm trying to make a dynamic dropdown menu and I'm getting this error in console. Uncaught TypeError: $.ajax is not a function at HTMLSelectElement.<anonymous> ((index):148) at HTMLSelectElement.dispatch (jquery-3.4.1.min.js:2) at HTMLSelectElement.v.handle (jquery-3.4.1.min.js:2) I'm following a page to make this dropdown and this is the link. views.py from django.shortcuts import render from . import forms from django.contrib.auth import authenticate,login,logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_protect from django.forms import modelformset_factory import requests import urllib.parse from apply_main.models import * def apply(request): def getLonLat(subdistrict,district,state): address = str(subdistrict)+", "+str(district)+", "+str(state) url = 'https://nominatim.openstreetmap.org/search/' + urllib.parse.quote(address) +'?format=json' response = requests.get(url).json() return response[0]["lat"],response[0]["lon"] form = forms.ApplyForm() if request.method == 'POST': form = forms.ApplyForm(request.POST) if form.is_valid(): application = form.save(commit=False) # subdistrict = application.cleaned_data.get("subdistrict_name") # district = application.cleaned_data.get("district_name") # state = application.cleaned_data.get("state_name") # (application.lat,application.lon) = getLonLat(subdistrict,district,state) application.save() return HttpResponseRedirect(reverse('apply_main:apply')) context = { 'form':form, } return render(request, 'apply_main/apply_form.html', context) def load_districts(request): state_id = request.GET.get('state') print(state_id,"\n"*5) districts = District.objects.filter(state_id=state_id).order_by('name') return render(request, 'apply_main/dist_dropdown_list_options.html', {'districts': districts}) def load_subdistricts(request): district_id = request.GET.get('district') subdistricts = Subdistrict.objects.filter(district_id=district_id).order_by('name') return render(request, 'apply_main/subdist_dropdown_list_options.html', {'subdistricts': subdistricts}) model.py from django.db import models from django.contrib.auth.models import User class State(models.Model): name = models.CharField(max_length=64) def __str__(self): return self.name class District(models.Model): name = models.CharField(max_length=64) state … -
Django override save method: to return super().save() or not to return?
I want to override model save method, but I've seen 2 types of codes: 1. def save(self): # some code return super().save() def save(self): #some code super().save() When would we use return when without return?