Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Post-save method to handle calculations in django admin forms
I have two models: Estimate and Product. Product's form is included as TabularInline inside Estimate's admin form. Each instance of Estimate creates at least one instance of Product. What I'm trying to do is calculate a total of Product's subtotals and have it show up in the estimate model after saving the instance for the first time. Code could probably explain what I'm trying to do better. I tried overriding Estimate's Save method and I tried post-save signals (it's commented out). Everything works the way I want it to, except I have to save the model instance twice to trigger the calculate function. My question is, is there a way to cut this process short? Have it entirely done with the first save? models.py class Estimate(models.Model): #other irrelevant fields tax = models.DecimalField(max_digits=8, decimal_places=2, validators=[MinValueValidator(0.0)], blank=True, null=True) total = models.CharField(max_length=15, blank=True, null=True) def save(self, *args, **kwargs): subtotals = Product.objects.filter(estimate_id=self.id).aggregate(pr_total=Sum('subtotal'))['pr_total'] or 0 self.total = subtotals if self.tax: self.total = subtotals + ((subtotals * self.tax) / 100) super(Estimate, self).save(*args, **kwargs) # @receiver(signals.post_save, sender=Estimate) # def calculate_total(sender, instance, **kwargs): # subtotals = Product.objects.filter(estimate_id=instance.id).aggregate(pr_total=Sum('subtotal'))['pr_total'] or 0 # instance.total = subtotals # if instance.tax: # instance.total = subtotals + ((subtotals * instance.tax) / 100) # signals.post_save.disconnect(calculate_total, … -
error occuring at test file in Inspection/Defect class in tests.py line 29
This is the code that's giving me trouble. I've asked about it in the last 2 hours and no one is responding to my question at Inspection/Defect Problem. If anyone can show me how to fix the problem, it would be appreciated!!! -
How to Format Dates in Python?
I have a field in a query set of type DateTime.DateTime: "datetime.datetime (2020, 6, 16, 22, 29, 43, tzinfo = )", I want to change the format of this field to: "%Y -%m-%d %T", how could I do it ?, I tried as follows but it tells me the following:" 'NoneType' object has no attribute 'strftime' ". CODE: test.append({'device_id': d.device_id_id, 'device_name': d.device_id.device_name, 'startdatettime': (d.startdatetime).strftime('%Y-%m-%d %T'), 'enddatetime': (d.enddatetime).strftime('%Y-%m-%d %T'), 'active': d.active, 'loggeduser': d.logged_user, 'area_id': d.area_id.id, 'area_name': d.area_id.area_name, 'digitaloutput_user_description': d.lightstate_id.do_id.user_description, 'lighstate_user_description': d.lightstate_id.user_description, 'color': (d.lightstate_id.do_id.color).replace('w3-', ''), 'shift_startdatetime': d.shift_startdatetime, 'shift_enddatetime': d.shift_enddatetime, 'shift_name': d.shift_name}) -
how to display the menu name in drop-down menu dynamically in Django
this is my index.html file <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Reports<span class="caret"></span></a> <ul class="dropdown-menu"> <li class="dropdown-header">Reports</li> <li> <div class="buttons pull-right"> <a href="{% url 'report:reporttest' %}" class="btn btn-xs btn-success" title="Add"><i class="fa fa-plus"></i></a> </div> <a href="{% url 'report:reporttwo' %}">Report one</a> </li> {% if name %} <li> <a href="{% url 'report:add' %}">{{name}}</a> </li> {% endif %} </ul> </li> the view.py file def reportone(request): return render(request, 'report_one.html') def reporttwo(request): return render(request, 'report_two.html') def reporttest(request): return render(request, 'add_report.html') def add(request): if request.method == "POST": #rept=ReportName.objects.all() #rept=ReportName() src=request.POST.get('src') width=request.POST.get('width') height=request.POST.get('height') name=request.POST.get('name') #context={'rept':rept} #if request.method == "POST": return render(request, 'report_one.html', {'src':src, 'width':width, 'height':height, 'name':name}) else: return render(request, 'report_one.html') i have created report successfully....but i want the report name which i was creating will display on the dropdown menu .... using the above code i can able to see the created report name in the dropdown but the problem is when we click on the report name which is shown in the dropdown is not showing the created report and report name will also remove from the dropdown menu .... i want all the report that i created before will show in the dropdown after the page get reload or reopen the page i believe … -
Correct way to update django to a specific (but not most recent) version via pipenv
I am currently using django==2.2.5, managing my dependencies via pipenv and would like to upgrade to django==2.2.15 Unfortunately the pipenv documentation does not say anything regarding the option of specifying a certain version when using pipenv update - hence my problem/question: Since the command pipenv update django would update my django to the latest 3.1 version but I only want to update to version 2.2.15 I have to use pipenv install django==2.2.15. True or Not? And if not, what would be the correct way? Since I am doing this the first time, I am amfraid to mess things up , so just wanted to be on the safe side, before proceeding.... -
Using a Real time update on a web app will that crash the server?
I have an app that consist of two types of users one type can post questions and the other type can answer now I'm integrating a real time updates when a user add a question all the other users get this question immediately without refreshing the page I using Pusher for that and once a user adds a question I send an alert to all the connect users nad once they receive this alert they make an ajax requests and get all the question again, my question is , is this a valid way to do that and can this method cause problems later on when deploy app to the server as you can see when I send the alert all the users will make an ajax request to the server at the same time will that cause my server to crash please help me thanks. -
how to preview checked box in another html file and show in the current html
I have two htmls. One is redirected as a result of a function and is as follows: first.html <div id="ck-button"> {% for item in items %} <label class="btn btn-custom gender-label m-1"> <input type="checkbox" id="myCheck" value="{{ item.0 }}" onclick='myFunction();'> <span> {{ item.1 }} </span> </label> {% endfor %} </div> and another one is the main html file which contents everything. second.html: <form method="POST" action="" enctype="multipart/form-data"> <fieldset class="form-group"> {% csrf_token %} <div class="content-section"> {{ form|crispy }} </div> <div> <label for="content"> choose items:</label> <p class="text-muted" id="previewItems"> </p> </div> </fieldset> <div class="form-group mt-7"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> <script> function myfunction() { var checkBox = document.getElementById("myCheck"); var text = document.getElementById("previewItems"); if (checkBox.checked == true){ text.style.display = "block"; } else { text.style.display = "none"; } } </script> Is it possible to get checked items in another html file and show it synchronously in the current html? or is there any other solution that could help me? Thanks -
keep the username even when I refresh the page django
I want to refresh my web page, and keep the username logged in. views: currentUser = [] def evt_stat(request): if request.method == 'POST' and 'login' in request.POST: username =request.POST['email'] password =request.POST['password'] currentUser = authenticate(username=username, password=password) currentUser.save() if currentUser is not None: return render(request, 'evt/index.html', {'currentUser': currentUser}) else: ErrorLogin= True return render(request, 'evt/login.html', {'ErrorLogin': ErrorLogin}) . . . return render(request, 'evt/index.html', {'ErrorLogin': ErrorLogin}) .html : <div class="mr-2 d-none d-lg-inline text-gray-600 small"> {{currentUser.first_name}} {{currentUser.last_name}}</div> when i do this i got this error return render(request, 'evt/index.html', {'uploaded_file_url': uploaded_file_url,'ErrorLogin': ErrorLogin}) UnboundLocalError: local variable 'ErrorLogin' referenced before assignment the problem here if I don't put the line: return render(request, 'evt/index.html', {'ErrorLogin': ErrorLogin}) the first time I log in I see the user's first and last name, but when I refresh the page, I lose the user's first and last name information. what can I do to keep the username even when I refresh the page -
Create database table with angular 10 and django rest framework
I wanted to allow the user/admin to create a table with inputs in the html (using angular for frontend), the columns desired with the types and options. Send those informations to Django (using rest framework) and to be created a model -> table in the database. My database is a mongodb I completely don't know how to do. Thanks in advance for your time ! -
Django-Rest-Framework dynamic routing
I have a set of analogue objects that I would like to return with a single view MY_OBJECTS = ['a', 'b', 'c'] class AnyObjectViewSet(ViewSet): def initial(self, request, *args, **kwargs): super().initial(request, *args, **kwargs) # How can I get this? self.obj_name = kwargs['obj_name'] def list(self, request, **kwargs) data = get_data(self.obj_name) # some function to retrieve dynamic data return Response(data) ### urls.py router = DefaultRouter() for obj in MY_OBJECTS: # How do I pass parameter to my router in a way that my viewset gets it? router.register(f"/api/{obj}", AnyObjectViewSet, basename=obj) My question: Is there a way to have one view for all the objects, setting the object name by url parameter? In theory I could make a factory that creates a ViewSet Class for any of my objects, but this seems very tedious. -
Javascript working only after I open a modal
So I have a problem where my script for a filter/search list used to work, added a few lines of code to open a modal when a certain event occurs and now strangely when I go on my page, I can't use the search/filter list, but when I open the modal and close it, then I can use it..? It looks like it has to process the modal script first to be able to use the search/filter script. I am working with Django and MySQL, here are the relevant lines of code: .html ( first lines are about the search function, the second part is the modal and third block is the table used in the search/filter function and the conditions for opening the modal ) <div class="search-right"> <input type="text" id="mySearchInput" placeholder= " Search a stock.." title="Stock Search" style="float:left"> </div> {% if warning %} <div id="myModalAddaStock" class="modalAddaStock"> <div class="modal-content"> <span class="closeAddaStock">&times;</span> <p>{{warning}} {% if stock_to_add %}{{stock_to_add}} {% endif %}{% if stock_to_replace %}{{stock_to_replace}} or {{flex}}{% endif %}</p> </div> </div>{% endif %} <div class="grid-itam-2bottom"> <table id="myTable1" class="myTable"cellspacing="0" cellpadding="1" border="1" width="100%"> <tr class="stockheader"> <th width="8%" style="text-align:center;">Symbol</th> <th width="35%"style="text-align:center">Company Name</th> <th width="8%" style="text-align:center">Sector</th> <th width="7%" style="text-align:center">Streak</th> <th width="12%"style="text-align:center">Market Cap</th> <th width="8%" style="text-align:center">Return</th> <th width="6%" … -
How to use SerializerMethodField as choices of ChoiceField?
I have a serializer as below, class customerSerializer(serializers.ModelSerializer): drop_list = serializers.SerializerMethodField(read_only=False) cust_choices= serializers.ChoiceField(choices=drop_list,allow_blank=True,allow_null=True,many=True) ............. ............. ............. def get_drop_list(self,obj): .......... return list If I try to create the choice using Serializermethodfield.It throws me the below error, TypeError: 'function' object is not iterable Please help to sort out. If there is another way.Suggest me. Thanks in advance. -
I cant go to the model I'm trying to update
My django Url## url(r'^Updatemodel/', Updatemodeldata.as_view()) Redirection takes place with url. No problem in view. I have defined everything but the model ı want does not come. Please help. -
How to make checks in the form when entering a field in Django
I'm a novice user of django. My intention is to add a check in the form to verify that the name entered by the user for "GroupCalenadr" is not already present. In case it is already present, return an error message otherwise everything is ok. My problem is that I don't know what works I have to use in the form.py to make these checks. Thank you very much to who will help me. In form.html: {% block content %} <form method="post"> {% csrf_token %} <table class="form form-table"> {{ form }} <tr><td colspan="2"><button type="submit" class="btn btn-info right"> Submit </button></td></tr> </table> </form> {% endblock %} In forms.py: class CalendarGroupsForm(ModelForm): class Meta: model = CalendarGroups fields = ('name',) def __init__(self, *args, **kwargs): super(CalendarGroupsForm, self).__init__(*args, **kwargs) In models.py: class CalendarGroups(models.Model): name = models.CharField(max_length = 155, blank=True, null=True) @property def get_html_url(self): url = reverse('', args=(self.id,)) return f'<a href="{url}"> {self.name} </a>' -
what are the pros and cons of using apache workers when deploying Django in production?
I've been looking at all the various ways to deploy a django project in a windows enviroment, and I came up with an interesting method - I'm now asking if this is a smart way to do it... step 1. Run the django server via cmd python manage.py runserver 8000 step 2. Point an Apache worker to direct incomming traffic to Django I won't pretend to be a networking master, but as long as Apache is the only thing outward facing and able to handle all the security....how insecure can this way be? I can't help but feel like this is cheesing it somehow.... but I'd love to hear any optinions on this! -
Django does not create migration to create index for legacy Foreign Key field
I have a legacy table that does not have an index on the foreign key field in a PostgreSQL database. According to the docs Django automatically creates an index for foreign key fields. I would like to add an index on this field. When I specify db_index=True on the foreign key field and run makemigrations it reports: No changes detected Example: class Member(models.Model): ... group_id = models.ForeignKey(Group, models.DO_NOTHING, db_index=True) # added `db_index=True` here Is there a way to get django to create a migration to create an index for this field? -
Ajax request to changing boolean value of object in django
i'm struggling to make ajax function that change the boolean value of an object without refreshing the page. It returns error 500. Model: class Donation(models.Model): is_taken = models.BooleanField(default=False) HTML: <div style="width: 50%; float:left" class="steps--container"> {% for d in taken %} <div style="width: 80%; float: left"> <h4>{{d.quantity}} bags of {% for c in d.categories.all %} {{c}} {% endfor %} by {{d.user.first_name}} {{d.user.last_name}} </h4> <input type="text" id="donation_id" value={{d.id}} hidden> </div> <div style="width: 20%; float:right"> <input type="button" onclick="updateStatus()" value="{{d.id}}" Mark as not taken> </div> <br> {% endfor %} </div> JS: function updateStatus() { var dId = document.getElementById("donation_id").value; var dIdInt = parseInt(dId, 10) $.ajax({ type: "GET", url: "/ajax/taken_or_not_taken/", data: { "donation_id": dIdInt } }).done(function(e){ console.log("done") console.log(dIdInt) }) .fail(function(e){ console.log('error') console.log(e) }) } View: def taken_or_not_taken(request): obj = request.GET.get('donation_id', '') print(obj) return JsonResponse(obj) Url: url(r'^ajax/taken_or_not_taken/$', views.taken_or_not_taken, name='taken_or_not_taken'), How can i make it works? -
Python Django 3.1 The included URLconf 'mysite.urls' does not appear to have any patterns in it
I'm currently learning django by tutorial. So I changed my return-renders to class-generic in views. in URLs I added as_view() and then it gave me an error. my traceback: File "D:\Anaconda3\lib\threading.py", line 916, in _bootstrap_inner self.run() File "D:\Anaconda3\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "D:\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "D:\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "D:\Anaconda3\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "D:\Anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "D:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "D:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "D:\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf 'mysite.urls' does not appear to have any patterns in it. If you see valid patter ns in the file then the issue is probably caused by a circular import. urls.py: from django.urls import path from . import views app_name = 'myapp' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:id>/', views.DetailView.as_view(), name='detail'), path('<int:id>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] views.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from .models import Question from django.template import loader from django.views import … -
Django. Conditional model field in admin form (Either link to image or upload image)
I don't know how to do kind of conditional field in model's admin form. I want a model that has multiple images that can be either uploaded or linked from another site. I came up with separate link and upload_file fields and choice field type and then conditionally handle and save it to the database but that approach looks very bad. It makes me to create custom save logic (which i don't know how to do) and it adds extra info into the database. I started to learn django just today, please, add simple solutions not touching django's advanced usage -
How to check current stock remaining
I am struggling to get current remaining stock in my inventory application. I have written code to calculate remaining quantity but it calculates based on purchased quantity only. I want to add total sold quantity and find the difference between purchased and total sold quantity. How do I calculate total sold quantity and calculate the remaining stock. models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100) slug = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.IntegerField(null=True, blank=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name class Stock(models.Model): sold_quantity = models.IntegerField(null=True, blank=True, default=0) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) def __str__(self): return self.product.name @property def get_difference(self): total = self.product.quantity-self.sold_quantity return total Views.py def add_sales(request): form = AddSalesForm() if request.method == 'POST': form = AddSalesForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.product.quantity -= instance.sold_quantity instance.save() return redirect('stock_details') contex = {'form': form} return render(request, 'stockmgmt/add_sales.html', contex) templates {% extends 'stockmgmt/base.html' %} {% block content %} <form method="GET"> <a href="{% url 'add_sales' %}" class="btn btn-primary">Add Sales</a> <p> <table class="table table-bordered"> <tr> <th>Item</th> <th>Category</th> <th>Purchased Qty</th> <th>Sold Qty</th> <th>Remaining Qty</th> <th>Price</th> <th>Action</th> </tr> {% for item in stocks %} <tr> <td>{{item.product.name}}</td> <td>{{item.product.category}}</td> … -
How organize pagination with a large number of pages in Django project?
I have a view.py product_list: ... from django.shortcuts import render, get_object_or_404 from .models import ProductCategory, Product, ProductDetail, ProductSpecialCategory from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger ... def product_list(request, category_slug=None, ): category = None categories = ProductCategory.objects.all() object_list = Product.objects.filter(available=True, is_active=True) if category_slug: category = get_object_or_404(ProductCategory, slug=category_slug) object_list = object_list.filter(category=category) paginator = Paginator(object_list, 1) page = request.GET.get('page') try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) return render(request, 'shop/products/list_by_category/product_list.html', {'category': category, 'categories': categories, 'products': products, }) Based on this handler, I did pagination.html: <nav aria-label="pagination" class="pagination_area"> <ul class="pagination"> {% if page.has_previous %} <li class="page-item next"> <a class="page-link" href="?page={{ page.previous_page_number }}"> <i class="fa fa-angle-left" aria-hidden="true"></i> </a> </li> {% endif %} {% for i in page.paginator.page_range %} {% if page.number == i %} <li class="page-item focused"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% elif i > page.number|add:'-1' and i < page.number|add:'1' %} {% else %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page.has_next %} <li class="page-item next"> <a class="page-link" href="?page={{ page.next_page_number }}"> <i class="fa fa-angle-right" aria-hidden="true"></i> </a> </li> {% endif %} </ul> On the interface, I get the **result**: I would like to organize in such a way that: Show … -
Choose certain field in Django import export
I am trying to export some data in Django Admin. And don't know how to make dynamic choices of fields to export, like choices of format file -
How to solve Model matching at /route/blah/ in django
Hello, I am currently making a Django Application that makes use of django allauth and Google Auth Issue is that when I login using django allauth and try to access the route /profile/view/ It throws this huge error at me, below is just the minified version For more help this is the code for the following files ... models.py from django.db import models from django.core.validators import FileExtensionValidator from django.utils import timezone from django.contrib.auth.models import User class Profile(models.Model): COUNTRY_CHOICES = ( ('No region selected ...', 'No region selected ...'), ('The Caribbean', 'The Caribbean'), ('Central America', 'Central America'), ('North America', 'North America'), ('South America', 'South America'), ('Oceania', 'Oceania'), ('Africa', 'Africa'), ('Europe', 'Europe'), ('Asia', 'Asia'), ) first_name = models.CharField(max_length=30, blank=True, default="John") last_name = models.CharField(max_length=30, blank=True, default="Doe") username = models.CharField(max_length=100, blank=False, null=False, default="FireCDN-User") description = models.TextField(max_length=240, blank=True, default="No informations provided ...") region = models.CharField(max_length=50, blank=False, default="No country selected ...", choices=COUNTRY_CHOICES) avatar = models.ImageField(upload_to='profile/avatars/', default="shared/avatar/default-avatar.png") created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Profiles" class FileUploads(models.Model): FILE_TYPE_CHOICES = ( ('No file type selected ...', 'No file type selected ...'), ('Stylesheets', 'Stylesheets'), ('JavaScript', 'JavaScript'), ('Documents', 'Documents'), ('Images/Pictures', 'Images/Pictures'), ('Scripts', 'Scripts'), ) user = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name="User Profile") file = models.FileField(upload_to='storage/files/', blank=False, null=False, validators=[ FileExtensionValidator([ … -
How can i read the client Windows Username in a Django intranet web based application?
3 Hello guys, I want to show a message like, hello windows username for the client and get the client windows username.But with win32 functions i get the server windows username, i want the client username, i tried with javascript and it doesn't work, somehow i need to acces his active directory and i don't know how, the site will be intranet and i tried using a LDAP library and somehow it didn't work, am i doing something wrong? Now the site is on a local server, is in develop.I think the domain will be the same because it's intranet, i am not so advance with the domain also and I saw that LDAP use this a lot. I have read about token login and i researched it and still no clue for me. Just give a lead to follow and i will. Thank you guys a lot for the patience.I have found a similar question but is outdated because they asked 7 years ago.And from what i've seen in javascript you can get the user from the user login, but i don t need a login page. And from session i don't think i am able to give the … -
Django form does not save new post using based view function
I have a model as follow: class Post(models.Model): title = models.CharField(max_length=150) author = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) imagefile = models.FileField(null=True, blank=True, upload_to='images', default='default.jpg') There is a bug in the view file that, when I use class base view I can post the new post but whenever I use it as a function it does not save the form. This one works(saves post in database): class PostCreateView(LoginRequiredMixin, AjaxFormMixin, CreateView): model = Post template_name = "app/postform.html" success_url = '/posts' form_class = postform But this one does not(does not save post in database): @login_required def PostCreateView(request): if request.method == 'POST': mform = postform(request.POST or None, request.FILES or None, instance=request.user) if mform.is_valid(): mform.save() # when I print something here, Ill see something messages.success(request, f'Yes!') return redirect('posts') else: mform = postform() return render(request, 'myapplication/postform.html', {'form': mform}) and in postform.html: <form method="POST" action="" enctype="multipart/form-data"> <fieldset class="form-group"> {% csrf_token %} <div class="content-section"> <!-- {{ form|crispy }} --> </div> </fieldset> </form> and form.py: class postform(forms.ModelForm): class Meta: model = Post fields = ("__all__") exclude = ['date_posted']