Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
django-rest-framework PUT and DELETE generic view
So I have this model over here. class Member(BaseModel): objects = models.Manager() user = models.ForeignKey('api_backend.User', db_index=True, on_delete=models.CASCADE) roles = models.ManyToManyField('api_backend.Role') cluster = models.ForeignKey('api_backend.Cluster', on_delete=models.CASCADE) Serializer for the same class PartialMemberSerializer(serializers.ModelSerializer): class Meta: model = Member exclude = ['cluster', 'roles'] @classmethod def get_user(cls, obj): return PartialUserSerializer(obj.user).data user = serializers.SerializerMethodField() I want to have a generic view where: the member object of the authenticated user who is present in a particular cluster can be either deleted or put. I have my base destroy view here class MemberPutDeleteView(generics.DestroyAPIView): queryset = api_models.Member.objects.all() serializer_class = api_serializers.PartialMemberSerializer permission_classes = [permissions.IsAuthenticated] def get_object(self): return api_models.Member.objects.get( user=self.request.user, cluster__id=self.kwargs['pk']) def destroy(self, request, *args, **kwargs): member = self.get_object() # if the member is the owner, don't remove member # the cluster must be deleted by the cluster-deletion endpoint. if member.cluster.owner == member.user: raise exceptions.ValidationError("you cannot leave this cluster as you own it.") return super(MemberPutDeleteView, self).destroy(request, *args, **kwargs) How can I also add a put method to this view? What I want to do here is: get the cluster id from the pk url parameter filter the member object which has the cluster id and also the user object as the requested user finally delete the object on delete request if … -
save result of get_absolute_url in django model Field
I want to save result of post.get_absolute_url() in my django model as Field. def get_absolute_url(self): return reverse('post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) For example absolute_url = models.CharField(...'result of post.get_absolute_url()'...). Is there any way to do this? Thanks. -
How to use get_or_create? Error: get() returned more than one Patient -- it returned 7
I have a function for fetch API where I create a Django model object for each object in the JSON and store the data in django model. The problem here is everytime I call the route it creates the records again and again, because I use create method, but I made an research that the best way to stop that is to use get_or_create. So, I tried this method but it looks like I missed something, because I got an error: feedback.models.Patient.MultipleObjectsReturned: get() returned more than one Patient -- it returned 7! this is my code before I have 2 for loops so I can loop through every patient and then through every role and save patient with a role: # FetchApi for Patients def fetchapi_patients(request): url = 'http://localhost:8000/core/users/roles/patient' headers={"Authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Imhha2FuQGdvLmNvbSIsImV4cCI6MTYxMDAxMTM0MSwib3JpZ19pYXQiOjE2MTAwMDc3NDF9.k2204d094DNUbEfFt8M_7chukOSjWWwfesPOH5jIiP8"} response = requests.get(url, headers=headers) #Read the JSON patients = response.json() #Create a Django model object for each object in the JSON and store the data in django model (in database) for patient in patients: Patient.objects.create(first_name=patient['first_name'], last_name=patient['last_name'], email=patient['email'], coreapi_id=patient['ID']) for role in patient['Roles']: Role.objects.create(role_name=role['name']) return JsonResponse({'patients': patients}) this is when I tried to use get_or_create method: for patient in patients: patientDatabase, created = Patient.objects.get_or_create(first_name=patient['first_name'], last_name=patient['last_name'], email=patient['email'], coreapi_id=patient['ID']) for role in … -
How to save Image using CharField max_length=1024 i.e longext in django
I am working on a project where we want the profile pic of user to be in a CharField i.e longtext. Now, in ModelForm for updating the user's profile I want to get profile pic and want to resize and compress it and save it in database with unique name like using timestamp. The problem that I have is that I can get image name using cleaned_data from form but cannot process it for resize or compression and it gives me the error of no file or directory is found -
Filtering object with multiple related models with M2M and ForeignKey
I want to filter university programs in list view. I have near to 200000 objects. When I do the query in ProgramSearchView I get double the number of objects because of "subject__parent__title". I am very bad at queries. How can I write the most efficient query here and which query do you think suites the most? Note: I've shortened fields in some models in order to decrease complexity here. My Model: class Program(models.Model): slug = models.SlugField(null=False, blank=False, unique=True, max_length=255) program_id = models.IntegerField(_("ID")) title = models.CharField(max_length=199) date_added = models.CharField(max_length=99, blank=True, null=True) requirements = JSONField(blank=True, null=True) details = JSONField(blank=True, null=True) academic_award = models.ManyToManyField("program.AcademicAward", verbose_name=_("Academic award")) subject = models.ManyToManyField("program.Subject", verbose_name=_("Subject"), blank=True) school = models.ManyToManyField("program.School", related_name='school', blank=True) class AcademicAward(models.Model): title = models.CharField(_("title"), max_length=250) # for ex. M.Sc., B.Sc. description = models.CharField(_("about"), max_length=450, null=True, blank=True) category = models.CharField(_("Category"), max_length=150, blank=True, null=True) # for ex. Degree, Certificate or Diploma class School(models.Model): title = models.CharField(_("Title"), max_length=950) description = models.CharField(_("About"), max_length=950, blank=True, null=True) campus = models.ForeignKey("program.Campus", verbose_name=_("Campus"), on_delete=models.CASCADE, max_length=255) class Campus(models.Model): title = models.CharField(_("title"), max_length=150) description = models.CharField(_("About"), max_length=950, null=True, blank=True) city = models.CharField(_("city"), max_length=150, null=True, blank=True) country = models.CharField(_("country"), max_length=150, null=True, blank=True) university = models.ForeignKey("program.University", verbose_name=_("university"), on_delete=models.CASCADE, max_length=255) class University(models.Model): title = models.CharField(_("Title"), max_length=250, null=True, blank=True) description … -
python api image uploading issue with request data
My api to save request data with image is like: class AddImageApiView(APIView): @swagger_auto_schema( operation_id="Add Image", operation_summary="Add Image", operation_decription="Add Image", ) @validator() def post(self, request, userdetail=None, version=None, format=None): data = request.data tasks = [] if data.getlist('files'): try: for file in data.getlist('files'): task_res = TaskResources(file=file, file_type='1', task=121) task_res.save() except Exception as e: print(e) and i am hitting the api like : url = settings.BASE_URL+'api/users/childs/addtask/' headers = {'token':settings.HTTP_TOKEN,'source':'WEB'} files = [] files.append(list(request.FILES.getlist('files'))) params = { 'files' : files } addtasksCall= requests.post(url, data=params,headers=headers) When i am hiiting the api image name only saving in my db . image is not getting uploaded on folder also not full path save in db . why it is saving only image name even i am sending the image object can anyone please help me related this ?? -
How to apply exclude for first resultant item of select_related() query in django
I am doing a left join using select_related() and then excluding few things based on condition using below code class ActiveclientViewSet(viewsets.ModelViewSet): queryset = Ruledefinitions.objects.select_related('pmdclinicalruleid').filter(pmdclinicalruleid__effectivedate__lt = timezone.now(),pmdclinicalruleid__retireddate__gt = timezone.now()).exclude(Q(rulename__isnull=True) | Q(rulename__exact='') | Q(rulename__startswith='OptumFormulary')) The above code applies exclude for entire select_related results. Instead i need to apply exclude only for first result item from select_related(). Any way to implement this? -
Making run a django web app inside docker along side a web app outside docker
As the title say, i'm trying to deploy a toy web app (Django) powered by Docker, with 3 containers, one for the app, one for postgresql and the last one for nginx. I want to deploy it on a virtual instance where i've already a running web app (Django) outside of Docker, with Nginx install globally on the machine. I've managed to making run both app. The first one, outside of docker, is accessible by a subdomain name (firstapp.mydomain.com) and as a Let's Encrypt Certificate. The second one is accessible by ip with 1337 port. I now want to access my second app (the docker one), through a second subdomain, that i've created (myapp2.mydomain.com), but i think there is some conflict with Nginx installed globally, becouse when i want to reach secondapp.mydomain.com, i'm always redirected to firstapp.mydomain.com Here is my nginx configuration : The first app (nginx install globally on the machin) file configuration upstream firstapp_server { server 127.0.0.1:8000; } server { listen 80; server_name firstapp.mydomain.com; return 301 https://firstapp.mydomain.$request_uri; } server { listen 443 ssl; server_name firstapp.mydomain.com; root /path/to/my/app; ssl_certificate /etc/letsencrypt/live/firstapp.mydomain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/firstapp.mydomain.com/privkey.pem; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) … -
I have a single defined primary key in my model, but Django throws multiple primary keys error
This is my code class BsValuesTTM(models.Model): corpname = models.CharField(max_length=100) co_name = models.CharField(max_length=100, primary_key=True) ACR = models.FloatField() Inventory = models.FloatField(null=True) CashCE = models.FloatField(null=True) CurrentAssets = models.FloatField() GrossPPE = models.FloatField() AccDepn = models.FloatField(null=True) NetPPE = models.FloatField() Intangibles = models.FloatField(null=True) NCA = models.FloatField() Assets = models.FloatField() i only have a single primary key in my model, Django throws this error django.db.utils.ProgrammingError: multiple primary keys for table "Main_bsvaluesttm" are not allowed I have changed the field for primary key, earlier it was corpname, and that field used to be a foreign key. I am using Postgresql12 with Django. -
Django Caching View Per User
I'd like to cache a view in my Django app. However, the result of the view varies for every user. I've tried using vary_on_cookie, but I can't get it to work: @cache_page(60 * 15) @vary_on_cookie def my_view(request): ... Is there a better way to do this? Thanks in advance. -
Encoding error occurs when importing csv file from Heroku
I made a project with a django. There was no problem when importing csv files in local. But when I put it on Heroku and import data from Heroku admin, this error occurs. "Imported file has a wrong encoding: 'utf-8' codec can't decode byte 0xba in position 99: invalid start byte" How do I solve this? -
I Can't Solve NoReverseMatch at /events/ Error
I got this error when I add event with status false. There is no problem at status true: NoReverseMatch at /events/ Reverse for 'event-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['events/(?P<url_sistem>[^/]+)/$'] I couldn't see the cause of the error It's my views.py file: from django.shortcuts import render, get_object_or_404 from .models import Event def event_list(request): events_f = Event.objects.filter(status=False) events_t = Event.objects.filter(status=True) return render(request, 'etkinlik/event_list.html', {'events_f':events_f , 'events_t':events_t}) def event_detail(request, url_sistem): event = get_object_or_404(Event, url_sistem=url_sistem) return render(request, 'etkinlik/event_detail.html',{'event':event}) This is urls.py: urlpatterns = [ path('', views.event_list, name='event_list'), path('<str:url_sistem>/', views.event_detail, name='event-detail') ] And this template file: {% extends 'base.html' %} {%block title%}Events | {%endblock%} {% block content %} <div class="container mt-4"> <div class="jumbotron"> <h4 class="display-4">Öne Çıkarılan Etkinlik</h4> <p class="lead mb-5">Bu etkinlik şuandaki en önemli ve popüler etkinliktir. Katılabilen herkesin katılmasını isteriz</p> {% if not events_t %} <h2>Şu anda öne çıkarılan yok</h2> {% else %} {% for event_t in events_t %} <a href="{% url 'event-detail' event_t.url_sistem %}" style="color:black;"> <div class="card mb-3" style="max-width:700px;"> <div class="row no-gutters"> <div class="col-md-4"> <img src="/media/{{ event_t.img_event }}" class="card-img" alt="etkinlik_foto"> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">{{event_t.title}}</h5> <p class="card-text">{{event_t.exp}}</p> <p class="card-text"><small class="text-muted">Etkinlik Tarihi: {{event_t.event_date}}</small></p> </div> </div> </div> </div> </a> {% endfor %} {% endif %} </div> {% for event_f …