Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have configure postgresql database to django project but when i run server, nothing happens , just "Watching for file changes with StatReloader"
i want to change my database from sqlite to postgresql but when i run server, nothing happens , no response , just "Watching for file changes with StatReloader" -
Django Secret Key Must Not Be Empty Error
I am trying to run django on AWS EC2 framework tensorflow_p36 which has its own virtualenv as tensorflow_p36. It is providing python3.6 as the language version. I found there was a conflict with mod_wsgi which was running on python3.5 so I had to reinstall it. Now the problem with mod_wsgi has gone but another problem -- Django secret key error Traceback (most recent call last): File "./manage.py", line 14, in application = django.core.handlers.wsgi.WSGIHandler() File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 135, in init self.load_middleware() File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/django/core/handlers/base.py", line 34, in load_middleware for middleware_path in reversed(settings.MIDDLEWARE): File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/django/conf/init.py", line 79, in getattr self._setup(name) File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/django/conf/init.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/django/conf/init.py", line 157, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "/var/www/picslo/picslo/settings.py", line 15, in django.setup() File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/django/init.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/django/conf/init.py", line 79, in getattr self._setup(name) File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/django/conf/init.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/django/conf/init.py", line 176, in init raise ImproperlyConfigured("The SECRET_KEY … -
Wagtail new installation : CSS not working
I tried the official installation guide for installing wagtail locally : first by creating a website second by integrating wagtail into a new website Each time it seemed to work fine functionally but all the CSS was broken (see pic down) I tried to do "manage.py collectstatic", it told me that 2/3 hundred files have been copied, I emptied the cache of my browser, loaded the page again, no change. In the console it seems that the files are sent : [14/Jul/2019 10:16:54] "GET /static/css/welcome_page.css HTTP/1.1" 200 3003 I restarted several times the tutorials from the beginning making sure I do each step exactly as described, nothing changes. When I begin with a new django project, the base django css is working before I add wagtail. I m using Python 3.6.8, Django 2.2.3 and Wagtail 2.5.1. What am I doing wrong ? -
django updateview pass request.id to field
I have a UpdateView class and I want to pass the user.id in event_agency of fields i.e the value of event_agency will be set to user.id and I will not have to take it as an input. # view for the event update page class EventUpdate(UpdateView): model = Event # the fields mentioned beindexlow become the entyr rows in the update form fields = ['event_name', 'event_venue', 'event_type', 'event_agency'] Without using UpdateView it can be done by creating a form instance and passing request, but how to do it with UpdateView class? I cannot for instance do class EventUpdate(UpdateView, request): -
Virtualenvwrrapper problem with virtualenvwrapper.sh
I am trying to install virtualevnwrapper but i failed.. It throws me this error: bash: /usr/local/bin/virtualenvwrapper.sh: No such file or directory I tried like this: $ pip install virtualenvwrapper ... $ export WORKON_HOME=~/Envs $ mkdir -p $WORKON_HOME And then i run $ source /usr/local/bin/virtualenvwrapper.sh and throws me this error bash: /usr/local/bin/virtualenvwrapper.sh: No such file or directory as I failed above commands, then I try with $ source ~/.local/bin/virtualenvwrapper.sh and throws me this error: /usr/bin/python: No module named virtualenvwrapper virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenvwrapper has been installed for VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and that PATH is set properly. I tried a lot to do it but i failed.. Can anyone help me in this case? -
How to display data in browser only for 1 day? after 24 hours it should be clear from browser
I need to display input data in browser only for 1 day. When i input data next day it should display only next day's data in browser -
Django allauth google extra_data
I've implemented google authentication using django-allauth, but I'd like to get additional data from the Google API about the user being authenticated. The immediate issue is that the username is being populated as the Google user's first name rather than the account username; however, I'd like to know what I can get from the API and how. I see in the providers->openid section of allauth docs that a extra_data can be specified, but I can't find any documentation on if this can be done for google provider, and if so what extra data can be requested. -
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?