Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin search bar based on dropdown attribute
I am trying to implement the search bar in Django admin panel to search in Django admin table. The search bar should have a select attribute drop-down in which I can select an attribute and search for that attribute in my table. I am new to this, Is there any pre-defined library or function I can use in DRF. Please help -
Django ImageField - resize and save as new
I want to resize an ImageField before saving the model and save the resized image to a new field. I use S3 storage. This is a method that I use: def _set_resized_image(self): width, height = SiteSettings.get_solo().get_image_size() a = self.top_image_backup.read() filename = self.top_image_backup.name + 'resized' img_to_resize = Image.frombytes('L',self.top_image_backup.size,a) img_resized = img_to_resize.resize([width,height]) self.top_image_backup_resized.save(filename, img_resized, save=True) Which raises Size must be a tuple obviously because the size is not a couple. But I'm not sure if frombytes is a best way to do that. Do you know how to make it work? -
ConnectionRefusedError at /accounts/register/ when i try to resgister user
folks. i face this error when try to registrate user in my web site. i am beginner. also i do not receive activation email. please see below code. Do you face this issue? How can i solve it? i tried to use different methods, but nothing helped. in my utilities.py in my app from django.template.loader import render_to_string from django.core.signing import Signer from bboard.settings import ALLOWED_HOSTS signer = Signer() def send_activation_notification(user): if ALLOWED_HOSTS: host = 'http://' + ALLOWED_HOSTS[0] else: host = 'http://localhost:8000' context = {'user':user, 'host':host, 'sign':signer.sign(user.username)} subject = render_to_string('email/activation_letter_subject.txt', context) body_text = render_to_string('email/activation_letter_body.txt', context) user.email_user(subject, body_text) in views.py def user_activate(request, sign): try: username = signer.unsign(sign) except BadSignature: return render(request, 'main/bad_signature.html') user = get_object_or_404(AdvUser, username=username) if user.is_activated: template = 'main/user_is_activated.html' else: template = 'main/activation_done.html' user.is_active = True user.is_activated = True user.save() return render(request, template) in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'localhost' EMAIL_PORT = 25 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False DEFAULT_FROM_EMAIL = 'webmaster@localhost' ALLOWED_HOSTS = [ '127.0.0.1', ] if i need to provide anything else, please let me know. -
Is the DRF ModelSerializer faster or slower than the standard Serializer?
At work we tend to stay away from using the ModelSerializer in the Django Rest Framework. From what I have heard it is said to be faster in some respects. Is this the case? And what are the advantages of using the standard serializer instead of the ModelSerializer? -
OperationalError djago firstore login
OperationalError at /login/ attempt to write a readonly database Request Method: POST Request URL: example.com/login/ Django Version: 3.0.8 Exception Type: OperationalError Exception Value: attempt to write a readonly database -
How to return errors from post request in django CBV.I want to render errors to html page . it is possible?
class LoginView(View): def get(self,request): return render(request,'new_login.html',{}) def post(self,request): email = request.POST.get('username') password = request.POST.get('password') user = authenticate(email=email, password=password) if user is not None: login(request,user) return redirect('/') This is my login view class . I write my custom backend and using email insted of username.if user is login then he can redirect t odashboard but im not able to handle errors.please help me. I want to render errors to html page.ex.if email/password is wrong error,then how can i dislpay these errors on html page -
Cumulative (running) sum of field Django and MySQL
class Tip(models.Model): prediction = models.ForeignKey(Prediction, on_delete=models.CASCADE) pl = models.DecimalField(decimal_places=3, max_digits=5, default=None, blank=True, null=True) class Prediction(models.Model): fixture = models.ForeignKey(to=Fixture, on_delete=models.CASCADE, related_name="predictions", null=True, blank=True) class Fixture(models.Model): date = models.DateTimeField() I'm trying to get the cumulative sum of the field pl in the Tip-model, this grouped by the date-field in the model Fixture. I tried the following with the Django ORM: Tip.objects.values("prediction__fixture__date__date").annotate(cum_pl=Window(Sum('pl'), order_by=F('prediction__fixture__date__date'))).order_by("prediction__fixture__date__date") But this query returns the cumulative sum per Tip instead of per date. How can I achieve this per date instead? -
TemplateDoesNotExist at /groups/ .....groups/group_base.html; Template-loader postmortem
i keep getting this error: TemplateDoesNotExist at /groups/ groups/group_base.html Template-loader postmortem Error during template rendering it seems to have a problem at the first line of group_base.html: {% extends "groups/group_base.html" %} here is the group_base.html simplesocial/groups/templates/groups/group_base.html {% extends 'base.html' %} {% block content %} <div class="container"> <div class="row"> {% block pregroup %}{% endblock %} {% block group_content %}{% endblock %} {% block postgroup %}{% endblock %} </div> </div> {% endblock %} idk if the problem is n the urls.py: simplesocial/groups/templates/urls.py #GROUPS URL.PY from django.conf.urls import url from groups import views app_name = 'groups' urlpatterns = [ url(r'^$', views.ListGroups.as_view(), name='all'), url(r'^new/$', views.CreateGroup.as_view(), name='create'), url(r'^posts/in/(?P<slug>[-\w]+)/$', views.SingleGroup.as_view(), name='single'), url(r'^join/(?P<slug>[-\w]+)/$', views.JoinGroup.as_view(), name='join'), url(r'^leave/(?P<slug>[-\w]+)/$', views.LeaveGroup.as_view(), name='leave'), ] or if it's in views: simplesocial/groups/views.py: from django.shortcuts import render from django.contrib import messages # Create your views here. from django.contrib.auth.mixins import (LoginRequiredMixin, PermissionRequiredMixin) from django.core.urlresolvers import reverse from django.views import generic from django.shortcuts import get_object_or_404 from groups.models import Group, GroupMember # from groups import models class CreateGroup(LoginRequiredMixin, generic.CreateView): fields = ('name', 'description') #This is related to the Group model model = Group class SingleGroup(generic.DetailView): model = Group class ListGroups(generic.ListView): model = Group class JoinGroup(LoginRequiredMixin, generic.RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse('groups:single',kwargs={'slug':self.kwargs.get('slug')}) def get(self, request, *args, **kwargs): group … -
Django won't redirect after widget closes
I am building an e-commerce website with Django. As a payment system I use WayForPay. My html click calls a JS function which creates a widget for payment on the cart page. (See the script) var wayforpay = new Wayforpay(); function pay(productN, productP, productC, amount, orderR, orderD, merchantSig, merchantAcc, merchantDomNa, currency, language, serviceUrl) { var productN1 = JSON.parse(productN); var productP1 = JSON.parse(productP); var productC1 = JSON.parse(productC); var homePage = serviceUrl.replace('/cart', ''); var thankyouPage = homePage.concat('/thankyou'); wayforpay.run({ merchantAccount : merchantAcc, merchantDomainName : merchantDomNa, authorizationType : "SimpleSignature", merchantSignature : merchantSig, orderReference : orderR, orderDate : orderD, amount : amount, currency : currency, language : language, productName : productN1, productPrice : productP1, productCount : productC1, serviceUrl : serviceUrl, }, function (response) { // on success }, function (response) { // on declined }, function (response) { // on pending or in processing } ); } After the payment they inform my server with a POST request about the status of transaction. Here is a part of cart function in views.py file function that gets post request. if request.method == 'POST': result_request = dict(request.POST) result_str = list(result_request.keys())[0] result_dict = json.loads(result_str) try: token = result_dict['recToken'] merchantSignature = result_dict['merchantSignature'] email = result_dict['email'] phone = result_dict['phone'] billingName … -
Can i create my Django project in C drive?
I have only C drive and trying to create the django project in that Drive. Steps I followed: Creating virtual environment which has python 3.6.4 and django 3.1.2 1. py -m pip install --user virtualenv 2. py -m venv env 3. .\env\Scripts\activate (env) C:\Users\abhinavkumar\Desktop\Project>python Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> (env) C:\Users\abhinavkumar\Desktop\Project>pip freeze asgiref==3.2.10 Django==3.1.2 pytz==2020.1 sqlparse==0.3.1 Now creating Django project 1. (env) C:\Users\abhinav\Desktop 2. mkdir project 3. cd project 4. django-admin startproject projectname. Issue i am facing is - I can't see the file projectname inside project directory(which i created in desktop). On again trying to create the project with projectname . it is showing as : CommandError: 'C:\Users\abhinavkumar\Desktop\Project\projectname' already exists -
How can I show recent posts and recent comments first in my blogging website?
I have successfully made the models for both comments and posts and they are showing up properly on the webpage but I want the newest post to be showed up first and the same for comments as well. views.py: from django.shortcuts import render, HttpResponse, redirect from blog.models import Post, BlogComment from django.contrib import messages # Create your views here. def blogHome(request): allpost = Post.objects.all() context = {'allposts': allpost} return render(request, 'blog/blogHome.html', context) def blogPost(request, slug): post = Post.objects.filter(slug=slug).first() comments = BlogComment.objects.filter(post=post) context = {'post': post, 'comments': comments} return render(request, 'blog/blogPost.html', context) def postComment(request): if request.method == 'POST': comment = request.POST.get('comment') user = request.user postSno = request.POST.get("postSno") post = Post.objects.get(sno=postSno) comment = BlogComment(comment=comment, user=user, post=post) comment.save() messages.success(request, 'your comment has been added') return redirect(f"/blog/{post.slug}") this is the blog home page where I want the newest post to be displayed first blogHome.html: {% extends 'base.html' %} {% block title %} blogs {% endblock title %} {% block blogactive %}active {% endblock blogactive %} {% block body %} <h2 class="text-center my-4">blogs by everythingcs</h2> <div class="container"> {% for post in allposts %} <div class="col-md-6"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 … -
Django ckeditor: why my code area didn't display properly?
I'm trying to use django-ckeditor to show some code. But when I pass the content to the frontend, the code area didn't display properly. I've tried {{article.content | safe}}, but it doesn't work. in the admin page, the code area displayed correctly. in the frontend page, the code area didn't display, just showed the code content -
How to leverage Django's authentication system in Next.js?
I am developing a web application which has backend written in Django (using Django REST Framework for API) and frontend written in Next.js. I was considering implementing user authentication in the frontend using tools like PassportJS or Auth0. But, is there a way to leverage Django's own authentication system and avoid using third-party libraries like the ones mentioned above? -
How can execute query on external PostgreSQL in Django
I've already a Django project with many models. So How can I access to the same PostgreSQL database (The same as my first project does) and load it's models programmatically into the new Django project. I tried the below code to access to the Models: from django.apps import apps apps.get_model('platform.credential') But It threw the below exceptions: 161 message += " Did you mean '%s'?" % app_config.label 162 break --> 163 raise LookupError(message) 164 165 # This method is performance-critical at least for Django's test suite. LookupError: No installed app with label 'platform'. And that's because this project doesn't have the platform application. (But another one has!) Question: So Is there any opportunity to access the PostgreSQL Models as the Django does? BTW I know that I can use the psycopg2 package but I'm seeking an alternative solution. -
Django-filter search same foreign key multiple time
I have this in my model models.py class Exercise(models.Model): LEVEL_CHOICES = [ ('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ] level = models.CharField( blank=False, null=False, max_length=1, choices=LEVEL_CHOICES ) ... In my filters.py class ExerciseFilter(django_filters.FilterSet): class Meta: model = Execise fields = [ 'name', 'tag', 'level' ] And, finally in my template <form method="get"> <div class="row"> <div class="form-group col"> <span class="">Name<span> {% render_field filter.form.name class="form-control" %} </div> <div class="form-group col"> <span class="">Level<span> {% render_field filter.form.level class="form-control" %} </div> <div class="form-group col"> <span class="">Tags<span> {% render_field filter.form.tag class="form-control" %} </div> </div> </form> And it's working fine, I can filter my exercises, and see only exercises that are Level 1 for example. it gives me an URL like this ?name=&level=1&tag= But I would like to be able to get exercise that are level 1 and 2 for example, something like this: ?name=&level=1&level=2&tag= Can't figure out how to achieve this... -
How to retriew data of Employee model in users registration form in Django
I am creating an ERP app using Django. I have the Employee model which holds the master data of the employee. Employees must register themselves before using the app. I have created a page where the employee enters his employee number and if an employee exists in the database he/she can register himself/herself to the app. In my registration form, I want to retrieve the information of the employee form employee model whose Employee Number is checked. how to do that? how can I pass the information of the employee to the registration form? please help -
Django - how to automatically associate user while filling the form
So I'm trying to create blog app. In this I have created a model Post which holds user submissions. I have also created a form to get user input into Post. The problem I'm facing is that I'm not able to automatically associate logged in user's id referenced while getting the input. model.py : from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Post( models.Model): title = models.CharField( max_length = 225 ) title_tag = models.CharField(max_length=225) author = models.ForeignKey( User , on_delete=models.CASCADE ) body = models.TextField() to temporarily resolve this I have found an option which gets users to select from a list of usernames form.py from django import forms from .models import Post class PostForm ( forms.ModelForm): class Meta : model = Post fields = {'title','title_tag', 'author','body'} widgets = { 'title' : forms.TextInput( attrs= {'class' : 'form-control', 'placeholder':'please write yur title'}), 'title_tag' : forms.TextInput(attrs={'class': 'form-control'}), 'author': forms.Select(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), } view.py : class CreatePost ( CreateView): model = Post form_class = PostForm template_name= 'create_post.html' #fields = '__all__' def create_post(request) : form = Post (request.POST or None) context = { 'form_': form } if request.method == 'POST': if form.is_valid(): publish = form.save(commit=False) #publish.author = request.user … -
how to display script output to web page flask / django
hi i create server client model in which client keep checking if new device add or not and send response to server side its working fine what i want to display the response i get from client to server on web browser continuously using flask or Django. this is my client code from socket import * import subprocess, string, time host = 'localhost' # '127.0.0.1' can also be used port = 53000 sock = socket() # Connecting to socket sock.connect((host, port)) # Connect takes tuple of host and port def detect_device(previous): import socket username2 = socket.gethostname() ip=socket.gethostbyname(username2) total = subprocess.run('lsblk | grep disk | wc -l', shell=True, stdout=subprocess.PIPE).stdout time.sleep(3) # if conditon if new device add if total>previous: response = "Device Added in " + username2 + " " + ip sock.send(response.encode()) # if no new device add or remove elif total==previous: detect_device(previous) # if device remove else: response = "Device Removed in " + username2 + " " + ip sock.send(response.encode()) # Infinite loop to keep client running. while True: data = sock.recv(1024) if (data == b'Hi'): while True: detect_device(subprocess.run(' lsblk | grep disk | wc -l', shell=True , stdout=subprocess.PIPE).stdout) sock.close() this is my server side code from socket … -
Django DRF - How can i retrive an object if i have only the foreign keys but not the pk with RetriveAPIView
I have 2 models (one is a custom user model) with a relation ManyToMany through a third model. I have the pks of the two first models in the client side and i need to retrive the relationship model object with a RetriveAPIView. How can i do it? Here is the code i got: models.py class Patient(models.Model): rut = models.CharField(max_length=50) userAccount = models.ManyToManyField('accounts.UserAccount', through='therapy.Therapy') class Therapy(models.Model): patient= models.ForeignKey(Patient, on_delete=models.CASCADE) userAccount = models.ForeignKey(UserAccount, on_delete=models.CASCADE) isActive = models.BooleanField(default=True) views.py class UpdateRetriveTherapyView(RetrieveUpdateAPIView): queryset = Therapy.objects.all() serializer_class = TherapySerializer urls.py (project urls) urlpatterns = [ path('api/patient/', include('apps.patient.urls')), path('api/therapy/', include('apps.therapy.urls')), path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), ] urlpatterns += [ re_path(r'^.*', TemplateView.as_view(template_name='index.html')) ] urlpatterns += [ path('api-auth/', include('rest_framework.urls')) ] therapy.urls.py (the relationship model urls) urlpatterns = [ path('<int:pk>', UpdateTerapiaView.as_view()), ] may be there is a way to pass fk as a parameter in the url but idk. -
Bootstrap tab - how to refer to a seperate url template
I trying make a tab shows the active tab when clicked which I have successfully done. I want to link the content of another html template when the tab is clicked, but when I do so the tab "function" stopped working. In my main URL I have the following code: <ul id="myTab" class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="{%url 'Safety' %}">Safety</a></li> <li class=""><a data-toggle="tab" href="{%url 'Quality' %}">Quality</a></li> </ul> I have also tried to added the following: <div id="myTabContent" class="tab-content"> <div class="tab-pane fade active in" id="home"> <a href="{%url 'Safety' %}"> </div> </div> But it does not seem to work. Thanks in advanced -
How to create ach nacha template file in python
i am looking for correct lib to fulfil this requirement. One lib is available on git is nacha3 but i am not sure this correct one?. -
How to post content of of Draftjs to Database
I am working on a project with reactjs as frontend and in the project I have articles and for the body of articles I am using Draftjs as editor to put text and pictures together and for this purpose I am using react-draft-wysiwyg package which it is working good at the frontend side, but I dont know How to save the result to the database. My backend is Django and django-rest-framework for creating rest api. Here is CreateArticle.js: import React, { useState, useEffect, useCallback } from 'react' import { useDispatch, useSelector } from 'react-redux' import { unwrapResult } from '@reduxjs/toolkit' import { useHistory } from "react-router-dom"; import { addNewArticle } from './managementSlice' import { selectUser } from '../authentications/authenticationsSlice' import './CreateArticle.scss'; import { selectAllSubjects, fetchSubjects } from '../subjects/subjectsSlice'; import { selectAllTags, fetchTags } from '../tags/tagsSlice'; import {EditorState, convertToRaw} from "draft-js"; import {Editor} from "react-draft-wysiwyg" import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'; export const CreateArticle = () => { const [title, setTitle] = useState('') const [photo, setPhoto] = useState('') const [slug, setSlug] = useState('') const [subjectId, setSubjectId] = useState(0) const [tags, setTags] = useState([]) const [addRequestStatus, setAddRequestStatus] = useState('idle') const user = useSelector(selectUser); const subjects = useSelector(selectAllSubjects) const allTags = useSelector(selectAllTags) const subjectStatus = useSelector((state) => state.subjects.status) … -
Django rest framework
my django rest framework serializer returns errors in JSON Object: { "username": [ "account with this username already exists." ], how can i make it to return errors in json like this { "username": "account with this username already exists.", } my serializer code: from rest_framework import serializers from account.models import Account class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = Account fields = ['username', 'email', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True} } def save(self): account = Account( username=self.validated_data['username'], email=self.validated_data['email'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match'}) account.set_password(password) account.save() return account -
How to check type of variable in Django template
Below is my sample code. I need to know the type of weather variable which may be List, Dictionary, or Tuple. Is there any easy way like we use type() in python? {% extends 'base.html' %} {% block title%} Home {% endblock %} {% block content %} <h3 class="text-center text-success">Weather Forecast!!</h3><hr> {{weather}} <hr> {% for w in weather%} {{w}}<br/> {% endfor%} {% endblock %} -
Django optional URL captured value
For following Django code: class PollMessageView(generics.ListAPIView): serializer_class = MessageSerializer lookup_url_kwarg = 'count' def get_queryset(self): count = self.kwargs.get(self.lookup_url_kwarg) queryset = Message.objects.all()[:count] return queryset urlpatterns = [ path('poll_message/<int:count>', PollMessageView.as_view(), name="poll_message"), ] How do I make the count parameter optional in the URL pattern? For example, if I visit /poll_message/ without a count, it would still call the PollMessageView (and I can set a default number for count if it's missing)?