Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError in models.py
Here is my models.py file. When I try to migrate it gives me an error. I changed Class name and it gives me an error. Now if I put even old name, it gives me the same error from django.db import models from tinymce.models import HTMLField class BlockTags(models.Model): pass class BlockTags_Text(models.Model): text = models.CharField(max_length=300, verbose_name='Заголовок 1', null=True, blank=True) block = models.ForeignKey(BlockTags, related_name="text", verbose_name='Заголовок 1', on_delete=models.CASCADE, null=True,blank=True) number = models.DecimalField(max_digits=3, decimal_places=0) ValueError: The field content.BlockTags.text was declared with a lazy reference to 'content.blocktags_text', but app 'content' doesn't provide model 'blocktags_text'. (venv) appledeMacBook-Pro:letbuycar apple$ -
How can I sort a table by click event on a select menu. JavaScript
I queried the data from the database using Django and I displayed the data into a table. I made a select menu using HTML and jQuery and now I want to create a click event on this select menu. How can I do, for example, select "Order by date" in the select menu, and start an on click event on the table? Select menu - HTML, Materialize and jQuery <div class="row"> <div class="input-field col s2 offset-s1"> <select> <option value="" disabled selected>View</option> <option value="1">Display all</option> <option value="2">Order by date</option> <option value="3">Order by price</option> </select> </div> <script> $(document).ready(function(){ $('select').formSelect(); }); </script> Table <tbody> {% block content %} {% for f in fields %} <tr> <td>{{ f.date }}</td> </tr> {% endfor %} {% endblock %} </tbody> -
Django template return all files in section
Here my problem, The user can add Sections, in the section he can add documents, what I would like to do it's to return all documents added in section I can't figure it out which way is the best to filter by section: Here my model for the Documents : class Document(models.Model): """ Staff of the hospital center services """ # ATTRIBUTES label = models.CharField( max_length=255, verbose_name='Intitulé' ) description = models.TextField( verbose_name='Description', blank=True, null=True ) document = models.FileField( verbose_name='Document' ) section = models.ForeignKey( 'espace_documentaire.EspaceDocumentaire', verbose_name="Espace Documentaire", related_name="documents", null=True, blank=True, on_delete=models.CASCADE ) dedicated_page = models.ForeignKey( "pages.Pages", verbose_name="Page", related_name="documents", null=True, blank=True, on_delete=models.CASCADE ) division = models.ForeignKey( "services.Division", verbose_name="Pôle", related_name="documents", null=True, blank=True, on_delete=models.CASCADE ) order = models.IntegerField( verbose_name="Ordre d'affichage", default=0 ) # TRACE date_created = models.DateTimeField( verbose_name="date de création", auto_now=True ) date_updated = models.DateTimeField( verbose_name="date de modification", auto_now=True ) def __str__(self): return self.section Here my Model for the Sections : class EspaceDocumentaire(models.Model): # ATTRIBUTES section = models.CharField( max_length=255, verbose_name='Nom de la section' ) colorsection = models.CharField( max_length=255, verbose_name='Couleur de la section' ) order = models.IntegerField( verbose_name="Ordre d'affichage", default=0 ) document = models.ForeignKey( 'documents.Document', verbose_name="Document", related_name="documents", null=True, blank=True, on_delete=models.CASCADE ) def __str__(self): return self.section Here my template : {% for ed in espace_documentaire %} … -
How to insert nested json data in all related table in django
I'm using Django REST framework, I'm stuck in Inserting this data into all related table. Please tell me how to insert all the data together in all related tables. I want to do that color should go to the color table, same for size in size table, same for variations in the variation table and the rest of the data should go to the product table. Json Data { "category": 15, "images": [ {"image_url": "https://images/1607679352290_0f32f124a14b3e20db88e50da69ad686.jpg", "main_image": true}, {"image_url": "https://images/1607679352290_0f32f124a14b3e20db88e50da69ad686.jpg", "main_image": false} ], "keywords": "leaxon", "long_description": "<p>l</p>", "mrp_price": "120", "selling_price": "908", "short_description": "<p>k</p>", "sku": "Sam-009", "stock": "7", "title": "Samsung", "have_variations": true, "variant": "Size-Color", "slug": "samsung-phone", "variations": [ { "image_url": "https://images/607679417554_0f32f124a14b3e20db88e50da69ad686.jpg", "mrp_price": 68, "selling_price": 86786, "sku": "iuy", "stock": 68768, "title": "hkj", "color": "red", "size": 9 }, { "image_url": "https://images/607679434082_0392bab5c6a3ec64552ea57aa69852a5.jpg", "mrp_price": 67, "selling_price": 6876, "sku": "hkjh", "stock": 868, "title": "yiui", "color": "blue", "size": 9 } ] } Models.py from django.db import models # Create your models here. from django.urls import reverse # Category table class Category(models.Model): title = models.CharField(max_length=50, default='') keywords = models.CharField(max_length=255, default='') description = models.TextField(max_length=255, default='') slug = models.SlugField(unique=False, default='') parent = models.ForeignKey('self', on_delete=models.SET_NULL, blank=True, null=True, related_name='children') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'product_category' ordering = ['-created_at'] … -
Creating importer service for Django
We run a medium-sized data-related website using Django. Previously, we imported new data from csv files. Now, these new data are pushed to us via an API. We need to update our software accordingly. Our importer service performs ongoing GET requests to another server to fetch new data. In total, there will be six services that keep the connection alive, and which may not interfere with our website that should keep running. We expect roughly 100 updates per second. We have thought of the following alternatives: Create software that only utilizes the ORM capability of Django and run it on a separate server/Docker virtualization. However, this raises the question how this can be done in a Pythonic manner. Any ideas or advice would be appreciated! -
How can I catch all 500 and above errors in DRF and log them?
I've looked through much of the SO responses regarding implementing this but I can't seem to find something that isn't deprecated or one that actually works for my use case. Basically, I have some API methods that return their own status codes. However, if for any reason there is a 500 Server Error or anything above 500 which indicates something strange happened (for example lets say the database connection got timeout), I want that to be logged to a file or e-mailed to an admin. I have tried using a custom exception handler but not all 500 errors are exceptions. So I resorted to writing custom middleware, which looked something like this class CustomApiLoggingMiddleware(MiddlewareMixin): def process_response(self, request, response): if response.path.startswith('/api/'): ...do stuff here The issue, however, is that there doesn't seem to be a status_code. To be frank I don't really know which response I'm actually getting. There's the 500 response returned by my API intentionally as a result of the API method, and there's the 500 response generated by Django in the backend if some kind of condition isn't met (let's say they sent a request without a proper header) I tried to generate a 500 response / error … -
my static(css , js)not loading in django sphinx project
i want to use sphinx in django .and i cant change directory (static).when i run server html is load but css & js not loading. /home/jojo/Documents/django/lolo/docs/sphinx/build/html/_static my settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) STATIC_ROOT = os.path.join(BASE_DIR, 'sphinx', 'build', 'html', '_static') STATIC_URL = '/_static/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'sphinx', 'build', 'html')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DEBUG = True ALLOWED_HOSTS = ['*'] and urls.py from django.contrib import admin from django.urls import path from auth_backends.urls import oauth2_urlpatterns from .views import DocsHandler urlpatterns = oauth2_urlpatterns + [ path('admin/', admin.site.urls), path('<doc_path>/', DocsHandler.as_view()), ] view.py is from django.http import HttpResponseNotFound from django.shortcuts import render from django.utils.translation import ugettext as _ from django.views.generic import View class DocsHandler(View): def get(self, request, doc_path): if not doc_path: doc_path = 'index.html' try: return render(request, doc_path) except: return HttpResponseNotFound(_('page not found')) and links in html file <script type="text/javascript" src="_static/js/modernizr.min.js"></script> <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="_static/language_data.js"></script> <script type="text/javascript" src="_static/translations.js"></script> <script type="text/javascript" src="_static/js/theme.js"></script> <link rel="stylesheet" href="_static/css/theme.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="_static/_themes/readthedocs-rtl/css/extra.css" type="text/css" /> docs main_app manage.py sphinx build html index.html ora.html _static css js _themes jquery.js … -
my testcases are failing in django for PUT and DELTE methods
i have build a basic crud api with django_rest_framework.when i write test cases for GET and POST it works fine ,But when i write test for PUT and Delete it gives me error. tests.py import json from django.urls import reverse from rest_framework.test import APITestCase from rest_framework import status from .models import Customer from .serializers import CustomerSerializer class PostCustomerTest(APITestCase): def test_post(self): data = { "name": "john", "address": "address", "phoneNumber": "2645662", "gstin": "26456", "outstandingbalance": 2356.26 } response = self.client.post("/api/",data) self.assertEqual(response.status_code,status.HTTP_201_CREATED) def test_get(self): response = self.client.get('/api',{},True) self.assertEquals(response.status_code,status.HTTP_200_OK) def test_put(self): data = { "name": "test", "address": "address", "phoneNumber": "2645662", "gstin": "26456", "outstandingbalance": .36 } response = self.client.put("/api/1/",data) serializer = CustomerSerializer(data) print(response.status_code) # self.assertEquals(response.data,serializer.data) self.assertEqual(response.status_code,status.HTTP_200_OK) def test_delete(self): response = self.client.delete("api/1/") self.assertEquals(response.status_code,status.HTTP_200_OK) views.py class CustomerView(APIView): def get_object(self, pk): try: return Customer.objects.get(pk=pk) except Customer.DoesNotExist: raise Http404 def get(self,request,format=None): cus = Customer.objects.all() serializer = CustomerSerializer(cus,many=True) return Response(serializer.data,status=status.HTTP_200_OK) def post(self,request,format=None): serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): serializer.save() print("after Save") return Response({ 'Status':True, 'Message':"Customer Added Successfully", },status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) def put(self, request, pk, format=None): customer = self.get_object(pk) serializer = CustomerSerializer(customer, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): customer = self.get_object(pk) customer.delete() return Response(status=status.HTTP_204_NO_CONTENT) models.py class Customer(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=50) phoneNumber = … -
unable to insert form in template: 'WSGIRequest' object has no attribute 'get'
I try to insert form in template and get an error 'WSGIRequest' object has no attribute 'get'I don't understand my form (BillForm) is based on a model (Orders) and I just want to display one of it fields (split_bill) in my index template that is a table I have look for this error in documentation and here on stackoverflow but did not understand the issue... forms.py class BillForm(forms.ModelForm): class Meta: model = Orders fields = ['split_bill',] views.py def index(request): orders = Orders.objects.filter(paid = False) # only ongoing orders (not paid) if request.method == "POST": billform = BillForm(request, data=request.POST or None) if billform.is_valid(): billform.save() return redirect('home') else: billform = BillForm(request) return render(request, 'cafe/index.html', {'orders':orders,'billform':billform,}) index.html <div class='container'> <h1>Dashboard</h1> <table id="table_id" class="table table-stripped table-hover" style="width:100%"> <thead> <tr> <th>Order</th> <th>Table</th> <th>Date</th> <th>Served</th> <th>Bill</th> <th>Paiment</th> <th>Actions</th> </tr> </thead> <tbody> {% for order in orders %} <tr> <td data-toggle="tooltip" data-placement="top" title=""> {{ order.order_id }} </td> <td data-toggle="tooltip" data-placement="top" title=""> {{ order.table_id }} </td> <td data-toggle="tooltip" data-placement="top" title=""> {{ order.created_at|date:"D, d M, Y" }} </td> <td data-toggle="tooltip" data-placement="top" title=""> {% if order.delivered %} <a style="margin-right: 40px;color:black;" data-order="{{ order.order_id }}" class="served" href="#"><i class="fa fa-check-square" aria-hidden="true"></i></a> {% else %} <a style="margin-right: 40px;color:black;" data-order="{{ order.order_id }}" class="served" href="#"><i class="fa … -
GitHub MonoRepo Beanstalk CodePipeline Django
I'm playing around with Beanstalk to deploy a private website project. Currently, my project is organized in a Monorepo containing the frontend being vue.js and backend being Django. And looks like this: -.ebextension -django.config -.elasticbeanstalk -config.yml -frontend -... -backend -backend -settings.py -wgsgi.py -... -manage.py -... At first, I deployed the backend from inside the backend directory which worked great, but now I'm trying to change that to trigger the deployment from GitHub. The CodePipeline works in principle except for the last step, wheres about to start the application where it fails because it cannot find the application, as it is in a subdirectory. How can I reference the WSGIPath in a subdirectory? I tried now many combinations like ./backend/backend.wsgi etc. But not one is accepted. option_settings: aws:elasticbeanstalk:container:python: WSGIPath: backend/backend.wsgi:application <--Not found aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: backend.settings packages: yum: python3-devel: [] postgresql-devel: [] container_commands: 00_list: command: "ls && ls backend/" leader_only: true 01_start: command: "echo starting initialization" 02_makemigrations: command: "source /var/app/venv/staging-LQM1lest/bin/activate && cd backend/ && python manage.py makemigrations" leader_only: true 02_migrate: command: "source /var/app/venv/staging-LQM1lest/bin/activate && cd backend/ && python manage.py migrate" leader_only: true Thanks in Advance -
Inconsistent "contains" filter behaviour for jsonfield mysql/sqlite
I'm getting inconsistent results depending on the backend database when using jsonfield "contains" queries. from polymorphic.models import PolymorphicModel import jsonfield class Action(PolymorphicModel): new_object = jsonfield.JSONField(null=True) In another model I filter on this jsonfield, but I get different results. On sqlilite the following works: return Action.objects.filter( new_object__contains={"ref_id": self.id} ).order_by("-created_at")[:5] On mysql I have to do the following: return Action.objects.filter( new_object__contains=f"\"ref_id\": {self.id}" ).order_by("-created_at")[:5] So it seems to me in one environment it's deserialising the json into a dict, whereas the other keeps it as string.. Does anyone have a good way of handling this? Could there an issue with one of the configurations not lining up with the database? -
Search filter using Serializer with Django and Javascript
I want to populate my data to the table in my webpage but it gives an error as undefined in my rows And The data from my database is not being displayed in the table. How should i call the serialized data. Can anyone please help me with this. The output should look like the below: Column1 Column1 Column1 Column1 Column1 Column1 Column1 Column1 Column1 2011:abc salary 234 456 567 43 21 67 89 gia salary 56 678 654 432 345 436 789 others 123 234 456 567 765 478 987 total 56 78 98 09 76 54 56 2012:xyz salary 234 456 567 43 21 67 89 gia salary 56 678 654 432 345 436 789 others 123 234 456 567 765 478 987 total 56 78 98 09 76 54 56 2013-pqr .... . . . But my output is being displayed as below: Column1 Column1 Column1 Column1 Column1 Column1 Column1 Column1 Column1 undefined: undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined: undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined … -
Django: is it safe to include secret data in the context dict used to render a template in a view?
Is data that is included in the context dict passed to the render function but is not called in the template accessible to the user or their browser? Is it ok to just pass a QuerySet to the template even when some of the fields of the models must be kept secret from the user? I would appreciate a reference to the official Django documentation or any other reliable sources confirming this is safe, if anyone finds one. Code Example models.py: class Riddle(models.Model): question = models.TextField() # show to user solution = models.TextField() # very secret views.py def riddles_list(request): data = Riddle.objects.all() return render(request, 'riddles.html', {'riddles': data}) riddles.html <ul> {% for riddle in riddles %} <li>{{ riddle.question }}</li> {% endfor %} </ul> Is this safe, or does the user has a way of accessing the solution of the riddle? Is the solution now available anywhere except the Django server? A possible approach would be to change the query to: data = Riddle.objects.values('question') Is this considered better code than just fetching the whole object? (for security, efficiency, readability, maintainability etc.) In the real code there are more calls like filter and annotate in the query, and the models have more fields. -
How to implement pyodbc with Django and storing the password for databases?
I developed a Django application, where a user can change the database dynamically through the UI. I tried using Django's integrated database configurations in settings.py but I had to do some workarounds but still faced some weird errors. Therefore I decided to use pyodbc with a connection string to connect to the database in my views.py. The User inputs his database credentials (table, user, password, host, port), which then get saved on a database. Every time a user needs some data following method gets invoked: con = DatabaseConnection.objects.all().first() conn_str = '{}/{}@{}:{}/{}'.format(con.user, con.password, con.host, con.port, con.name) Everything works fine, but how exactly do I store the password(or the rest of the data) correctly? I thought about encrypting and decrypting the password in my views.py but that wouldn't make sense, would it? -
Javascript: How can I display the total price for the values that are inputted into it?
I am creating a project that will serve as a grocery store. The customer will click on the checkboxes and then click a submit button, prompting an alert to show the values that were clicked and the total price. home.html <form action="{% url 'js' %}" method="POST" id="menuForm"> {% for post in posts %} {% if post.quantity > 0 %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ post.category }}</a> </div> <h2><a class="article-title" >{{ post.title }}</a></h2> <p class="article-content"> Price: ${{ post.Price }}</p> <p class="article-content"> Sale: ${{ post.Sale }}</p> <input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }} </input> </div> </article> {% else %} {% endif %} {% endfor %} <button id="btn" type="submit" form="menuForm">Confirm Purchase</button> </form> <script src="{% static "JS/javascript.js" %}" type="text/javascript"></script> javascript.js function getSelectedCheckboxValues(name) { const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`); let values = []; checkboxes.forEach((checkbox) => { values.push(checkbox.value); }); return [values]; console.log(getSelectedCheckboxValues('products')) } console.log(values) var price = 0; var tPrice = 0; for (var i = 0;i<values.length;i++){ if (values[i] == 'Milk'){ var MPrice = 3.99 tPrice = price+MPrice; } if (values[i] == 'Cheese'){ var CPrice = 4.50 tPrice = price + CPrice; } if (values[i] == 'Yogurt'){ var YPrice = 1.99 tPrice = price … -
Django admin - combine two models
I have setup a small support application at my website, but to integrate it and get the full potential out of it I as an administrator should have the opportunity to also reply onto support tickets the user has opened. Otherwise a support application is pretty useless I guess ... So my question is how can I combine these two models at django admin to reply onto a support ticket? I need to get the replies underneath the actuall support ticket plus a form to add a reply at django admin... Can smb. Help: class SupportTicketReplies(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to=referential_models, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='support_ticket_reply_author', verbose_name='Author', blank=True) content = models.TextField(verbose_name="Content", max_length=3000) creation_date = models.DateTimeField(auto_now_add=True, blank=False) class SupportTickets(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) ticket_id = models.IntegerField(default=ticket_id_generator, unique=True, blank=False, null=False, editable=False) requester = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) category = models.IntegerField(choices=TICKET_CATEGORY, verbose_name='Ticket Category') subject = models.CharField(max_length=40) problem_description = models.TextField(max_length=3000) status = models.IntegerField(choices=STATUS_OF_TICKET, verbose_name='Ticket Status', default=0) reply_relation = GenericRelation(SupportTicketReplies, related_query_name='reply_relation') creation_date = models.DateTimeField(auto_now_add=True, null=True) Thanks in advance -
ValueError: cannot assign "value": "field" must be a "object" instance
i was building a django app for dbms project and i had to write the code to update a row using mysql (i have to use cursor), so i used the below syntax but i am getting a value error cursor.execute("update profiles_author a,address_country c set country_id=%s, about=%s, photo=%s where a.country_id=c.id",[country,about,photo]) Error is as follows... Cannot assign "1": "Author.country" must be a "Country" instance. i tried to switch off and on the foreign key contraint but i believe thats not the problem and it didnt work anyway cursor = connection.cursor() cursor.execute("set foreign key constraint=0;") cursor.execute("update profiles_author a,address_country c set country_id=%s, about=%s, photo=%s where a.country_id=c.id",[country,about,photo]) cursor.execute("set foreign key constraint=1;") Is there anyway to do this by using cursor or something where i can do it using mysql code or saving it using the model object is the only option? pardon my question format if i did some mistakes, Thank you -
Margin Right Auto in bootstrap is not working in Django
I am a bootstrap and Django beginner and I want to know why my margin-right is not working in Django. I was following a YouTube tutorial. Here is that link: https://www.youtube.com/watch?v=qDwdMDQ8oX4 Here is the code I have used; {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'blog/main.css' %}"> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top d-flex"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item nav-link" href="#">Login</a> <a class="nav-item nav-link" href="#">Register</a> </div> </div> </div> </nav> </header> <main role="main" class="container"> <div class="row"> <div class="col-md-8"> {% block content %}{% endblock %} </div> <div class="col-md-4"> <div class="content-section"> <h3>Our Sidebar</h3> <p class='text-muted'>You can put any information here you'd like. <ul class="list-group"> <li class="list-group-item list-group-item-light">Latest … -
Google Analytics with local Django Application
I am trying to add Google Analytics (GA) to my Django application and I am a beginner to Django. My application is not deployed to the internet, i.e. I access it through http://127.0.0.1:8000/. According to this tutorial https://pypi.org/project/django-google-analytics-app/, I need a tracking code which I cannot get because GA does not accept http://127.0.0.1:8000/ as a website URL. How can I add GA to my local Django app and get the related analytics on GA. Thanks a lot for your help! -
Updating field value in views
I've a model with name Task with the following attributes: class Task(models.Model): jobid = models.CharField(max_length = 10, null = True) worker = models.ForeignKey(Worker, null = True, on_delete=models.SET_NULL) machine = models.ForeignKey(Machine, null = True, on_delete=models.SET_NULL) production_count = models.IntegerField(default = 0) qc_passed = models.IntegerField(default = 0) target_count = models.IntegerField(null = True) duration = models.IntegerField(default = 0) def __str__(self): return (self.jobid) I want to update the duration field with the time difference. The time difference is the time duration for which the form shows up on the screen. def HMImachine1(request, pk_test): machinevalue = 9 worker = Worker.objects.get(empid = pk_test) totaltask = worker.task_set.all() task = totaltask.filter(production_count = 0, machine = machinevalue) if not task: return redirect('HMI_notauth') start_time = datetime.datetime.now() form = ProductionForm(instance = task[0]) content = {'form': form, 'task': task[0], 'start_time': start_time} if task: if (request.method == 'POST'): form = ProductionForm(request.POST, instance = task[0]) if form.is_valid(): form.save() end_time = datetime.datetime.now() diff = end_time - start_time worktime = divmod(diff.total_seconds(), 60) sec = int(worktime[1]) total_time = sec + task[0].duration task[0].duration = total_time task[0].save(update_fields = ['duration']) return redirect('login') return render(request, 'MachAutomation/HMI_production.html', content) The ProductionForm updates the production_count and qc_passed. I tried the following in the shell: >>> task <QuerySet [<Task: JB1010>, <Task: JB1050>]> >>> start_time = datetime.datetime.now() … -
How do I save data in my Django DB when I am taking Inputs from Modal table Form?
I am trying to make a Profile settings page where when I click on Edit (name or description or others) then it will pop up a modal form and then I want user to edit their name and then that name should be saved in the Django DB and display that changed value in the profile settings page. This is what I have tried, but I'm still not able to save data in Django DB. This is my views.py: def seller_profile_settings(request): data = {} if request.user.is_authenticated: try: details = detail.objects.filter(email=request.user).first() except: return redirect('/userdetail/logout') if details.vendor: data = { "user": details } if request.method == "POST": if request.POST.get('submit'): if form.is_valid(): description = request.POST.get('description') name = request.POST.get('name') contact = int(request.POST.get('email')) mission = request.POST.get('mission') address = request.POST.get('address') t_and_c = request.POST.get('t_and_c') details.description = description details.name = name details.contact = contact details.mission = mission details.t_and_c = t_and_c details.address = address a = customer_address(email=request.user.email, address=addresss, permanent=True) a.save() details.info_update = True details.save() return redirect('userdetail/seller_profile_settings.html') return render(request,'userdetail/seller_profile_settings.html', {"details":details}) and below is my HTML file where I am taking user inputs: <form method="POST" enctype="multipart/form-data" action="{% url 'seller_profile_settings' %}"> <input type="hidden" name="csrfmiddlewaretoken" value="kcu26KY77seywzOvJAc18zISS2zwQO1gCLsDwwHU7dFzHcs4FQcPMg6TQr0MbisQ"> {% csrf_token %} <table class="table table-hover"> <tbody> <tr> <th>Name</th> <td class="font-weight-normal">{{ details.name }}</td> <td data-toggle="modal" data-target="#exampleModalLong"><a href="#"><i … -
Manage requests and optimize server utilization in django
Actually, I need some suggestions for a server-based architecture. So let me explain the whole architecture first. I have two Django servers that are used for multiple operations, but the system which I am talking about is, server(A) calls the server(B) with 4 big JSON files nearly ~10MB, so every request has these 4 files, size may vary. And the sever(B) processes the data which consists of more CPU intensive tasks, multiple IO tasks, DB operations, etc. Now the problem I am facing is: I don't have a proper system to receive all the requests in an optimized manner so that I can reduce the round trip time for the requests. And I need to process all these requests on the server(B) parallelly and utilize all the resources of my server(B). Right now it's not utilizing the resources properly, though I have used multiprocessing. Any suggestion will be helpful. Thank You -
in-place-edit in Django/Python not working
i am looking to use inplaceedit in my django app. I did the installation and it went well : pip install django-inplaceedit==0.77 On top of the base.html i have <!DOCTYPE html> <html lang="en"> <!-- Static assets - Used to load the Favicon --> {% load static %} {% load inplace_edit %} {% inplace_toolbar %} .... I get the following error : Exception Value: Invalid template library specified. ImportError raised when trying to load 'inplaceeditform.templatetags.inplace_edit': No module named 'django.core.urlresolvers' if I keep following the turtorial and add the following to the urls.py, I get : ... File "C:\Users\franky.doul\AppData\Local\Programs\Python\Pyth -packages\inplaceeditform\urls.py", line 20, in <module> from django.conf.urls.defaults import patterns, url ModuleNotFoundError: No module named 'django.conf.urls.defaults' Anything that I am missing or doing wrong please? -
Django - get latest item from get_object_or_404
I want to return an object from my get_object_or_404 method but my query returns multiple objects. Is there a way to get last or first item? This is how I do it: return get_object_or_404(BatchLog, batch_id=self.kwargs["pk"]) I know it is not possible but this is kind of what I need: return get_object_or_404(BatchLog, batch_id=self.kwargs["pk"].last()) -
How do I customize how Django handles successful password resets?
I have sub-classed Django's password reset views and everything works fine, however, when the reset link is invalid it displays a template. I would like it to be a message. So, for example, when the link is valid, it displays the password reset form and then a success message with a redirect (this is how it functions at the moment). When the link is invalid, though, it should display an error message with a different redirect. How would I be able to add that error message and redirect? urls.py from .views import * urlpatterns = [ path('password-reset/', PasswordResetView.as_view(), name='password-reset'), # password reset view re_path(r'^password-reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password-reset-confirm'), # password reset confirm view ] views.py class PasswordResetConfirmView(PasswordResetConfirmView): template_name = 'accounts/password-reset-confirm.html' post_reset_login = True post_reset_login_backend = 'django.contrib.auth.backends.ModelBackend' def get_context_data(self, **kwargs): context = super(PasswordResetConfirmView, self).get_context_data(**kwargs) context['title'] = 'Password reset' return context def form_valid(self, form): messages.success(self.request, 'Your password has been successfully reset.') return super().form_valid(form) def get_success_url(self): student = self.request.user return reverse_lazy( 'home') password-reset-confirm.html {% extends 'base.html' %} {% block content %} {% if validlink %} <div class="floating-labels auth"> <div class="container"> <form method="POST" autocomplete="off" class="shadow" novalidate> {% csrf_token %} <div class="mb-4"> <h4 class="mb-3 heading">Reset password</h4> <hr> </div> {% include 'accounts/auth.html' %} <button class="btn btn-lg btn-one btn-block …