Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ProgrammingError at /api/accounts/ relation does not exist
I have this django app on windows 10 python 3.6.2 django 1.11.5 djangorest 3.6.4 postgreSql 9.6 I'm using a custom User Model(AppUser) in the accounts app and i have AUTH_USER_MODEL = 'accounts.AppUser' in my settings file. I migrate in this order as advised from various sources migrate auth migrate accounts migrate to migrate all other apps And migrations succeeds as expected. The problem begins when i try to access the api through the browsable api ProgrammingError at /api/accounts/ relation "accounts_appuser" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "accounts_appuser" WHERE " I've delete all .pyc files created migrations again and got the same error. Through the process of trying over and over sometimes migration reports No migrations to apply Im starting to think the problem is from postgre -
login() and logout() of django.contrib.auth.views
//models.py from django.contrib.auth.models import AbstractUser from django.contrib.sessions.models import Session class CustomUser(AbstractUser): addr1= models.CharField(max_length=20) addr2= models.CharField(max_length=20) city= models.CharField(max_length=20) state= models.CharField(max_length=20) forms.py from django.contrib.auth.forms import AuthenticationForm from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'})) password = forms.CharField(label="Password", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'password'})) //project/urls.py(the outer one) from django.contrib.auth import views from student.forms import LoginForm url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.logout, {'next_page': '/home'}), //login.html(the login template) <div class="container"> <section id="content"> <form action="{% url 'login' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <h1>Login Form</h1> <div class="imgcontainer"> <img src="{% static 'student/patient.jpg' %}" alt="Avatar" class="avatar"> </div> <div class="username"> {{ form.username.label_tag }} {{ form.username }} </div> <div class="password"> {{ form.password.label_tag }} {{ form.password }} </div> <div class="submitb"> <input type="submit" value="Log In" name="mybtn"> </div> <div class="resetb"> <input type="submit" value="Reset"> <a href="#forgotpwd">Forgot password?</a> </div> <input type="hidden" name="next" value="{{ next }}" /> </form> </section> </div> this is the settings.py //settings.py LOGIN_REDIRECT_URL = '/login/sample' is the login() and logout() being called here when i login and logout in this manner?...if not then can i extend the login() and logout() of django.contrib.auth??? -
selecting specific object from list in django template
I am working with a formset_facotry and I am having an issue trying to figure something out. I have a list of users returned from a queryset in views.py file. I also have a list of forms that are created based on the number of objects returned from the list query. What I want to happen is that it selects the first object returned and display it before the first form that is to be displayed. Then grab the second object and displayed it right before the second form and so on... General idea behind it is the followoing: I want it to do something like this general template: header = 'Add record' + groupName if message: print(message) count = 0 for f in form: expenses[0] f.as_p count = count + 1 I want to grab a specific item based on the count within the loop: Here is the code that I have in the template: {% extends "base.html" %} {% block content %} <h2>Add expense - {{ currentGroup.name }}</h2> {% if message %} <p>{{message}}</p> {% endif %} <form action="." method="POST"> {% csrf_token %} {{ form.management_form }} {% with count=0 %} {% for f in form %} {% for expense … -
Anchor tag appending field to current url
I have a model with a field website_link class Partner(models.Model): website_link = models.CharField(max_length=120) And I access it in the template like so <div class="col-sm-3 col-sm-offset-1"> {% if instance.logo %}</a> <!-- website link just gets appended to the end of current url for some reason--> <a href="{{ instance.website_link }}"><img src='{{ instance.logo.url }}' class='img-responsive' alt=""></a> {% endif %} </div> When I call this in the template inside of an anchor tag the link navigates to the current url with the website_link appended to the end. So if instance.website_url = www.partnerone.com instead of the linke going to "www.partnerone.com" it goes to "http://127.0.0.1:8000/partners/partner-one/www.partnerone.com" -
Django add foreign field to a query
I have two tables: menu and foodtype class Foodtype(models.Model): foodtype_en = models.TextField() active = models.BooleanField() class Meta: managed = False db_table = 'foodtype' class Menu(models.Model): title_en = models.TextField() description_en = models.TextField() active = models.BooleanField() id_foodtype = models.ForeignKey(Foodtype, models.DO_NOTHING, class Meta: managed = False db_table = 'menu' Also, I generated a combined table: class MenuSerializer(serializers.ModelSerializer): foodtype_en = serializers.CharField() class Meta: model = Menu fields = ('id', 'title_en', 'active') And I'm trying to get all the active menu records. And I have: menu = Menu.objects.filter(id_truck=idtruck).annotate(foodtype=foodtype) What is wrong with my query? -
"Table 'nest.auth_user' doesn't exist"
I am creating a custom user registration form and I keep getting this error. How do I correct this. > ProgrammingError at /Identity/register/ (1146, "Table 'nest.auth_user' > doesn't exist") I adjusted the authentication system to use email instead of username and I switched from SQlite to Mysql. # Create models for Identities app. from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.db.models.signals import post_save from django.contrib.auth.models import User # Create your models here. class UserManager(BaseUserManager): # Create a model manager for User model with no user name field use_in_migrations = True def _create_user(self, email, password, **extra_fields): # Create and save a User with the given email and password if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): # Create and save a regular User with the given email and password. extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): # Create and save a SuperUser with the given email and password. extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise … -
Django Sessions table displaying only admin id
sessions Session key session data Expire date z8mmy56dgxtw7kiohhsczvdfugydt958 {} Oct. 12, 2017, 10:50 p.m. bnxre1r8muapvy1znvqu0msectghm2vm {u'_auth_user_hash': u'ca7e738308ed261de83fe3c80c9a4657b37e8c81', u'_auth_user_id': u'2', u'_auth_user_backend': u'django.contrib.auth.backends.ModelBackend'} Oct. 12, 2017, 10:14 p.m. 0erbl0nmfsj4vzczubslpea3eagyzroe {u'_auth_user_hash': u'ca7e738308ed261de83fe3c80c9a4657b37e8c81', u'_auth_user_id': u'2', u'_auth_user_backend': u'django.contrib.auth.backends.ModelBackend'} Oct. 12, 2017, 11:21 p.m. I have three users in my CustomUser(AbstractUser) table but no matter which one is logged in, the auth_user_id shows id=2 that is the id of the superuser admin. The other two ids are not shown. what is wrong here? I have not handled sessions explicitly. i have used django's inbuilt auth system using AbstractUser. -
Django restframework: How serialize two models queryset?
I have the following situation: A user can have more than one profile. Here is my models class. Something like this example: models.py class Profile: name=models.Charfield() class UserProfile: user=models.ForeignKey(User) profile = models.ForeignKey(Profile) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' Here I'm returning all my users by JSON but I would like to add a new field called profiles that returns all ids profiles that the user have. { "id": 1, "name" : "John" .... profiles = [1, 2] } How can I get(query) all profiles that the user have and add them on my final JSON? -
fetchone and fetchall returning null
I have a table userToken with three columns: piEmail , piCode, piToken This is how I created this table: class UserToken(models.Model): piEmail = models.CharField(max_length=128) piCode = models.CharField(max_length=128) piToken = models.CharField(max_length=128, unique=True, default=uuid4) piToken is autoFill, I do not insert this value. Now I am inserting value in this table and in the next line trying to fetch the token value for the random value which I inserted in table: random_number = User.objects.make_random_password(length=10, allowed_chars='123456789abcdefghijklmno') userToken_instance = UserToken.objects.create(piEmail='abc@abc.com', piCode=random_number) userToken_instance.save() cursor = connection.cursor() cursor.execute("SELECT piToken FROM app_usertoken where piCode = %s", (random_number,)) row = cursor.fetchall() But it is returning null. when I check in the table, value is there. I tried many ways but not working. worst thing is the below query is working fine, so I am not able to figure out what is wrong with the Where clause: cursor.execute("SELECT piToken FROM app_usertoken") Below statement returns null: cursor.execute("SELECT piToken FROM app_usertoken WHERE piCode ='h1cj82ongk'") -
filtering objects in descending order in django
I am trying to show a table of schools in a cluster(city or town) in a descending order with respect to school average marks. <table class="table"> <thead> <tr> <th>School</th> <th>Strength</th> <th>Average</th> </tr> </thead> <tbody> {% for school in school_order %} <tr> <td><a href="{% url 'data:school_detail' state.id region.id cluster.id school.id %}">{{ school.school_name }}</a></td> <td>{{ school.strength }}</td> <td>{{ school.get_average }}</td> </tr> {% endfor %} </tbody> </table> This is the table I'm trying to display in my template school_order = cluster.school_set.all().order_by('-get_average') This is how I'm trying to get school_order in view.py get_average is not a field for model school but it is a method I used in the model. class School(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) region = ChainedForeignKey(Region, chained_field="state",chained_model_field="state", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE) cluster = ChainedForeignKey(Cluster, chained_field="region",chained_model_field="region", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE) school_name = models.CharField(max_length=250) facilitator = models.CharField(max_length=250) f_number = models.IntegerField() f_email = models.EmailField() school_logo = models.FileField(default='') strength = models.IntegerField() def get_average(self): return self.avergae_set.latest('average_date').average_value This is my model for school. The error I'm getting is cannot resolve keyword 'get_average' into field. Please help! -
TemplateDoesNotExist at /accounts/register/ accounts/register.html
why i still getting this error even though i already create register.html? i already read about this error and i already try to put in settings.py : TEMPLATES_DIRS [ os.path.join(BASE_DIR, '/profiles/accounts/templates')] and still nothing have changed . i try to create my own customize registration form . can anyone help me please ? im new in django and python . i dont know what went wrong because i already create the template by following this tutorial : https://www.youtube.com/watch?v=5x97gGspzjY -
Getting associated values from Python dictionary that is using lists
Ok, so I am working on an application that can go through a number of different database objects, compare the string and return the associated id, first name and last name. I currently have it to where I am building a list of tuples and then populating a dictionary with the key and values(using a list). What I want to do next is find the Max percentage and then return the associated fist and last name from the dictionary. I know the description is a little confusing so please look at the below examples and code: # My Dictionary: {'percent': [51.9, 52.3, 81.8, 21.0], 'first_name': ['Bob', 'Bill', 'Matt', 'John'], 'last_name': ['Smith', 'Allen', 'Naran', 'Jacobs']} # I would want this to be returned: percent = 81.1 (Max percentage match) first_name = 'Matt' (First name associated with the max percentage match) last_name = 'Naran' (Last name associated with the max percentage match) # Code so Far: compare_list = [] compare_dict = {} # Builds my list of Tuples compare_list.append(tuple(("percent", percentage))) compare_list.append(tuple(("first_name", first_name))) compare_list.append(tuple(("last_name", last_name))) # Builds my Dictionary for x, y in compare_list: compare_dict.setdefault(x, []).append(y) Not sure where to go to return the first and last name associated with the Max percentage. … -
What framework or tool has been used to build kegbot-server
What framework or tool has been used to build kegbot server? https://github.com/Kegbot/kegbot-server I can see there it's using Django, but i can't find manage.py and the directories structure does't look like typical django project. Is it some constructor? Or maybe kind of django fork? Or maybe it's just packaged thing that supposed for deployment but not contribution? -
Django not finding templates
I'm trying to set up a Django app for a project, but I'm having trouble with the templates folder being found. Here is my layout... -Alexa -Alexa -__init__.py -settings.py -urls.py -wsgi.py -AlexaApp -migrations -static -css -js -templates -login.html -__init__.py -admin.py -apps.py -models.py -tests.py -views.py -manage.py settings.py INSTALLED_APPS = [ 'Alexa', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Alexa.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] urls.py from django.conf.urls import url from django.contrib import admin from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', auth_views.login, {'template_name': 'templates/login.html'}), url(r'^logout/', auth_views.logout), ] I've tried adding os.path.join(BASE_DIR, 'templates') to my TEMPLATES DIRS, but that didn't help. I've also tried adding 'Alexa' and 'AlexaApp' to my INSTALLED_APPS as well. I've also tried changing the 'templates/login.html' to a direct path the template folder with no success. I'm sure it's something simple, but not sure where I'm messing up. I'm using Django 1.11.5. Can anyone help me out? Thanks in advance! Dylan -
SAML SSO Authentication with Django REST Framework
I'm currently working on a AngularJS front-end and Django REST back-end. I've been using django-rest-auth in the past to authenticate my connections between the two, but I now have to integrate a SSO authentication using SAML. I've looked around and decided to use python3-saml, but any of the documentation and use case examples (for this package and any other) are applied for pure Django applications. I've been basing myself on OneLogin's django/flask guide and I tried making a custom Middleware that would catch my requests, but the implementation of the redirects provided by OneLogin does not work with REST call (obviously). I've also seen some people using the AUTHENTICATION_BACKENDS Django setting and I'm wondering if it's maybe more what I'm looking for. Thank you for any help. -
Django Template Form
This is how my form input field looks like! <td>Email:</td> <td>{{ form.email }}</td> It's giving Email: & then input field as usual. In < input /> fields we have placeholder="..." which shows up in the input. But in my case how can I pre-populate email inside input as a placeholders? -
how to make django render the default home page produced by apache
As is known, after issuing a request through web explorer, apache will return its default static home page to the explorer. I'm using django and apache with mod_wsgi to deploy my site(i.e. django app on apache web server). How to route the processing to django mapping rules defined in views.py to dynamically produce a home page(i.e. index page) for that site when I issue a request to that server running apache? Thanks in advance! -
Blue footer in Gentelella Theme
I'm currently working with this fantastic theme. For context I'm using the django flavor django-gentelella. My problem is when I remove some elements from the side bar a blue footer appears, those elements are the following: Removing <div class="sidebar-footer hidden-small"> Blue Footer appears: Not removing the above class but if you remove some menu elements from the side bar when you click the hamburger to minimize the sidebar, blue footer again: I tried to replicate both scenarios on the demo: gentelella demo but only the first scenario can be reproduced, probably because the template is not being rendered. I'm not a CSS expert but if someone can help me I would really appreciate it. -
Using Django, how do I set a default value for a foreign key select when creating a new item
I've come to the end of the DjangoGirls tutorial and have been trying to add some extra functionality of my own I have a new model called Subject. Each blog post now has a subject such as cookery, gardening, astrophysics, general, etc. When a blogger writes a new post, I want to force the Subject dropdown to default to 'General', but my template (post_edit.html) doesn't give me access to the SELECT so I can't set a default value post_edit.html: {% extends 'blog/base.html' %} {% block content %} <div> <h1>New post</h1> <form method="POST" class="post-form">{% csrf_token %} {% if form.non_field_errors %} <ul> {% for error in form.non_field_errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} {% for field in form %} <div id="{{ field.auto_id }}_container"> {{ field.help_text }} <div> <span class="staticdata">{{ field.label_tag }}</span> <span class="staticdata">{{ field }}</span> </div> <div id="{{ field.auto_id }}_errors"> {{ field.errors }} </div> </div> {% endfor %} <button type="submit" class="save btn btn-default">Save</button> </form> </div> {% endblock %} forms.py from django import forms from .models import Post, Subject from django.contrib.auth.models import User class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'text', 'subject', 'author') models.py from django.db import models from django.utils import timezone class Post(models.Model): author … -
Authentication login in django (AbstractBaseUser model)
I have a problem at the moment of the authenticity of a user since I have a custom model which the primary key comes from a People table. views.py That's where the authentication is done It is not taking the user model from django.shortcuts import render, redirect from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import authenticate, login from django.http import HttpResponse from django.template import loader def user_new(request): if request.method == "POST": form = AuthenticationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.set_password(User.password) user.save() return redirect('index', User.User) else: return render(request, 'login.html', {'form': form}) else: form = NewUserForm() return render(request, 'login.html', {'form': form}) def index(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): User = form.cleaned_data['username'] password = form.cleaned_data['password'] User = authenticate(username=User, password=password) if User is not None and User.is_active: login(request,user) return redirect('/privada') else: return HttpResponse('Algo salio mal') else: return HttpResponse('El formulario no es valido') else: form = AuthenticationForm() ctx={'form':form} return render(request, 'index.html', ctx) Model People In this model of people we create the person to whom a user will be assigned and the data that is sent to the user table is the id of the person model from django.db import models from apps.area.models import Area from apps.company_dependence.models import CompanyDependence from apps.position.models import … -
Highlight exact phrase with haystack/elasticsearch in Django
My web app uses Django Haystack with Elasticsearch as the search engine. My SearchForm child class filters for exact search (content__exact parameter) if the search query contains a token with quotes. class NepSearchForm(SearchForm): # ... def search(self): if not self.is_valid(): return self.no_query_found() if not self.cleaned_data.get('q'): return self.no_query_found() sqs = self._parse_query(self.cleaned_data['q']) if self.load_all: sqs = sqs.load_all() return sqs def no_query_found(self): return self.searchqueryset.all() def _parse_query(self, query): """ Parse query treating modifiers 'AND', 'OR', 'NOT' to make what they're supposed to. :param query: query entered in search input box in form :param sqs: SearchQuerySet until now :return: SearchQuerySet object """ words = iter(shlex.split(query)) result = self.searchqueryset for word in words: try: if word == 'AND': result = result.filter_and(content=words.__next__()) elif word == 'OR': # TODO: fail when changing order of the words. See # TODO: functional test: # TODO: test_search_with_OR_modifier_returns_correct_objects result = result.filter_or(content=words.__next__()) elif word == 'NOT': result = result.exclude(content=words.__next__()) # if "word" is compounded of more than one non blank word the # term is inside quotes elif len(word.split()) > 1: result = result.filter(content__exact=word) else: result = result.filter(content=word) except StopIteration: return result return result I'm using the Django template tag {% highlight %} to highlight the terms searched in my app, like in: … -
During tests, how to override a Django setting used in the urlconf?
In my Django project's urlconf I have something like this: from django.conf import settings from django.conf.urls import include, url urlpatterns = [ url(r'^{}/blog'.format(settings.MY_ROOT_DIR), include('weblogs.urls')), # ... ] In my settings.py I'll have something like: MY_ROOT_DIR = 'phil' This is so I can set the root directory, that's used in several places, in one place (the settings). When I come to test URLs, I use the @override_settings decorator: from django.test import TestCase, override_settings from django.urls import reverse @override_settings(MY_ROOT_DIR='terry') class WeblogUrlsTestCase(TestCase): def test_post_detail_url(self): self.assertEqual( reverse('post_detail', kwargs={'slug': 'my-post'}), '/terry/blog/my-post/' ) However, @override_settings doesn't appear to do anything - the MY_ROOT_DIR value used in urls.py is always "phil", never the overridden setting of "terry". I've also tried @modify_settings, and using it on the test method, rather than the class. I guess the urlconf is is loaded by Django before @override_settings takes effect? Is there a way around this? Or a better solution altogether? -
django + nginx + uwsgi + ssl giving post 403 forbidden error from react?
I run django + nginx + uwsgi with https in production, and the front end uses react. The react code requests the production site for the apis during development. When js code uses POST it causes a 403 forbidden. I think this occurs because the host and referer headers are different when posting from localhost to the production site with ssl. It was working fine when I was using gunicorn. I would like to find a workaround so that I can POST from the js code while developing the react app. This is my nignx conf. server { listen 80; server_name www.tratoli.com,tratoli.com; #return 301 https://$host$1; rewrite ^(.*) https://www.tratoli.com$1 permanent; } server { listen 443 ssl; ssl_certificate /etc/nginx/sites-available/tratoli_ssl.crt; ssl_certificate_key /etc/nginx/sites-available/tratoli_ssl.key; server_name www.tratoli.com; location = /favicon.ico { alias /home/ubuntu/django/new_backend/favicon.ico; } location /static/ { alias /home/ubuntu/django/new_backend/static/; } location / { include uwsgi_params; uwsgi_pass unix:///home/ubuntu/django/new_backend/tratoli/tratoli.sock; } location /chat/ { proxy_pass http://52.66.167.160:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Origin ''; proxy_read_timeout 300; } location ~* \.(?:jpg|jpe?g|png|gif|ico|css|js|eot|ttf|woff|otf)$ { root /home/ubuntu/django/new_backend/; expires 30d; add_header Pragma public; add_header Cache-Control "public"; } location =/sw.js { root /home/ubuntu/django/new_backend/static/react_mobile/js/; } } And this is my uwsgi ini file [uwsgi] socket = /home/ubuntu/django/new_backend/tratoli/tratoli.sock uid = 1000 gid = 33 … -
Unescaping characters with Python (Django)
I am trying to show a list of Objects from my Postgres DB like this: # -*- coding: utf-8 -*- @python_2_unicode_compatible @csrf_exempt def eventlist(request): esemenyek = Event.objects.all().values() esemenyek_list = list(esemenyek) return JsonResponse(esemenyek_list, safe=False) This would work great but I use characters like óüöűáéúő and instead of these I get their escaped version like \u0171\u00e1\u00e9\u00fa\u0151\u00f3\u00fc\n\r. I spent a couple of hours trying to figure it out without any luck. -
Get multiple values
fields = ['first_name', 'last_name', 'birth_date'] user__first_name, user__last_name, birth_date = self.fields.get(fields) As self.fields is a list, it is not possible to do such thing. How could it possible to modify it so that it works?