Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access session variables from render funcition of the plugins in Django Cms
I have a view called create_pdf(request), which takes a json from the body of the httprequest, and I have some plugins defined in a page (/input_url). After rendering the page, I save it to pdf in here: pdfkit.from_url(input_url, output) Being the output the folder I want the pdf in. I want to fill the plugins with the info contained in the json, but the only way to access it is by saving the json in a folder and open the file in each of the plugins. Is there anyway to save globally the instance of the json by session and access it from the render function of the plugins? I know I can save the info in a session variable from the view, but I don't know the way to access to it from the render function of the plugin. Thanks for helping. -
Django, how to display comments on a blog post in post template only for login user
Django, how to display comments on a blog post in post template only for login user , i made these below mentioned models & views. Now my comments are successfully storing in database with name of user but the problem is its not shown on post . so far only count is displaying to see how many comments posted so far! def get_comments(self): return self.comments.all().order_by('-timestamp') class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) commentfield = models.TextField() post = models.ForeignKey(Blogpost, related_name='comments', on_delete=models.CASCADE) def __str__(self): return self.user.username **My Forms** from django import forms from .models import Blogpost, Comment class CommentForm(forms.ModelForm): commentfield = forms.CharField(widget=forms.Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Type your comment', 'id': 'usercomment', 'rows': '4' })) class Meta: model = Comment fields = ("commentfield",) **My Blog Post Views** def blogpost(request, year, month, day, post): category_count= get_category_count() latest = Blogpost.objects.order_by('-publish')[0:4] post = get_object_or_404(Blogpost, slug= post) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = post form.save() return redirect('.') context = {'post':post, 'latest': latest, 'category_count': category_count, 'form': form, } return render(request, 'blog/blogpost.html', context) **My Templates** <div class="post-comments"> <header> <h3 class="h6">Post Comments<span class="no-of-comments"> ({{ post.comments.count }})</span></h3> </header> {% for comment in post.get_comments %} <div class="comment"> <div class="comment-header d-flex justify-content-between"> … -
How do I use a different EMAIL_BACKEND for certain emails in django
I'm trying to send emails from 2 different backends. Most emails are being sent via AWS SES but I want a few from Outlook365 (because these will actually be stored/reviewed). So within settings.py I have EMAIL_BACKEND = 'django_ses.SESBackend' to use the AWS SES backend. I'm then trying to create a new connection when I want to send from Outlook as follows: with get_connection( backend = 'django.core.mail.backends.smtp.EmailBackend', host = 'smtp.outlook.office365.com', port = 587, user = 'myuser@mydomain.co.uk', password = 'password!', use_tls = True, ) as connection: email = EmailMultiAlternatives( subject=context['subject'], body=text_message, from_email='myuser@mydomain.co.uk', to=[user.email], connection=connection ) email.attach_alternative(html_message, "text/html") email.send() This generates the error: smtplib.SMTPSenderRefused: (530, b'5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [LO2P265CA0076.GBRP265.PROD.OUTLOOK.COM]', 'myuser@mydomain.co.uk') However, if I set these within settings.py (instead of using AWS) it will work (but means all other emails also go from here). Why isn't my get_connection working and how do I fix it? -
How can I refer to other urls' captured values in Django?
So, I am writing code with Python and Django (and other web dev requirements). from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path('wiki/<str:name>/', views.info, name="info"), path("create", views.create, name="create"), path("results", views.search, name="search"), path("wiki/<str:name>/edit", views.edit, name="edit") ] The problem I am facing is that in path("wiki/<str:name>/edit", views.edit, name="edit"), I get an error: NoReverseMatch at /wiki/Django/> Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['wiki/(?P[^/]+)/edit$']> And I want to refer to the url in path('wiki/<str:name>/', views.info, name="info") Please help me fix the error -
why compressing this less file doesn't work?
Story is that I got to work in old Django project. I did some changes to models, and only models. But now I get error when compressing less file using django-compressor. What is odd: I can compress files locally, but server pipeline fails. The command that fails is: python manage.py compress --force error I get is: CommandError: An error occurred during rendering /code/app/portal/templates/portal/presentation_company.html: ParseError: Unrecognized input. Possibly missing '(' in mixin call. in /var/www/mojksiegowy24.pl/static/less/presentation.less on line 239, column 32: 238 background: #00AFBE; 239 .transition; 240 } whole part of less file: .print-button { text-align: right; margin-bottom: 20px; margin-top: 20px; a { .fa { padding-right: 10px; } text-decoration: none; font-size: 12px; line-height: 30px; display: inline-block; color: #fff; background: #C2C2C2; border-radius: 2px; padding-left: 10px; padding-right: 20px; &:hover { background: #00AFBE; .transition; } } } I checked linux / windows end line chars and it is ok. Please help. I'm stuck, .less noob with no idea what to do. My biggest problem is that reverting changes done to models doesn't solve problem! And I'm not sure if that's important: Server uses GitLab Pipelines to deploy Dockerized Django app. -
Django tests logs Bad or Unauthorized requests
I recently upgraded from django 1.11 to django 3.0. Currently, when i launch python manage.py test, django logs any bad or unauthorized requests from my tests, the fact is : it did not log such while on 1.11 Exemple : .2021-01-06 18:04:20,374 Unauthorized: /api/image/create ..2021-01-06 18:04:20,426 Bad Request: /api/image/transfer/create .2021-01-06 18:04:20,436 Bad Request: /api/image/transfer/create ... ---------------------------------------------------------------------- Ran 3 tests in 0.008s OK Preserving test database for alias 'default'... Did i miss something while reading django changelog ? I'd like some light because i do not want to make a distribution without knowing if it's only warning or real error. -
Python crash course 19-5 object has no attribute 'owner'
learning python through the python crash course book. Having this issue where somehow it says that there is no attribute 'owner' for each blogpost when there seems to be one? Would appreciate any guidance, cheers all! Added to the very bottom of settings.py #MY SETTINGS LOGIN_URL = 'users:login' models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=50) text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title This is the code when i run django shell to see the owner associated with each blogpost from blogs.models import BlogPost for a in BlogPost.objects.all(): print(a, a.owner) My first post! aaaaaa ll_admin Second blog post ll_admin No season 2 in product ll_admin ll_admin is this the tutle ll_admin ssd ll_admin ssaaa ll_admin views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import BlogPost from .forms import BlogPostForm # Create your views here. def index(request): """The home page for blogs""" return render(request, 'blogs/index.html') @login_required def posts(request): """Show all blogposts""" posts = BlogPost.objects.filter(owner=request.owner).order_by('date_added') context = {'posts': posts} return render(request, 'blogs/posts.html', context) @login_required def new_post(request): """Add a new blogpost""" if request.method != 'POST': #No data submitted; create a blank … -
can't install. pip install -r requirements.txt
ERROR: Command errored out with exit status 1: 'e:\django-pos-master\venv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Use rs\asada\AppData\Local\Temp\pip-install-82_9dan8\pillow_f761b25e426a43f6891c453cc664459a\setup.py'"'"'; file='"'"'C:\Users\asada\AppData\Local\Te mp\pip-install-82_9dan8\pillow_f761b25e426a43f6891c453cc664459a\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"' r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\asada\AppData\Local\Temp\pip-record-lt_0q0si\install- record.txt' --single-version-externally-managed --compile --install-headers 'e:\django-pos-master\venv\include\site\python3.9\Pillow' Check the logs for full com mand output. -
Update entry with file instance DRF, Vue.js 3
I have a table that has a models.FileField in it. I'm able to create the file from a Vue.js website POST request, but when I want to update the instance I have to upload the file again. The problem is not from Vue.js, because I can't update even using the DRF pre-built page. How can I update the instance without having to upload the document again? -
is there any way to use variables like {{ ct{{ forloop.counter }} }} in HTML File in django?
views.py: for i in range(1, 4): params[f"ct{i}"] = '<h1>ct'+i+ '</h1>' index.html: <h1>{{ct{{forloop.counter}} }}</h1> Is there any way to use <h1>{{ct{{forloop.counter}} }}</h1> in My HTML File? -
How to save django manytomany field without through table
I face a vicious cycle that I cannot break out of; Lets say I have a following model: class AgregatorProductCoupon(models.Model): AgregatorProductId = models.ManyToManyField(Product, related_name="coupons", db_column='AgregatorProductId', verbose_name=_("Agregator Product Id")) class Meta: managed = True db_table = 'AgregatorProductCoupon' when I try to save an instance, I get an integrity error stating "<AgregatorProductCoupon: AgregatorProductCoupon object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. but when I try to save without the m2m rel, I obviously get an error for a required field missing. Cannot insert the value NULL into column 'AgregatorProductId', table 'test_dbo.dbo.AgregatorProductCoupon'; column does not allow nulls. INSERT fails. I cannot redesign the tables as they are bound to other places too. How to go about it? Any help would be much appreciated. -
PostgreSQL and Django Query for report not working
I am using Python Django and PostgreSQL to build our report app. I am using below mention query to find some details. the query mention below is running fine in PostgreSQL command line and giving result in 2 sc for 2 million cards but when i i am try the same in Django application it is taking too much of time and the web page is expired while running this query. can anyone help how to make query faster in Django? Or help me in correcting this query to be used in Django rows = M_Assign.objects.raw(''' select C.id,M."merchant_name",C."MERCHANT_ID",S."store_id" Owning_Store_ID ,S."store_name" Owning_Store_Name,F."franchisee_name" Owning_Group,C."ACCOUNT_NUMBER",C."STORE_ID",C."GIFT_LIST_REF" FROM vdaccount_card_assign C INNER JOIN vd_merchant_master M ON C."MERCHANT_ID"=M."merchant_id" AND C."MERCHANT_ID"='003561002966107' INNER JOIN vd_store_master S ON S."store_id"=C."GIFT_LIST_REF" OR C."GIFT_LIST_REF"='' INNER JOIN vd_franchisee F ON S."franchisee_id"=F."franchisee_id" ''') Regards Sachin -
xhtml2pdf not converting css properly django
hey guys so i have been using this library for a while now and i just encounter this error that by using this library its not converting my css of my html properly to pdf, i used this library to generate voucher internet for my client, does anybody now how can i fix this? thanks, here's my code voucher.html <!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> * { box-sizing: border-box; } .row { display: flex; margin-left:-5px; margin-right:-5px; } .column { flex: 50%; padding: 5px; } table { border-collapse: collapse; border-spacing: 0; width: 100%; border: 1px solid #ddd; } th, td { text-align: left; padding: 16px; text-align: center; } tr:nth-child(even) { background-color: #f2f2f2; } @page { size: letter landscape; margin: 2cm; } </style> </head> <body> <div class="row"> {% for data in akun %} <div class="column"> <table> <tr> <th colspan="2">Voucher Internet 1 Hari</th> </tr> <tr> <td>Username</td> <td>{{akun.username}}</td> </tr> <tr> <td>Password</td> <td>{{akun.password}}</td> </tr> <tr> <td>Harga</td> <td>{{akun.harga}}</td> </tr> <tr> <td colspan="2">Mikadmin.net</td> </tr> </table> </div> {% endfor %} </div> </body> </html> view.py def voucher_profile(request): mikrotik_session = request.session.get("mikadmin") template = get_template('voucher.html') host = mikrotik_session.get("host") username = mikrotik_session.get("username") password = mikrotik_session.get("password") con = routeros_api.RouterOsApiPool(host=host,username=username,password=password,plaintext_login=True) api = con.get_api() content = api.get_resource('ip/hotspot/user/profile') content_user = api.get_resource('ip/hotspot/user') username_paket_profile = request.POST['name-profile'] valid … -
Which approach would be better to build a application?
First Approach: Building a application in a traditional way that is when we want data from database connect to database and fetch it. Second Approach: Another way is to build a web service/API and hit that endpoint and it returns data. I want to build both web and mobile application.So, I thought to build a web service/API and utilize it in web and mobile application. First of all,What I am telling is it correct? If Yes, Whether this approach is correct? Or I should build using first approach? Is there any advantage and disadvantages of both? -
Django PWA session is not maintained
I have created an application using Django and PWA and everything works good except for the session. When I enter into the application after a couple of hours It asks me to login in again. However, if I use the web instead of the app my session is maintained forever. How can I solve It and maintain the pwa user session maintained? Thank you! -
Django tests: what is the difference between "with self.assertRaises()..." and simply "self.assertRaises"
could you please help me to understand what is the difference between these 2 syntaxes in Django tests (Python 3.7): def test_updateItem_deletion(self): # some logic in here with self.assertRaises(OrderItem.DoesNotExist): OrderItem.objects.get(id=self.product_1.id) And: # all the same, but self.assertRaises not wrapped in 'with' self.assertRaises(OrderItem.DoesNotExist, OrderItem.objects.get(id=self.product_1.id)) The first one worked and test passed. But the second one raised: models.OrderItem.DoesNotExist: OrderItem matching query does not exist. Does it somehow replicate the behaviour of try/catch block? Thank you a lot! -
MySQL fix Incorrect String Value with Django DB Settings
I'm having errors writing to MySQL from Django. Traceback below: File "/home/neil/web_app/venv/lib/python3.8/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/home/neil/web_app/venv/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xE2\\x9D\\x96 \\x0AT...' for column 'body' at row 1") I have attempted to set the encoding of the DB. Settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'citator_migration', 'USER': ..., 'PASSWORD': ..., 'HOST': ..., 'OPTIONS': { 'init_command': "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; SET sql_mode='STRICT_TRANS_TABLES', character_set_connection='utf8mb4'" }, } } Related: Setting Django/MySQL site to use UTF-8 Incorrect string value: '\xE2\x80\xAF(fo...' for column 'description' at row 1 Error: INSERT INTO my_table_name Incorrect string value: '\xE2\x80\xAF(fo...' for column 'description' at row 1 Error: INSERT INTO my_table_name What am I doing wrong? Is it possible to remedy with Django Settings or do I need to query MySQL directly to change the encoding? Should I be changing to utf8mb4 or latin1? The source of the data is a Postgres DB behind a Drupal API. It is fetched over http and then written to the DB with Django models -
Stripe Payment with Django
I've been unable to generate token in the stripe. Just getting Invalid parameter. Here is my views.py: class PaymentView(View): def get(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) if order.billing_address: context = { 'order': order, 'DISPLAY_COUPON_FORM': False, 'STRIPE_PUBLIC_KEY': settings.STRIPE_PUBLIC_KEY } return render(self.request, 'payment.html', context) else: messages.warning(self.request, "You've not added billing address.") return redirect('e_commerce:checkout') def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total()*100) # cents try: charge = stripe.Charge.create( amount=amount, currency="usd", source=token ) # order.ordered = True # create the payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() # assign the payment to the order #order_items = order.items.all() #order_items.update(ordered=True) #for item in order_items: #item.save() order.ordered = True order.payment = payment # TODO assign ref code #order.ref_code = create_ref_code() order.save() # print("your order placed!") messages.success(self.request, "your order was successful.") return redirect("/e_commerce") except stripe.error.CardError as e: # Since it's a decline, stripe.error.CardError will be caught body = e.json_body err = body.get('error', {}) messages.warning(self.request, f"{err.get('messages')}") return redirect("/e_commerce") except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly messages.warning(self.request, "Rate limit error") return redirect("/e_commerce") except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to Stripe's API messages.warning(self.request, "Invalid parameters ,Please try … -
django.core.exceptions.ImproperlyConfigured error: Requested setting INSTALLED_APPS, but settings are not configured
Background: I am working on a microservices project that consists of two apps: Django app(admin app) and Flask app(main app). Each of these runs on a Docker container. The error occurred as I was trying to implement a functionality that whenever a product is liked in the main app, the information is passed on to the admin app via RabbitMQ, so that the likes could also get updated in its database. I keep getting this error in the admin app, because of which the likes are not updated in the database of the admin app. django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Relevant files: Here is the consumer.py file of the admin app. from products.models import Product import pika import json import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "admin.settings") django.setup() params = pika.URLParameters( 'amqps://mynfehiw:zXmApSaqRu8AJo3oTmJTxGzzEo8KTs6F@lionfish.rmq.cloudamqp.com/mynfehiw') connection = pika.BlockingConnection(params) channel = connection.channel() channel.queue_declare(queue='admin') def callback(ch, method, properties, body): print('Received in admin') id = json.loads(body) print(id) product = Product.objects.get(id=id) product.likes = product.likes + 1 product.save() print('Product likes increased!') channel.basic_consume( queue='admin', on_message_callback=callback, auto_ack=True) print('Started Consuming') channel.start_consuming() channel.close() Here is the manage.py file in the admin app: #!/usr/bin/env python """Django's command-line … -
Retrieve values from the JOIN of two models without foreign key (Django)
I want to retrieve the values of two columns related to two different models (without foreign keys). In SQL, I would write it as this: SELECT employees.name, companies.name FROM employees JOIN companies ON companies.location=employees.location; Suppose the two models are called Employee and Company. They have no foreign keys in common, and I am not allowed to change the models. How can I have the same in Django? Should I necessarily write a raw SQL query? -
How can i run my python model automatically after specific time interval?
Hey everyone hope you all are fine .... I want to ask something from you, recently I build my model (Random Forest) in python machine learning and I got my predictions and make a web app in django that shows predicted values in front end. Now I want to deploy my web app and wants that after specific time interval my data become downloaded from api automatically, similar for data training file and data prediction file. Each task should run automatically after specific time interval because now each time I run program separately for data downloading, data training and doing prediction on data I want all these task should run automatically after specific time interval how I will achieve this task.... ? -
Can I use the input from search_fields in list_filter in Django Admin
I have an application that has Artist and Album (one Artist can have multiple Albums) models. class Artist(models.Model): name = models.CharField(max_length=200) class Album(models.Model): name = models.CharField(max_length=200) ... num_stars = models.IntegerField() artist = models.ForeignKey(Artist, on_delete=models.CASCADE) I have a Album_Admin(admin.ModelAdmin) in which I want to search by Artist. Also I want to filter by num_stars, but I want the filter to use the input from the search field, search_term, to create the filter choices. I am using the admin.SimpleListFilter. I tried to store the value from the search field (search_term) in a global variable and than use the variable in the filter, but Changelist view first makes filtering, then it gives filtered queryset as parameter to your get_search_results function. Any suggestion how to achieve this ? Example: The image above is an example image in which, in the search bar is entered the Artist_ID, And in the filter section is the wanted solution (only two options to filter by, the ones that has the Artist_ID -
How to remove items from queryset based on condition and then return as json response in django
I am doing join operation using select_related() and filtering records using below code class ActiveclientViewSet(viewsets.ModelViewSet): queryset = Ruledefinitions.objects.select_related('pmdclinicalruleid').filter(pmdclinicalruleid__effectivedate__lt = timezone.now(),pmdclinicalruleid__retireddate__gt = timezone.now()) serializer_class = RuledefinitionsSerializer In the above code, is it possible to check whether the first item from queryset has rulename field value as empty and if it is empty i need to return remaining queryset items in json response if not empty return all items as json response. -
JavaScript module not working in Edge (version 44, make 18.17763)
I am having trouble with my JavaScript module in the Edge browser. In Chrome everything works perfectly. Since my users have both Edge and Chrome available to them, the application has to work in both. In my html head-section I have: <script type="module" src="{% static "js/app.js" %}"></script> The {% static "js/app.js" %} is a django template-tag. The app.js begins like this: "use strict"; import { editor } from "./editor.js"; import { homepage } from "./home.js"; import { contactPage } from "./contact.js"; jQuery( window ).on( "load", () => { // code... } In the inspector network-tab I can see that app.js, editor.js, home.js and contact.js are loaded with status 200 (OK). The console gives me: HTML1406: Invalid start of a tag '<?' HTML1500: The tag can not be a self-closing tag Those warnings are generated in an svg-file that starts with <?xml ..... and when I remove that and close the tags in the svg with a proper closing-tag the problem is NOT solved. As I said: in chrome everything works fine. I don't know if there is any other code that could be relevant. Maybe anyone else came across this problem. I am clueless. -
Django: How to switch relations between two objects
I am having issues updating a website I run. Essentially, the users on the website cannot be used anymore, so people have to create new accounts. However, users have ManyToMany relations with other tables in the database, and I want to be able to move the relations from the old users to the new ones. Is there any good way to do this in Django or directly in the database? I am using PostgreSQL.