Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ordering one-to-many by "reverse related" model
I have two models with a one-to-many relationship, say: class EmailSeries(Model): class Meta: ordering = [] name = CharField(...) class Email(Model): title = CharField(...) content = TextField(...) date = DateTimeField(...) series = ForeignKey(EmailSeries) Would it be possible to order EmailSeries by the date field of the Emails that have it as series? For example when viewing EmailSeries objects in django's admin I would like to see them ordered by the earliest date of all the emails belonging to each series. Is this possible? If so, what would I have to put into Meta.ordering for that to work? -
Django Formset MultiValueDictKey Error When Editing an Object
I am working with formsets for the first time and am receiving this error. It is interesting, because I have a 'Create' version of this view, and an 'Edit' version. The formset works just fine while Creating a new object, but when I try to Edit one I get this issue. I've seen online this having to do with the form.id but I don't think that's the case or I feel I wouldn't be able to use the create view successfully. Any thoughts on how I could try to resolve this? The error message highlights the line manifests = form2.save(commit=False) views.py def EditProformaView(request, pk): ManifestForm= modelformset_factory(ProformaManifest, fields =('ProductCode', 'DescriptionOfGoods', 'UnitQty', 'Type','Amount', 'Price')) item = get_object_or_404(Proforma, pk=pk) if request.method == "POST": form = ProformaForm(request.POST, instance=item) form2 = ManifestForm(request.POST) if form.is_valid(): new_proforma = form.save() manifests = form2.save(commit=False) #this is the line that creates the error for manifest in manifests: manifest.proforma = new_proforma manifest.save() data = form.cleaned_data #get the data from the form manifestData = form2.cleaned_data context = { 'data': data, 'manifestData': manifestData, } pdf = render_to_pdf('proforma_preview.html', context) ... messages.success(request, "Success: Proforma Has Been Created!") return redirect('HomeView') else: ... else: form = ProformaForm(instance=item) qs = ProformaManifest.objects.filter(proforma=pk) form2 = ManifestForm(queryset = qs) context = … -
How to make create() method of model's manager return a model object
I have a model User() for which I have created a custom manager class UserManager(). In UserManager() I have created a method create_user() which stores the information in database for model User(). Model User() class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='profile_pictures/', max_length=None, null=True, blank=True) is_active = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = 'email' Manager UserManager() class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password,profile_picture=None): if not email: raise ValueError('Users must have an email address.') user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, profile_picture = profile_picture, ) user.set_password(password) user.save(using=self._db) # return model instance. It returns email address of the newly created user. return user I want create_user() to return id as a User Object. In the current scenario it returns email of the user. I am expecting create_user() method to return something like this - <User: User object (2)>. -
How to use pdf.js with django? or other way to embed pdf files in django? I want a non-javascript solution
I want to embed the pdf files in the html page, I could not find a reliable way around. How can I use pdf.js with Django or is there a library for django to do that? Particularly how to use it via CDN? Do I have to use node.js to run this?(i hope not) -
how to get selected choice from charfield and use it to make able another charfield in Django?
models.py: class Ligne(models.Model): Num_ligne = models.DecimalField(max_digits=8, decimal_places=0, null=True) CIN_ab = models.DecimalField(max_digits=8, decimal_places=0, null=True) FIXE='fx' MOBILE='mob' ligne_types = [ (FIXE, 'Fixe'), (MOBILE, 'Mobile'), ] Type = models.CharField(max_length=100,choices=ligne_types, null=True) forms.py: class Ligne_form(forms.ModelForm): Reseau=forms.CharField(required=False,disabled=True) Localisation=forms.CharField(required=False,disabled=True) class Meta: model = Ligne fields= [ 'Num_ligne', 'CIN_ab', 'Type' ] -
Django orm raw query with joins
i get this error when trying to execute my query: 'int' object is not iterable jobs = Job.objects.select_related("company").raw(""" select * from jobs_job left join jobs_job_position on jobs_job.id = jobs_job_position.job_id left join categories_position on categories_position.id = jobs_job_position.position_id left join categories_position_parent_cat on categories_position_parent_cat.position_id = categories_position.id left join categories_industry on categories_industry.id = categories_position_parent_cat.industry_id where categories_industry.id=12 limit 5 """) for job in jobs: print(job) In the for job in jobs line. I tried a simpler query: jobs = Job.objects.select_related("company").raw("select * from jobs_job limit 5") And that works fine. Is something wrong with joins and django orm or did I maybe write it in a bad way? The raw SQL query is working fine as well -
Django RecursionError: maximum recursion depth exceeded in comparison
I have seen many such errors but none of them matched what i am searching so kindly help me to understand where am i making mistake in saving signals in django. I know that save method is running infinity time but how do i stop in my code as I am beginner not able to understand what or where exactly i should be making changes. from django.db import models import random import os from .utils import unique_slug_generator from django.db.models.signals import pre_save, post_save class ProductQuerySet(models.query.QuerySet): def active(self): return self.filter(active=True) def featured(self): return self.filter(featured=True, active=True) class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model, using=self._db) def all(self): return self.get_queryset().active() def features(self): return self.get_queryset().featured() def get_by_id(self, id): qs=self.get_queryset().filter(id=id) if qs.count() ==1: return qs.first() return None # Create your models here. class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to='products/', null=True, blank=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) objects=ProductManager() def __str__(self): return self.title def __unicode__(self): return self.title def product_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(product_pre_save_receiver, sender=Product) This is may model.py -
Django Signal dispatch after related fields is updated
I have 2 models class Mapping(Model): title = models.CharField(max_length=22) class Query(Model): field = models.CharField(max_length=22) type = models.CharField(max_length=10, choices=(('=', 'Equals', ('in', 'Contains'))) value = models.CharField(max_length=256) mapping = models.ForeignKey(Mapping, null=True, blank=True, related_name='queries') So a mapping can have Multiple Queries. I need to do some operation to match Employees (a seperate model) who map to a Mapping after it is created, So i tried to use Signals @receiver(post_save, sender=Mapping) def do_something(instance, created, **kwargs): print("SIGNAL Received !!") print(instance.queries) # Gives None The problem here is that the signal is dispatched before Query objects are creted and i get None when trying to access instance.queries I cannot use the m2m_changed as this is not a ManyToManyField. I also thought of changing the signal sender to Query Model instead of Mapping Model but it wont work as I need to map employees to mapping only if they satisfiy all the queries of a Mapping for which i need to run the task on Mapping Object rather than Query. Please suggest any possible solutions. -
Orders Template not displaying data
For some reason while trying to display my order details in the user.html nothing appears on the website. All the base.html data appears, all thats missing is the order information. I'm not sure what is causing this problem as all my files seem to be linked correctly. Is there anything that I need to add? All help greatly appreciated! models.py - users from django.db import models from django.contrib.auth.models import User from fuisce.models import Product from django.db.models.signals import post_save class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' models.py - orders from django.db import models # Create your models here. from carts.models import Cart from users.models import Profile STATUS_CHOICES =( ("Started", "Started"), ("Abandoned", "Abandoned"), ("Finished", "Finished"), ) class Order(models.Model): user = models.ForeignKey('users.Profile', null=True, blank=True, on_delete=models.CASCADE) order_id = models.CharField(max_length=120, default='ABC', unique=True) cart = models.ForeignKey('carts.Cart', on_delete=models.CASCADE) status = models.CharField(max_length=120, choices=STATUS_CHOICES, default="Started") sub_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2) tax_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2) final_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __string__(self): return self.order_id urls.py from django.urls import path from . import views from carts import views as cart_views from orders import views as order_views urlpatterns = [ path('', views.home, name='fuisce-home'), path('subscription/', views.subscription, … -
Pass password in a hash table Django
I am pretty new in Django. I built a website where you can create a user and share posts. My question is how can I pass the password in a hash table when the user registers to the website instead of plain text? I have tried to use make_password but when I was monitoring the protocol on Wireshark I saw the password (I am using the Django built-in User module): Wireshark -
Adding placeholder in django forms
I have a extended form from usercreation form in django , I want to add placeholder to email and password . forms.py class ExtendedUserCreationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['email','password1','password2'] def save(self, commit=True): user = super().save(commit=False) user.username = user.email user.email = self.cleaned_data['email'] if commit: user.save() return user These is the forms.py where extended form with help of UserCreationform in django , How do i add placeholder to email and password fields. -
Pandas dataframe not acting as expected once deployed to heroku (Django project)
I have created a program which does data entry and returns a pandas table (the info is saved in a list, called JOB_INFO, at the top of the views.py file - I will attach this below) with some results which can be downloaded. I also have the table rendering on the html page that has the data entry form - the table renders below the form and updates(appends) with each user input(form submit). This is works perfectly in development on my local machine, but when it's been successfully deployed to heroku, it starts acting up and not behaving as expected. Examples include: Not updating the table - the form seems to submit but the table doesn't update. If I keep trying, it suddenly works. But then I'll try another and the previous one disappears and only the latest one will show in the table. It just seems so random. Not emptying the list - I have a button to clear the table but that doesn't work either. If I click the button a bunch of time it might work suddenly. But then randomly some information will show up in the table again that I thought was cleared! Info in downloaded … -
User Prefetch queryset annotated value outside prefetch related annotate
I have 3 models like below: class Customer(models.Model): customer_name = models.CharField(max_length=100) customer_phone = models.CharField(unique=True, max_length=11) customer_address = models.TextField(max_length=200, null=True) objects = CustomerManger() class Order(models.Model): customer = models.ForeignKey(Customer, related_name='order_customer', on_delete=models.CASCADE) ordered_date = models.DateTimeField(auto_now_add=True) is_paid = models.BooleanField(default=False) paid_total = models.FloatField(default=0) objects = OrderManager() class OrderedItem(models.Model): product = models.ForeignKey(ProductVariant, on_delete=models.CASCADE) price_per_product = models.FloatField(default=0.0) discount_percent = models.IntegerField(default=0) quantity = models.IntegerField(default=0) order = models.ForeignKey(Order, related_name='ordered_items', on_delete=models.CASCADE) I need all customers with extra calculations like total purchase items and the total dues. So, My query looks like this: data = self.model.objects.prefetch_related( Prefetch( 'order_customer', queryset=Order.objects.prefetch_related('ordered_items').annotate( due=Case( When(is_paid=False, then=Sum(F('ordered_items__quantity') * F( 'ordered_items__price_per_product') * (Value(1) - (F('ordered_items__discount_percent') / 100.00))) - F( 'paid_total')), default=Value(0), output_field=FloatField() ) ), to_attr='order' ) ).annotate(total_due=Sum(F('order_customer__due'))) I need the data like this: [ customer: { customer_name, customer_id, total_due, total_purchased_item } ] Here I count the due for per order inside Prefetch queryset and put the value in due. But outside the prefetch annotation, I can't access the value due. But normal annotated values can be accessed in chain annotate. It gives me an error "Unsupported lookup 'due' for AutoField or join on the field not permitted." I can't find out the problem solution. Is there any solution or any idea please share. Thanks in advance. -
Why can't I use ".update()" with a Django object?
I've been trying to update a Django object with: object_name.update(name="alfred") The thing is that when I get the object name this way: object_name = myobject.objects.get(id=object_id) the method update won't work. But when I get the object this way: object_name = myobject.objects.filter(id=object_id) it will work Why does this happen? Is it because the last object is a queryset? Is there anyway to use .update with a django object? thank you! -
Can not import multiplie statements in Django URL Page
In my Django Project, I have a Main URL Page(in Project File) to this, When I try to import views from two different Django apps then only one Import statement is activated and another one shows an error "Unused import statement". But actually I need both import statements. Because I have two views these have come from two different apps. So how can I import multiple views from different apps -
Django forms.ModelChoiceField queryset problem with models.manager
I am having trouble making a ModelChoiceField queryset in a ModelForm. The related model.objects manager has been overridden to filter the results in order to get only instances created by the actual user. Here are my models : class Bloc(ModelPrive): TYPE_BLOC = ( ('pleinchamps', 'plein champs'), ('tunnel', 'tunnel'), ('pepiniere', 'pépinière'), ('autre', 'autre'), ) nb_planche = models.IntegerField(null=True) caracteristique = models.CharField(max_length=200, null= True, blank=True) geom = models.PolygonField(srid=4326) type_bloc = models.CharField(max_length=200, blank=True, choices=TYPE_BLOC) nom = models.CharField(max_length=200, null=True, unique= True) class ModelPrive(models.Model): created_by = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, editable=False) class Meta: abstract = True objects = ModelPriveManager() class ModelPriveManager(models.Manager): def get_queryset(self): user = get_current_user() return super().get_queryset().filter(created_by=user) In my manager the get_current_user() returns the actual user that has been intercepted by a custom middleware. Here is my form : class BlocFormList(ModelForm): choix_bloc = forms.ModelChoiceField(queryset = Bloc.objects.all().order_by('nom'), required=True) class Meta: model = Bloc fields = ['choix_bloc'] Here is my view : def planification(request): form_bloc = BlocFormList() if request.method == 'POST': # some other code return render(request, 'planification.html', locals()) The problem is, when I do a Bloc.objects.all() in views I get the expected answer (Bloc.objects.filter(created_by=user)) but when it is done inside the queryset of the modelform, it returns nothing (as if there were no active user). After … -
Error during template rendering django (maximum recursion depth exceeded)
I have a base.html under templates/project1 directory which is extended from home/about/blog.html pages. In base.html, i separated header section on separate file named header.html with the following code. {% include "project1/header.html" %} The code in header.html is as follow: {% extends "project1/base.html" %} <header> <nav> <ul id="navigation"> <li><a href="{% url 'nata-about' %}">About Us</a></li> <li><a href="{% url 'nata-blog' %}">Blog</a></li> {% if user.is_authenticated %} <li><a href="{% url 'profile' %}">&nbsp; Profile</a></li> <li><a href="{% url 'logout' %}">&nbsp; Logout</a></li> {% else %} <li><a href="{% url 'login' %}"> &nbsp; Login</a></li> <li><a href="{% url 'register' %}"> &nbsp; Register</a></li> {% endif %} </span> </ul> </nav> </header> When i run the program, it displays an error as follow; Error during template rendering In template D:\pypro\nata\nata_App\templates\nata\header.html, error at line 7 maximum recursion depth exceeded which means it is showing error on below line: {% if user.is_authenticated %} -
Django Server does not start When using keep.alive()
I am using realtime stock price to get real time data using SDK. i successfully got data from this SDK but other django services not working like web page and API. below image show process. But when i remove client.keep_alive() working fine but after some time channel closed. -
filtering in nested for loops (django templates)
I have two models, books and genres. class Book(models.Model): title = models.CharField(max_length=300) author = models.CharField(max_length=100) year = models.IntegerField() genre = models.ForeignKey('Genre', on_delete=models.CASCADE) class Genre(models.Model): title = models.CharField(max_length=20) On my webpage, I want to display each genre, and within each genre, only the books whose year is 1950 or later. The code in my template looks like this: {% for genre in genres %} <h1> {{genre.title}} </h1> {% for book in genre.book_set.all %} {{book.title}} {% endfor %} {% endfor %} The problem with this is that it shows ALL of the books in that genre, and not just the books published after 1950. Is it possible to filter the result of genre.book_set.all in some way to get only those that match a certain attribute? -
Django API is throwing error r("Expecting value", s, err.value)
I created the API for restful services. but it is throwing error raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) API url is path('api/(?P\d+)/$', views.EmployeeDetailsCBV.as_view()), view is class EmployeeDetailsCBV(View): def get(self,request,id,*args,**kwargs): emp = Employee.objects.get(id=id) emp_data = { 'eno':emp.eno, 'ename':emp.ename, 'esal':emp.esal, 'eaddr':emp.eaddr, } json_data = json.dumps(emp_data) return HttpResponse(json_data,content_type='application/json') -
'ManagementForm data is missing or has been tampered with
I am using the following code in my django app which is working fine if I use it as it is but when I extend the base to the following html it throws the following error: django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with'] HTML <html> <head> <title>gffdfdf</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="/static/jquery.formset.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <form id="myForm" action="" method="post" class=""> {% csrf_token %} <h2> Team</h2> {% for field in form %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% endfor %} {{ form.player.management_form }} <h3> Product Instance(s)</h3> <table id="table-product" class="table"> <thead> <tr> <th>player name</th> <th>highest score</th> <th>age</th> </tr> </thead> {% for player in form.player %} <tbody class="player-instances"> <tr> <td>{{ player.pname }}</td> <td>{{ player.hscore }}</td> <td>{{ player.age }}</td> <td><input id="input_add" type="button" name="add" value=" Add More " class="tr_clone_add btn data_input"></td> </tr> </tbody> {% endfor %} </table> <button type="submit" class="btn btn-primary">save</button> </form> </div> <script> var i = 1; $("#input_add").click(function () { $("tbody tr:first").clone().find(".data_input").each(function () { if ($(this).attr('class') == 'tr_clone_add btn data_input') { $(this).attr({ 'id': function (_, id) { return "remove_button" }, 'name': function (_, name) { return "name_remove" + i }, 'value': 'Remove' }).on("click", function () { var a … -
How to integrate micro service in django [closed]
How to integrate micro service in Django. Is there any possibility to work with Django rest framework. -
Does django transaction.non_atomic works in management scripts?
I would like to update every entry in a single transaction. For that reason I wrote following management script: class Command(BaseCommand): help = 'perform health check on all instances' def printit(self): print('commited...') @transaction.non_atomic_requests def handle(self, *args, **options): # perform health check and data collection on all known servers print('Performing health checks...') for instance in Instance.objects.all(): with transaction.atomic(): instance.collect_stats() transaction.on_commit(self.printit) In the documentation @transaction.non_atomic_reqeuests can be activated for views. Does this option effect also management scripts? -
How close does a database need to be to the application to get decent performance?
A bit of an odd problem. I've literally lifted code from one tests.py page to another (test_main.py and copied code to test_models.py), including copying the imports at the top of the page, but the data feature works on one page but not the other. I'm also not understanding the difference between import xxxx and from xxx import xxx. from django.test import TestCase from journal.models import Ledger, COAGroup, JournalEntry, Project, LineItem from decimal import Decimal from django.urls import reverse from datetime import datetime from dateutil.relativedelta import relativedelta from django.contrib.auth.models import User Line that fails: journal_entry = JournalEntry(user=User.objects.get(pk=1), date=datetime.date.today(), type="JE", description='Test journal entry') Fail message: ====================================================================== ERROR: test_is_reconciled (journal.tests.test_models.LedgerTest) Check that is_reconciled() gives correct response ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Philip\CodeRepos\Acacia2\journal\tests\test_models.py", line 24, in test_is_reconciled journal_entry = JournalEntry(user=User.objects.get(pk=1), date=datetime.date.today(), type="JE", description='Test journal entry') AttributeError: 'method_descriptor' object has no attribute 'today' ---------------------------------------------------------------------- -
How to loop multiple form fields in a table then submit
Ideally i am working on attendance of members, On a given date, members who have attended are roll called, then their status submitted at once in the attendance table. here is my code views.py def make_attendence(request): if request.method=="POST": form=AttendanceForm(request.POST, request.FILES,) if form.is_valid(): form.save() messages.success(request, f'Members Attendance For Today has been Made') return redirect('attendence-history') else: form=AttendanceForm() all_members=CustomUser.objects.all() context={'form':form, 'all_members':all_members} return render(request,'make_attendance.html',context) make_attendance.html <form method="POST" enctype="multipart/form-data" > {% csrf_token %} {% load crispy_forms_tags %} <table id="data-table" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%"> <div class="col-lg-4 form-group"> <label for="date">Date:</label> <input type="date" name="date" class="form-control" id="date" required="*" > </div> <thead> <tr style="font-weight: bolder;"> <td>Name</td> <td>Attendance</td> <td>Social fund</td> </tr> </thead> <tbody> {% for member in all_members %} <tr> <td>{{member.full_name}}<input type="hidden" id="full_name" name="full_name" value="{{member.full_name}}"></td> <td>{{form.status}}</td> <td>{{form.social_fund}}</td> </tr> {% endfor %} </tbody> </table> <button type="submit" class="btn btn-primary" >Submit</button> </form> The problem am facing is that on submit, only one record is saved in the attendance table. Any help is highly appreciated.