Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I redirect a Django form submit to a new tab after form validation?
I have a Django form with two dropdown integer fields and a submit button. A user selects values from these dropdown fields and click on submit button. The Django template performs a form 'post' and sends these two dropdown values to my Django views. Django views performs the form validation by validating these two dropdown fields values. If the form is not valid, it will send the error message to the Django template and I can display the error message on the same form page above the form. If the form is valid, then it will redirect to a new URL. Issue: How do I tell my Django view to redirect the URL to a new tab only after the form is valid? -
How can I deploy django web app on cpanel
I am trying run my django web app on cpanel and have followed a few tutorials. I have edited my settings.py file for production, I have created a virtual environment, installed django and all the necessary packages used by my app, edited passenger_wsgi.py to import application from my app, as detailed in this video tutorial However, when I try and visit the url that should be associated with the app I get the message We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later. I assume this is because of something I have missed/have not done. This my the structure of my project gradboost -->__pycache__ -->classroom __init__.py apps.py decorators.py forms.py models.py urls.py ------>templates ------>templatetags -->django_school __pycache__ __init__.py settings.py urls.py wsgi.py -->public -->static -->templates -->tmp manage.py passenger_wsgi.py public_html This is what I have written in passenger_wsgi.py from django_school import application Steps I took: --> ran setup python app --> specified python version (3.7) --> application startup file = passenger_wsgi.py --> application entry point = application --> installed relevant packages in virtual environment in server terminal -
How to get list of models that is registred in django admin?
I want to get list of models that is registered in django admin. And set in settings which models i want to see in Django admin. -
Django unable to find settings file in Elastic Beanstalk
I keep getting the following error in the logs of Elastic Beanstalk: [Tue Jan 21 14:10:12.032655 2020] [:error] [pid 3349] [remote 127.0.0.1:128] File "/opt/python/run/venv/lib64/python3.6/importlib/__init__.py", line 126, in import_module [Tue Jan 21 14:10:12.032658 2020] [:error] [pid 3349] [remote 127.0.0.1:128] return _bootstrap._gcd_import(name[level:], package, level) [Tue Jan 21 14:10:12.032664 2020] [:error] [pid 3349] [remote 127.0.0.1:128] File "<frozen importlib._bootstrap>", line 994, in _gcd_import [Tue Jan 21 14:10:12.032670 2020] [:error] [pid 3349] [remote 127.0.0.1:128] File "<frozen importlib._bootstrap>", line 971, in _find_and_load [Tue Jan 21 14:10:12.032677 2020] [:error] [pid 3349] [remote 127.0.0.1:128] File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked [Tue Jan 21 14:10:12.032702 2020] [:error] [pid 3349] [remote 127.0.0.1:128] ModuleNotFoundError: No module named 'vspmschool.settings' It is related to the wsgi file. What am I doing wrong? -
Generate OpenApi schema with pure django
I am building Web API with pure Django views (not Django REST Framework). Is there any way to generate OpenApi schema without DRF? -
Flaws in Django-React apps
I am building a Web app, powered by react in frontend and Django in the backend. It uses Django REST framework for providing raw data to react But when it came to data transfer, I got scared.. I was told to use CORS headers and use a WHITELIST list to mention the allowed urls which access the data. Also, when I need to feed an entry in database, I need to make further allowances. So is it safe to go like this? I think one can easily steal data midway. -
Django periodic task
I'm writing an app in Django, and need to perform periodically some task on my DB (updating all records, using live data). And there's my question: how to do that in simplest way. I tried using Celery with Redis server - actually it never worked. Im using MS Windows and Pycharm, and encountered constant errors with dependencies, and different versions compatibilities. On some random forum, even found someone claiming that newer version of Celery is not supported on Windows. It's jannuary 2020. All tutorials found are already few months old. I dunno if versions are changing so often, or whats going on. Mayby someone have simple working template, or something / -
How to get the HTTP Response status in django class based views?
I am using Django 2.2. I want to get the HTTP response status code while code is successfully rendered through CBV( Django's class-based view ). I am able to do it when I am using render() method in Function-based views. Any guidance will be very much appreciated. My code look's like this class CalendarView(generic.ListView): model = <my model> template_name = < my template path > def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) < my code block for assigning HTML data to context > return context Here I am returning the context and it's successfully getting renders over the browser as HTML, but how can I get HTTP response status code in views.py ?? -
Django Fullcalendar - render on more than one html
I have an HTML page where my calendars are rendered with no problems at all. But, I want to preview all of my calendars to another page also, something like {% include %}(which won't work). Is there any way to do that without making another function, and render it separately? This is my calendars.html: {% extends 'base.html' %} {% load static %} {% block title %} Kalendar {% endblock title %} {% block content_row %} <!--------------------------------------------- FULLCALENDAR LINKS ----------------------------------------------> {% include 'main/partials/_link_fullcalendar.html' %} <!--------------------------------------------- FULLCALENDAR LINKS END ------------------------------------------> {% if messages %} {% for message in messages %} <div class="container-fluid"> <div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert">&times;</button> <strong>Uspešno!</strong> {{ message }} </div> </div> {% endfor %} {% endif %} {% if calendars %} {% for cal in calendars %} <script> document.addEventListener('DOMContentLoaded', function () { let calendarEl = document.getElementById('{{ cal.id }}'); ////////////////////////////////////////////////////////////////////////////////////////////// let calendar1 = new FullCalendar.Calendar(calendarEl, { minTime: "07:00:00", maxTime: "22:00:00", businessHours: { startTime: '08:00', // a start time (10am in this example) endTime: '21:00', // an end time (6pm in this example) }, height: 'auto', locale: 'sr', plugins: ['dayGrid', 'timeGrid', 'list', 'interaction'], defaultView: 'timeGridThreeDay', header: { left: 'today', center: '{{ cal.name|title }}', right: 'dayGridWeek,timeGridThreeDay' }, views: { timeGridThreeDay: … -
Not allowed to load local resource: Cant load images from my postgresql database
Im working on application that stores dota2 heroes names types and images in my postreSQL database. Backend is in Django using Graphql. For frontend im using React with Apollo client. After storing everthing in base and images as paths to my folder in database i tried to load them via graphql query. Name of the hero is working as well as type but when i try to load image i get this, Not allowed to load local resource: https://prnt.sc/qqrvb0 in index.js i only have this(i didnt refactored a code yet) import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import { ApolloProvider } from '@apollo/react-hooks'; import { useQuery } from '@apollo/react-hooks'; import { ApolloClient } from "apollo-client"; import { InMemoryCache } from "apollo-cache-inmemory"; import { HttpLink } from "apollo-link-http"; import gql from "graphql-tag"; const cache = new InMemoryCache(); const link = new HttpLink({ uri: "http://localhost:8000/graphql/" }); const client = new ApolloClient({ cache, link }); const HEROES_DOTA2 = gql` query { heroes { name heroType image } } `; const HeroesDota = () => { const { loading, error, data } = useQuery(HEROES_DOTA2); if (loading) return <p>Loading...</p>; if (error) return <p>Error :(</p>; return data.heroes.map(({name, heroType, image }) => ( <div … -
How to pass an id to a view as an argument in Django?
I am learning Django and at the moment I am at a really basic level. In this project, I am building a minimal cart app, and so far I have managed to display on the homepage some items and the relative price. I would rather, if possible to not use sessions for this project. I have now added an 'add' link next to each item in the list so that when the user clicks on it, that item will be added to the cart. (I was trying to do the same with an 'add' button but as far as I understood that implies the creation of a form, which will be my next issue to tackle.) I would like to display everything (menu items and cart summary) on the homepage. The newly created 'add_to_cart' view function takes in a request and an item and returns the request, the same HTML as home, and as the context, the 'cart_items' variable. My problem is that I can't figure out how to pass the item id, in order to 'get' that item in the query and then add it to the cart. The code I have produced so far is the following. models.py … -
Django Rlationships levels
I have 3 models : User, Attribute, Site. class User(models.Model): userid = models.CharField(max_length=200, primary_key=True) name= models.BooleanField(null=True) def get_absolute_url(self): return reverse('myapp:index') def __str__(self): return self.userid class Site(models.Model): pK_site = models.CharField(max_length=200, primary_key=True) name = models.CharField(max_length=200,null=True) def __str__(self): return self.pK_site class Attribute(models.Model): userid = models.ForeignKey(User, on_delete=models.CASCADE) role= models.CharField(max_length=200) site = models.ForeignKey(Site, on_delete=models.CASCADE) def __str__(self): return str(self.site) def get_absolute_url(self): return reverse('myapp:edit', kwargs={'pk' : self.userid.pk}) My problem is when i get for example the list of all the attribues (Class : Attribute) in a view, i can't get the Site of this attribute or its user in the template. Someone has a suggestion to do that ? thank you -
Facebook Oauth works but Google Oauth2 error : redirect_uri_mismatch in Django
I've a Django project where i want to have login feature using Google and Facebook. with the given below setup, i'm able to login using Facebook but when trying to login with Google, i keep getting : Error: redirect_uri_mismatch I've tried following urls in Authorized redirect URIs http://localhost:8000 http://localhost:8000/complete/google-oauth2/ http://localhost:8000/oauth/complete/google-oauth2/ Settings.py INSTALLED_APPS= [ ... 'social_django', # <-- social-auth-app-django .... ] MIDDLEWARE = [ .... 'social_django.middleware.SocialAuthExceptionMiddleware', .... ] TEMPLATES = [ ..... 'OPTIONS':{ .... 'social_django.context_processors.backends', # <-- related to social auth 'social_django.context_processors.login_redirect', # <-- related to social auth } ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = 'core:landing_page' LOGOUT_REDIRECT_URL = 'core:landing_page' MEDIA_ROOT = os.path.join(BASE_DIR,'pictures') MEDIA_URL = '/pictures/' ACCOUNT_DEFAULT_HTTP_PROTOCOL='https' SOCIAL_AUTH_URL_NAMESPACE = 'social' #facebook social auth details SOCIAL_AUTH_FACEBOOK_KEY = 'XXXXXXXXXXXXXX' # App ID SOCIAL_AUTH_FACEBOOK_SECRET = 'XXXXXXXXXXXXXXXXXXXXX' # App Secret #google social auth details SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'XXXXXXX-XXXXX.apps.googleusercontent.com' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'XXXXXXXXXXXXXX' in urls.py path('oauth/', include('social_django.urls', namespace='social')), # <-- social auth url in html <a class="btn button_google" href="{% url 'social:begin' 'google-oauth2' %}">LOGIN</a> in google+ api -
Why define create_foo() in a Django models.Manager instead of overriding create()?
Reading the Django docs, it advices to make a custom creation method for a model named Foo by defining it as create_foo in the manager: class BookManager(models.Manager): def create_book(self, title): book = self.create(title=title) # do something with the book return book class Book(models.Model): title = models.CharField(max_length=100) objects = BookManager() book = Book.objects.create_book("Pride and Prejudice") My question is that why is the previous one preferred to simply overriding the base class's create method: class BookManager(models.Manager): def create(self, title): book = self.model(title=title) # do something with the book book.save() return book class Book(models.Model): title = models.CharField(max_length=100) objects = BookManager() book = Book.objects.create("Pride and Prejudice") Imo it seems that only overriding create will prevent anyone from accidentally using it to make a illformed model instance, since create_foo can always be bypassed completely: class BookManager(models.Manager): def create_book(self, title): book = self.create(title=title, should_not_be_set_manually ="critical text") return book class Book(models.Model): title = models.CharField(max_length=100) should_not_be_set_manually = models.CharField(max_length=100) objects = BookManager() book = Book.objects.create(title="Some title", should_not_be_set_manually ="bad value") -
I want to upload the image to the database using default form in django but the image is not uploaded.It shows "No file chosen"
forms.py from django import forms from .models import Posts class PostForm(forms.ModelForm): class Meta: model = Posts fields = ['topic','post','thumbnail','author'] models.py class Posts(models.Model): topic = models.ForeignKey(Topic,on_delete=models.CASCADE) post = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author,on_delete=models.CASCADE) thumbnail = models.ImageField() def __str__(self): return f"{self.post[:20]}..." class Meta: verbose_name_plural = 'posts' views.py def add_post(request): if request.method == 'POST': form = PostForm(data=request.POST) if form.is_valid(): form.save() return redirect("/") else: form=PostForm() context = {'form':form} return render(request,'blog/add_post.html',context) add_post.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <form action="{% url 'blog:add_post' %}" method='post'> {% csrf_token %} {{form.as_p}} <input type='submit'> </form> </body> </html> when i try to submit the form the thumbnail field shows "no file chosen" automatically even when i have chosen the file.so please help me solve this issue!!! when i try to submit it shows "No file chosen" even when i chose -
query to fetch x starting with letter x having highest x
I Have 2 models class Author(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) email = models.EmailField() def __str__(self): return self.name class Article(models.Model): title = models.CharField(max_length=120) description = models.TextField() body = models.TextField() author = models.ForeignKey('Author', related_name='articles', on_delete=models.CASCADE) def __str__(self): return self.title what will be the query to fetch all those author whose name start with "a" and have written more than 6 articles. -
Adding full path to django MarkdownX images?
I have added a MarkdownxField to my django model, and it works well. I can edit it witha proper preview from the admin panel. However, when I added images to the markdown there's a problem. My app is built in React and is served from a different port on the domain. When MarkdownX adds the image to the markdown file it does so with a relative path, so the call goes to the client port instead of the server port where it automatically saves the image. I've looked through the settings options for MarkdownX but couldn't find something that would help out. The image is uploaded an saved well. But the client side can't get to it. -
Django Framework - Filling models
Does it possible to auto fill fields in same table with identical data without filling it with same data separately in Django Framework? models.py class Person(models.Model): name = models.CharField() first_phone = models.CharField() # <-- user fills only single input: 12345 second_phone = models.CharField() # <-- auto set using field: first_phone third_phone = models.CharField() # <-- auto set using field: first_phone -
RegisterForm() missing 1 required positional argument: 'request'
So I'm making a custom user model. This is what I'am following Here. I have been pretty much following the tutorial but still I cant make it done. Error: RegisterForm() missing 1 required positional argument: 'request'. here's my code. forms.py from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import User class UserAdminCreationForm(forms.ModelForm): """ A form for creating new users. Includes all the required fields, plus a repeated password. """ password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email',) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserAdminCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ password = ReadOnlyPasswordHashField() class Meta: model = User fields = ('email', 'password', 'active', 'admin') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on … -
Building a contribution functionality in django (i do not necessarily need the code just an idea)
NOTE I am not necessarily asking for code to build this, just ideas on how to do this. Links and blog posts for pointers are welcome. I am building a rest api. I have a model class Showcase(models.Model): title = models.CharField(max_length=50) description = models.TextField(null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="Showcases") created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=255, unique=True) def __str__(self): return self.title I am trying to build a functionality where the user that created a showcase can add users that contributed to the project which is the showcase. I was thinking of making this its own model like this: class Collaborators(models.Model): post = models.ForeignKey(Showcase, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) skill = models.ForeignKey(Skill, on_delete=models.CASCADE, null=True) role = models.TextField(null=True) added_on = models.DateTimeField(null=True) def __str__(self): return f"{self.user.name} collaborated on {self.post.name}" The user would have to search for users and then add them as a contributor to the showcase, which is where my brain scrambles a bit. The other important thing is that I want to be able to randomly go to a user and get ALL the showcases he has contributed to. -
'utility_tags' is not a registered tag library
While I was applying the i18n translation library to my project, I faced the following error: django.template.exceptions.TemplateSyntaxError: 'utility_tags' is not a registered tag library. But I can't find an official documentation and a forum about this problem. My code here: search.html {% extends "base.html" %} {% load i18n utility_tags %} <-- just pay attention to this {% block content %} <h2>{% trans "Search" %}</h2> <form method="get" action="{{ request.path }}"> <div class="well clearfix"> {{ form.as_p }} <p class="pull-right"><input type="submit" value="Search" class="btn btn-primary"></p> </div> </form> {% if query %} <h3>{% trans "Results" %}</h3> {% for result in page.object_list %} <p><a href="{{ result.object.get_url_path }}">{{ result.object.title }}</a></p> {% empty %} <p>{% trans "No results found." %}</p> {% endfor %} {% if page.has_previous or page.has_next %} <nav> <ul class="pager"> <li class="previous"> {% if page.has_previous %} <a href="{% modify_query page=page.previous_page_number %}"> {% endif %} <span aria-hidden="true">&laquo;</span> {% if page.has_previous %}</a>{% endif %} </li> {% for num in page.paginator.page_range %} <li>{% if num = page.number %} class="selected"{% endif %}> <a href="{% modify_query page=num %}"> {{ num }}</a> </li> {% endfor %} <li class="next"> {% if page.has_next %} <a href="{% modify_query page=page.next_page_number %}"> {% endif %} <span aria-hidden="true">&raquo;</span> {% if page.has_next %}</a>{% endif %} </li> </ul> </nav> {% … -
Deploying Vue-Django-graphene on NGINX
I apologise if this question is considered answered, however it seems that in my specific circumstances other solutions haven't managed to solve my issue so far. I have a django-vue project which uses GraphQL to communicate between vue and django. I am trying to serve my web app with uwsgi and NGINX, and the Django portion works fine, however there seems to be some issues when looking for the Vue /dist/ static files e.g. get http://ip.ip.ip.ip:8000/js/app.js ERR_ABORTED 404, same goes for CSS for the app and chunk-vendors. This is unfortunately my first deployment so my understanding is fairly shaky, however it seems pretty clear that NGINX doesn't understand the path to the dist folder correctly, but the variations I've tried so far haven't managed to get it to work. mysite_nginx.conf: # hubdev_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///srv/hub/hub.sock; # server 127.0.0.1:8001; } # configuration for the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name ip.ip.ip.ip; charset utf-8 root /srv/hub/frontend/dist/; index index.html; # max upload size client_max_body_size 75M; # 'Adjust to taste' # Django media # none yet … -
Django MEDIA_URL
I have this href calling the When I upload file this seems to be find Url: localhost:8000/media/name.pdf But when I update the name via ajax the url is like this Url: localhost:8000/nameofapp/media/name.pdf Every time I press that I get a wrong empty .html Can any one tell what went wrong here -
Upload file in two different folders and rename of file?
I could upload two different files in the same folder using django. But I have to upload it to two different folders and before uploading file it also have to be renamed with the time it got uploaded I have no idea as I am a beginner to django. Here is the code for uploading in same folder without renaming. My View.py def uploadFile(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() return render(request, 'core/upload.html', { 'form': form }) My Model.py class Document(models.Model): document = models.FileField(upload_to="documents/") My form.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('document', ) Could anyone please help me to figure out code for models.py and views.py . -
Upgrade problem with python3-django because of python-django-common on Debian 9
I have Debian 9 and can't upgrade python3 because python3-django needs python-django-common. What could I do to avoid this problem ? error when upgrading python My python versions