Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django auto logged out user on inactivity still display as active user
I'm working on a project using Python(2.7) and Django(1.11) in which I need to display only logged in users for a specific function. I have achieved to log out the user by the following settings in settings.py: SESSION_COOKIE_AGE = 180 SESSION_SAVE_EVERY_REQUEST = True LOGOUT_REDIRECT_URL = 'login' and I need to get active users of type driver which is I'm getting as: def get_all_logged_in_users(): # Query all non-expired sessions # use timezone.now() instead of datetime.now() in latest versions of Django sessions = Session.objects.filter(expire_date__gte=timezone.now()) uid_list = [] # Build a list of user ids from that query for session in sessions: data = session.get_decoded() print(data) uid_list.append(data.get('user_id', None)) # Query all logged in users based on id list return user_table.objects.filter(id__in=uid_list, user_type='driver') It was working till a few days ago but suddenly stopped working anymore. When I refresh the page after the time SESSION_COOKIE_AGE passed it redirected to the login page which is perfect but in the database, the is_active for that user is still True and it's still displaying in the get_all_logged_in_users. How can I solve this issue? -
How to set a sign to mark activated users in admin panel
When people register in my website admin gets email notification and admin activates the user. But now, I have many people are registering, that's why I need a field where activated users has a tick or green color. I have no idea how to do that. Anyone has any idea? -
Can't register an active user for my tests
I'm trying to write some tests with django-rest-auth and the following code: def create_user(username='john', email='johndoe@test.com', password='doe'): user = get_user_model().objects.create( username=username, email=email, is_active=False) if password: user.set_password(password) else: user.set_unusable_password() user.save() return user def test_jwt_auth(): username = 'user' email = 'user@foo.com' password = 'pass' create_user(username=username, email=email, password=password) resp = client.post(REST_LOGIN_URL, {'email': email, 'password': password}) assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST) The client.post work fine as long as I don't change/create the user with is_active=True. When I do I get the following error: Error Traceback (most recent call last): File "C:\Users\Ekami\Documents\workspace\NomadSpeed-Web\users\tests.py", line 64, in test_jwt_auth resp = self.client.post(REST_LOGIN_URL, {'email': email, 'password': password}) File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\test.py", line 300, in post path, data=data, format=format, content_type=content_type, **extra) File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\test.py", line 213, in post return self.generic('POST', path, data, content_type, **extra) File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\test.py", line 238, in generic method, path, data, content_type, secure, **extra) File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\test\client.py", line 422, in generic return self.request(**r) File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\test.py", line 289, in request return super(APIClient, self).request(**kwargs) File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\rest_framework\test.py", line 241, in request request = super(APIRequestFactory, self).request(**kwargs) File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\test\client.py", line 503, in request raise exc_value File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\ProgramData\Anaconda3\envs\nomad\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view … -
How to make a require object available whenever I type something in search bar in django?
I made a search bar but whenever I write something in it, the link shows http://127.0.0.1:8000/?srh=something and I am not understanding why the the specific picture with title is not showing. It is showing me all pics with title but I want only that pic with title which I write as a title in search bar. Which things to add in this code? index.html {% load static %} {% static 'images/fulls' as baseUrl %} {% static 'images/thumbs' as hiUrl %} <form class="new" method="GET" action=""> <input type="text" placeholder='Search..' name="srh" value="{{request.GET.srh}}"> <br> <button type="submit" class="btn btn-danger"> Search </button> </form> <div> {% for dest1 in target1 %} <div> <a href="{{baseUrl}}/{{dest1.img}}"> <img src="{{hiUrl}}/{{dest1.img}}" alt="" /> <h3>{{dest1.title}}</h3> </a> </div> {%endfor%} </div> <div> {% for dest2 in target2 %} <div> <a href="{{baseUrl}}/{{dest2.img}}"> <img src="{{hiUrl}}/{{dest2.img}}" alt="" /> <h3>{{dest2.title}}</h3> </a> </div> {% endfor %} </div> views.py def index(request): query = request.GET.get('srh') if query: match = Destination.objects.filter(desc__icontains=query) target1 = a, b= [Destination() for __ in range(2)] a.img = 'Article.jpg' b.img = 'Micro Tasks.jpeg' a.title = 'Article Writing' b.title = 'Micro Tasks' target2 = c, d = [Destination() for __ in range(2)] c.img = 'Data Entry.jpg' d.img = 'Translation Jobs.jpg' c.title = 'Data Entry' d.title = 'Translation Jobs' context = … -
Displaying fixed ForeignKey fields inline in Django/Django-Admin
I have a model that looks like this: class Order(models.Model): # [...some scalar fields...] lens_right = models.ForeignKey(Lens, on_delete=models.CASCADE, related_name='lensright') lens_left = models.ForeignKey(Lens, on_delete=models.CASCADE, related_name='lensleft') with Lens being another model class with a couple of CharFields (and a backlink to the corresponding Order object since Django demanded it). So there are supposed to be always exactly two Lens objects per Order object. Now, in Django Admin, these Lens fields are treated like ordinary foreign key objects, i.e. I get a select dropdown that lets me choose an existing Lens object. However, what I really want is to enter the Lens objects' values directly in an inline form with text fields. A lot like a TabularInline or StackedInline admin model displays it, but inline as ordinary fields would be and accounting for the fact that there are exactly two Lens objects, never more and never less. How can I achieve this? And is this the most suitable design, or is there a better one in your opinion? Any other hints are welcome as well. Thanks. -
Django2/Python3 : Django raises a TypeError when sorting dict()
i am building an e-comerce website and i have to filter products by price, there are a lot of relations in place so i'll get straight to my point. i fetch the Queryset then create a dict with it. then i sort the dict by values using sorted() sorted() works perfectly and i get the output that i need. But if 2 products have the same price it raises a TypeError ( maybe because of 1>1 == False i think) : print(d) {<Product: Product 1>: Decimal('10.00'), <Product: Product 2>: Decimal('10.24'), <Product: Product 3>: Decimal('10.16'), <Product: Product 4>: Decimal('10.00')} sd = sorted((v, k) for (k, v) in d.items()) TypeError: '<' not supported between instances of 'Product' and 'Product' I have tried the same scenario with plain python and no errors are raised so i assumed, this is a Django related error. So, how can i counter this Error in my Except Block in my Django project ? -
How to you put a checkbox in a django.contrib.auth.forms UserCreationForm
I have multiple fields in my Django UserCreationForm including the already included username, password 1, and password 2. I have also added and email field. I am unable to add a checkbox. from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) #checkbox field should go here? class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] I want there to be a checkbox to declare if the user wants to register as a teacher or as a student. -
PostgreSQL Full Text Search Accuracy
Is there any way to improve the accuracy of Full Text Search on Postgres? I'm using it with Django and a simple search for invest doesn't return results with the word investor. I assume this is because the stemming algorithm is returning invest* and investor as two different stems. -
How can I fix TypeError: a bytes-like object is required, not 'str' on travis cause the test run fine on my local machine
Am setting up Travis for a Django project and I want to be able to get test coverage but am getting some error and Here's a link to my Travis build -
How to write your own throttle rate limit
I want to add features for limiting the number of password reset attempts. For example, Twitter limit the number of password reset attempts 5 times a day. -
Django multiple calendars
For my app, I have to manage a different calendar for each user. I found some django apps that provide calendar managing system but none that I found provided an option for multiple calendars. I will have to open a new calendar for each new user. I can might use one calendar and tag somehow each event for a user but I think there might be a better way to handle this. Separating the calendars will be easier to manage in my opinion. Doe's someone have a recommendation for an app that already does it or if not, a recommendation how to approach it? Thanks a lot, Itai -
Truncate text in the middle, Django Template Tag
Is there a native way to do truncatechars in the middle of a long text? Example of what I'm looking for: word = '123456789' {{ word|truncatechars_middle:4 }} displays: 12...89 -
Django TestCase multiple object with for foregin key
I am going through trouble writing a TestCase for the last few days and that is creating multiple objects and passing it related field to compare. At first see my tests.py file: from django.test import TestCase from library.models import Book, Author class TestSingleArticle(TestCase): def setUp(self): self.namelist = ['jhon', 'doe', 'trial', 'bill'] for name in self.namelist: self.author = Author.objects.create(name=name) self.book = Book.objects.create(author=author, title='book title', body='book body') def test_single_article_get(self): # i will compare here with assertEqual I have created 4 authors and now I want to create 4 books with that 4 author.. but I couldn't do it Here you go to see my models.py file: from django.db import models class Author(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author') title = models.CharField(max_length=200) body = models.TextField() def __str__ (self): return self.title I know how to compare with self.assertEqual My problem only creating multiple/4 book with that 4 author.. as you notice in the book model, the author is a foreign key.. I hope you got my issue... Can anyone help me in this case? -
How do I expose Wagtail search in a Django Graphene query?
Given the general structure: class Article(Page): body = RichTextField(...) search_fields = Page.search_fields + [index.SearchField('body')] class ArticleFilter(FilterSet): search = SearchFilter() class Meta: model = Article fields = ['slug'] class Query(ObjectType): articles = DjangoFilterConnectionField(ArticleNode, filterset_class=ArticleFilter) I thought to create a "SearchFilter" to expose the wagtail search functionality, since I ultimately want to perform full text search via graphql like so: query { articles (search: "some text in a page") { edges { nodes { slug } } } } "search" is not a field on the Django model which is why I created a custom field in the Django FilterSet. My thought was to do something like: class SearchFilter(CharFilter): def filter(self, qs, value): s = get_search_backend() return s.search(value, Article) # not sure how to get the model? The search returns a DatabaseSearchResults instance rather than a QuerySet so the endpoint fails. Obviously one way to get this to work would be something like: return qs.filter(pk__in=[r.pk for r in s.search(value, Article)]) however, I'm curious if there's a better pattern that's more efficient. Should the "search" be moved outside of the FilterSet and into the Query/Node/custom connection, and if so, how can I add an additional field to "articles" to see it as the … -
View variables not interpreted as variable
Some variables seem to not be interpreted as variables but as string I'm starting on Django and am following a tutorial in which I came across this piece of code : In template : <ul> {% for key, value in couleurs.items %} <li style="color:# {{ key }} ">{{ value }}</li> {% endfor %} </ul> I should add that in my code editor (VSC) the " "color:# {{ key }} " " part is in a different color then the rest In view : def rainbow(request): couleurs = { 'FF0000':'rouge', 'ED7F10':'orange', 'FFFF00':'jaune', '00FF00':'vert', '0000FF':'bleu', '4B0082':'indigo', '660099':'violet', } return render(request, 'blog/rainbow.html', locals()) The errors displayed are in the 3rd line of the template : _The error displayed when I hover my mouse over the # is "property value expected" _And the one for } is "at-rule or selector expected" The code should print the colors in color (ex : red in red etc...) Thanks in advance ! English not first language btw so sorry if I misspelled stuff -
In django user model , i want to add contact ,username and role fields
I have created AbstractBaseUser in my Models.py , and i am able to create email,password,first_name and Last_name. I want contact,username and Role as well in the same User Model. Can anyone help me? -
Displaying comments for questions only when they exist
I need to display messages on a Django template. Each message can have 0 to many comments. I need to display the comments for each message. However, if a message has no comments, then it is 'None' and I can't iterate over it. The problem is occurring in Django templates. #models.py class User(models.Model): firstName = models.CharField(max_length = 255) lastName = models.CharField(max_length = 255) email = models.CharField(max_length = 255) birthDate = models.DateField() password = models.CharField(max_length = 255) createdAt = models.DateTimeField(auto_now_add = True) updatedAt = models.DateTimeField(auto_now = True) objects = UserManager() class Message(models.Model): content = models.TextField() user = models.ForeignKey(User, related_name = "messages") createdAt = models.DateTimeField(auto_now_add = True) updatedAt = models.DateTimeField(auto_now = True) objects = UserManager() class Comment(models.Model): content = models.TextField() message = models.ForeignKey(Message, related_name = "comments", default = []) createdAt = models.DateTimeField(auto_now_add = True) updatedAt = models.DateTimeField(auto_now = True) objects = UserManager() #views.py #Main wall page #Renders wall.html def wall(request): wallDict = { "message" : Message.objects.all() } return render(request, "loginRegApp/wall.html", wallDict) #wall.html <!DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="utf-8"> </head> <body> <div class="container"> <a href="/logout">Log out</a> <form action="message/create" method="post"> {% csrf_token %} <h4>Post a message</h4> <textarea name="message"></textarea> <input type="submit" value="Post a message"> </form> {% for message in messages %} <div> <h6>{{message.user.firstName}} … -
Django Post Signal on some remote DB
I have two different projects Project1 settings default - project 1 database db2 - project 2 database project2 settings default - project 2 database What I did to use serializers, models of project 2, etc in project 1 . I copied the complete app from project 2 to project 1 and registered the model in settings.py and also removed the migrations folder so that any time I makemigrations in project 1 shell it does not create any migrations for project 2 apps in (project 1 and thus migrating wont add any models of project 2 in project 1 ). Now the problem I am facing is I have to use post_save signal on model of project 2 app that I imported in project 1. and get notified in project1 @receiver(post_save, sender=Project2Model) def project2model_save_hook(sender, instance, created, **kwargs): print(created) this will work only when this signal is present in project 2 but not in project 1. In project 1 this is never called when object is created in default db of project 2 or db2 of project 1 How should I proceed? -
Why doesn't js script work at django web-site?
I'm new in Django and JS. Trying to create HTML5 audioplayer with custom controls. When I start page nothing happens. Tested this mp3 with default player and everything is ok. So I think static settings is correct. Folders structure: -stream (the app) - ... - static - stream - audio - test.mp3 - scripts - player.js - templates - ... - index.html This is my index.html. The base template is almost empty. {% extends "base_generic.html" %} {% block content %} {% load static %} <script src="{% static "stream/scripts/player.js" %}" type="text/javascript"></script> <audio src="{% static "stream/audio/test.mp3" %}" type="audio/mpeg"> {% endblock %} And this is my player.js var aud = $('audio')[0]; aud.play(); I expect that when I open the page the music will start playing. -
How to solve the problem of attribute error in django?
I am trying to make the search bar work. Whenever I type something in views.py, it should be appeared and others shouldn't. I have written code which I will show but when I run the code, it gives me attribute error type object 'Destination' has no attribute 'filter'. How to solve this problem? index.html <form class="love" method="GET" action=""> <input type="text" placeholder='Search..' name="srh" value="{{request.GET.srh}}"> <br> <button type="submit" class="btn btn-danger"> Search </button> </form> views.py from django.shortcuts import render from . models import Destination from django.db.models import Q def index(request): query = request.GET.get('srh') if query: match = Destination.filter( Q(desc_icontains=query)).distinct() target1 = a, b= [Destination() for __ in range(2)] a.img = 'Article.jpg' b.img = 'Micro Tasks.jpeg' a.desc = 'Article Writing' b.desc = 'Micro Tasks' app url from . import views urlpatterns = [path('', views.index, name='index')] main url from django.contrib import admin from django.urls import path, include from firstapp.views import * urlpatterns = [ path('admin/', admin.site.urls), path('', include('firstapp.urls'))] -
I am new to django. How to resolve the csrf token missing or incorrect error? I have used render request in views
403 forbidden. CSRF token missing or incorrect. I have already tried from django.views.decorators.csrf import csrf_protect, it doesn't work. I have not used render_to_request either. -
Django-Rest-Framework: Make A PUT Request to API
So I want to make a put request to change the content of a message in my chat/messaging app. class MessageView(viewsets.ModelViewSet): http_method_names = ['get', 'post', 'put', 'delete', 'patch'] queryset = Message.objects.all() serializer_class = MessageSerializer filter_backends = ( django_filters.rest_framework.DjangoFilterBackend, rest_framework.filters.OrderingFilter, ) filter_fields = ['room'] class UserMessageView(MessageView): def get_queryset(self): return Message.objects.filter(canview__user=self.request.user) #get def get(self, request): hello_param = request.GET["helloParam"] #post def post(self, request): hello_param = request.POST["helloParam"] #put def put(self, request): hello_param = request.PUT["helloParam"] #patch def patch(self, request): hello_param = request.PATCH["helloParam"] #delete def delete(self, request): hello_param = request.DELETE["helloParam"] This is the error I get: 'Request' object has no attribute 'PUT' - If You have any idea how to fix this please respond! :) Thank you! -
I am trying to import gensim, pandas and numpy in my django project but getting import error
I am getting an import error as i try to import gensim, pandas and numpy in django views. How can I import them. I have installed the libraries in virtual environment. -
Conditional Form Field in Django wizard form
I am using wizard forms in django. I want to create a form field only if answer to some other form field is marked "yes" otherwise I don't want this new form field. How can I do this ? I have tried some other answers but most of them tells about how to mark field required or not but I want to display that field only if answer to other field is "Yes" Django Form Wizard with Conditional Questions In below code I want to display field "Pool2" only if answer to field "Pool" is marked "yes" otherwise I don't want that field. forms.py class ListingForm2(forms.Form): Pool = ( ("Yes","Yes"), ("No","No"), ) Pool = forms.ChoiceField(choices = Pool,label = "Does your property have a pool ?") Pool2 = forms.CharField(required=False) Views.py class ListingWizard(SessionWizardView): template_name = 'listing_form.html' form_list = [ListingForm1,ListingForm2,ListingForm3,ListingForm4] def done(self, form_list, **kwargs): save_data(form.cleaned_data for form in form_list) return render(self.request,'done.html',{ 'form_data' : [form.cleaned_data for form in form_list], }) -
django group by match
I want to group by match name i sorted by rank however i failed to group by match. What should you suggest to me [It looks like your post is mostly code; please add some more details.] [It looks like your post is mostly code; please add some more details.] [It looks like your post is mostly code; please add some more details.] (sorry for spam) Now my list; I want like this; html <!-- TABLE --> <div class="table standings"> <!-- TABLE ROW HEADER --> <div class="table-row-header"> <!-- TABLE ROW HEADER ITEM --> <div class="table-row-header-item position"> <p class="table-row-header-title">{{ team.broyale_match.name }}</p> </div> <!-- /TABLE ROW HEADER ITEM --> <div class="table-row-header-item padded"> <p class="table-row-header-title">Maç</p> </div> <div class="table-row-header-item padded"> <p class="table-row-header-title">Sırası</p> </div> </div> <!-- /TABLE ROW HEADER --> {% for team in teams %} <!-- TABLE ROWS --> <div class="table-rows"> <!-- TABLE ROW --> <div class="table-row"> <!-- TABLE ROW ITEM --> <div class="table-row-item position"> <!-- TABLE TEXT --> <p class="table-text">{{ forloop.counter }}</p> <!-- /TABLE TEXT --> <!-- TEAM INFO WRAP --> <div class="team-info-wrap"> <!-- TEAM LOGO --> <img class="team-logo small" src="{% static 'img/flags/' %}{{ team.team.country_code }}.svg" alt="{{ team.team.country_code }}"> <!-- /TEAM LOGO --> <!-- TEAM INFO --> <div class="team-info"> <p class="team-name">{{ team.team.name }}</p> …