Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change error response message of TokenObtainPairView?
TokenObtainPairView class is used for token based authentication with jwt token now i am getting error message as when i put wrong login detials for user { "detail" : "No active account found with the given credentials" } i want to change it like { "detail" : "email or password is incorrect!" } -
How to tag current page on navbar list?
I am using Django, so I have header.html that is included on every page. How can I change the header so it recognizes the active page and makes it selected. {% load static %} <header> <div id="header"> <div id="logo"> <div id="logo_text"> <!-- class="logo_colour", allows you to change the colour of the text --> <h1><a href="/home">Priimo<span class="logo_colour">Puit</span></a></h1> <h2>Hea puit!</h2> </div> </div> <div id="menubar"> <ul id="menu"> <!-- put class="selected" in the li tag for the selected page - to highlight which page you're on --> <li class="selected"><a href="/home">Esileht</a></li> <li><a href="/products">Tooted</a></li> <li><a href="/services">Teenused</a></li> <li><a href="/about">Meist</a></li> <li><a href="/contact">Kontakt</a></li> </ul> </div> </div> </header> -
raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'doc' in line csv_file =request.FILES['doc']
I really spent a lot of time trying to solve this problem. Here is my views.py def data_upload(request): template="Try.html" prompt ={} if request.method == "Get": return render (request, template, prompt) if request.method == 'POST': csv_file =request.FILES['doc'] print(csv_file.name) print(csv_file.size) if not csv_file.name.endwith('.csv'): message.error(request, 'this is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) the error is in the line csv_file =request.FILES['doc'] -
Unable to use logout function in django with react app
I want to logout user from django.auth from react component and I don't know how should i integrate my urls with react app. And i have no problem with login its working correctly. when i login from my login form it also logged in my django/admin, but when i logout from my website it does not log out from my admin panel. Api app urls.py from django.urls import path from backend.api.views import * app_name = 'backend' urlpatterns = [ path('booklist/', api_user_details, name='userdetails'), path('login/', login_auth , name='login'), path('signin/', Signin , name='Signin'), path('usercheck/', checkusername , name='usernamecheck'), path('update/', update , name='update'), path('logout/', logout_view , name='logout') ] Api Views.py from django.contrib.auth import logout def logout_view(request): logout(request) return redirect('login') React app component import React,{useContext} from 'react'; import './profile_name_block.css'; import profileimg from '../../../person.png'; import { UserContext } from '../../../contexts/UserContext'; // import login from '../../../icons/login.png' import logout from '../../../icons/login.png' import profile from '../../../icons/profile.png' import bookico from '../../../icons/books.png' import request from '../../../icons/request.png' const Profiled = () => { // eslint-disable-next-line const [user,setUser]=useContext(UserContext); const Logout = () => { setUser({ logged: false, User_details: {} }) localStorage.clear(); window.location.href='/api/logout'; } const expand = () => { var x = document.getElementById('profile_log'); console.log(x.style.display) if (x.style.display === 'none' || x.style.display === '') { x.style.display … -
Can't pull all static files from heroku using git pull heroku master
So I was using Django admin page from the Heroku server to add some data that includes static pictures, and when I wanted to pull that static pictures to my local project it shows the usual Already up-to-date. message. I have tried cloning the project but still don't get the files that I need. and yes the pictures are there because I can open it from the Django admin page. I know that I was supposed to work locally then push, but it was already done and I want to know is there any solution for this ? -
how to add order by date_created in a django loan history model
class LoanInfoStatusHistory(models.Model): """Model that saves a history of a loan.""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # pylint: disable=invalid-name loan = models.ForeignKey(Loan, on_delete=models.PROTECT) previous_status = models.CharField(choices=Loan.LOAN_STATUS, max_length=20) new_status = models.CharField(choices=Loan.LOAN_STATUS, max_length=20) update_date = models.DateTimeField(auto_now_add=True) def __str__(self): """ Unicode representation for a LoanInfoStatusHistory model. :return: string """ return '{}: {} - {}'.format(self.loan.id, self.previous_status, self.new_status) -
function detailed view is not redirecting to detailview.html page
i am trying to create a detailview in django.. when i am clicking in the listview items.. the url in browser is shoing id .. like http://localhost:8000/blog/2 but it is giving 404 page not found error.. please see.. views.py def detail_view(request, id=None): movie = get_object_or_404(BlogPost, id=id) context = {'BlogPost':BlogPost, } return render(request, 'blog/blogdetail.html', context) urls.py path('list', BlogList.as_view(), name='list'), path('(?P<id>\d+)',detail_view, name='detail') list.html <div class="post-body"> {% for p in post %} <a href="{{ p.id }}"><blockquote>{{p}}</br></br>{{p.Date}}</blockquote> </a> {% endfor %} the blogdetail.html page is in the same directory in which bloglist.html page is.. models.py class BlogPost(models.Model): title = models.CharField(max_length=500) writer = models.CharField(max_length=150,default='my dept') category =models.CharField(max_length=150) image = models.ImageField(upload_to='images') post = models.TextField(max_length=2000) Date = models.DateField( default=datetime.date.today) -
Click button in table and redirect to same page
I have a view: class ProductList(SingleTableView): model = Product template_name = "app/product_list.html" table_class = ProductTable where in every row there is a button that should perform function(): class ButtonColumn(tables2.Column): empty_values = list() def render(self, value, record): return mark_safe(f"""<a href="/link/{record.id}/"><button class="btn btn-info">link</button></a>""") this ButtonColumn provides a button and once it is clicked: path("link/<int:pk>", views.LinkView.as_view(), name="link"), And the corresponding view: class LinkView(TemplateView): model = Product template_name = "app/product_list.html" def get_success_url(self): return reverse_lazy('product-list') def get_context_data(self, **kwargs): context = super(LinkView, self).get_context_data(**kwargs) function[kwargs] # <------------------ context["table"] = Product.objects.all() return(context) My problem is with the Linkview - I want it to perform function with some URL transmitted paramters and return to the former page (app/product_list.html). How can I achieve this? -
How to call shared_task asynchronously
I have such celery-task from celery import shared_task @shared_task def send_to_sap(act_id): act = ActOfWithdrawal.objects.get(pk=act_id) if settings.SYNCHRONIZATION: response = requests.post( settings.PI.API_CREATE, json={} ) And I want to execute it in asynchronous mode from view, and I'm trying to do this like this from tasks import send_to_sap def send_to_sap(request, pk): # some logic... if serializer.is_valid(): serializer.save() send_to_sap.apply_async(kwargs={'act_id': pk}) return Response(status=status.HTTP_200_OK) -
CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed
I recently encountered this error. CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. I had Ubuntu 20x Django 3x Python 3.8 / venv here i am writing how i fixed the error It turns out that Django didn't see my gettext and I had to install it. sudo apt-get install gettext -
Passing context in django auth views
I have this in my django project: path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='password_change_done.html'), name='password_change_done'), path('password_change/', auth_views.PasswordChangeView.as_view(template_name='password_change.html'), name='password_change'), in these html pages for the above urls I have to pass some information too as context. So how do I pass context in such type of urls which have no custom view -
Making Django messages appear in a specific place on the page
I have a registration form, and I want my errors to appear under my submit button. How could I make that work? +i'd like to add custom classes to my messages. My forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row, Column class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] #override def __init__(self, *args, **kwargs): super(UserRegisterForm, self).__init__(*args, **kwargs) #Custom classok self.fields['username'].widget.attrs['class'] = 'input' self.fields['email'].widget.attrs['class'] = 'input' self.fields['password1'].widget.attrs['class'] = 'input' self.fields['password2'].widget.attrs['class'] = 'input' #Custom label self.fields['username'].label = "" self.fields['email'].label = "" self.fields['password1'].label = "" self.fields['password2'].label = "" #Custom placeholder self.fields['username'].widget.attrs['placeholder'] = 'Username' self.fields['email'].widget.attrs['placeholder'] = 'Email address' self.fields['password1'].widget.attrs['placeholder'] = 'Password' self.fields['password2'].widget.attrs['placeholder'] = 'Confirm Password' #Help text off for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None My views.py file: from django.shortcuts import render from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Your account has been created! You are now able to log in!') return redirect('landing-home') else: form = UserRegisterForm() return render(request, 'users/register.html',{'form':form}) I … -
Can a empty string be passed in the url in django?
I am working on a django project which have a posts page. I have its url as follows: path('posts/<str:sort>', views.posts, name='posts'), and this is what its view looks like: def posts(request,sort) b="" if b=="time": posts=Post.objects.all().order_by(b) else: posts=Post.objects.all() return render(request,posts.html,{'posts':posts}) Now what I want is that if there is nothing passed as sort in the url or the url is like : /posts/ I want to display all posts but if the parameter is 'time' then I want to order_by as in my view. But currently if nothing is passed in url for sort then I get the error that no path found the url. -
Want the Fill the Django ForeignKey in another Html page with different forms contain that key
I am making the CV page, I want to link my Skill, language etc class(table) to Main person table/class, But for that i need to submit skill table first because my person table contain foreign key for skills But as per CV form name & personal info comes first. Also i can put it in one page but i want to go to next page for each subinformation, so is it possible i can commit= false person.save, But python do not let me to pass variable from one class to another. models.py ''' from django.db import models from django.core.validators import MinLengthValidator from django.conf import settings import datetime class Workexperience(models.Model): work = models.TextField(null=True, blank=True, max_length=256, help_text='eg: Juniorengineer: at L&T ') def __str__(self): return self.work class Education(models.Model): school = models.TextField(max_length=200) college = models.TextField(null=True, blank=True,max_length=200) def __str__(self): return self.school class Skills(models.Model): skill = models.CharField( max_length=256, help_text='Add skills sperated by commas eg: programming, Matlab') def __str__(self): return self.skill class Languages(models.Model): language = models.CharField( max_length=256, help_text='Add language sperated by commas eg: English, Gujarati') enter code here def __str__(self): return self.language class Person(models.Model): name = models.CharField( max_length=100, help_text='Enter a name (e.g. Harry Virani)', validators=[MinLengthValidator(2, "It must be greater than 1 character")] ) picture = models.BinaryField(null=True, blank=True, … -
how to make a like wise button django
I have an Article model which has a votes IntegerField, now I want to make it so that when the user clicks it the votes go up by one and that I managed to make, however, how can I make so next time he clicks it goes down by one. views.py: @login_required def vote(request, article_id): article = get_object_or_404(Article, pk=article_id) vote, created = Vote.objects.get_or_create(article=article, user=request.user) if created: article.votes += 1 article.save() return JsonResponse(data = {"vote": "Voted! Thank you for the vote."}) return JsonResponse(data = {"vote": "You already voted for this article."}) I have a Vote model which has a user and article foreignkey. The button which "likes" article with ajax: <button id="vote" class="button">vote</button> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> var voted = false; $("#vote").click(function (e) { if (!voted) { e.preventDefault() var upvotes = $("#total_votes").html() voted = true; var updatedUpVotes = parseInt(upvotes) + 1 $("#total_votes").html(updatedUpVotes) $.ajax({ url: 'vote/', method: "GET", data: {}, success: function (data) { console.log(data) }, }) } }) </script> Now the other problem is that when the user refreshes the page when he clicks the like button it goes by 1 just in the UI and not in the database, How can I save it so when he comes to an article … -
Allow post request in Apache deployed Django 3.1
I need for my Django app to be able to receive unsolicited POST requests, without the CSRF token. This question has been asked before here, but the answer given, implementing a class based view with functions get and post has not helped me. This is my view class: class WebHooks(TemplateView): def get(self, request): return HttpResponse("get") def post(self, request): return HttpResponse("post") I also added the directive <Location "/"> AllowMethods GET POST OPTIONS </Location> to my httpd.conf for Apache and set the CSRF_USE_SESSION constant in Django's settings.py to False. Testing this with Postman keeps returning "get". The server access log reads POST /url HTTP/1.1" 403 3366. How do I enable POST requests? -
Cannot resolve keyword 'like_count' into field
I'm trying to get data from the model preoperty but i get this error: "Cannot resolve keyword 'like_count' into field. Choices are: comments, created_at, id, likes, text, title, updated_at, user, user_id" My Post model is: class Post(AutoTimeStamped): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="posts") title = models.CharField(max_length=260) text = models.TextField() def __str__(self): return f"Post {self.id}: {self.title}: created {self.created_at}" @property def comment_count(self): return self.comments.count() @property def like_count(self): return self.likes.count() My Post node is: class PostNode(DjangoObjectType): id = graphene.ID(source='pk', required=True) like_count = graphene.Int(source="like_count") comment_count = graphene.Int(source="comment_count") class Meta: model = Post interfaces = (graphene.relay.Node,) It works for my user model, but I'm getting this error when querying posts -
How to create a ModelForm field based on a RelatedManager?
I'm creating a multiple choice quiz with the following models.py: class Question(models.Model): question = models.CharField(max_length=200) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) correct = models.BooleanField(default=False) choice_text = models.CharField(max_length=200) This way, a question's choices can be accessed through its RelatedManager choice_set e.g. q.choice_set.all(). I don't know how to then create a Radio Input Form for each Question? I created the following forms.py: class QuestionForm(ModelForm): class Meta: model = Question fields = ['choices'] However, I'm not sure how I can create a field based on each question's choice_set and then have a radio input for each choice in each question's choice_set? I want the end result to be urls that end up like this: question/1, question/2, etc. with the Question title, radio inputs for the choices and next and previous buttons (where applicable). I have the following FormView and template: views.py class QuestionFormView(generic.FormView): form_class = QuestionForm model = Question template_name = 'quiz/question-form.html' question-form.html <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> -
How open uploaded file in django rest framework?
I try to write a library application on django rest framework. I have two models: File and Book: class File(models.Model): file = models.FileField(upload_to="books//%Y/%m/") class Book(models.Model): filename = models.CharField(max_length=100) title = models.CharField(max_length=200) author = models.CharField(max_length=100) year = models.IntegerField() path = models.TextField() isbn = models.CharField(max_length=100) tags = models.TextField(max_length=200) last_access = models.BinaryField() cover_image = models.BinaryField() upload_date = models.DateTimeField(auto_now=True, db_index=True) owner = models.ForeignKey('auth.User', related_name='uploaded_files', on_delete=models.CASCADE) size = models.IntegerField(default=0) def __str__(self): return self.author + ' - ' + self.title Serializator and view class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = "__all__" class FileViewSet(viewsets.ModelViewSet): queryset = File.objects.all() serializer_class = FileSerializer permission_classes = [permissions.IsAuthenticated] How can i open uploaded file in ModelViewSet? Or i must use a generic APIView to override put/post operation for my needs? -
Django Reversion - How to set_comment with Django Rest
I'm trying to save comment in table reversion_revision. However i still got empty value comment What i tried In ModelViewset class ReversionViewMixin(object): def dispatch(self, *args, **kwargs): with transaction.atomic(), reversion.create_revision(): response = super(ReversionViewMixin, self).dispatch(*args, **kwargs) reversion.set_user(self.request.user) reversion.set_comment('Hello') return response @permission_classes([CustomUserPermission]) @parser_classes([MultiPartParser, JSONParser]) class HistoryViewset(ReversionViewMixin, viewsets.ModelViewSet): queryset = Version.objects.all() serializer_class = VersionSerializer filter_backends = (filters.DjangoFilterBackend,) # if pagination page = none, it will return all page def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) if 'page' in request.query_params: page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Any Help, Pls :( Thanks in advance... -
Django Master/Detail
I am designing a master/detail solution for my app. I have searched for ever in the django docs, also here and elsewhere I could, so I guess the answer is not that obvious, despite being an answer many people look for - not only in django, but in every language, I think. Generally, in most cases, the master already exists: for example, the Django Docs illustrate the Book example, where we already have an Author and we want to add several Books for that Author. In my case, the parent is not yet present on the database think of a purchase order, for instance. I have thought to divide the process in two steps: the user would start to fill in the info for the master model (regular form) and then proceed to another view to add the lines (inline formset). But I don't think this is the best process at all - there are a lot of possible flaws in it. I also thought about creating a temporary parent object in a different table and only having a definitive master when the children are finally created. But it still doesn't look clean. Because of that, for my app it … -
CreateView with OneToOneField relation in one View
I'm a Django beginner and try to implement a class based CreateView with two forms and an OneToOne relation but have no glue how to do this in one view. For example: the following is given: #models.py # some imports.. class RedItem(models.Model): name = models.Charfield(max_length=255) storage = models.OneToOneField("Storage", on_delete=models.CASCADE) class BlueItem(models.Model): name = models.Charfield(max_length=255) storage = models.OneToOneField("Storage", on_delete=models.CASCADE) class Storage(models.Model): shelf = models.Charfield(max_length=255) room = models.Charfield(max_length=255) ...the View: #views.py from django.views.generic.edit import CreateView from .models import RedItem, BlueItem, Storage # some other imports.. class RedItemCreate(CreateView): model = RedItem fields = ['name'] template_name_suffix = "_form" and a Form: <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> The question is now how can a user fill in both (e.g. RedItem + Storage) in one batch? Thanks in advance for any direction. -
Django Rest framework Model serialiser omit null from response
This question is based off another question I have a similar though somewhat different problem: in the original question the user wants to omit a null field from his json response: [ "meta": { "title": null, "name": "XYZ" } ] The one of the answers uses .to_representation() to filter out the title: from operator import itemgetter class MetaTagsSerializer(serializers.ModelSerializer): class Meta: model = MetaTags def to_representation(self, instance): ret = super().to_representation(instance) ret = OrderedDict(filter(itemgetter(1), ret.items())) return ret This works beautifully. The issue I am running into using this method is that I have cases where all my fields get filtered out, leaving me with an empty dictionary: [ {}, { "name":"XYZ" } ] I have tried modifying the method: from operator import itemgetter class MetaTagsSerializer(serializers.ModelSerializer): class Meta: model = MetaTags def to_representation(self, instance): ret = super().to_representation(instance) ret = OrderedDict(filter(itemgetter(1), ret.items())) if not bool(ret): return None return ret But that is also not what I'm looking for, since I get this: [ null, { "name":"XYZ" } ] So my question is: is there a way to filter out the empty dictionary/null completely? I tried passing allow_null=False to the ModelSerialiser but that also doesn't work. -
Django using Ajax for get data without refreshing page
n the last 48 hours. I create a view it works and it displays name correctly but I want to show that How long has it been since the data was sent. I want to do this with Ajax and table will be update without refreshing. I wrote something for that but I get an error. TypeError at / int() argument must be a string, a bytes-like object or a number, not 'NoneType' How can I use Ajax correctly, please help me views.py def get_48_hours(request): increment = int(request.GET.get('append_increment')) increment_to = increment + 10 time_48 = timezone.now() - timedelta(hours=48) results = NavigationRecord.objects.filter(datetime__gte=time_48).order_by('-datetime')[increment:increment_to] paginator = Paginator(results, 10) # Show 50 data per page page = request.GET.get('page') try: results = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. results = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. patients = paginator.page(paginator.num_pages) context = { 'results': results, } return render(request, 'navigation.html', context) models.py class Vehicle(models.Model): id = models.IntegerField(primary_key=True) plate = models.CharField(max_length=30) def __str__(self): return str(self.plate) class NavigationRecord(models.Model): id = models.IntegerField(primary_key=True) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) datetime = models.DateField(default=timezone.now) latitude = models.FloatField() longitude = models.FloatField() def __str__(self): return str(self.vehicle) class meta: abstract … -
How to send notifications to gmail from contact form using Django and pushbullet
I'm helping someone update a website that was built a few years ago using Django. On the site there is a contact form that a user fills out and the request is sent to the site admin. My friend wants to get notifications to their gmail account also when the contact form is submitted. The previous developer wrote a code that seems to attempt to do this with Pushbullet API. I'm not familiar with using Pushbullet so I'm trying to find out how this is supposed to work. If anyone is familiar with this way of sending notifications to gmail via the Pushbullet API please enlighten me a bit. I've included the code that is supposed to accomplish the goal. import logging import os from typing import List from django.core.mail import EmailMessage from pushbullet import PushBullet # todo Add mr tires api to .env pb = PushBullet(os.getenv("PUSHBULLET_API")) # Get an instance of a logger logger = logging.getLogger('mail_admins') class Notify: subject: str message: str from_: str = "none.anyname@gmail.com" to: List[str] = [ 'contactemail@gmail.com' 'example@tmomail.net', # 'example@txt.att.net', ] bcc: List[str] = [ # 'example@txt.att.net', 'contact@gmail.com' ] reply_to: List[str] = ['contactemail@gmail.com'] @staticmethod def send(subject: str, message=''): try: logger.info(f"Sending email:\nSubject: {subject}\nMessage:{message}...") email = EmailMessage(subject, …