Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't see code (every function and class block shows 3 dots ) in django modules when open with ctrl+click in vscode
enter image description here i try to uninstall and reinstall vscode and also try different python version(3.8 & 3.6) interpreter can't fix my issue -
Django 'featured' field? ModelName.objects.filter(featured=True)
ModelName.objects.filter(featured=True) I saw it. I looked it up. I didn't find any answer. I assumed it's mean featured like it's name and pretend I didn't have any question at all. But now I saw it again. WHAT IS THIS? How do Django model decide an objects is "featured". Is it true by default? Is it true when all property is not null or blank? Why is it true? Please someone give me the answer or I'll pretend I've already known it again. -
Multiple django server with a database server
I'm trying to create an application with the python3 Django web framework. and each of the features will be separated by docker container with different Django. The reason I'm trying to separate each feature is because to provide stable service even if one of the features is down or not functioning properly. for example, the app has a content web page. once client clicks the web page, then it shows content to the customer. btw the content is collected by the admin user manually with a specific URI. once it requests the URI, then django starts to collect the data from the API server and the data stored in MySQL database. However, while collecting the contents via API server, the web contents are not functions properly since django app still being progressing to collect bunch of data from API server. Therefore, I'd like to separate each function in the different Django webserver which running on docker container indivisually. To do that, multiple Django server will be running on each docker container, but, the database will be using the same single MySQL server. ex) models.py are defined by Django main server: class Menu(models.Model): school_name = models.CharField(max_length=120, null=True) Year = models.DecimalField(max_digits=65, decimal_places=0, … -
Which is better for blockchain Flask or django?
My app is a web app where the UI logic is from react JS and blockchain code is written in python, but I am having trouble in understanding which framework to choose for my backend , can somebody help me? -
Django MultiValueDictKeyError handling media
I am working on a django application in which i must store uploaded media to root/media and am getting the following error: 'media' Request Method: POST Request URL: http://127.0.0.1:8000/home Django Version: 3.2.6 Any help or pointers would be greatly appreciated! views.py code: def home(request): form = PostForm() signupform=SignupModelForm() comments=CommentForm() post=Post.objects.all() commentall=Comments.objects.all() member = Member.objects.all() user = User.objects.all() if request.method == "POST": form = PostForm(request.POST,request.FILES) comments=CommentForm(request.POST) if form.is_valid() and request.POST['action']=='posting': data=form.save(commit=False) data.user = request.user data.media = request.POST['media'] data.save() print("posted status") return redirect("/home") home.html code: <form method="post" enctype="multipart/form-data" style="float:left; width:100%; margin-left: -10%;"> {% csrf_token %} {{ form.as_p }} <button type="submit" name="action" value="posting">Post</button> </form> Thank you! -
Deploying app fails with nginx and react/django
I've been trying to deploy a React+Django app in development but without success. So everything works fine locally using Django's python3 manage.py runserver In deployment, I am using gunicorn+nginx. When I set gunicorn and test it everything works fine. However, when I add nginx on top, the website works but it has lots of bugs, server calls fall 1 in 3 times, and the app is not stable. For example, I have a counter to count the numebr of visits in each page and it just keeps giving the sums of different combinations of visits each time I change the page, in short, the app is not stable. Here is my nginx configuration file /etc/nginx/sites-enabled/myapp server { listen 80; server_name myip; client_max_body_size 700m; client_body_buffer_size 16k; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /path/to/app; } location /media/ { root /path/to/app; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/myapp/myapp.sock; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; try_files $uri /index.html; } location /api { include proxy_params; proxy_pass http://unix:/home/ubuntu/myapp/myapp.sock; } } I have no clue what's going on. Does nginx have to be configured specifically to allow React's api/ urls? -
Is there a simple way to check if a mail backend is valid in Django without sending a mail?
In my tool the users can provide a mail backend using certain keys and send their mails via the backend. This all works, but I would love to have a quick check if the provided backend actually will work. Using something like this check_mail_connection doesn't work as this actually returns False even though I entered a valid connection. from django.core.mail import get_connection class User(models.Model): ... def get_mail_connection(self, fail_silently=False) return get_connection(host=self.email_host, port=self.email_port, username=self.email_username, password=self.email_password ... ) def check_mail_connection(self) -> bool: from socket import error as socket_error from smtplib import SMTP, SMTPConnectError smtp = SMTP(host=self.email_host, port=self.email_port) try: smtp.connect() return True except SMTPConnectError: return False except socket_error: return False I don't want to send a test mail to confirm, as this can easily get lost or fail on a different part of the system. -
How can I resolve IndexError: list index out of range
I am trying to cal a django model function but i am getting list index error. This is the User model. ......................... fields ......................... def performance(self, start_time, end_time): actual = Sum("scores", filter=Q(status="completed")) q = self.taskassignt.filter( due__gte=start_time, due__lt=end_time ).annotate(actual=actual, total=Sum("scores")) return (q[0].actual / q[0].total) * 100``` ```user.performance(timezone.now() + timedelta(days=-7), timezone.now())``` is how I used it in my view.py. why am I getting this error? -
How to make a search method in django app
I have three models. How to do a search method to browse my three models together. For example if i search for the word "bluebird" in the search bar, i want it to browse through the three models to return the result to me. I saw on a forum the chain method that can be imported from itertools but i don't know how to use it ! models.py class Category(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True) def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=250) photo = models.ImageField(upload_to='pics/authors/', default='pics/default-author.jpg') biography = models.TextField(blank=True) def __str__(self): return self.name class Book(models.Model): author = models.ManyToManyField(Author) editor = models.CharField(max_length=250, blank=True) title = models.CharField(max_length=250) description = models.TextField(blank=True) date_added = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) cover = models.ImageField(upload_to='pics/covers/', default='pics/default-cover.jpg') pdf_file = models.FileField(upload_to='pdfs/books/', default='pdfs/default-pdf.pdf') categories = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.title -
How to make Django queries with associated tables?
I'm trying to create a 'saved post' feature on a website. I'm struggling with how to create a query that I can use to populate my HTML template with posts. Here are my models: class User(AbstractUser): pass class Post(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=500) class SavedPost(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey (User, on_delete=models.CASCADE, null=True) My .views looks like this def savedpostsview(request): posts = Post.objects.all savedposts = posts.savedpost_set(user = request.user) return render(request, "posts/savedposts.html",{ 'savedposts': savedposts }) Right now I'm getting the error "'function' object has no attribute 'savedpost_set'". I know I'm getting something wrong syntactically, but I've been reading documentation forever and can't figure out what it is for the life of me. Does anybody have any insight into what I'm doing wrong? -
Separate tags - Django
I have small code in template: {% for tags in profile.tag_i %} <span class="badge bg-primary">{{tags}}</span> {% endfor %} and this is output in browser when i use only this code : <span class="badge bg-primary">{{profile.tag_i}}</span> i have output look but i want output like this How to separate tags? -
Cannot run Django server from atom IDE but it works from os cli
Just as the title says. Whenever I input python manage.py rumserver in the the terminal in atom I get this message: (myDjangoEnv) ➜ first_project python manage.py runserver File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax But when I execute the same command in the cli outside of any program, it works fine. I think I need to update the settings in atom somehow but I don't see any relevant settings. -
Update JavaScript with Django view values
In the js file below 'use strict'; $(document).ready(function() { buildchart() $(window).on('resize', function() { buildchart(); }); $('#mobile-collapse').on('click', function() { setTimeout(function() { buildchart(); }, 700); }); }); function buildchart() { $(function() { var graph = Morris.Donut({ element: 'chart-pie-moris', data: [{ value: 60, label: 'Order' }, { value: 20, label: 'Stock' }, { value: 10, label: 'Profit' }, { value: 5, label: 'Sale' } ], ...... I want to be updating the values in buildchart() function the values returned by my views file functions. Example def order(request): a = 'calculated integer value' return a So I would like to pass in order function to replace 60 in buildchart() function. how can I achieve this? Please help a newbie -
Graph a Model by grouping by Month and Category
Say I have the following Model that I would want to group by Month (month & year) and group by category. class VolunteerRecord(models.Model): eventname = models.CharField(******) category = models.CharField(******) hours = models.FloatField(******) date = models.DateField(******) owner = models.ForeignKey(******) I would like to display this information in a graphical view for the past 12 month using chart.js. Line chart using one line per category x-axis will be the past 12 months (Jan 2021, Feb 2021, March 2021, April 2021, etc.) y-axis will be the total sum of hours Example output variables would be: labels [datetime.date(2021, 1, 1), datetime.date(2021, 2, 1), datetime.date(2021, 3, 1), datetime.date(2021, 7, 1)] category1 [10, 15, 17, 10] category2 [18, 25, 12, 16] category3 [11, 15, 20, 14] -
Using class based views in django how would I insert data into a join table
for example I have 3 classes defined as such class Timecard(models.Model): site_code = models.CharField(max_length=200) contractor_name = models.CharField(max_length=200) approved = models.BooleanField(default=False) date = models.DateTimeField(default=timezone.now) class Job(models.Model): job_code = models.CharField(max_length=200) description = models.CharField(max_length=200) hourly_rate = models.DecimalField(max_digits=10, decimal_places=2) max_hours = models.PositiveIntegerField() time_card = models.ManyToManyField(Timecard, through="Timecard_Job") class Timecard_Job(models.Model): time_card = models.ForeignKey(Timecard, on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE) hours_worked = models.DecimalField(max_digits=10, decimal_places=2) I have the following class governing my view class FillTimecard(CreateView): model = Timecard form_class = CreateTimeCardForm template_name = 'timesheet/timesheetSubmit.html' success_url = reverse_lazy("index") finally I have the following form class class CreateTimeCardForm(forms.ModelForm): class Meta: model = Timecard fields = ['site_code', 'contractor_name', 'date','job'] job = forms.ModelMultipleChoiceField( queryset=Job.objects.all(), widget=forms.Select ) When I select the job from the drop down I want to also be able to enter the hours worked on that specific job and that be inserted into the join table. If someone can just provide resources that will help me achieve this it would be appreciated. -
Django - Setting StaticRoot in settings.py for AWS S3 bucket during deployment?
I'm trying to run Django locally, but when I upload images I want it to go to an AWS S3 Bucket that's made public. I went through a tutorial to do this and the went through setting STATIC_URL and STATICFILES_STROAGE, but they didn't set STATIC_ROOT so it's still using a local folder. Does this mean when I'm deployed and saving static files such as images, it'll be saved to the STATIC_ROOT or will it be saved to STATICFILES_STORAGE? If it's saved to STATIC_ROOT during deployment, how do I change it to save to the AWS S3 Bucket instead? -
why doesn't my home page recognize 'object_list' in views?
I have a navbar template and I want to make it dynamic. When I want to do this in the template, nothing happens: {% for platform in object_list %} <li><a href="#">{{platform.title}}</a></li> {% endfor %} This code only works in the platform.html file but I want to show the navbar in all of my html files It is in platform.html(platform URL) and it should be like this And this one is in home url but it is an empty subnav this is my models from django.db import models # Create your models here. class Platform(models.Model): PLATFORM_CHOICES = ( ('PC', 'PC'), ('PS', 'playstation'), ('XBOX', 'Xbox'), ('NS', 'nintendo switch'), ) title = models.CharField(max_length=4, choices=PLATFORM_CHOICES, verbose_name= "platform") slug = models.SlugField(max_length=100, unique=True) class Meta: verbose_name = "platform" verbose_name_plural = "platforms" def __str__(self): return self.title class Game(models.Model): title = models.CharField(max_length=50) description = models.TextField() slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(upload_to="images") platform = models.ManyToManyField(Platform) class Meta: verbose_name = "game" verbose_name_plural = "games" def __str__(self): return self.title this is my views: from .models import Game, Platform from django.shortcuts import get_object_or_404, render from django.views.generic import ListView, DetailView, TemplateView # Create your views here. def home(request): return render(request, 'blog/home.html') class GameList(ListView): template_name = "blog/game.html" model = Game games = Game.objects.all() … -
Django modelforms?
I get error in django "ValueError at /register/ ModelForm has no model class specified." Screen:Click Files: views.py def register(request): if request.method == "POST": user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit= False) new_user.set_password = (user_form.cleaned_data["Password"]) new_user.save() return render(request, "main/account/register.done.html", {"new_user":new_user}) else: user_form = UserCreationForm() return render(request, "main/account/register.html", {"user_form": user_form},) forms.py class User_form(forms.ModelForm): class Meta(): model = User fields = ["username", "email",] username = forms.CharField(max_length=150 , required=True,), email = forms.CharField(max_length= 20, required=True,), def clean_password2(self): cd =self.cleaned_data if cd['password'] != ["password2"]: raise forms.ValidationError("Password dont match") return cd["password2"] register.html {% block title %}Create an account{% endblock %} {% block content %} <h1>Create an account</h1> <p>Please, sign up using the following form:</p> <form action="." method="POST"> {{ user_form.as_p }} {% csrf_token %} <p><input type="submit" value="Create my account"></p> </form> {% endblock %} -
Parallax effect overlap and Bootstrap wont align div
Fairly new to web development. I am attempting to make a responsive website for both mobile and desktop. I'll be honest, its terrible right now. But I'm working on it. I currently have 2 major issues that I've been fighting with for about a full day now. Also Yes I am running django on the backend and vue as a cdn on the front. I have deployed rellax js into the website for a paralax effect however its creating an ugly overlap and I can't seem to get ride of it. Once I deployed rellax js my text that was supposed to be center of the landing page disappeared to the bottom. I would like it centered. Could anyone help me with these issues? Also any input as to how to make this mobile friendly would be awesome, I was just going to lock the images at a certain size if the screen was small. HTML {% include 'core/navbar.html' %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static "css/style.css" %}" /> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" /> <link href="assets/vendor/aos/aos.css" … -
How to create a new token with custom created datetime in Django Rest Framework?
I am using Token Authentication in my Django Rest Framework project. I have noticed that while creating a token, if I specify the created datetime field in the create method, than the token is not created with that value, for example: new_token = Token.objects.create(user=user, created=datetime(2021, 9, 7, 10, 10, 10, tzinfo=timezone.utc) will not create the token with the specified datetime but will use the current UTC time. To make it work i have to perform another operation on this object and save the modified object again like this: new_token = Token.objects.create(user=user) new_token.created = datetime(2021, 9, 7, 10, 10, 10, tzinfo=timezone.utc) new_token.save() I think this will make two queries on the DB, first while creating and then while modifying the created datetime which is not very elegant. Can someone please tell me why Django is not setting the datetime in the first way? I'm very new to this framework so please pardon me if I'm overlooking something very simple here. Thanks! -
Django/Python - How can I get few user (Logged In) details in settings.py
I'm beginner in Django and need to develop a app where I'm using two databases (Default and Other) 'default' DB will be same for all users authentication but need to use 'Other' where I want to fetch some database connection variables from active/logged in user to create to Database connection and get apps data. Can anyone help me out here. -
Django translation not working on nginx server
I'm working on django translation, and after deploying to an nginx server translating page doens't work anymore, with no errors it just does nothing.Even though it works just fine in my local machine. Here's my settings USE_I18N = True USE_L10N = True from django.utils.translation import gettext_lazy as _ #Example for English and German LANGUAGES =[ ('en', _('English')), ('fr', _('French')), ('ar', _('Arabic')),] And the folders are named ar, and fr. I tried answers from previous questions but nothing worked. I even added proxy_pass_header "Accept-Language"; to nginx conf. And unlike previous problems where they had linux folder naming problem for example zh_cn to zh_CN, my folder has only two letters as a name. If you can guide me through this I'd appreciate it. Thanks you. -
missing 1 required positional argument: 'department'
class Student: def __init__(self, name, student_number): self.name = name self.student_number = student_number self.classes = {} def enrol(self, course_running): self.classes.append(course_running) course_running.add_student(self) class Department: def __init__(self, name, department_code): self.name = name self.department_code = department_code self.courses = {} def add_course(self, description, course_code, credits): self.courses[course_code] = Course(description, course_code, credits) return self.courses[course_code] class Course: def __init__(self, description, course_code, credits, department): self.description = description self.course_code = course_code self.credits = credits self.department = department self.department.add_course(self) self.runnings = [] def add_running(self, year): self.runnings.append(CourseRunning(self, year)) return self.runnings[-1] class CourseRunning: def __init__(self, course, year): self.course = course self.year = year self.students = [] def add_student(self, student): self.students.append(student) maths_dept = Department("Mathematics and Applied Mathematics", "MAM") mam1000w = maths_dept.add_course("Mathematics 1000", "MAM1000W", "1") mam1000w_2013 = mam1000w.add_running(2013) bob = Student("Bob", "Smith") bob.enrol(mam1000w_2013) Hi, would someone please be able to explain why this code is not working? The error message I am receiving is: Traceback (most recent call last): File "G:\Shares\Website\Development\Intranet\HealthcareProject4\HealthcareProject4\Population\Schools.py", line 49, in mam1000w = maths_dept.add_course("Mathematics 1000", "MAM1000W", "1") File "G:\Shares\Website\Development\Intranet\HealthcareProject4\HealthcareProject4\Population\Schools.py", line 19, in add_course self.courses[course_code] = Course(description, course_code, credits) TypeError: init() missing 1 required positional argument: 'department' Press any key to continue . . . -
Write nested serializer with GenericRelatedField()
I have the following code in which in one of the models I am using a polymorphic model with the django ContentType framework. models.py from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.fields import GenericRelation # Create your models here. class LastName(models.Model): last_name = models.CharField(max_length=100) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() def __str__(self): return self.last_name class Person(models.Model): first_name = models.CharField(max_length=100) last_name = GenericRelation(LastName) def __str__(self): return self.first_name serializers.py from django.db import models from rest_framework import serializers from .models import Person, LastName from django.contrib.contenttypes.models import ContentType class LastNameSerializer(serializers.ModelSerializer): class Meta: model = LastName fields = '__all__' class PersonSerializer(serializers.ModelSerializer): last_name = LastNameSerializer(required=False, many=True) class Meta: model = Person fields = ['id','first_name', 'last_name'] def create(self, validate_data): last_names = validate_data.pop('last_name') person = Person.objects.create(**validate_data) for l_name in last_names: model = self.Meta.model names = LastName(content_object=person, **l_name) names.save() person.last_name.add(names.id) person.save() return person In the serializer.py I am trying to create query to add more than one dictionary with more than one last_name as the create() method above as same as if you added a non-polymorphic serializer. The payload I am trying to send to the Person endpoint is as follow: Post: { "first_name": "Oliveira", "last_name": [ {"last_name":"Prado"}, {"last_name":"Moreira"}, … -
How can I fix 'QuerySet' object has no attribute 'get_performance'
I am having dificulty importing model in template tag.. get_performance is a model method in users model. I am trying to import the model so that I can use get_performace but this is the error I am getting 'QuerySet' object has no attribute 'get_performance' ......................... fields ......................... def get_performance(self, timezone.now() + timedelta(days=-2), timezone.now()): actual = Sum("scores", filter=Q(status="completed")) q = self.taskassignt.filter( due__gte=timezone.now() + timedelta(days=-2), due__lt=timezone.now() ).annotate(actual=actual, total=Sum("scores")) return (q[0].actual / q[0].total) * 100 Here is my template tag from django import template from django.utils import timezone from datetime import timedelta from ..models import User register = template.Library() @register.simple_tag def performance(user, start_time=timezone.now() + timedelta(days=-2), end_time=timezone.now()): user = User.objects.all() return user.get_performance(timezone.now() + timedelta(days=-7), timezone.now())```