Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Made a simple blogging site with django, original posts that were made with manage.py exists and resolve, new posts with nginx/uwsgi do not resolve
I wrote a simple django website that seemed to completely work when running it with manage.py. I have since set up the site to run off of nginx/uwsgi and now new posts show up on the front page, but when I try to go to the page to reveal the blog post details I get a Not Found page. Can anyone help me figure out what I have done wrong? Here is my blog/urls.py from django.urls import path from . import views app_name = "blog" urlpatterns = [ path('', views.index, name='index'), path('<int:welcome_id>/', views.welcome_detail, name='welcome_detail'), path('blog/<int:category_id>/', views.category, name="category"), path('blog/<int:category_id>/<int:blog_id>/', views.blog_post_detail, name="blog_detail"), ] Here is my blog/views.py from django.shortcuts import render from django.template import loader from django.http import HttpResponse, Http404 from .models import WelcomePage, BlogPost, Categories def index(request): latest_welcome_message = WelcomePage.objects.order_by('id') latest_blog_posts = BlogPost.objects.order_by('id') categories = Categories.objects.order_by('id') template = loader.get_template('blog/index.html') context = {'latest_welcome_message' : latest_welcome_message, 'latest_blog_posts' : latest_blog_posts, "categories" : categories} return render(request, 'blog/index.html', context) def welcome_detail(request, welcome_id): try: welcome_message = WelcomePage.objects.get(pk=welcome_id) except WelcomePage.DoesNotExist: raise Http404("Question does not exist") return render(request, 'blog/detail.html', {'welcome_message':welcome_message}) def category(request, category_id): try: category = BlogPost.objects.get(categories=category_id) blogs_of_category = BlogPost.objects.all() except BlogPost.DoesNotExist: raise Http404("Blog does not exist") return render(request, "blog/category.html", {"category_id":category_id, "category":category, "blogs_of_category":blogs_of_category}) def blog_post_detail(request, category_id, blog_id): try: blog_post_detail … -
Polymorphic queryset in a Django ListView renders the template as many time as objects have the queryset
I have a polymorphic model using the polymorphic library on Django with one ParentModel and several ChildModel and I want to use the parent model with all his children in a queryset the queryset that I am using in my ListView is something like this <PolymorphicQuerySet [<ChildModel1: model description>, <ChildModel2: model description>]> But when my list view render my template, it renders my template as many time as child objects have if I have one object from ChildModel1, one from ChildModel2, and one from ChildModel3 it renders my HTML three times on the same screen one below another -
Don't start a thread in ASGI django while in manage.py
I am using Django 4.0.1 with the channels extension, so I'm using the ASGI interface. In one of my applications, I'm using it's AppConfig.ready() method to start a thread / asnyc loop - specifically the paho.mqtt package via loop_start(). If a message arrives on a subscribed topic, this application handles some business logic. This works fine for my usecase - with the exception of two problems: It's also started when I use any manage.py command. ./manage.py runserver (with reload enabled) will spawn a second process, which results in two connections being made - and I only need one. While I could use a filesystem-mutex to block the execution of a second application, I'd like to know, if there's a more "Django way" of solving this? -
Simple Math on One Webpage
I'm currently trying to do something as basic as adding two numbers the user inputs onto the page and showing the result on the same page but I'm running into problems. index.html {% extends "project_long_page/base.html" %} {% block body %} <form action="." method="POST"> {% csrf_token %} {{ forms }} <input type="submit"> </form> {% endblock %} views.py from django.shortcuts import render import datetime from django import forms from django.shortcuts import render class NewTaskForm(forms.Form): num1 = forms.IntegerField(label="Number 1") num2 = forms.IntegerField(label="Number 2") # Create your views here. def index(request): return render(request, "project_long_page/index.html") def add(request): return render(request, "project_long_page/index.html", { "form": NewTaskForm() }) urls.py from django.urls import path from . import views app_name = "project_long_page" urlpatterns = [ path("", views.index, name="index") ] Current Webpage Output Desired Webpage Output (While keeping original values inputted) Thank you for helping if you assist :,) Edit: In case you want to see this... -
XAMPP with WSGI not rendering django page
I am trying to run django on XAMPP Apache server and followed the steps mentioned here. Here are the changes in Apache config: When access the application in browser below is the result instead of django page: Please help what I am missing in this ? -
CustomUserCreationForm doesn't work in django
I am working on user registration app in django. I can write in inputs, but when I click submit button it doesn't do anything. My views.py file is: from django.urls import reverse_lazy from django.views import generic from .forms import CustomUserCreationForm class SingupPageView(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy("login") template_name = "registration/singup.html" My urls.py file is: from django.contrib import admin from django.urls.conf import path from . import views urlpatterns = [ path("singup/", views.SingupPageView.as_view(), name="singup"), ] My admin.py file is: from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm CustomUser = get_user_model() class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username',] admin.site.register(CustomUser, CustomUserAdmin) My singup.html file is: {% extends '_base.html' %} {% block title %}Sing Up{% endblock title %} {% block content %} <h2>Sing Up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="button">Sing Up</button> </form> {% endblock content %} -
How to submit a form with django ajax without parsing the input
I have a modal form that I use when users need to create something without leaving the page they are on. And to avoid refreshing the page after the modal form submission, I am using ajax to submit the form. For a series of reasons, I can't parse the form field by field so I was trying to find a way to get all the form data and submit them with a "general" approach and then process the post-request in my view (populate the form with the POST). However, the approach I am using is not working and I was hoping someone had an alternative idea. <body> <!--Modal --> <div class="modal fade" tabindex="-1" role="dialog" id="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"> <!-- Popup --> <div class="pop-up-form"> <div class="pop-up-form__wrp"> <!-- Title --> <div class="pop-up-form__title-wrp"> <h2 class="pop-up-form__title">Create New</h2> </div> <!-- END Title --> <!-- Form --> <form class="pop-up-form__form" id="form"> {% csrf_token %} {% for field in form %} <div class="pop-up-form__input-wrp"> <label class="pop-up-form__label" for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field|add_class:"pop-up-form__input" }} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} <!-- <div class="form-group{#% if field.errors %#}invalid{#% endif %#}"></div> --> <!-- BTNs --> <div class="pop-up-form__btn-wrp"> <button data-dismiss="modal" … -
Django Rest Framework ModelViewSet When Posted?
I have a simple rest application. models.py : class Check(models.Model): crypted = models.TextField() anid = models.IntegerField() def __str__(self): return str(self.anid) serializers.py : class CheckSerializer(serializers.ModelSerializer): class Meta: model = Check fields = ['crypted', 'anid'] views.py : class CheckViewSet(viewsets.ModelViewSet): serializer_class = CheckSerializer queryset = Check.objects.all() urls.py : router = routers.DefaultRouter() router.register('all', CheckViewSet) urlpatterns = [ path('', include(router.urls)), ] Here is what I need : I need to make a code run "when I posted into this page" How can I provide this? -
SQLite3 Integrity Error When Running "createsuperuser"
I am trying to extend the default Django User model by linking to it through a OneToOneField. I successfully migrated the changes and registered my Profile model inside admin.py, however, when I try to run the command python manage.py createsuperuser and fill in the information I get an Integrity Error. django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_profile.date_of_birth I know what the issue is. I have a field called date_of_birth which is required, and I can't leave it blank, that raises the exception. I want a simple solution, but couldn't think of one, and I don't want to add a bunch of blank=True snippets to all of my required fields. Here's my code. models.py from django.contrib.auth.models import User from django.db import models class Language(models.Model): # - [ CHOICES ] - # name = models.CharField(max_length=20) # - [ METHODS ] - # def __str__(self): return self.name class Skill(models.Model): # - [ CHOICES ] - # name = models.CharField(max_length=20) # - [ METHODS ] - # def __str__(self): return self.name class Profile(models.Model): # - [ CHOICES ] - # GENDER_CHOICES = [ ('Female', 'Female'), ('Male', 'Male') ] EDUCATIONAL_LEVEL_CHOICES = [ ('None', 'None'), ('Primary School', 'Primary School'), ('Secondary School', 'Secondary School'), ('High School', 'High School'), … -
Django Rest - Post Data and File
I have two models like so: class Tool(...): name = models.CharField(unique=True, ...) class Dataset(...): file = models.FileField(...) tool = models.ForeignKey(...) I want to send a post request such that I can create a Dataset instance, upload a file and specify which Tool the instance belongs to. Furthermore, it would be ideal if I could use the Tool name (which is unique) when sending the post request. So far I can upload a file successfully if I remove the tool from the DatasetSerializer. But when I add the tool to the DatasetSerializer I get a 400 Bad Request error without any further details in the console. Here are my serializers and views files: serializers.py class ToolSerializer(serializers.ModelSerializer): ... class DatasetSerializer(serializers.ModelSerializer): tool = ToolSerializer() class Meta: model = models.Dataset fields = ['tool', 'file', ...] views.py from rest_framework.parsers import MultiPartParser class DatasetViewSet(viewsets.BaseModelViewSet): parser_classes = [MultiPartParser] ... And here is the request I am trying to do: # I am using the tool id here, but would prefer to use the name requests.post( ... data = { 'tool' : 1 }, files = { 'file' : open('file/path','rb') } ) -
channels_presence.models.Presence runtimeError
its my first time implementing a Websockets with Django and I'm struggling to do this. I keep getting this error everytime I try to runserver: RuntimeError: Model class channels_presence.models.Presence doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. My settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'votemanager', 'roommanager', 'rest_framework', 'multiselectfield', 'django_filters', 'channels', ] CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } Can someone help me? -
How use uuid as primary key and slug for url in Django App?
I defined uuid to as primary key for my model and url. Now we want to use slug in the url, but we have a production database and the objects are using their uuid as id. Instead of modify the database type for the primary key (postgres), is posible to keep the primary key as uuid and use slug for the url? model.py class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.SlugField(null=True) urls.py urlpatterns = [ path("", Article.as_view(), name="article_list"), path("<slug:slug>", ArticleDetail.as_view(), name="article_detail"), ] template <a href="{% url 'articles:article_detail' article.slug %}">{{article.title}}</a> This configurations is giving me a ValidationError with ['“my-slug” is not valid UUID.'] Thanks -
Need to confirm this ER diagram of simple transfermakt like databse to use in django
I'm creating a simple transfermarkt like database to use in django but I think I have the wrong ER relations, would love some help if possible. This is what I have (not complete): ER Diagram Also, I'm using this tool: http://onda.dei.uc.pt/v3/ -
What is the most similar framework to Django in java [closed]
What I liked most about Django was the built in admin page, built in database manager, simplicity of creating dynamic websites, and built in authentication, although the admin page and database manager aren't a must. -
Django/Python - Datapicker and data from server
I've been trying for a while to figure out how to make a data picker that uses moment.js (website: http://www.daterangepicker.com), and connect it to my database which is displayed by a table, and the data is displayed from the server as a loop, and for no reason I can't get it to work. Maybe it just can't be done, I don't have the strength anymore, so I'm asking here if someone could help me how it can be done. I need to make a "datapicker" which will have a range selected by the client, and will automatically filter the database, and display the table only with rows that meet the query. test-table.js import moment from "moment"; $(document).ready(function() { $(function() { var start = moment("2022-01-01 12:34:16"); var end = moment("2022-03-03 10:08:07"); function cb(start, end) { $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); } $('#reportrange').daterangepicker({ startDate: start, endDate: end, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] } }, cb); cb(start, end); }); $('#reportrange').on('apply.daterangepicker', function(ev, picker) { var start = picker.startDate; var end … -
How can I update my customuser table when user is created by django-allauth social login?
I've integrated django-allauth google and facebook login successfully but I'm having problem with my custom user model I want to update is_customer field in to True in my user model here is my user model class UserManager(BaseUserManager): def create_customer(self, email, phone=None, password=None, **extra_fields): '''Creates and saves a new user''' if not email: raise ValueError('Users must have an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.phone = phone user.set_password(password) user.is_customer = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): '''Custom user model that supports using email instead of username''' phone = models.CharField(unique=True, max_length=15, null=True) email = models.EmailField(max_length=255, unique=True) fname = models.CharField(max_length=255, default='None') lname = models.CharField(max_length=255, default='None') is_customer = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone'] this how my signup page looks in my signup page I've facebook, google, and normal signup form for user who don't have account on both. I think is there any way I can override django-allauth socialaccount model. One thing I forgot to mension that facebook and google login proccess handled by django-allauth forms so they don't call my User.objects.create_customer() method is there way to call this method so it will become easy for … -
django: how to make query be not lazy executed?
I have problem with query lazy execution in my custom Manager method. In it i want to separate query by model CharField choices and return dict[choice, QuerySet]. model.py part: ... PRODUCT_STATUS = [ ('pn', 'Запланировано'), ('ga', 'В процессе (Ознакомляюсь)'), ('rv', 'Повтор'), ('ac', 'Завершено'), ('ab', 'Брошено'), ('pp', 'Отложено'), ] class ExtendedManager(models.Manager): def separated_by_status(self, product_type): query = super().get_queryset().all() dict_ = {} for status in PRODUCT_STATUS: dict_.update({status[1]: query.filter(status=status[0]).all()}) return dict_ ... views.py part with manager use: ... class ProductListView(ContextMixin, View): template_name = 'myList/myList.html' def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: product = kwargs.get('product') if product not in {'film', 'game', 'series', 'book'}: raise Http404 context = self.get_context_data() context['title'] = f'Список {product}' context['dict_queryset'] = Product.objects.separated_by_status(product) return render(request, self.template_name, context) ... django debug toolbar result: here The problem is that the query is lazy executed in the manager, but in templates it is already fully executed for each PRODUCT_STATUS element separately. How cat it be optimized to execute 1 time? I'm very sorry if I use the term "lazy" incorrectly. -
Send data to database via fetch and subsequently display this data to html page via fetch again without submitting form or refreshing the page
I have a django app. I'm typing a comment in a form and I'm sending it to my database via fetch. my js code document.getElementById("comment-form").onsubmit = function write_comment(e) { e.preventDefault(); const sxolio = document.getElementsByName("say")[0].value; fetch('/comment', { method: 'POST', body: JSON.stringify({ say: sxolio }) }) .then(response => response.json()) .then(result => { //print result console.log(result); }); my views.py @requires_csrf_token @login_required(login_url = 'login')#redirect when user is not logged in def comment(request): if request.method != 'POST': return JsonResponse({"error": "POST request required."}, status=400) new_comment = json.loads(request.body) say = new_comment.get("say", "") user = request.user comment = Comment( user = user, say = say, photo = Userimg.objects.get(user = user).image ) comment.save() return JsonResponse({"message": "Comment posted."}, status=201) Next thing i wanna do is to display this comment and all the other data from my db, to my html page without refreshing.The moment i push the post button i want the comment to be dispayed. I dont want to update the page with some element.innerHTML = data. my js code function display_comments() { fetch('/all_comments') .then(response => response.json()) .then(all_comments => { do some stuff my views.py @login_required(login_url = 'login')#redirect when user is not logged in def all_comments(request): all_comments = Comment.objects.order_by("-date").all() print(all_comments[0].serialize()) return JsonResponse([comment.serialize() for comment in all_comments], safe=False) If i … -
Template File not found
So I am trying to open a template from... But the template file is not shown as below... from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): return render(request, "home/index.html") Weird thing is that my webpage still works, and when I delete that function it does not. Here is some additional Info... settinbgs.py # Application definition INSTALLED_APPS = [ 'project_long_page', 'about', 'home', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] home/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] -
Django Processing Bar between two requests
I have a calculation-intensive application, it takes inputs and processes about 10-15 formulas on the inputs including NPV, IRR-like calculations. I am implementing the calculations using template tags in django. Below are the code snippets : [filters.py][1] @register.filter def **client_irr**(value,arg): fcf_list = [] for i in arg: fcf_list.append(fcf(value,i)) return round(npf.irr(fcf_list) * 100,2) [inputs.html][2] <div class="products-row"> <div class="product-cell price">{{ i.parameter }}</div> <div class="product-cell price">{{ i.units }}</div> <div class="product-cell price">{{ i.values|**client_irr:**total_time}}</div> </div> There are a lot of calculations like these!! I am implementing these calculations correctly? I am not sure, I find this way completely wrong! The request for (/inputs) calculating the values takes about 20-22 seconds and the UI gets stuck, this creates a very user experience(UX). So, I am looking for either a processing bar(which I am unable to get a good tutorial in Django) or a way to optimize these calculations. Thank you, folks!! It means a lot! If you have any solutions please help! -
Django - Geting fields by values_list in queryset
I have trouble getting values by values_list(From what I've read it is supposed to this) from my db in django: stocks_query = Indexes.objects.filter(Symbol=index).values("Date","Open", "High", "Close", "Low","Volume") print(stocks_query.values_list("Date", flat=True)) Every time I get QuerySet object <QuerySet [datetime.date(2021, 12, 28), datetime.date(2021, 12, 27), datetime.date(2021, 12, 26), datetime.date(2021, 12, 24)... -
Django Image Form upload & update is not working properly?
models.py class ProductVariantsImages(DateTimeModel): product_variant = models.ForeignKey(ProductVariants, on_delete=models.CASCADE, related_name='product_variants_images') display_image = models.ImageField(upload_to='product_images/', null=True) item_image1 = models.ImageField(upload_to='product_images/', null=True) item_image2 = models.ImageField(upload_to='product_images/', null=True) item_image3 = models.ImageField(upload_to='product_images/', null=True) def __str__(self): return str(self.product_variant) forms.py class ProductVariantsImagesForm(forms.ModelForm): class Meta: model = ProductVariantsImages fields = ('display_image','item_image1','item_image2','item_image3') views.py if request.method == "POST": print(request.POST) item = ProductVariants.objects.get(item_num=pk) product_id=item.product_id admin_user = CustomUser.objects.get(id=request.user.id) product_variant = ProductVariantsImages.objects.filter(product_variant=item) product_form = AdminProductForm(request.POST, instance=product_id) item_form = ProductVariantsForm(request.POST, instance=item) variant_images_form = ProductVariantsImagesForm(request.POST,request.FILES,instance=product_variant[0]) if product_form.is_valid(): product = product_form.save(commit=False) vendor = request.POST.get('vendoruser') vendoruser = CustomUser.objects.filter(id=vendor) product.vendoruser = vendoruser[0] product.save() if item_form.is_valid(): item = item_form.save(commit=False) item.save() if variant_images_form.is_valid(): --------> #Problem comes here variant_image = variant_images_form.save(commit=False) variant_image.save() return redirect('loomerang_admin:loomerang_admin_products') I am getting the form details correctly. When I am updating the details is all worked fine. I have four image inputs. When I update the single image file input in the template, the other image fields were also updated. how to do this correctly? -
Does Django Rest Framework have a built in solution for a Validation API?
By Validation API, I mean an API that simply takes in a field and a field type, and returns the validation result, without attempting to create, update, or delete anything. Rough Example I would want a request like this curl -X POST /api/validation -H 'Content-Type: application/json' -d '{"type":"email","value":"invalid.email@@com"}' To return a body like this: { 'Enter a valid email address.' } Use Case Let's say you have a decoupled frontend and backend, and the backend is an API using the Django Rest Framework. In the frontend you may have a sign up flow that has several pages. Page 1: user enters an email, and we check if it's valid Page 2: user enters a phone number, and we check if it's valid Finally, create a user with those fields In this flow, it would be useful to validate the email and phone number with the backend at separate times without attempting to create a User first. You wouldn't want to create a partial user with just an email, and then later patch that user to update the phone number field, because --- well because you just wouldn't want to. Why not take care of the validation in the frontend? Because … -
How Database should I use for django other than django admin?
After making a whole project, when deploying it in the heroku server, I came to know that heroku doesn't accept sqlite3 database. So what should I do? Will I change the database or will I change the hosting site? But I cannot find a good free hosting site. Please someone suggest what to do? -
Django OAuth2 Toolkit implementation authorization call returns login page html
I am new with the Django OAuth2 Toolkit (and relatively new with Django still) and am trying to implement it with an already existing API (DRF). Up until now, the authorization of the API has worked through a static token that is passed through along with the request. On the website itself, users are able to login and session authentication is enabled. I installed the toolkit as per the instructions and have created an authorization code application with the 'skip authorization' toggle ticked. I am now trying to access the authorization server with the following URL (as a GET): http://127.0.0.1:8000/o/authorize/?response_type=code&client_id=client_1&redirect_uri=http://127.0.0.1:8000/trial&code_challenge=WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U&code_challenge_method=S256&scope=read&client_secret=secret_1 When I try to call this (via postman, API or browser) I get back the login page instead of the code as expected. I do not understand why this is happening and how to skip this. Any ideas or help would be much appreciated!