Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NGINX proxy_pass to another container in Kubernetes pod
I'm hoping someone might know how to make this work... I've spent hours on this one and am probably just barely missing it. I'm using Kubernetes and have built a pod with several containers including nginx and django. They are setup using the following: nginx runs on port 80, a service has already exposed it and external traffic reaches this point just fine and serves static content. django runs using daphne on 0.0.0.0:8000 I use proxy_pass to send traffic to Django on port 8000, but get the 502 bad gateway error. I tested everything on Docker before pushing to Kubernetes, so I had: proxy_pass http://django:8000 But I have tried all the following without success: http://localhost:8000 http://127.0.0.1:8000 http://django (with upstream server 127.0.0.1:8000) and several others... What is the best way to setup a proxy_pass to another container in the same pod? -
how to display django search results in template
i'm new to django and i'm working on a project, i need to create a search functionalit where users can search data in models, i've tried coding it this way but even when i search for items that are in models, it doesn't display any result. i really need help view.py def search(request): query = request.GET.get('q') results = Myhouses.objects.filter(Q(name_of_accomodation__icontains=query) | Q(type_of_room__icontains=query) | Q(location__icontains=query)) return render(request, 'account/index.html') template <form method='GET' action='{% url "search" %}'> <input type='text' name='q' placeholder="Enter Search Keyword" value='{{ request.GET.q }}' id='intry'> <input type='submit' value='Search' class='button_1' id='sub1'> </form> -
Django admin override FK field and expose in Admin
I have a simple Model: class Tier(models.Model): number_groups = models.PositiveIntegerField(null=True, blank=True) Which can be a FK of another Model: class Account(models.Model): tier = models.ForeignKey( AccountTier, null=True, on_delete=models.PROTECT) number_groups = models.PositiveIntegerField(null=True, blank=True) The number_groups attribute can be overridden in the Account Model. This allow my users to Select, in the admin page, from a list of predefined Tier instances. Sometimes though a user might want to set a specific value to number_groups that should only live in the Account instances. I was thinking a straight way to do this was with a method in the Account Model: def number_groups(self): if self.number_groups: return self.number_groups elif self.tier: return self.tier.number_groups return self.number_groups But with this approach I can't make this field appear in the Admin, which is defined: @admin.register(Account) class AccountAdmin(admin.ModelAdmin): fields = ('number_groups',) What is the best way to have the admin correctly show this field and allow overriding it in the Account Instance ? -
How to upgrade django project multiple versions (1.8 to 1.11+)?
I'm upgrading an old project running on Django 1.8 to at least Django 1.11 for LTS. I've heard upgrading a django project multiple versions can be difficult and frustrating. I haven't done this, so my question; is it better to do an upgrade per version, 1.8 -> 1.9 -> 1.10 -> 1.11. Or do you advice me to upgrade straightaway to 1.11 from 1.8. Please leave your best thoughts on this and other things I need to keep in mind while upgrading. Thanks in advance -
my Django DayArchiveView is not detected in urls.py
I created several date-based views in Django, and while views for year and month function as expected, the view to display days is not detected. For instance, if I try to get 'balance/2018/', or 'balance/2018/04/' the views will be displayed, while 'balance/2018/04/02' will fail. I understand that the problem must be with urls.py configuration, but I just cannot find it in documentation. I also tried passing day_format='%d' to as_view method, without any results. my urls.py file from django.urls import path, re_path from .views import ArticleYearArchiveView, ArticleMonthArchiveView, ArticleDayArchiveView from . import views urlpatterns = [ path('', views.index, name='index'), path(r'<int:year>/<int:month:>/<int:day>/', views.ArticleDayArchiveView.as_view(day_format='%d'), name='show_day'), path(r'<int:year>/<int:month>/', views.ArticleMonthArchiveView.as_view(month_format='%m'), name='show_month'), path(r'<int:year>/', views.ArticleYearArchiveView.as_view(), name='show_year'), ] my views.py file from django.shortcuts import render from django.views.generic.dates import YearArchiveView, MonthArchiveView, DayArchiveView from django.http import HttpResponse from django.db.models import Sum from .models import Category, Article import datetime # Create your views here. def index(request): num_of_articles = Article.objects.all().count() num_of_categories = Category.objects.all().count() return render(request, 'index.html', context = { 'num_of_articles':num_of_articles, 'num_of_categories':num_of_categories}) class ArticleYearArchiveView(YearArchiveView): queryset = Article.objects.all() date_field = 'financial_day' make_object_list = True def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['summation'] = Article.objects.all().filter(financial_day__year=kwargs['year'].year).aggregate(Sum('amount_of_money'))['amount_of_money__sum'] return context class ArticleMonthArchiveView(MonthArchiveView): queryset = Article.objects.all() date_field = 'financial_day' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['summation'] = Article.objects.all().filter(financial_day__year=kwargs['month'].year).filter(financial_day__month=kwargs['month'].month).aggregate(Sum('amount_of_money'))['amount_of_money__sum'] return context class ArticleDayArchiveView(DayArchiveView): queryset … -
Signal for the default user registration of django
I would like after creating a user to run a method and create content in other tables of this user that was created but I do not have a user model since I use the default model for the record. Problems: -I do not have user model (use the default model) -I want to choose the newly created user to create the other records in other tables -I'm not an expert in django (I'm just trying to solve a problem in another area and this would help) I like the way to do it in this post: https://simpleisbetterthancomplex.com/tutorial/2016/07/28/how-to-create-django-signals.html Creating a signals.py to control the signals -
How to use `set` : get related set from a related set of a model in django
I would like to get a list of allowances of specific employee and I would like to use set in my query. How do I achieve this.. so far this is how I have implemented the query: emp = Employee.objects.filter(pk=1).prefetch_related('user','payslip','salary').values('user__first_name','user__last_name','user__id' ...: ,'payslip__id','salary__salary_value','payslip__allowances_set') { "allowances":[], "deductions":[], "tax_id_number": "A500000080Q", "salary__salary_value": null, "department": 1, "hr_number": "HG/5000/2018", "user__last_name": "Cannon", "payslip__deductions": 2, "user_id": 2, "user__first_name": "Nick", "payslip__id": 2, "payslip__allowances": 3 }, -
How to add a new field to Django form Registratio?
I'm new to python/Django, there is only 1 week I'm learning it. I'm trying to make a simple signup login registration. The problem is Django has the fields first_name, last_name, email, password. I'm ok with that, I'm trying to add a new field to it, a location field, to get the state where the person lives. And also I would like to have acess to this field later. My first try, I just tried to change last_name field to location, but when I checked the admin page to see the recorrds, it didn't work, the field last_name was there and it was empy, and there was no field location inside of the admin page. I've read and tried 2 solutions (Adding a new field along with username and password in django's login form) and (How to add extra fields to django registration form?). There is my code. Also I'm being able to create new registration with same e-mail, how can I do that to make possible to use the e-mail only once? Thanks for the help and sorry if the answer is right in front of me and I can't see it. # forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, … -
Django app not launching on Elastic Beanstalk AWS
When I deploy my Django project on elastic beanstalk I get a 500 Internal Server error. I have tried everything,The EB dashboard looks okay health is perfect and no mention of any errors in there. Can anyone shed some light on this? ============= i-03980c0f6a1094e3c ============== ------------------------------------- /var/log/httpd/error_log ------------------------------------- [Wed Apr 04 13:15:51.669498 2018] [suexec:notice] [pid 3065] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Wed Apr 04 13:15:51.684578 2018] [http2:warn] [pid 3065] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive. [Wed Apr 04 13:15:51.684588 2018] [http2:warn] [pid 3065] AH02951: mod_ssl does not seem to be enabled [Wed Apr 04 13:15:51.685042 2018] [lbmethod_heartbeat:notice] [pid 3065] AH02282: No slotmem from mod_heartmonitor [Wed Apr 04 13:15:51.686951 2018] [mpm_prefork:notice] [pid 3065] AH00163: Apache/2.4.27 (Amazon) mod_wsgi/3.5 Python/3.6.2 configured -- resuming normal operations [Wed Apr 04 13:15:51.686971 2018] [core:notice] [pid 3065] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Wed Apr 04 13:16:13.037691 2018] [mpm_prefork:notice] [pid 3065] AH00169: caught SIGTERM, shutting down [Wed Apr … -
How to get user's birthday from python-social-auth
so I've set up my Django app, and I want to get birthday from Facebook and save it somewhere in the pipeline. I did request scope: SOCIAL_AUTH_FACEBOOK_SCOPE = ['email','user_birthday'] Most answers to similar question use the response dict returned by Facebook. However, when I print it, I have this: { 'id': .., 'expires': .., 'name': .., 'granted_scopes': ['user_birthday', 'email', 'public_profile'], 'access_token': .. } How do I get the actual birthday? -
how to apply defer function in my following model.py file to lazy load fields?
class Event( OwnedModelMixin, TimeStampedModelMixin, RandomIDMixin, models.Model, ): after_sunset = models.BooleanField(default=False) date = models.DateField(blank=True, null=True) notes = models.TextField(blank=True, default="") is_published = models.BooleanField(default=False) is_public = models.BooleanField(default=False) shabbos = models.BooleanField(default=False) starts = models.TimeField(blank=True, null=True) venue = models.ForeignKey(Venue, editable=False, blank=True, null=True) community = models.ForeignKey(Community, blank=True, null=True) def __str__(self): # pragma: no cover """ Returns a reprsenative fields depending on the event type """ child_events = ( 'bar_mitzvah', 'bar_mitzvah_kiddush', 'bris', 'kiddush', 'shalom_zochor', 'vachnacht', ) if self.event_type in child_events: return '{} on {},is_published: {}'.format( self.event_type, self.date, self.is_published ) else: return '{} on {},is_published: {}'.format( self.event_type, self.date, self.is_published ) There are almost 160 attributes which I have not included in it.But all the attributes are not needed all time. I want to lazy load those attributes to improve the performance.As there are 160 attributes and there are 1000 rows.How can I? -
Registering models for translation using django-modeltransltation causes error with MPTTModel
I am using django 2.1 with django-modeltranslation 0.12.2 and django-mptt 0.9.0 When I try to register a model for translation that extends MPTTModel I get that error: File "/home/peter/Desktop/dokkanz/listing/urls.py", line 3, in <module> from . import views File "/home/peter/Desktop/dokkanz/listing/views.py", line 16, in <module> class CategoryListView(ListAPIView): File "/home/peter/Desktop/dokkanz/listing/views.py", line 17, in CategoryListView queryset = Category.objects.root_nodes() File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/mptt/managers.py", line 72, in wrapped return method(self, *args, **kwargs) File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/mptt/managers.py", line 635, in root_nodes return self._mptt_filter(parent=None) File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/mptt/managers.py", line 72, in wrapped return method(self, *args, **kwargs) File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/mptt/managers.py", line 410, in _mptt_filter return qs.filter(**self._translate_lookups(**filters)) File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/mptt/managers.py", line 100, in get_queryset self.tree_id_attr, self.left_attr File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/modeltranslation/manager.py", line 379, in order_by return super(MultilingualQuerySet, self).order_by(*new_args) File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/django/db/models/query.py", line 1013, in order_by obj = self._chain() File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/django/db/models/query.py", line 1156, in _chain obj = self._clone() File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/modeltranslation/manager.py", line 234, in _clone return super(MultilingualQuerySet, self)._clone(**kwargs) TypeError: _clone() got an unexpected keyword argument '_rewrite' kanz/lib/python3.6/site-packages/mptt/managers.py", line 72, in wrapped return method(self, *args, **kwargs) File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/mptt/managers.py", line 635, in root_nodes return self._mptt_filter(parent=None) File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/mptt/managers.py", line 72, in wrapped return method(self, *args, **kwargs) File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/mptt/managers.py", line 410, in _mptt_filter return qs.filter(**self._translate_lookups(**filters)) File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/peter/.virtualenvs/dokkanz/lib/python3.6/site-packages/mptt/managers.py", line … -
Unsupported lookup 'between' for TimeField or join on the field not permitted
I have a model like this: class Article(models.Model): title = models.CharField(max_length=200) content = models.TextField() create_time = models.DateTimeField(auto_now_add=True,null=True) and I write a query statement in view function like this: from datetime import time start_time = time(hour=17) end_time = time(hour=18) articles = Article.objects.filter(create_time__time__between=(start_time,end_time)) but Django raise Exception django.core.exceptions.FieldError: Unsupported lookup 'between' for TimeField or join on the field not permitted.,django document says it is right.if I want filter hour between 17 to 18,what should I do? -
Determine/Find underlying SQL field type of a Django Field
Is there an easy way to determine or find the underlying SQL field type of a Django Field, for any of the supported by default database backends? I have searched on the web and there is no documentation over how the Django fields are represented in SQL in each of the supported databases. The only way for me to see the underlying SQL field type, is to run the mysqlmigrate command of manage.py and examine the SQL code. -
Add button not showing in Django admin
I am trying to add the related objects from django tutorial of it's documentation https://docs.djangoproject.com/en/1.11/intro/tutorial07 But there is no add button showing in it I've checked this answer too but it did not help Add button not showing up in Django tutorial 02 This is my admin.py from __future__ import unicode_literals from django.contrib import admin from home.models import * # Register your models here. class ChoiceInline(admin.StackedInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None,{'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin) This is my models.py from __future__ import unicode_literals from django.db import models # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) This is showing in my admin page python used is python 2.7 -
Serializing joined tables in serializers rest framework
So i am trying to serialize multiple joined tables with django serializers. I cant find a way to do this. The query being executed is raw sql. The models are as below class UserDetail(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) mobile_number = models.IntegerField() national_id = models.CharField(max_length = 30) date_created = models.DateTimeField(auto_now_add = True) address = models.CharField(max_length = 250) merchant_name = models.CharField(null = True, max_length = 30) class Account(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) account_number = models.BigIntegerField() balance = models.FloatField() account_type = models.ForeignKey(AccountType, on_delete = models.CASCADE) The json for the expected result should as below { "userdetail": { "mobile_number":"" }, "account": { "account_number":"" }, "user": { "first_name": "", "last_name": "", "email":"" } } The raw sql query is as below queryset = Account.objects.raw('''SELECT auth_user.first_name, auth_user.id, auth_user.last_name, auth_user.email, authentication_userdetail.mobile_number, authentication_account.account_number FROM public.auth_user, public.authentication_account, public.authentication_userdetail WHERE auth_user.id = authentication_userdetail.user_id AND auth_user.id = authentication_account.user_id ''') If there is an alternative way to do this without using raw sql i would greatly appreciate it as im not a fan of executing raw sql queries with django ORM -
Getting Django logs outputting to Heroku's logs from consumers.py
My settings are configured to experiment with logging, but I'm unable to get them to print on the Heroku logs. This is in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'root': { 'level': 'WARNING', 'handlers': ['sentry'], }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'sentry': { 'level': 'ERROR', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', 'stream': sys.stdout } }, 'loggers': { 'django.db.backends': { 'level': 'ERROR', 'handlers': ['console'], 'propagate': False, }, 'raven': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, 'sentry.errors': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, 'django.security.DisallowedHost': { 'level': 'ERROR', 'handlers': ['console', 'sentry'], 'propagate': False, }, }, } In my consumers.py I have: import logging logger = logging.getLogger('django.db.backends') logger.info('initial log message') I'm trying to get the initial log message printing but this won't do it. Logging with logger = logging.getLogger('django.db.backends'), logger = logging.getLogger('sentry.errors'), and logger = logging.getLogger('raven'), in other files does work. What is it about consumers.py that doesnt allow logging? -
Django: context of modified query list
I have a database with blog style documents, i.e., author's name, publication date, body text, etc. I have built a django framework to output entries from the database as a result of a search term. That part is ok. The problem is that I want to show sections of the body text with the matched search terms highlighted (equivalent to a google search result). This means that I can't create a template tag with the body_text attribute only, because that text is not highlighted. I already did a function that receives as input the query and the body text and outputs the same text with the found search terms in bold. My problem now is how do I pass this result to the html template? Using the tutorial from Django documentation suppose you have the following views.py: def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) and the correspondent template: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} Now suppose you have the function in views.py: def signal_tokens(text,query_q): ... return new_text What should … -
Python - product of two field with a foreign key
I would like to know how to calculate the product of two field : score in FeatureInfo and ratio in Feature. Thanks! class Feature(models.Model): name = models.CharField(max_length=255, unique=True, null=True) ratio = models.IntegerField(null=True) class FeatureInfo(models.Model): name = models.CharField(max_length=255, unique=True, null=True) score = models.IntegerField(null=True) feature = models.ForeignKey(Feature, on_delete="CASCADE") total = score * Feature.ratio -
How to use prefetch_related
How do I use prefetch_selected to get the first and last name of the employee class below. class Employee(models.Model): """ Model, which holds general information of an employee. """ user = models.OneToOneField(User, related_name='users', on_delete=models.CASCADE, unique=True) photo_logo = models.FileField(null=True, blank=True) Here is how I have implemented my query emp=Employee.objects.filter(pk=1).select_related('user').values('user_first_name','user_last_name','id') But I get the following logs after running a print statement in django shell Cannot resolve keyword 'user_first_name' into field. Choices are: address, address_id, attendance, basic, -
get django-rest-framework-social-oauth2 user details after login
login using google works fine. user is register in both social_auth_usersocialauth & auth_user table on DB, everything working. how to get user details in my view i need a class/ function to get user's { id:, username:, email:, } -
Hitting Firebase from django development server
I am using firebase-admin library for python. Whenever I try to hit firebase from localhost(http://127.0.0.1) i am getting below error. [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600) Is there any way to test firebase from localhost. -
how to install pip remotely using ssh
Hi I hope someone can point me in the right direction. I am trying to upload a django project which I have developed locally on my machine and now moved the project files to a server and am trying to install django on the server. I have Python 2.7.5 installed and accessed the server remotely using ssh (putty) I can confirm Python is installed by running the command python --version I don't have pip installed as when i run the command pip --version I get following notification -bash: pip: command not found I am new to django and python so not sure what I should do to install both django and pip. p.s In my requirements file and when working locally I have pip and django installed correctly and all working. -
Not able to make slug work in Django
I am building one project in which i used slug for urls. But it doesn't seem to be working. My regex pattern is right I have tested it. I have used id before and then it worked fine but if i use slug in place of id it creates error. Here is my code models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True) class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name class Country(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True) class Meta: verbose_name = 'Country' verbose_name_plural = 'Countries' def __str__(self): return self.name class News(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) country = models.ForeignKey(Country, on_delete=models.CASCADE) description = models.TextField(max_length=1500) pub_date = models.DateTimeField() class Meta: verbose_name = 'News' verbose_name_plural = 'News' def __str__(self): return self.title urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.Home, name='index'), url(r'^[a-z0-9-]+$/detail', views.detail, name='detail')] views.py def detail(request, slug): nd = get_object_or_404(News, slug=slug) return render(request, template_name="app/detail.html", context={'nd':nd}) detail.html {% extends "base.html" %} {% block title %}Detail{% endblock %} {% block content %} <div class="home"> {% for n in nd %} <h2>{{ n.title }}</h2> <h4>{{ n.category }}</h4> <h4>{{ n.pub_date }}</h4> <p>{{ n.description }}</p> {% endfor … -
What is the name of local server use to run django App?
Django server name which is use to run app locally. As php use apache server to run app locally.