Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not parse the remainder: '=' from '='
I had a project working on python 2.7, and django 1.8. Everything was working fine but when I updated to django 2.2 and python 3.7 I am getting the error could not parse the remainder: '=' from '=' . The error is in 3rd line of code below. Any help? {% for elem in artHeaders %} {% if elem in artDetails %} {% if elem == "file_tags" %} -
Why I cannot use Django Signals to reload HTML page
I want to reload or refresh a HTML page (block content) when a specific table from the database is saved. My first idea was to use Django Signals (post-save() method). This trigger would have triggered a view or rendered a html template. But I read that it is not possible and/or it's not best practice. Why it is not possible to use a Django Signal for this purpose and what is the best practice? Do you know another methodology than avoid AJAX request? Many thanks in advance for your answer. -
Python 2.7 and 3.8.0 compatible django-redis serializer
I Have two server running one is running on python2.7 and another on python3.8. for both the servers we have the common Django-cache server. python2.7 server is setting up cache in the Django-cache and python3.8 trying to read this throwing an error saying File "/usr/local/bin/python-3.8.0/lib/python3.8/site-packages/django_redis/serializers/pickle.py", line > 35, in loads return pickle.loads(value) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 1: ordinal not in range(128) i already read the below post with the same question link my goal here is to able to read and from both versions of python to the common django-cache. -
can anyone help me, why I am getting food is not defined error ? I have attached the structure of Django module
enter image description here I have added food app. inside food app i added url.py. TO import food.url.py i used include method to import food.url.py in mysite.url.py. but while running the server i am getting error as food is not defined -
to_representation takes two different value types
I don't understand to_reprsentation(self, value) well, I have a case like this when I use postman status returns "ORDERED, ..." when I post and create an order and the value in to_reprsentation is of type int when I open localhost:8000/orders/, I get Order object can't be converted into int, value is of type Order this time. I searched every single article I found, I didn't understand both methods to_representation & to_internal_value models.py class Product(models.Model): title = models.CharField(max_length=120) price = models.FloatField(max_length=20) def __str__(self): return f"{self.title} - {self.price}" class Meta: ordering = ['price'] @property def images(self): for image in Image.objects.filter(product=self): yield image.src.url and class Order(models.Model): ORDER_STATUS = ( (STATUS.UNORDERED, 'Unordered'), (STATUS.ORDERED, 'Ordered'), (STATUS.BEING_PROCESSED, 'Being processed'), (STATUS.BEING_PROCESSED, 'Being Delivered'), (STATUS.DELIVERED, 'Delivered'), (STATUS.RECEIVED, 'Received'), (STATUS.REFUND_REQUESTED, 'Refund requested') ) products = models.ManyToManyField(Product) # status = models.IntegerField(choices=ORDER_STATUS, default=STATUS.UNORDERED) class Meta: ordering = ['pk'] serializers.py class ProductSerializer(serializers.ModelSerializer): images = serializers.SerializerMethodField() class Meta: model = Product fields = ['id', 'title', 'price', 'images'] def get_images(self, obj): request = self.context.get('request', None) for url in obj.images: yield request.build_absolute_uri(url) class StatusField(serializers.RelatedField): def to_internal_value(self, value): try: if int(value) > STATUS.ORDERED: raise APIException("Can't update an ordered order.") except ValueError: raise APIException('Unknown order status code') except TypeError: raise APIException('Order status must be an integer.') return … -
Django Queryset with annotate
I am writing one method in Django Manager model. I want to write method that finds out number of all sold copies (books) per author. I have two models and method written in Manager. My problem is that method should also be chainable from any Author queryset, for example something like Author.objects.filter(...).exlucde(...).total_copies_sold() should also work. Example: author = Author.objects.create(...) Book.objects.create(..., author=author, copies_sold=10) Book.objects.create(..., author=author, copies_sold=20) author_total_books = Author.objects.total_copies_sold().first() >>> author_total_books.copies 30 Below my code. It works like in example above, but then I try something like: author_books = Author.objects.filter(id=2).total_copies_sold() I got 'QuerySet' object has no attribute 'annotate' class AuthorManager(models.Manager): def total_copies_sold(self): return self.get_queryset().annotate(copies=Sum('book__copies_sold') class Author(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) objects = AuthorManager() class Book(models.Model): title = models.CharField(max_length=120) copies_sold = models.PositiveIntegerField() author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books') -
NameError at /checkout/payment/ name 'client' is not defined with razorpay payment integration
i am trying to implement razorpay payment integration with my django project but i am not able to understand the flow of the payment gateway, it shows me the error with the following code. please help me. views.py def payment(request): order = Order.objects.get(user=request.user, ordered=False) amount = int(order.get_totals() * 100) print(amount) if request.method == 'POST': charge = client.order.create(amount=amount, currency='INR', receipt=order) # Create the Payment payment = Payment() payment.razorpay_order_ID = charge['id'] payment.user = request.user payment.amount = int(order.get_totals() * 100) payment.save() else: # order = Order.objects.get(user=request.user, ordered=False) # context = { # 'order': order # } return render(request, 'checkout-form.html') return redirect('checkout:payment/') checkout-form.html <div class="col-md-6"> <form action="{% url 'checkout:payment'%}" method="POST"> {% csrf_token %} <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <h3>Payment</h3> <label for="fname">Accepted Cards</label> <div class="icon-container"> <i class="fa fa-cc-visa" style="color:navy;"></i> <i class="fa fa-cc-amex" style="color:blue;"></i> <i class="fa fa-cc-mastercard" style="color:red;"></i> <i class="fa fa-cc-discover" style="color:orange;"></i> </div> <label for="cname">Name on Card</label> <input type="text" id="cname" name="cardname" placeholder="John More Doe"> <label for="ccnum">Credit card number</label> <input type="text" id="ccnum" name="cardnumber" placeholder="1111-2222-3333-4444"> <label for="expmonth">Exp Month</label> <input type="text" id="expmonth" name="expmonth" placeholder="September"> <div class="row"> <div class="col-md-6"> <label for="expyear">Exp Year</label> <input type="text" id="expyear" name="expyear" placeholder="2018"> </div> <div class="col-md-6"> <label for="cvv">CVV</label> <input type="text" id="cvv" name="cvv" placeholder="352"> </div> </div> <div class="row"> <div class="col-md-6"> <input type="submit" value="Pay" class="btn btn-primary br-tr-3 br-br-3"> </div> </div> <input … -
Django - Getting latest of each choice
I have two models: the gas station and the price of a product. The price can up to have 4 choices, one for each product type, not every station has all four products. I want to query the latest entry of each of those products, preferably in a single query: class GasStation(models.Model): place_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255, null=True, blank=True) class Price(models.Model): class Producto(models.TextChoices): GASOLINA_REGULAR = 'GR', _('Gasolina regular') GASOINA_PREMIUM = 'GP', _('Gasolina premium') DIESEL_REGULAR = 'DR', _('Diesel regular') DIESEL_PREMIUM = 'DP', _('Diesel premium') product = models.CharField(max_length=2, choices=Producto.choices) fecha_cre = models.DateTimeField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) I've tried with: station.price.filter(product__in=['GR', 'GP', 'DR', 'DP']).latest() But it only returns the latest of the whole queryset, not the latest price of each product type. I want to avoid querying for each individual product because some stations don't sell all types .Any advice? -
javascript request for django like a submit button
I have a button in the html code with which I trigger a re-rendering of the html page. this also works without problems. now i don't want to generate the re-rendering with the html button, but with clicking on a javascript object. how should I do that? i mean: that only this line of code would have to be added to my javascript: <a href="{% url 'water' %}" class="btn btn-dark">Water</a> my idea is that when i click i send an ajax call to. it is also successfully received in view.py, but the page is not re-rendered. I assume that the ajax call has not yet been completed from the javascript page? $.ajax( { headers: { "X-CSRFToken": token }, type: "POST", url: 'water', data: { 'waterarray[]': waterdata, }, success:function (){}, complete:function (){}, error:function (xhr, textStatus, thrownError){} }); and the new render: return render(request, '/water/waterform.html', {'wos': OESR}) How can I do that? -
Having locally scoped CSS in Vue when creating a component using Vue.extend({})
var myComponent= Vue.extend({ template: ` <div class="container"> </div> ` , props: [], components: {} , data() { return { } }, methods: { } }) I have a component above that is created using the Vue.extend. It takes in data, methods and other things that are all locally scoped. I'm wondering if I can have CSS that is locally scoped to this component within the object passed to vue.extend() I'm not using nodejs (using django) so I don't think I can use the recommended syntax within .vue elements (If I'm mistaken and I can use .vue files and the below syntax please let me know): <style scoped> /* local styles */ </style> -
how to check given datetime has offset in python
i have this three datetime from the user input with offset like below 2019-04-02 11:11:31.552611+00 and 2019-06-20 12:48:56.862291+05:30 and 2019-06-20 12:48:56.862291+00:00 which is saved in my Django local database but now i have to check this datetime has offset other than +00:00 so how to check? -
how to exclude specific api from applying all the authorization of python middleware
Let suppose I Have a webhook that will request to my python server and I want to allow that request to process without applying any middleware authorization of python. I don't want to make more costly process of request/response by processing all the requests in my custom middleware. -
How to pull data from a ETL system from a DJANGO app
Without further details so far, I was asked to build a django app that will pull data from a ETL system and display it to the user. (At this point I do not know if the users will be able to edit) and whether the ETL system has some kind of endpoints. (I am planning to use PostgreSQL as database) What would the best way to approach it from the limited amount of details above? -
Is it able to create such self signed ssl certificate to avoid check challange
Background I have a third-party framework that does some network requests to the URL which I provide to it. The format of requests is: https://10.0.2.2:8000/api/.... Since the schema is https I constantly receive the error message from the third party lib: The certificate for this server is invalid. You might be connecting to a server that is pretending to be “10.0.2.2” which could put your confidential information at risk. The server is a Django application started with python3 manage.py runserver_plus 10.0.2.2:8000 --cert-file _my_cert.crt I've tried a lot of ways to generate and install the self-signed certificate to the simulator and run the server, however, none of them have helped to avoid the error in the third party lib. The Question So I'm wondering if this makes sense at all. Is it possible to generate and install self-signed certificate into iOS simulator which will avoid not require a to solve the challenging as is described here: https://developer.apple.com/documentation/foundation/url_loading_system/handling_an_authentication_challenge/performing_manual_server_trust_authentication?language=objc Please, provide proof for any kind of answer whether yes or no. -
Advice on token generation for links
Quite similar to the process of requesting a new password with the django auth views, when a user registers on my site they fill in a form which creates a user with the is_active flag set to False. Then an email is sent to the site administrator to approve the registration. The email contains two buttons: 'accept' and 'reject'. When the administrator presses the 'accept' button it flips the is_active flag to True and sends an email to the user to notify them that their request has been approved. At the moment, if the administrator presses 'reject' all that happens is an email is sent to the user. My issue is that when the accept button has been pressed, the token that is generated by 'token':token_generator.make_token(user) is still valid after the link has been used. This is because the token is generated by 1. user pk, 2. user password hash, 3. last login date and 4. the current datetime. Therefore the difference between the before state of the user (is_active=False) and the after state of the user (is_active=True) are indistinguishable to the token generator. I want to avoid the possibility of the site admin pressing the accept button more than … -
Create Django user by URL for django admin site
Is it possible to create a user through a url and not through Django admin site? https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication -
Django Polls Tutorial: How to resolve Just In Time Debug Errors while navigating to admin page?
While following the tutorial for django (polls), I got this error. How can I resolve it? The error happens when I go to admin url. Django==3.0 Python (venv) C:\workspace\django\mysite>python Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. Error while navigating to admin page -
Django, in HTML template i used jinja2 in id = snackbar but when i click on the button the pop is just showing but no {{MSG}} in it
here is the url, views for contact.html where i am unable to get the {{MSG}} in popup . urls: url(r'^contact', TemplateView.as_view(template_name= 'contact.html')), url(r'^insertenquiry', insertenquiry, name='insertenquiry'), views: def insertenquiry(request): if request.method == 'POST': fn = request.POST['firstname'] ln = request.POST['lastname'] emailid = request.POST['email'] say = request.POST['saysomething'] obj = Enquiry(fname=fn, lname=ln, email=emailid, saysomething=say) obj.save() msg = "sent success" return render(request,"contact.html",{'MSG':msg}) Template(HTML) <!-- Use a button to open the snackbar --> <button onclick="myFunction()">SEND ENQUIRY</button> <!-- The actual snackbar --> <div id="snackbar">{{MSG}}</div> -
SALEOR: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty
I already crossed the whole internet searching for a soluction, I already setted the secret key with setx, direct on settings.py, direct on system variable. I already readed the docs, already seen the official mirumee discussions, I've seen and tried all the soluctions of similar posts, I was using python 3.8, I already downgrade to python 3.7. downgrade my postgres, from 12 to 9.4, my node to 10. I tried to remove any imports as I had readed in others posts. Already used a code in python to generate a 50 characters secret key. I HAD THE COURAGE TO LEFT MY LINUX MINT TO INSTALL A FUCKING WINDOWS 10. I tried to set the python conf, out and inside the env. I really tried to do it for myself and fail. Now I ask for help. If not , I will give up this. I cannot set the secret key: All I have: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. follow my settings: import os.path import warnings import dj_database_url import dj_email_url import sentry_sdk from django.contrib.messages import constants as messages from django.core.exceptions import ImproperlyConfigured from django_prices.utils.formatting import get_currency_fraction from sentry_sdk.integrations.django import DjangoIntegration … -
How to open data in pop up using bootstrap model in datatables
Here, I am trying to populate data from db in a popup box. I am using datatables in Django template and rendering data. Now I want a view button on my page and the button should open a popup box corresponding to the row. I have gone through datatable documentation - https://datatables.net/extensions/responsive/examples/display-types/bootstrap4-modal.html where we can populate the data but here problem is, how can we get data from server or how can we process data from server for popup box. Any solution? Could you please suggest solutions? <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-body"> <table id="service_center" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>Vehical</th> <th>Service Date</th> <th>KMS</th> <th>View</th> </tr> </thead> </table> </div> </div> </div> </div> </section> {% endblock %} {% block scripts %} <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.bootstrap4.min.js"></script> <script src="https://cdn.datatables.net/select/1.3.0/js/dataTables.select.min.js"></script> <script src="/static/plugins/datatables/dataTables.editor.js"></script> <script src="/static/plugins/datatables/editor.bootstrap4.min.js"></script> <script> $(document).ready(function () { $.extend(true, $.fn.dataTable.defaults, { columnDefs: [ { targets: '_all', defaultContent: '' } ] }); var table = $('#service_center').DataTable({ "pageLength": 100, "serverSide": true, "bSearchable":true, "dom": 'blfrtip', "ajax": "/dt/veh_service/?format=datatables", "columns": [ { "data": "m.veh_number" }, { "data": "service_date" }, { "data": "kms" },{ "data": "id", "bSortable": false, "mRender": function (data, type, full) { return '<a class="btn btn-sm btn-primary" href="/veh_service/' + … -
The command migration did not execute
I have a challenge here. I am currently building an application,and I tried to add my app to the settings,in this way : *INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]* In the model,here is the code : *from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)* Initially I used this command in the terminal *cd myproject manage.py migratrate* Here is the output: Apply all migrations: admin,auth,contenttypes,sessions Running migrations:No migrations to apply. Having defined my database in the model,I used the following command.Please,how do I fix this? Note that I am a beginner in Python and Django -
Getting URL Kwargs into Django ListView Object Attributes
I've got a class-based-view and I'm trying to implement breadcrumbs into it. I'm using django-bootstrap-breadcrumbs & django-view-breadcrumbs, but because of our unique URL structure we have an ID in the URL of almost all of the urls. I've setup the breadcrumbs appropriately, but need to get the person_id kwarg into the 'crumbs' attribute on the ListView URLs look like this: path( "<person_id>/trees/", views.TreeListView.as_view(), name="tree_list", ), path( "<person_id>/trees/<pk>/", views.TreeDetailView.as_view(), name="tree_view", ), path( "<person_id>/trees/<tree_id>/planes/", views.PlaneListView.as_view(), name="plane_list", ), path( "<person_id>/trees/<tree_id>/cord/<pk>/", views.CordDetailView.as_view(), name="cord_view", ), I've setup my view according to the documentation: class TreeListView( LoginRequiredMixin, UserPassesTestMixin, ListBreadcrumbMixin, ListView ): # pylint: disable=too-many-ancestors login_url = "/login/" model = Tree template_name = "tree_list" crumbs = [('My Test Breadcrumb', reverse('tree_list', args=[self.kwargs["person_id"]]))] As you can see in the last line - the crumbs is what is supposed to create the breadcrumbs that display on the page. The issue is that I get an error (which seem pretty obvious) that there is no 'self' item with that object. My question is - how do I get that person_id from the URL so I can pass it as the argument to the URL? -
Redirecting a user to google in django
after the user has registered, they will be redirected to a html page containing ((We have sent a conformation email to your email address please <a href="{% url '??' %}">confirm</a> it to activate your account.)). what should I replace ((?)) with ? -
Nginx, Django, Docker-Compose CORS Policy Problem
I'm trying to build my first docker-compose for a project at my university. We have an angualt frontend running on a naginx server. A manager to connect front- and backend and some backend stuff. The connection from the manager to the backend is no problem. The manager runs on a django server and the backend on flask. The problem is the connection between the nginx server and the manager on django. Every time i try to do an REST request the error show up: Access to XMLHttpRequest at 'manager:8000/training-data' from origin 'http://localhost:8080' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https# I set the header in the nginx.conf, and allowed cors in the django server as you can see in the code snippet below: nginx.conf: user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; server { listen 80; server_name localhost; location / { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, … -
How to compare different json show like git diff
I want check different 2 json result after i changed my code. This change maybe true or not, and i want show it like compare git diff. My question is: How to compare text, and show different of this like git diff? Or anyway more friendly for user? I use python3 and django rest framework Thank you very much