Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying a django application to heroku, attempt to login gives the error "Programming error at /admin/login "auth_user" does not exist. Why?
After successfully deploying a django application to heroku. I get this error when I attempt to log in via the built-in django-admin. My application is pretty simple with just two apps. None of the apps has any views, just models and it works okay locally. The database is SQLite and migrations seem to be fine. The error traceback: Environment: Request Method: POST Request URL: https://******.herokuapp.com/admin/login/?next=/admin/ Django Version: 2.1.1 Python Version: 3.6.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'general', 'user_details'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', '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') Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) The above exception (relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/sites.py" in login 398. return LoginView.as_view(**defaults)(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 45. β¦ -
Saving Django User Breaks Account Login
I used the following for my authentication: https://github.com/davesque/django-rest-framework-simplejwt Everything seems to work, but when I edit the user in Django Admin panel, it breaks the account (meaning I can no longer login). Once I click the save button on a working account, attempts to login claim that the password / username combo is invalid. Does this make any sense? Could the password field be somehow getting overwritten or autofilled? Could it have anything to do with django-rest-framework-simplejwt? I've also noticed that the superuser email address keeps autofilling the email field in the admin page, so if I forget and save, it overwrites the email address of that user. I don't use email address for login (just username & password), but I'm wondering if that's related? I did a fair bit of googling and found nobody with the same issue. Any insight greatly appreciated. -
why can't I retrieve data from model without using a forloop
I shouldn't use a for loop if I have different approach right? to avoid big o(n)? so here's what I have. models.py class Drama(models.Model): name = models.CharField(max_length=255) views.py def index(request): theOffice = Drama.objects.filter(name='The Office') return render(request, 'index.html', { 'theOffice':theOffice, }) and now in the template {{ theOffice.name }} the above displays nothing, what really bothers me is if I use a for loop it works, {% for theOffi in theOffice %} {{ theOffi.name }} {% endfor %} But then, what's the point of using filter?I can just get objects.all() and use {% if drama.name == "the office %} am I missing something? I'm really confused -
Using Date Range with FilterSet Django
I'm trying to create a Date Range Filter , so this is my Model and filter: class Caixa(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) data = models.DateField('Data') total = models.DecimalField('Total', decimal_places=2, max_digits=10, null=True) unidade = models.ForeignKey(Unidade, on_delete=models.CASCADE) def __str__(self): return "Caixa " + self.unidade.nome class CaixaFilter(django_filters.FilterSet): data_inicial = django_filters.DateFilter(field_name='data', lookup_expr='gte'), data_final = django_filters.DateFilter(field_name='data', lookup_expr='lte') class Meta: model = Caixa fields = ['data'] So, in my HTML i have the following: <form method="get"> <div class="row"> <div class="col s6"> {% render_field filter.form.data_inicial class="datepicker" %} </div> <div class="col s6"> {% render_field filter.form.data_final class="datepicker" %} </div> </div> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Buscar </button> </form> But only "data_final" field appear in HTML. -
django include hides content in my main page
I'm an absolute newbie in web development! Pls help me out here. I'm trying to reuse a content in my django app and I see that when I use the include tag, i get the result from the resuable html code but it comes on top of the div i have in my main page and it hides it. as you can see in the result, line 1 and line 2 are hidden and only line 3 is visible. How do i get the div come after the header block. Can you please let me know what is wrong here. enter image description hereenter image description here -
can not use different fields for each object in serializer django rest framework
I want to create a udemy like web app and using django rest framework for the backend and mysql as database. i have a model named 'Lessons' that contains list of all lessons and one of the fields is 'video-link'. also i have another model names Purchases that have two ForeignKey fields :Users and Lessons. i want to show the Lessons to all users but for the download field i have to lookup the pair (User , Lesson) in Purchases and if He has the course i will show him the download field. here is my code : class LessonsViewSet(viewsets.ModelViewSet): queryset = models.Assignments.objects.all() authentication_classes = (TokenAuthentication,) def get_serializer_class(self): if self.request.user.is_staff : print(self.request.user) return serializers.FullAccessLessonsSerializer elif self.request.user.is_active: return serializers.PartialAccessLessonsSerializer print(self.request.user) return serializers.BasicAccessLessonsSerializer and these are my serializers : full access for admins : class FullAccessLessonsSerializer(serializers.ModelSerializer): class Meta: model = models.Assignments fields = ('id','title','description','dllink' ) basic access for not loggedin users : class FullAccessLessonsSerializer(serializers.ModelSerializer): class Meta: model = models.Assignments fields = ('id','title','description') and partial access for students : class PartialAccessAssignmentsSerializer(serializers.ModelSerializer): """A serializer for all Lessons""" def __init__(self, *args, **kwargs): fields = kwargs.pop('fields', None) super(PartialAccessAssignmentsSerializer, self).__init__(*args,**kwargs) print(self.fields.get('id')) self.fields.pop('dllink') class Meta: model = models.Assignments fields = ('id','title','description','dllink' ) I have done anything i could β¦ -
Obtaining path that follows the domain
Within my view, I'm interested in obtaining the characters that follow the domain name. For example, if a user types https://www.example.com/aboutus into the address bar, I want to be able to grab only '/aboutus' and assign it to a variable. Similarly, if they enter www.example.com/aboutus or example.com/aboutus, I want to obtain only '/aboutus' and assign it to a variable. Thanks! -
Wagtail - Heroku - collectstatic and WhiteNoise during deploying
I'm following the new tutorial from https://wagtail.io/blog/wagtail-heroku-2017/ But I have trouble with collectstatic and the white noise package remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing requirements with pip remote: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 10, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect remote: for path, storage in finder.list(self.ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 125, in list remote: for path in utils.get_files(storage, ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files remote: directories, files = storage.listdir(location) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 313, in listdir remote: for entry in os.listdir(path): remote: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_4d889a5985b9c262c637b03bd07e9098/hello/static' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve β¦ -
How should we use google analytic script in django?
Can we add google analytic script in tag and push it to the GitHub or we should keep it secret i.e. add it to the .env file and call in . When I tried by the second one it appears in the source page as it is and also not working properly. -
ImportError: No module named channels.asgi
I have the following content in wsgi.py file: import os import sys from channels.asgi import get_channel_layer from django.core.wsgi import get_wsgi_application sys.path.append('/home/project') sys.path.append('/home/project/Project_Web_Main') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project_Web_Main.settings") application = get_wsgi_application() channel_layer = get_channel_layer() but I have the following error when importing: from channels.asgi import get_channel_layer ImportError: No module named channels.asgi -
Django push file update on server
I am trying to create a simple calendar application on Django. The idea is there is a text calendar stored in a file (calendar.txt). Anyone that goes to the page can change the current calendar in a textarea, and when they click "Submit" their changes are pushed to the file. I have the input and writing the input part finished, but I am running into one issue: to update calendar.txt, the server itself has to restart. I want to try and get past this in some way because I want it to be that anyone can log onto the website at any time, and access the current calendar without having to restart the server or anything. Here is my program (I put in a fake calendar for testing purposes). My question is: Is there any way to update files on the server without a restart? Any help would be greatly appreciated! And one more thing: I am trying to do this programatically, i.e right through the Python script. -
How to pass diffrent id's for django summernote form
I have a comment form for a model in django and I render multiple instance of the form on my template using SummernoteWidget. The problem is the form only submits the first instance of the form and ignores the rest because they share the same Id. How do I pass multiple Id's for each form instance -
Favicon.ico in Django app cannot be found resulting in 502 Error
I'm completely stumped. I have written a Django application that is being hosted by A2 and is served up through passenger wsgi. It functions in development, but on deployment, it fails with the following error: Failed to load resource: the server responded with a status of 502 (Bad Gateway) /favicon.ico:1 So, I figure that the favicon must not be able to be found by the application. I have an index.html that contains the following in the head: <link rel="shortcut icon" href="{% static 'icons/roger.ico' %}" type="image/x-icon" /> That doesn't seem to do it. I tried adding it to my app.urls as a view like so: from django.contrib import admin from django.urls import path from django.conf.urls import include, url from django.views.generic.base import RedirectView from django.conf import settings favicon_view = RedirectView.as_view(url='static/favicon.ico', permanent=False) urlpatterns = [ path('admin/', admin.site.urls), path('resume/', include('resume.urls')), path('favicon.ico', favicon_view), ] Works in dev again, not in deployment. I'm not sure if it is a problem with my static folder or what. I understand that there's loads of threads about favicon.ico, but none seem to be much relevant (for Ruby on Rails) or I have already tried the solutions above, which failed. Any ideas on how to get past this favicon.ico 502 β¦ -
Apollo-client returns "400 (Bad Request) Error" on sending mutation to server
I am currently using the vue-apollo package for Apollo client with VueJs stack with django and graphene-python for my GraphQl API. I have a simple setup with vue-apollo below: import Vue from 'vue' import { ApolloClient } from 'apollo-client' import { HttpLink } from 'apollo-link-http' import { InMemoryCache } from 'apollo-cache-inmemory' import VueApollo from 'vue-apollo' import Cookies from 'js-cookie' const httpLink = new HttpLink({ credentials: 'same-origin', uri: 'http://localhost:8000/api/', }) // Create the apollo client const apolloClient = new ApolloClient({ link: httpLink, cache: new InMemoryCache(), connectToDevTools: true, }) export const apolloProvider = new VueApollo({ defaultClient: apolloClient, }) // Install the vue plugin Vue.use(VueApollo) I also have CORS setup on my Django settings.py with the django-cors-headers package. All queries and mutations resolve fine when I use graphiQL or the Insomnia API client for chrome, but trying the mutation below from my vue app: ''' import gql from "graphql-tag"; import CREATE_USER from "@/graphql/NewUser.gql"; export default { data() { return { test: "" }; }, methods: { authenticateUser() { this.$apollo.mutate({ mutation: CREATE_USER, variables: { email: "test@example.com", password: "pa$$word", username: "testuser" } }).then(data => { console.log(result) }) } } }; NewUser.gql mutation createUser($email: String!, $password: String!, $username: String!) { createUser (username: $name, password: $password, email: β¦ -
Should I version control manage.py in Django?
Using this command: django-admin.py startproject mysite The following directory structure is generated: mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py Do I need to version control manage.py which contains: #!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', '[REDACTED].settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) Looking at the contents of the file, I don't think I need to, but just to be sure, I'm asking you lovely people :) -
Logging each API calls into a separate file
I have a Django Application whose each API calls are associated with a transaction_id. I want to create separate log files for each transactions_id. In simple words I want to have multiple files which I will be using for logging. How can i do this using Django's built in logging system ? I can have multiple handlers in a single logger. But as per my requirement FileHandlers has to added in run time whose file name will be the transaction_id. This can be done. But the problem is if I have 4 transactions running at a time, 4 handlers will be added to the same logger, and according to documentation logs will be sent to each handlers resulting in 1 transaction log file logging the rest 3 transactions logs as well. Following is what I have come with: class TransactionLogger: def __init__(self, transaction_id, cid=None): self.logger = logging.getLogger('transaction_logger') logger = self.logger fileHandler = logging.FileHandler(transaction_id, mode='a') formatter = logging.Formatter('%(levelname)s %(asctime)s %(filename)s:%(lineno)s - %(funcName)s() ] %(message)s') fileHandler.setFormatter(formatter) self.logger.addHandler(fileHandler) self.logger.propagate = False self.logger.handler_set = True At the beginning of each transactions I instantiate the logger as : logger = TransactionLogger(transaction_id).logger and log as follows: logger.debug("Hello World") How can I maintain n number of log β¦ -
Project ideas of django
I have to do a project regarding django.i want to use machine learning to make my project much better .But iam not getting ideas .Would you please suggest me in selecting project?? -
Nginx working outside Docker but not inside
I'm making a personal website using Django, Gunicorn, Nginx and Docker. When I execute: gunicorn --chdir personal-website --bind :8000 personal_website.wsgi:application The output is: [arturocuya@localhost personalwebsite]$ gunicorn --chdir personal-website --bind :8000 personal_website.wsgi:application [2018-09-09 11:49:02 -0500] [5161] [INFO] Starting gunicorn 19.6.0 [2018-09-09 11:49:02 -0500] [5161] [INFO] Listening at: http://0.0.0.0:8000 (5161) [2018-09-09 11:49:02 -0500] [5161] [INFO] Using worker: sync [2018-09-09 11:49:02 -0500] [5165] [INFO] Booting worker with pid: 5165 And it works (kinda, configuration for static files is yet to be done) The problem is that when I run the Docker container with sudo docker-compose up, I get 502 Bad Gateway I'm suspecting that the problem is how I use the ports but I don't really understand how it should be done. This is my folder structure . βββ config β βββ nginx β βββ conf.d β βββ local.conf βββ docker-compose.yml βββ Dockerfile βββ personal-website βββ manage.py Dockerfile # Start from an official image FROM python:3.6 # The following is an arbitrary location choice RUN mkdir -p /opt/services/personalwebsite/src WORKDIR /opt/services/personalwebsite/src # Copy the project code COPY . /opt/services/personalwebsite/src # Install dependencies RUN pip install django gunicorn Pillow # Expose Port 8000 EXPOSE 8000 # Define the default command to run when starting the β¦ -
django.db.utils.ProgrammingError: relation "auth_user" does not exist - django 2.0.2
I've tried all of the solutions from the top results for this question on Google; none of them work: doing python manage.py migrate auth before `python manage.py migrate didn't work (same error) changing all references to 'auth.User' in my models to AUTH_USER_MODEL didn't work (same error), and neither did get_user_model() (makemigrations detected no changes anyway) doing python manage.py makemigrations [app_with_user_relation] did not work either (migrations were made, but still got the same error) Does anyone have any new suggestions? I hear downgrading to Django 1.7 might work, but that is not an option for me. -
More of one prepopulated_fields for django admin
I'm in training with Django and I would to convert my actual blog from Wordpress to Django. Then I will try to recreate any part of Wordpress structure(or at any rate I hope to do this...) I have this into models.py: class KeyConcept(models.Model): text = models.CharField(max_length=50, verbose_name="Concetti chiave", help_text="Every key concept must be not longer then 50 characters") slug = models.SlugField(verbose_name="Slug", unique="True", help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents") def __str__(self): return self.text def get_absolute_url(self): return reverse("keyconceptView", kwargs={"slug": self.slug}) class Meta: verbose_name = "Concetto chiave" verbose_name_plural = "Concetti chiave" class Argument(models.Model): type = models.CharField(max_length=20, verbose_name="Categoria", help_text="Every argument must be not longer then 20 characters") slug = models.SlugField(verbose_name="Slug", unique="True", help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents") def __str__(self): return self.type def get_absolute_url(self): return reverse("argumentView", kwargs={"slug": self.slug}) class Meta: verbose_name = "Categoria" verbose_name_plural = "Categorie" class Post(models.Model): title = models.CharField(max_length=70, help_text="Write post title here. The title must be have max 70 characters", verbose_name="Titolo") short_description = models.TextField(max_length=200, help_text="Write a post short description here. The description must be have max 200 characters", verbose_name="Breve descrizione dell'articolo") contents = models.TextField(help_text="Write your post here", verbose_name="Contenuti") publishing_date = models.DateTimeField(auto_now=False, auto_now_add=True, β¦ -
How do I solve the error 'IntegrityError at /admin/auth/user/add/ UNIQUE constraint failed: user_details_profile.phone' in Django?
I am trying to add a new user via the built-in django admin but I keep getting this error. Even trying to create a superuser via the terminal gives the same error. All other models not associated with the user work fine. The code inside my models.py file is as follows. Traceback: http://dpaste.com/2BB7G65 from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from django.core.exceptions import ObjectDoesNotExist from general.models import Ward # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) firstname = models.CharField(max_length=20) middlename = models.CharField(max_length=20) lastname = models.CharField(max_length=20) loc_id = models.CharField(max_length=8, unique=True) ward = models.ForeignKey(Ward, related_name="wards", null=True, on_delete=models.SET_NULL) phone = models.CharField(max_length=10, unique=True) address = models.CharField(max_length=255) postal_code = models.CharField(max_length=15) def __str__(self): return "{} {}".format(self.user.first_name, self.user.last_name) class Meta: verbose_name_plural = "Personal information" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): try: instance.profile.save() except ObjectDoesNotExist: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): try: instance.profile.save() except ObjectDoesNotExist: Profile.objects.create(user=instance) What am I missing? Someone please help. -
How to setup Django + React on hosting?
I've done Django + React application. I build React code using 'npm run build' and moves that files to hosting together with Python files, I've set up static files in Django app, and now when I'm going to site URL, I see that all static files are loaded. But they don't run. And when on the local environment I saw pretty JS app, now on hosting I see a white screen and when I select compiled JS files in Network tab in Developers Tools (Preview response) I read message "You need to enable JavaScript to run this app." (for CSS too). I know that this is a noob question. But can you help me to solve this issue? Thank you. -
DRF Swagger custom docs
I've different serializers for a view based on the query parameter code. All my APIs(Views) have different serializers based on code. Here's my code:- class BorrowerView(generics.CreateAPIView): def get_serializer_class(self): """Get Serializer for a View from Config.""" code = self.request.GET.get('code') serializer_class = serializer_config[product_code] return serializer_class queryset = Borrower.objects.all() Is it possible to have API docs rendered as per the provided code? -
In Django is it possible to specify separate `http` verbs with same urlpattern?
I am creating a registration form in Django 2.1. In the typical examples people are using same views method both for showing forms and accepting POST request from forms like following: In urls.py: urlpatterns = [ path('auth/register', auth.register, name='register') ] and in the view named auth.py: from django.shortcuts import render from blog_admin.forms import SignUpForm from django.contrib.auth.forms import UserCreationForm def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): # do registration stuff... else: form = SignUpForm() return render(request, 'blog_admin/auth/register.html', {'form': form}) but I want to use separate method for showing the form and handling registration process and also want to use identical urlpatterns one with GET and one with POST functionality, like following: in urls.py urlpatterns = [ # can we limit it range, so that it only works for GET request path('auth/register', auth.show_registration_form, name='register_show'), # can we limit it range, so that it only works for POST request path('auth/register', auth.register, name='register') ] and in the view named auth.py: from django.shortcuts import render from blog_admin.forms import SignUpForm from django.contrib.auth.forms import UserCreationForm def show_registration_form(request): form = SignUpForm() return render(request, 'blog_admin/auth/register.html', {'form': form}) def register(request): # do registration stuff... If need some more example from other frameworks, in php Laravel it β¦ -
Simple Example Django Multi-Select Checkbox Dropdown
I am trying to make a dropdown box in Django 2.0.5 that will allow for the selecting of checkboxes while the dropdown stays open (like what is shown in the picture below) I have looked into possibly using django_select2 as a backup, but I would prefer not to use that. Is this possible within django itself? Is there any library that I could use? And is the some example example I could see? Any help would be appreciated. Thanks! Dropdown of checkboxes