Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to connect Athena database to django
I am working to build dashboard on tables of athena. I have tried django-pyodbc in database settings but it is not working. -
Django data not showing on production because of perforamance
I faced a problem with django, I guess this problem is related to latency. I have a views and templates. Everything is working great in my development server. but in production, some data now showing. At first see this views: def servery_company(request,pk): instance = get_object_or_404(Company.objects.filter(pk=pk,is_deleted=False)) company_details = ConDetails.objects.filter(company_details=instance) c = copy.copy(company_details[0]) total_consumption = int(c.jan_amount) + int( c.feb_amount) total_consumption_mean = copy.copy(total_consumption / 12) enery_fare_item_total = FareItem.objects.aggregate(Sum("price"))['price__sum'] enery_fare_item_mean_month = FareItem.objects.aggregate(Avg("price"))['price__avg'] result = (total_consumption_mean * float(enery_fare_item_mean_month) context = { "title": "Company Details:", "instance": instance, "company_details": company_details, "today": datetime.date.today(), "total_consumption": total_consumption, "total_consumption_mean": total_consumption_mean, 'enery_fare_item_total': enery_fare_item_total, "enery_fare_item_mean_tweleve_month": enery_fare_item_mean_tweleve_month, "result": result, } return rende(request 'company.html',context) If you closely look at the views, there is a variable name result you see, all the data is showing both the local server and production server. Only problem is,Only the result variable data not showing in production but it works in local server very well. I am using apache2 server. I am not sure why it is occurring. Can anyone suggest me how to fix this problem? what is the coz of this issue? Your help is much appreciated Thanks -
Unbound Error when having two Django forms in a single HTML page
I have created a simple ToDo List app using Django. Recently I have worked on adding Due Dates to each task/todo. It works fine too. But to add a due date to any task, users will have to go to another URL and then add the date. What I want to do is have a due date Django form right in the Home page below every single task. When I try to accomplish this, I was successfully able to show the due form below each task, but when I input a day and press enter, Django throws an Unbound Local Error. The two forms I am having on my single Home page are the todo_form which is a single input field that is used to create new todos on the Home page and this due_form that will handle Due Dates. This is my views.py home function def home(request): if request.method == "POST": if "due_form" in request.POST: due_form = DueDateForm(request.POST) if due_form.is_valid(): days = due_form.cleaned_data.get("due_date") if days == "today": days = 0 elif days == "tomorrow": days = 1 elif days == "next week": days = 7 elif days == "yesterday": days = -1 elif days == "last week": days = … -
update table in django from json
I have created a webpage with a table (bootstrap) I am reading a json file and displaying it in the table as follows {% extends "blog/base.html"%} {% block content%} <h1>Table Page</h1> <table class="table table-borderless table-dark"> <thead> <tr> <th scope="col">#</th> <th scope="col">Email</th> <th scope="col">Count</th> </tr> </thead> <tbody> {% for post in posts %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{post.Email}}</td> <td>{{post.Count}}</td> </tr> {% endfor %} </tbody> </table> {% endblock content%} it works well, however the JSON file I am reading from keeps updating every 4-5 minutes and I need to constantly update the page, this is my views.py from django.shortcuts import render from django.http import HttpResponse import json with open('/home/usr134/tracker.json') as f: config=json.load(f) def table_test(request): context = {'posts':config} return render(request,'blog/my_table.html',context) I am new to django, I found plenty of ways to update but they use SQL, is there an easy way to do it ? -
Column values depends on another column
Hey i have a table where three columns... Item name, raw weight, product weight... Item weight is already defined so user get the drop down for it... And user have to input raw weight it's decimal... Now for a product weight... I have already data about it... Like for item A product weight = 0.5*raw weight... Like wise for B product weight = 0.7*rawweight... There are so many.... So my q is that how can i define backend side the logic of products weight column... Using offest etc.... Thanks.... -
What is more efficient for web development in Django : to perform calculations in python code or make valuation in MySql?
What is the most efficient way of organising and balancing code provided that the application: has large data as it is analytics web and it is all about calculations and analysis needs faster response smooth functioning of the web Would appreciate your insight and recommendation. -
Display the text in the same line in Django templates
I just started with Django. I rendering the text coming from the database. Even though it is in <li> tag the text is rendering in the new line. I also tried giving class col-md-2 but no use. Thanks in advance. <section class="resume-section p-3 p-lg-5 d-flex align-items-center" id="skills"> <div class="w-100"> <h2 class="mb-3">Skills</h2> {% for skill in skills.all %} <ul class="list-inline dev-icons"> <li class="list-inline-item"> <h5> &emsp;{{skill}} </h5> </li> </ul> {%endfor%} </div> views.py skills = Skills.objects return render(request,'home.html',{'jobs':jobs,'projects':projects, 'skills':skills}) -
How do I convert 2020-03-20T04:00:00.000Z string to DateTime in Django?
My datetime parameter is '2020-03-20T04:00:00.000Z'. How can I convert it to datetime & how can separate in date & time. -
Which is best to use for Data Science Project , Flask or Django?
Which one would be the best for Data Science Project ? Django or Flask .... I need to make a school management system and their I need to use Machine Learning Algorithms for Predictions and modeling .. I am confused whether to use Django or Flask? .. The web app will be fully loaded with different kinds of features and facilities . The web project will be very heavy loaded . So Kindly Please help me to choose and suggest which framework will be the best one for fully loaded web application and which one framework (Django or Flask) is more secure ? Thank You 😊 -
Production settings not available in celery task
My settings are structured like: /Settings/ - init.py - base.py - dev.py - prod.py The constant RANDOM_VAR is set in base.py My celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings.prod') app = Celery("tasks") app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() I have a file called fetchdata.py from django.conf import settings def fetchdata(source): print(os.environ['DJANGO_SETTINGS_MODULE']) print(settings.RANDOM_VAR) results in: app.settings.prod AttributeError: module 'app.settings' has no attribute 'RANDOM_VAR' Why is from django.conf import settings not loading the production settings. -
Access object value by other object value in template in Django?
This {{ category.id }} returns me 1 This {{ categories_counts.1 }} returns me data But {{ categories_counts.category.id }} doesn't work? Is it possible to access value by other object value? -
How do I redirect user to a dynamic page that displays the data he/she input in a form in Django?
I've just started learning Django, and ran into a problem. So I'm trying to make a user-specific page that shows the information of each user which he/she has input in the beginning. I have a form InputUserForm in ModelForm. Below is my function in views.py, which I intended to let the user input his/her information in url '.../inputuserinfo' and then trying to redirect him/her to a page that shows the information he/she input. def inputuserinfo(response): if response.method == 'POST': form = InputUserForm(response.POST) if form.is_valid: form.save() return HttpResponseRedirect("usermain/"+"%i" %UserInfo.authuser_id) *authuser is a ForeignKey connected to the User, in my model. Obviously I'm having trouble in the return part. As mentioned earlier, what I was trying to do was as soon as the user submits the form, a dynamic page with the information he/she has input would show up. I have usermain.html file, and path('usermain/<int:id>', ...) in my urls.py, but I cannot figure out what the problem is. I'm not sure if this is clear enough for you to understand, but this is the best I could explain with my limited knowledge in Django :( I very much appreciate your help! :) -
Django_filter on an apiview
I have been trying to use the Django_filter on an APIView, but it just does not work. I am trying to implement a filter search, on some fields on a model. below is how the model is set up class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=250) picture = models.TextField(null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=255, unique=True, blank=True) class Skill(models.Model): name = models.CharField(max_length=60) subcategory = models.CharField(max_length=60, blank=True, null=True) created_on = models.DateTimeField(auto_now=True) updated_on = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.DO_NOTHING) the views.py set up is also as shown below from django_filters import rest_framework as filters class UserFilter(filters.FilterSet): email = filters.CharFilter(lookup_expr='icontains') name = filters.CharFilter(lookup_expr='icontains') profiles__skills = filters.CharFilter(lookup_expr='icontains') class Meta: model = User fields = ('email', 'name', 'profiles__skills') class ListUsersView(APIView, MyPaginationMixin): ''' Gets all the users in the database ''' queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [AllowAny] pagination_class = api_settings.DEFAULT_PAGINATION_CLASS filterset_class = UserFilter def get(self, request): page = self.paginate_queryset(self.queryset) if page is not None: serializer_context = {"request": request} serializer = self.serializer_class(page, context=serializer_context, many=True) return self.get_paginated_response(serializer.data) and finally my serializer.py class UserSerializer(serializers.ModelSerializer): slug = serializers.SlugField(read_only=True) class Meta: model = User fields = ('email', 'name', 'slug', 'picture') … -
Django Rest Framework: urls with multiple slugs
I am develping the API for my blog. Every articles is related to a category, then the url of an articles is like this: "<slug:slug_category>/<slug:slug_post>/". Now my blog run without API and the previous path working fine. I need to have the same path with the API, then I've created this api view: @api_view(["GET"]) def blogPost_details_apiview(request, slug_post, slug_category): try: object = BlogPost.objects.get(slug_post=slug_post, slug_category=slug_category) except BlogPost.DoesNotExist: return Response({"Error": { "code": 404, "message": "Article not found!" }}, status=status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = BlogPostListSerializer(object) return Response(serializer.data) and this is the code in urls.py: path('<slug:slug_category>/<slug:slug_post>/', views.blogPost_details_apiview, name="details-blogpost"), I see this error: FieldError at /api/blog/gis/corso-applicativo-di-base-sistemi-informativi-territoriali/ Cannot resolve keyword 'slug_category' into field. Choices are: attachment, attachment_id, category, category_id, contents, description, draft, header_image, highlighted, id, publishing_date, slug_post, tags, timestamp, title, updating_date What I've wrong? I'm using Django 2.2 -
How do i store multiple photos that the author uploads in a blog?
I am stuck with how do i store all the photos that the author places in various sections in a blog. Can i use the same model with some ImageField but then What if there are multiple photos! As one field stores only one photo. Or, is it better to create a separate model class, so that i can get all the photos in a blog by referencing. Even then, how will it store multiple photos? -
Can Django queryset generate a SQL statement with self join?
I have a table that relates parents to children, it has the following data: +-----+-----+-----+--------+ | pid | rel | cid | relcat | +-----+-----+-----+--------+ | 13 | F | 216 | 1 | | 13 | F | 229 | 1 | | 13 | f | 328 | 2 | | 13 | F | 508 | 1 | | 13 | F | 599 | 1 | | 13 | f | 702 | 2 | | 560 | M | 229 | 1 | | 560 | m | 702 | 2 | +-----+-----+-----+--------+ I can find brothers of 229 by joining npr table to itself with SQL: SELECT npr_a.cid, CASE (SUM(IF(npr_a.relcat=1 AND npr_b.relcat=1,1,0))) WHEN 2 THEN '~FB~' WHEN 1 THEN '~HB~' ELSE '~Foster~' END AS BrotherType, abs(person_details.isalive) as isalive FROM person_details, npr npr_a, npr npr_b WHERE ( npr_b.cid = 229) AND ( npr_a.pid = npr_b.pid ) AND ( npr_a.cid <> 229) AND ( npr_b.relcat <> 3 ) AND ( npr_a.relcat <> 3 ) AND ( person_details.id = npr_a.cid ) GROUP BY npr_a.cid; to get: +-----+-------------+---------+ | cid | BrotherType | isalive | +-----+-------------+---------+ | 216 | ~HB~ | 1 | | 328 | ~Foster~ | … -
Django prefetch_related and inheritance
I am running into an issue with prefetch_related on a property of an inherited model.- In models.py I have: class Security(models.Model): name = models.TextField() ...other fields class Fund(Security): ...other fields @property def underlying_security(self): return self.maps_when_mapped.get().original_security_id class SecurityToSecurityMap(models.Model): original_security = models.ForeignKey(Security, related_name="maps_when_original") mapped_security = models.ForeignKey(Security, related_name="maps_when_mapped") and in serializers.py class UnderlyingSecuritySerializer(serializers.Serializer): id = serializers.IntegerField() name = serializers.CharField() class FundSerializer(serializers.ModelSerializer): underlying_security = UnderlyingSecuritySerializer(read_only=True, allow_null=True) class Meta: model = Fund fields = ("id", "name", "underlying_security") Now, I when I am quering fund objects: queryset = Fund.objects.prefetch_related("maps_when_mapped__original_security") Django ignores prefetching. Experimented with `Prefetch, tried moving property to the parent - no luck, still getting hundreds on queries. Any way this can be optimised? I am using Django 2.2 with Postgres 11 -
css broken after extending templte django
I'm quite new to django and I'm trying to build my first website. I've read that we can use template so they are used in several pages. I create my own template and then tried to extend it in a few pages. I have a login/register page. The view worked perfectly but when I extended the template, css broke and I do not have my body customized anymore (so no css). Any idea on how to fix it ? By the way, my template is a header that includes a nav bar. And i used a : {% block content%}{% endblock %} At the end of my template My register page looks like this: Any idea why my css not working anymore ? -
Sending email in Django throws Address family not supported by protocol exception
I'm sending emails using Django version 2.2 and have tested it on the local machine and it works. But the same code throws [Errno 97] Address family not supported by protocol exception. I also couldn't find any solution online. I have rechecked my code and there is nothing wrong in it. I'm using google smtp server with app_password. Below are Details. settings.py file EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "*******@gmail.com" EMAIL_HOST_PASSWORD = "app_password" Email Sending Function subject = 'Account Password reset mail' ctx = { "user" : self.user, "website" : settings.WEBSITE_NAME, "site_url" : settings.WEBSITE_URL, } msg = render_to_string('login/forgot_password_email.html',ctx) from_email = settings.WEBSITE_ADMIN_EMAIL to_email = [self.cleaned_data.get('email'),] result = send_mail(subject, '', from_email, to_email, fail_silently=False, html_message=msg) return result I even try to login to server through SSH and execute through the shell but returns the same error. >>> from django.core.mail import send_mail >>> res = send_mail('Subject here', 'Here is the message.', 'example@gmail.com', ['example@gmail.com'], fail_silently=False,) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/y6d62pncrpga/virtualenv/public_html/django/app2/3.7/lib/python3.7/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/home/y6d62pncrpga/virtualenv/public_html/django/app2/3.7/lib/python3.7/site-packages/django/core/mail/message.py", line 291, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/y6d62pncrpga/virtualenv/public_html/django/app2/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages new_conn_created = self.open() File "/home/y6d62pncrpga/virtualenv/public_html/django/app2/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 63, in open … -
How to print a receipt from a POS-system made in django from a webserver?
I've tried to print from an Epson printer in my django project using the python-escpos module on localhost. The problem is that the text size is either too small or too large. Text size 1 is very small and text size 2 is too large as the text doubles from size: 1 to size: 2. Can the problem be solved in the same module or is there a need for another module and which module could I otherwise use in django on a Linux machine? The second problem is when I deploy the project to a Linux-webserver, then how can the web server connect to the local printer from the website? And is it possible to install a universal driver for all printers on the web server or does a driver need to be installed for each printer locally on each client machine? Any help would be appreciated - thanks in advance! -
Prevent Duplicated user entries - Django
I'm working on a crud operation that corresponds to multiple users. Whenever I hit the update function, a new entry is being added without modifying the existing one. Can someone help me out with this? views.py def employee_form(request,id=0): if request.method == 'GET': if id == 0: # req = request.user.designation form = EmployeeForm(request) else: employee = Employee.objects.get(pk=id) if employee in request.user.employee.all(): form = EmployeeForm(request,instance=employee) else: return redirect('/emp') return render(request,'employee-form.html',{'form':form}) else: if id==0: form = EmployeeForm(request,request.POST) if form.is_valid(): print("Im passed") name = form.cleaned_data["name"] contact = form.cleaned_data["contact"] designation = form.cleaned_data["designation"] t = Employee(name=name,contact=contact,designation=designation) t.save() request.user.employee.add(t) else: employee = Employee.objects.get(pk=id) if employee in request.user.employee.all(): form = EmployeeForm(request,request.POST,instance=employee) if form.is_valid(): print("Im passed") name = form.cleaned_data["name"] contact = form.cleaned_data["contact"] designation = form.cleaned_data["designation"] t = Employee(name=name,contact=contact,designation=designation) t.save() request.user.employee.add(t) return redirect('/emp') I pretty much understand it's creating a new entry because of request.user.employee.add() I've tried making it update(), It threw an error update() has only 1 positional argument. -
PATCH AJAX Request to Django API View returns 405 (Method not allowed)
I am having issues making a PATCH request to my django backend. I'm utilizing Ajax to submit the request but I get a 405 Method Not Allowed response and I'm not sure why. I've noticed others have had issues with the urls, but I'm pretty sure this is not a problem in my case. Below is the Ajax request, the urls, and the view (which doesn't do anything at the moment). Thanks in advance. Ajax Request $jQuery.ajax({ url: "{% url 'definitional_phrase_update' 1 %}", data: {'definition': 'update_definition' }, cache: false, contentType: false, processData: false, type: 'PATCH', success: function(data){ window.location = "{% url 'definitional_phrase_review' %}"; } }); Urls url(r'^def/definitional_demo$', views.definitional_demo, name='definitional_demo'), url(r'^def/definitional_upload$', views.definitional_patient_upload, name='definitional_upload'), url(r'^def/definitional_view/(?P<report_id>[0-9]+)/$', views.definitional_view, name='definitional_view'), url(r'^def/definitional_phrase_review$', views.definitional_phrase_review, name='definitional_phrase_review'), url(r'^def/definitional_phrase_update/(?P<term_id>[0-9]+)/$', PhraseReview.as_view(), name='definitional_phrase_update') Simple View class PhraseReview(APIView): def update(self, request, *args, **kwargs): print("here") -
Django multiple dropdowns showing model objects
I want to have multiple dropdowns, each showing the available objects from one specific model. So Dropdown 1: Apples Oranges Pears and, Dropdown 2: Apples Oranges Pears etc. The bonus question is to have these dropdowns linked/be dependent so that as the user selects items, these chosen items are removed from the remaining dropdowns. Is this possible? -
how to write __str__ func in this case?
i have a 'user' model that have a OneToOneField to User Model and another model named 'user_agent' that have a foreign key to 'user' model. how can i use 'first_name' and 'last_name' in the str func?! class users(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default='') user_type = models.ForeignKey(types, on_delete=models.SET_NULL, blank=True, null=True) mobile = models.CharField(max_length=20) active_code = models.CharField(max_length=50, blank=True) date_send_active_code = models.DateField(default=now, blank=True) count_send_active_code = models.IntegerField(default=0) token = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class user_agent(models.Model): user = models.ForeignKey(user_models.users, on_delete=models.CASCADE) agent = models.ForeignKey(agents, on_delete=models.CASCADE) parent = models.ForeignKey("self", on_delete=models.CASCADE, default='1') def __str__(self): return "(" + self.user.first_name + " " + self.user.last_name + ")" -
Is there a way I can filter by any one of x in a django query
In my webwapp, I would like the user to be able to filter search results by selecting categories from the sidebar. The data GET request in the view retrieves the list of selected options and are parsed out. This data to filter by is then separated into lists, as shown in the following snippet from Index in views.py: class Index(View): def get(request): ... some checks to ensure its a valid request... if valid: dietTypeList = request.GET.getlist('diettype[]') #['meat','vegetarian',...] categoryList = request.GET.getlist('categories[]') #['Italian','Western',...] .... return render(request,'results.html',context_dict) .... I would then like to filter the results within the .filter() filter function so that my results are any of the selected categories, with any of the dietary types applied to those categories. I have looked into Q queries however im not sure how to do the following in any case How do I effectively do the following: results = Recipe.objects.filter(Q(name__contains=searchCriteria) & Q(category=any of categoryTypeList ))