Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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())``` -
Django "render" is not accessed Pylance
i got this problem after downloading django and creating an app, in the file "views.py" the import "from django.shortcuts import render" says django "render" is not accessed Pylance, and my index(request) function has this message "request" is not accessed Pylance, i have downloaded it correctly and reinstalled but still don't working. my code with the message It's not a sintax error -
How to download image or files from Django model
I'm kinda new to python and I'm creating a website that users can buy Hi-Res images and now I'm looking for a way to let user to download the images that they've bought, from the Django model, Here is my pic model: class Pic(models.Model): name = models.CharField(max_length = 60, blank = False) description_sizes = models.TextField(blank = False, name = 'des_sizes', max_length = 360) captured_time = models.DateField(blank = False) price = models.IntegerField(blank = False) preview = models.ImageField(upload_to = f'static/post/preview/', null = False, blank = False) tags = models.CharField(max_length = 1000, blank = False) image_files = models.FileField(upload_to ='posts/ogFiles', null = True, blank = False) My views.py : def singlePostView(request, pic_id = None): pic = Pic.objects.get(id = pic_id) print(pic) context = { 'pic':pic, } return render(request,"post/single_post_view.html", context) I'm looking for way to make a button or link to download the image_file from pic model in the single view, and I've been searching for this for couple of days now and I've just came across these : xsendfile module or using serve like this : <a href="/project/download"> Download Document </a> and in urls.py: url(r'^download/(?P<path>.*)$', serve, {'document root': settings.MEDIA_ROOT}), well for xsendfile module it's not really an efficient way bc was originally designed for Apache … -
HTML tags are showing up in browser when rendering a django formset (template)
I'm learning django and I have an issue when rendering out a formset. I have a modelform and created a modelformset_factory from it. When I'm rendering out the template html tag are showing up on the webpage(UI). In the html every tag is closed accordingly. Can you help me how can I solve this problem? Thank you. My template: {% for form in test_formset %} {% csrf_token %} <td> <input class="form-control" type="text" value="{{ form.name }}" name="name_{{ form.id | default:'' }}" /> </td> {% endfor %} {{ test_formset.management_form }} Attached you can see an image how it appears in UI. image here -
Am I missing something in my urlpatterns?
I'm trying to create a simple update function for my recipes, and i'm having some trouble with my urlpatterns. This is my desired url path, but I keep getting an 404 (Page not found) error. path('update-recipe/<slug:recipe_slug>/', views.update_recipe, name='update_recipe'), my views.py file is like this. def update_recipe(request, recipe_slug): form = RecipeForm() return render(request, 'recipes/update_recipe.html', {'form': form}) if i change my urlpattern to the following, everything seems to work correctly. But that isnt what I'm trying to achieve. path('<slug:recipe_slug>/', views.update_recipe, name='update_recipe'), The output with the above url. I dont seem to understand what I'm doing wrong, I've tried following videos to the dot as well, but i get the same result. -
django formset.is_valid() return false
while working on django inline formset formset.is_valid() code is not working properly models.py class product_list(models.Model): date=models.DateTimeField(auto_now_add=True,null=True) deal=models.ForeignKey(dealForm, null=True, blank=True , on_delete=models.CASCADE) pro_name=models.ForeignKey(wareForm, null=True, on_delete=models.CASCADE) pro_quantity=models.IntegerField() def __str__(self): return self.name in views.py file formset.is_valid() is return false. i think my code have problem in defining Delivery Formset data but still trying to figure out what's wrong in this code also not show deal field in template views.py def myproduct(request, pk): x=wareForm.objects.all() DeliveryFormSet=inlineformset_factory(dealForm, product_list, fields=('deal','pro_name','pro_quantity'), extra=len(x), can_delete=False) dealer=dealForm.objects.get(id=pk) formset=DeliveryFormSet(queryset= product_list.objects.none() , instance=dealer) #date=datetime.datetime.now().strftime("%d-%m-%y") if request.method == 'POST': formset=DeliveryFormSet(request.POST,instance=dealer) if formset.is_valid(): for f in formset: print ('testing') return HttpResponseRedirect('delivery.html') else: formset.errors context={'name':'Product list','formset':formset,'dealer':dealer} return render(request, 'product.html',context)` template {% extends "base.html" %} {% block content %} <div class=container> <div style="text-align: center;"> <h1>Dealer Name: {{dealer.proprietor_name}}</h1> </div> <div> <form action="" method="post"> {% csrf_token %} {{form.management_form}} {% for field in formset %} {{field}} <hr> {% endfor %} <input type="submit" value="Submit" class="btn btn-primary"> </form> </div> </div> {% endblock %} -
Static files are not loading in Django
Why I am receiving files can't be found error while loading all the static files even after setting everything correctly. ERROR CODE: Admin Section - settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '') - urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('Welcome.urls')), path('auth/', include('Authentication.urls')), path('ad/', include('Ads.urls')), path('user/', include('UserDashboard.urls')), path('admin/', include('AdminDashboard.urls')), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Apps Section - template <link href="{% static 'css/user/style.css' %}" rel="stylesheet"> - Folder Structure -
Django query filter by another dataset
I have 2 User models: User: Default user model: Account: Custom User model, which is an extension of the defualt user model, as I wanted to add a custom field to it called 'Status'. The problem is that I wanted to filter the data based on the current User, so id usually do something like: Account.objects.filter(usernmae = User).values_list('status', flat=True) The problem is that the Account dataset doesnt have the username but they both have the same ID. I was thinking of doing something like this: Status = Account.objects.filter(user_id=User.objects.filter(username = user).values_list('id', flat=True)).values_list('status', flat=True) But then i get the following error: I imagine there is a way better way of doing it, if yall could help me out. -
How to go 2 layers deep reverse relations inside django models?
I'm using a single User model for authentication and creating multiple "type" accounts using the User model. Every type has a different dashboard so different things to show. Organization -> Teacher -> Student Q - I want to list the teachers and their corresponding students when inside a organization account ? It is a listView so I want to know how would I use revere relations to list all the students under specific teachers from an Organization account ? class User(AbstractUser): ... class Organization(models.Model): user_id = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='superAdmin') ... class Teacher(models.Model): user_id = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='faculty') super_admin_id = models.ForeignKey( SuperAdmin, on_delete=models.CASCADE, related_name='faculty') ... class Student(models.Model): user_id = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user') faculty_id = models.ForeignKey( Faculty, on_delete=models.CASCADE, related_name='student') ... If there's any advice on how I can improve the existing model schema, I'd like to know that as well. -
How to show row numbers in django admin listview using the frontend
I wanted to show row number in django admin listview as in the image tried doing it in the admin.py with the following code in different modeladmins: indexCnt = 0 def index_counter(self, obj): count = Basic_inspection.objects.all().count() if self.indexCnt < count: self.indexCnt += 1 else: self.indexCnt = 1 return self.indexCnt But there are problems with this approach, it gets disordered when changing the list page, changing the "sort by" or even when multiple requests to the site. How can I show row numbers in listview using the templates?