Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Random Number Guesser using Django-Python
I want to Implement a Number Guessing Game using Django. However, I am facing issues since with every guess since it gets reloaded and therefore the number changes. Any Suggestions? def RanNum(request): number = random.randint(1,20) print('Ans:',number) if request.method=="POST": guess=request.POST['Guess'] num_guesses = 0 guessed_number= False while not guessed_number: if not is_valid_num(guess): messages.info(request,"A number between 1 and 20 ony (Not Counted):") return redirect('/game') continue else: num_guesses +=1 guess = int(guess) if guess < number: messages.info(request,"Too LOW.Guess again:") return redirect('/game') elif guess > number: messages.info(request,"Too HIGH.Guess again:") return redirect('/game') else: messages.info(request,"No of Guesses:") messages.info(request,num_guesses) return redirect('/game') guessed_number = True messages.info(request,"thanks for playing") return render(request,template_name='html/RandomNumApp/Ran.html',) else: return render(request,template_name='html/RandomNumApp/Ran.html',) -
Django: pagination with prefetch_related
I have a model specifications which are divided into categories. For the template, in order to display the category as an header in the table, I make a prefetch_related on the Category like this: categories = Category.objects.distinct().prefetch_related('specifications').filter(filters) Now I can loop over the categories and show the related specifications like: {% for category in categories %} <tr> <th colspan="7">{{ category.name }} - ({{ category.abbr }})</th> </tr> {% for specification in category.specifications.all %} ... I also want to use the paginator, but now the paginator only counts the categories and not the related specifications. Is it possible to paginate on the specifications with the given query or should I change the query to retrieve all the specifications? -
How to set 2 attributes to primary key together in Django?
I have a model in Django: class Subject(models.Model): level = models.CharField(max_length=50) subject_name = models.CharField(max_length=50) teacher_name = models.ForeignKey(Teacher, on_delete=models.CASCADE) total_seats = models.IntegerField() subject_details = models.CharField(max_length=50) For the Subject table I want the level and the subject_name together to be primary keys. In fact, I dont want any other objects to have the same name and level. I know I can use unique_together but where do I mention the primary_key = True? -
Python Official Stripe Client Creating Two Customers
This code I'm using below works perfectly, except when checkout is complete I have noticed two customer entries are being made every time someone checkouts on my site. One has the default source set and one does not. I have attached a screenshot. https://i.ibb.co/8dd0Cxz/Screenshot-from-2020-04-20-11-15-25.png @login_required def checkout(request): if request.method == 'POST': plan = Plan.objects.get(nickname=request.POST['plan']) stripe_customer = stripe.Customer.create( email=request.user.email, source=request.POST['stripeToken']) stripe_subscription = stripe.Subscription.create(customer=stripe_customer.id, items=[ {'plan': plan.id}], trial_from_plan=True) Subscription.sync_from_stripe_data( stripe_subscription ) return redirect('settings') else: if request.method == 'GET': plan = Plan.objects.get(nickname=request.GET['plan']) return render(request, 'plans/checkout.html', {'plan': plan, 'price': '0'}) I have tried changing {'plan': plan.id} to {'plan': plan} and I get error: Request req_0WL0lW2orGwLMV: No such plan: Family; one exists with a name of Family, but its ID is plan_H5fvA8jJ0qX9qF. -
WebGL warning: texImage: Alpha-premult and y-flip are deprecated for non-DOM-Element uploads
So I have been trying to use Map-box to plot coordinates in my App, but when I provide the .png file to act as marker, i get this following error: WebGL warning: texImage: Alpha-premult and y-flip are deprecated for non-DOM-Element uploads. Screenshot -
How to get different data in queryset ForeignKey?
This is one of my models: class MyModel(models.Model): field_1 = models.ForeignKey(Table_1, related_name='some_name') field_2 = models.ForeignKey(Table_2, related_name='other_name') # other fields The queryset I get for this model contains id for the Foreign Keys. I want to get unique_id instead. I tried using .values, but it didn't solve the purpose, because it returns dicts, but I require the model objects instead. So what should I do to get unique_id in the queryset object? -
Issue with Django filtering
I have a problem with my code and I don't know how to fix it! I used Django Filters and Django Tables 2 to build a filterable list from a db table. The filter in itself works fine, but I found out that if I leave all filters empty I get the entire table on the web page, while in this case I want zero results. Any suggestion / advice would be greatly welcomed! See code below: tables.py from .models import Casualty import django_tables2 as tables from django_tables2 import TemplateColumn from django_tables2.utils import A class CasualtyTable(tables.Table): edit = TemplateColumn(template_name='casualties_update_column.html', verbose_name='') delete = TemplateColumn(template_name='casualties_delete_column.html', verbose_name='') def before_render(self, request): if request.user.has_perm('casualty.change_bar'): self.columns.show('edit') else: self.columns.hide('edit') if request.user.has_perm('casualty.delete_bar'): self.columns.show('delete') else: self.columns.hide('delete') class Meta: model = Casualty exclude = ('author', 'added_by', 'updated_by', 'date_created', 'date_updated') attrs = {"class": "casualties" , "style": "overflow-x:auto;"} filters.py import django_filters from .models import Casualty class CasualtyFilter(django_filters.FilterSet): first_name = django_filters.CharFilter(label = 'First Name', lookup_expr='contains') last_name = django_filters.CharFilter(label = 'Last Name', lookup_expr='contains') middle_name = django_filters.CharFilter(label = 'Middle Name', lookup_expr='contains') ref_nr = django_filters.CharFilter(label = 'Ref Nr', lookup_expr='contains') service_nr = django_filters.CharFilter(label = 'Service Nr', lookup_expr='contains') rank = django_filters.CharFilter(label = 'Rank', lookup_expr='contains') regiment = django_filters.CharFilter(label = 'Regiment', lookup_expr='contains') how_they_died = django_filters.CharFilter(label = 'How Died', lookup_expr='contains') date_of_death … -
how to optimize the query here with select_related?
i have class A(models.Model): field_a = models.OneToOneField(B, on_delete=models.CASCADE) class B(models.Model): field_b = models.charField() how to write the most optimum query here using select_related or something else? My use case is to get the field_a of model A. queryset_b = B.objects.get(field_b="some name") queryset_a = A.objects.get(b=queryset_b).field_a it hits the db twice. Can i do this thing in one db hit using select_related? -
How Can I Use Django 3 with MongoDB?
Is there a way that I can use Django 3 + MongoDB because djongo (the package which integrates MongoDB and Django) requires Django 2.x. Note that I don't want to move to Django 3 for specific reasons. I just wanna explore it. and I need MongoDB because I am writing a data analysis web app (since NoSQL Databases Perform well when working with large data sets). thanks in advance. -
Unable to add User to new Group in Django unittest
Adding a User to a new Group (in a Django unittest) results in Django.core.exceptions.FieldError This exception has got me stumped. I am merely writing the following unittest as an example to learn the Django unittest system before I use the rest_framework APITestCases. TLDR; I have reset my environment, tested in the Django debug interactive environment with the same code and attempted to add the user multiple ways. The unittest still fails, the debug shell still works... Details I wrote the following test (for conscientiousness I omitted the assert statements...) class modelsTests(TestCase): def testUserModel(self): # we should begin with no users... self.assertEquals( User.objects.count(), 0 ) # create some demo users, 2 exactly... User.objects.create(username="test user", email="test@unittest.com") # add the first user to a group, not the second Group.objects.create(name="Test") user = User.objects.first() user.groups.add(Group.objects.get(name="Test")) # create the second user without any groups User.objects.create(username="another user", email="anothertest@unittest.com") I then run the test (which includes several assert statements after the snippet) with, py manage.py test testdrivendevelopment.tests This returns the following error code and stack trace, Creating test database for alias 'default'... System check identified no issues (0 silenced). F.E ====================================================================== ERROR: testUserModel (testdrivendevelopment.tests.test_models.modelsTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\alber\OneDrive - UTS\UTS\ProgSoc\TDD workshop\testdrivendevelopment\tests\test_models.py", line 40, in … -
Сreate a full copy of the object from UpdateView or from ListView in Django
I have Class Based views for my models. I want to create a full copy of the object and go to editing it. I would like to do this from UpdateView with a special button for copying, but it is a good option from the list of objects. How can I do this? Below is the code for one of the models. My ListView: class KeysView( LoginRequiredMixin, CustomPermissionRequired, ListView, ): model = ApiKey context_object_name = 'apikey' paginate_by = 20 template_name = 'db_visual/apiKeys.html' def get_queryset(self): filter_kwargs = {} filter_args = [] search = self.request.GET.get('search', '') if search: filter_args.append( Q(description__icontains=search) | Q(id__icontains=search) ) return ApiKey.objects.filter(*filter_args, **filter_kwargs) \ .order_by('-id') def get_context_data(self, **kwargs): context = super(KeysView, self).get_context_data(**kwargs) context['search'] = self.request.GET.get('search', '') return context My UpdateView: class UpdateKeyView( SuccessMessageMixin, CustomPermissionRequired, UpdateView ): model = ApiKey pk_url_kwarg = 'apikey_id' template_name = 'db_visual/update_key.html' form_class = KeyForm success_url = reverse_lazy('keys') success_message = "Ключ <a href='%(url)s'>%(description)s</a> " \ "успешно изменен!" def get_success_message(self, cleaned_data): return self.success_message % dict( cleaned_data, url=reverse_lazy( 'update_key', kwargs={'apikey_id': self.object.id} ), )