Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Password protect page django
I would like to make a registration page for judges, but I would like to make sure that before entering the registration page you have to enter the password, each judge will have the same one that I will make available to them, he needs a simple page with one window to enter the password previously given by me. If someone would be able to say how I can create such a model and then its form, or if there is any other easier way, I will be grateful for any hints -
Adding fields during runtime Django
Im working on a personal project using django rest framework. Im stuck with something. Problem is, Initially user will be adding 3 options. If user wants he can add as many options he want. All those options should be added dynamically by just pressing on "add fields". How should my approach to this should be? -
What is the best WYSIWYG editor to upload images and videos for Django
I've used Froala and its Django package (django-froala-editor), the first downside is Froala is not free and the second one is to upload videos. For images, it works like a charm but not for videos. Any suggestion for WYSIWYG editor for Django that supports image and video uploading out of the box? -
Local Variable Referenced Before Assignment Error Django
I am working on an eCommerce website. While saving billing and shipping information, I have a checkbox where user can input billing address and set is as the same shipping address. For that, I have used the instance of billing address which I have taken from the user and saved in the database when the user inputs the billing info. Since it is inside if statement, when I reference it in the shipping_address, it shows local variable referenced before assignment Error! I know why this error occurred, but unable to find how can I approach to solve it. I tried using global at the top of the function, but that too did not work. forms.py class CheckoutForm(forms.Form): # Billing Address billing_country = forms.ChoiceField( choices=COUNTRY_CHOICES, required=False) billing_address = forms.CharField(required=False) billing_address2 = forms.CharField(required=False) billing_zip = forms.CharField(required=False) # billing_phone = forms.IntegerField(required=False) # Shipping Address shipping_country = forms.ChoiceField( choices=COUNTRY_CHOICES, required=False) shipping_address = forms.CharField(required=False) shipping_address2 = forms.CharField(required=False) shipping_zip = forms.CharField(required=False) # shipping_phone = forms.IntegerField(required=False) # UTILITIES same_shipping_address = forms.BooleanField(required=False) set_default_billing = forms.BooleanField(required=False) use_default_billing = forms.BooleanField(required=False) set_default_shipping = forms.BooleanField(required=False) use_default_shipping = forms.BooleanField(required=False) models.py class Address(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) country = models.CharField(choices=COUNTRY_CHOICES, max_length=15) street_address = models.CharField(max_length=100) town_city = models.CharField(max_length=50) postcode = models.CharField(max_length=15) address_type = models.CharField(choices=ADDRESS_CHOICES, max_length=1) … -
Can we use multiple framework (both front end and back end) to build a website?
I am a newbie ( HTML CSS/ zero level ) to web development and when I search the internet there are literally tonnes of web framework for both front end and backend development. Like Django, PHP, NodeJs, ReactJs, VueJs etc. So can anyone please sort out best framework and also one of my major doubt is Can I built or use different framework simultaneously to build a website (front end and back end) OR Should I possibly learn some from above list and do my work with it ( That means we cannot use multiple language at once like Djanog PHP and Nodejs etc togther). If we can do so , building a website with multiple framework possess any advantage or it will be fairly difficult manage.. -
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. plz help me out plz
I'm trying to connect a form with the database but I encounter this error any expert plz help from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.conf import settings # Create your views here. def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['pass'] cnfrm_password = request.POST['cnfrm_password'] phone_number = request.POST['phone_number'] user = User.objects.create_user(username=username, password=password, email=email, first_name=first_name,last_name=last_name, phone_number=phone_number) user.save() print('user created') return redirect('/') else: return render(request, 'register.html') -
How do I create a Django superuser in ssh?
I am deploying Django with PostgreSQL in Azure for a school project, per this tutorial. I am working with Django 2.1.2, and Python 3.7.5. In the "Run Database Migrations" step of the tutorial, I am instructed to open an SSH session and run the following commands: cd site/wwwroot source /antenv/bin/activate python manage.py migrate python manage.py createsuperuser When I run the 'createsuperuser' command, I expect a prompt for a username, email address, and password, but I am not prompted for any of these. Instead, the SSH session prompts me for another input: (antenv) root@62a62185684a:/home/site/wwwroot# As such, I am unable to log in to my Django installation. When I attempt a login, I receive the following error message: The traceback is at the end of this message. I expect to be able to create a superuser in Django, and use that superuser account to configure the app. Instead, I receive the ProgrammingError message and am unable to proceed. Any help would be gratefully received. I have Googled the various error message, searched StackOverflow, and searched YouTube for tutorials, and I have reached a roadblock. Environment: Request Method: POST Request URL: http://nicholas-blog.azurewebsites.net/admin/login/?next=/admin/ Django Version: 2.1.2 Python Version: 3.7.5 Installed Applications: ['polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', … -
Add foreign key relationship on the existing table
I have two models A and B in my django app but, they have don't have relationship between them. I want to add one to many relationship between them. How to add this relationship without loosing the data -
Best way to do simple API calls between Django server and android application?
I'm building a system where I store a Member model on a Django server, one of the attributes of Member is score which is what I want to change using API calls. My question is what would be the best way to do this? I looked into the Django REST framework but it seems a bit overkill for what I'm trying to do. I've been trying to pass the necessary information through the url using regular expressions but I'm unsure if it will work. Outline of what I need is below iOS/Android app makes request sending pk and score to add to total server updates appropriate model instance and returns True/False to app depending if save was successful -
How do I ensure that an event can have zero or multiple sessions?
I have two models, and I have to create a condition between these two models. The condition can be 0 or multiple sessions of an event as follows. How can I do this. class Session(models.Model): name=models.CharField(max_length=100) start_date=models.DateField() end_date=models.DateField() speaker=models.CharField(max_length=100) slug = models.SlugField(unique=True, editable=False, max_length=100) class Event(models.Model): name = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() session=models.ForeignKey(Session,on_delete=models.CASCADE) slug = models.SlugField(unique=True, editable=False, max_length=100) -
Show number of objects in Many to Many Relationship? (Django)
I have a simple blog created in Django with Posts and Comments for each post. I'm trying to show the total number of comments for each post on the home page but I can't get the total to show. Here's my model: class Post(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) title = models.CharField(max_length=100, blank=False) content_text = models.TextField(blank=False, max_length=3000) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Comment(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) post = models.ForeignKey(Post, on_delete= models.CASCADE) content_text = models.TextField(max_length=500) created_date = models.DateTimeField(auto_now_add=True) My views.py: def home(request): posts = Post.objects.all() return render(request, 'post/home.html', {'posts': posts}) And lastly my html file: {{ post.comments.count }} The other information displays correctly such as {{post.title}}. Any ideas what I'm doing wrong? Thanks! -
How to remove currently image path and clear check box in django forms?
I want to remove this field from from django forms. enter image description here forms.py class ProfileForm(ModelForm): class Meta: model = Profile fields = '__all__' exclude=['user'] -
Template for Carousel not showing context variable
I have made a Slider Model which contains 3 images and Texts related to it to slide in a Carousel My problem is that I want these images to be shown from the newest to oldest. If I remove the {% if sliders %} {% for slider in sliders %} the latest image only appears because in the views it is filtered by .latest('timestamp') I have also tried to replace .latest('timestamp') in the views with .all() it still didn't work This is the model: class Slider(models.Model): title = models.CharField(max_length=60) image = models.ImageField(blank=False, upload_to='Marketing') header_text = models.CharField(max_length=120, null=True, blank=True) middle_text = models.CharField(max_length=120, null=True, blank=True) footer_text = models.CharField(max_length=120, null=True, blank=True) button_text = models.CharField(max_length=120, null=True, blank=True) active = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.title def get_image_url(self): return "%s/%s" % (settings.MEDIA_URL, self.image) I've had help with the view which is as follows: class HomeView(ListView): model = Item paginate_by = 10 template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) try: context['marketing_message'] = MarketingMessage.objects.filter( active=True).latest('timestamp') except MarketingMessage.DoesNotExist: context['marketing_message'] = None try: context['slider'] = Slider.objects.filter( active=True).latest('timestamp') except Slider.DoesNotExist: context['slider'] = None return context This is the template: {% if sliders %} {% for slider in sliders %} <div class="carousel-item {% if forloop.first … -
CSS file isn't applying to the page, not loading under sources
I was trying to link a css file to my html, and for some reason the css won't load in. Below I'll supply the html and css code. When I open the page source, the css href works fine, I can click on it and it takes me to the css file, but when I inspect I can see that the css file is not part of sources. I've tested my code on JSFiddle and it works fine there, as well as on the snippet here. I also tried pressing ctrl + f5 and shift + f5 to refresh the page without caches, but nothing changed. So I don't know what else to do to fix this. I've been doing it on Chrome so I tested it real quick on Firefox but still, no changes. Thanks in advance for any help. raw html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> <link rel="'stylesheet" type="text/css" href="{% static 'polls/styles.css' %}"> </head> <header> <div class="site-header" width="100%" height="100px"> <h3><a class="site-header-link" href="/polls">Home</a></h3> </div> </header> <body> {% block content %}{% endblock %} </body> </html> Runnable html and css. li a { color: green; } body { background: grey; } .question-display … -
Join two sets of data of the same table in django
I want to select two sets of data from the same table and them join them using a common field class modelA(models.Model): year = models.IntegerField() week = models.IntegerField() sales = models.IntegerField() pillar = models.IntegerField() I want two select data from the (for example) week 8 and 9 of the year, then join them using the corresponding pillar so i get something like this: Using sql i think it should look like this, but i don't know how to translate that to django select * from ( select * from data where year = 2020 and week = 8 ) as A join ( select * from data where year = 2020 and week = 9 ) as B on A.pillar = B.pillar -
usage of ('/') in the following django code
I started a todo app tutorial and having a problem into fully understanding code in this part of it: def index(request): tasks = Task.objects.all() form= TaskForm() if request.method == "POST": form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') ''' just the part which used redirect('/') , what is the meaning of this sign (( ('/') )) and if you could explain to me why is it important to specify for the app that if the request method is POST do the following moves? -
Save successfully validated form fields when other fields fail
I have a rather long form including validation which I would like users to fill out. If the user submits the form successfully then it is saved to the db. I am aware that some users may attempt to submit the long form, only to have it raise validation errors, then leave my site and return to complete it later. I would like the form fields which are successfully validated to be saved (or is it possible to have them save automatically without the user needing to press the submit button?) so if the user exits the site they can later return and only have the fields which failed validation blank, not the entire form. views.py def needs_analysis(request): if request.method == 'POST': form = PersonalInformationForm(request.POST, request.FILES, instance=request.user.personalinformation) if form.is_valid(): form.save() return redirect('enrolment-index') else: form = PersonalInformation(instance=request.user.personalinformation) context = { 'form' : form } return render(request, 'enrolment/personal_info.html', context) Thank you. -
"FieldList" with foreign objects
Let's say I have cars running in different races. I want an ordered list in Race with the cars that will run. The problem is I want to manually modify that list from admin interface. class Car(models.Model): id = models.CharField(max_length=16, primary_key=True) class Race(models.Model): title = models.CharField(max_length=255) start_grid = models.ForeignKey(Car,on_delete=models.CASCADE) I have read many posts about ordering on related ForeignKey based on some filters like creation date or so, but this particular case requires to define a manual order. Don't exist some kind of models.ListField so my solution is to create a list of related Car ids and store JSON string in Race. But feeling that is not a good idea How can I create a field that contains an ordered list of foreign objects/id and be compatible with modify the order from admin interface? -
DJANGO - static doesnt load when using <int:pk>
I am a newbie and I tried to solve this problem now for hours. My CSS files work normally on every other url but when I enter OrderUpdateView.as_view() it doesn't work anymore. It shows the site but there is no css styling. I can send forms.py if needed. from django.conf.urls import url from django.urls import path from .views import * urlpatterns = [ url(r'^$', index, name='index'), url(r'^profile$', profile, name='profile'), url(r'^order/', OrderListView.as_view(), name='order'), url(r'^create/', CreateOrderView.as_view(), name='add_order'), path('update/<int:pk>/', OrderUpdateView.as_view(), name='edit_order'), path('done/<int:pk>/', done_order_view, name='done_order'), path('delete/<int:pk>/', delete_order, name='delete_order'), path('action/<int:pk>/<slug:action>/', order_action_view, name='order_action'), # ajax_calls path('ajax/search-products/<int:pk>/', ajax_search_products, name='ajax-search'), path('ajax/add-product/<int:pk>/<int:dk>/', ajax_add_product, name='ajax_add'), path('ajax/modify-product/<int:pk>/<slug:action>', ajax_modify_order_item, name='ajax_modify'), ] Here are my settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'bz28yb5yaw37@=!@&3e@e)1a)p1!_zt)wxs5a8*s%qhv21&sjk' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'inventory', 'django_tables2', 'import_export', ] 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 = 'inventory_management_system.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', … -
Template not displaying any data in Django application (Django 3.05)
Basically, I'm building a Django application that's like a blog. So, my "social" page is supposed to display posts (that right now I'm adding through the admin page). However, when I load that page, nothing shows up. Here's my views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Posts # Create your views here. def home(request): context = { 'posts' : Posts.objects.all() } return render(request, 'social/social.html', context) Here's my models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Posts(models.Model): post_title = models.CharField(max_length = 20, help_text = 'Enter post title') post_text_content = models.TextField(max_length = 1000) post_author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) post_date = models.DateField(auto_now = True, auto_now_add = False) ### Make seperate model for image content ### class Meta: ordering = ['post_title', 'post_author', 'post_date', 'post_text_content'] def __str__(self): return self.post_title class Author(models.Model): first_name = models.CharField(max_length = 100) last_name = models.CharField(max_length = 100) date_of_birth = models.DateField(null = True, blank = True) user_name = models.CharField(max_length = 20) class Meta: ordering = ['user_name', 'first_name', 'last_name', 'date_of_birth'] def __str__(self): return str(f'{self.first_name}, {self.last_name}, {self.user_name}') Here's my social.html: {% extends "social/base.html" %} {% block content %} <h1>Your Feed</h1> <p>This is your feed. Here, you'll see posts from people you follow.</p> … -
Cannot integrate Django and Charts.js, data wont pass from views
Cannot pass data from Django Views to template in which im using charts.js garphs to display my graph. The paid and unpaid fields wont show on graph but the labels does. How do i fix that. Whats the right syntax. Here's the code: My View: def graph2(request): labels = [] data1 = [] data2=[] queryset = due.objects.order_by('-paid')[:10] for Due in queryset: labels.append(Due.months) data1.append(Due.paid) data2.append(Due.unpaid) return render(request, 'account/graph2.html', { 'labels': labels, 'data1': data1, 'data2': data2, }) Template: <script> new Chart(document.getElementById("bar-chart-grouped"), { type: 'bar', data: { labels: {{ labels|safe }}, datasets: [{ barPercentage: 0.5, barThickness: 6, maxBarThickness: 8, minBarLength: 2, data: {{ data1|safe }} }], datasets: [{ barPercentage: 0.5, barThickness: 6, maxBarThickness: 8, minBarLength: 2, data: {{ data2|safe }} }] }, options: { title: { display: true, text: 'Population growth (millions)' } } }); </script> Model: class due(models.Model): months= models.CharField(max_length=30) paid = models.PositiveIntegerField() unpaid = models.PositiveIntegerField() def __str__(self): return "{}-{}".format(self.months, self.paid,self.unpaid) -
If i have to run cron job every Friday at 10am, is this the rite setting: 0 17 5 * * *
If i have to run cron job every Friday at 10am, is this the rite setting: 0 17 5 * * * Thanks -
Django non-static content not rendering
I'm using kubernetes and containers. nginx ingress controller. Also nginx container is serving up static content. The landing page (static) works just fine (checked with incognito, no caching). Soon as I go to a page that requires rendering something from the backend, it times out. I logged into the containers and cannot see any immediate issues in the log files or elsewhere. I shut down all the containers and started them fresh. Still nothing from the Django side is responding. Here is my nginx config (in Kubernetes/yaml format): apiVersion: v1 kind: ConfigMap metadata: name: nginx-config data: nginx.conf: | events { worker_connections 1024; } http { server { access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; listen 8080; server_name localhost; location ^~ /.well-known/acme-challenge/ { default_type "text/plain"; } location /static/ { autoindex on; alias /code/core/static/; include /etc/nginx/mime.types; } location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:8080/; } } } I can't tell what the issue is. Any ideas on how to troubleshoot? -
Bootstrap django - nav dropdown issue
Hi this is my first django project. I am trying to implement base templating. Using django 3 and free sb admin 2 template. I am having an issue with nav dropdown, what i am missing ? I was also having issue with sidebar but fixed that with templatetags. Please check my template attachment here. This is what it currently looks like Thanks in advance -
FileNotFoundError at /main/insert_phone/
I am building a django app which sends texts using twilio. I'm trying to have it get the body of the message from a text file which is in the same directory as my views.py file, which is where the code for sending the text is. I'm getting this error: "FileNotFoundError at /main/insert_phone/ [Errno 2] No such file or directory: 'textgenrnn_texts.txt'" and I'm not sure why because the name of the file is correct. Here is the part of the views file where the issue is: from django.shortcuts import render, redirect from django.http import HttpResponse, HttpRequest from django.core.exceptions import ValidationError # import pymsgbox from .models import Phone from .forms import Post import subprocess from twilio.rest import Client ... def insert_phone_item(request: HttpRequest): phone = Phone(content=request.POST['content']) try: phone.full_clean() except ValidationError: return redirect('/main/list/') phone.save() # get receiver from postgres db reciever = Phone.objects.values_list('content', flat=True).distinct() # get text body from file with open('textgenrnn_texts.txt', 'r') as myfile: text = myfile.read() client.messages.create(to=reciever, from_=sender, body=text) return redirect('/main/list/')