Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any GCash API for Django Web Apps
I want to integrate a Gcash API for the payments of the user in my ecommerce website -
Using a model to get the fields for another model
I have one model to define the fields in my system class MetadataField(models.Model): FIELD_TYPE = ( ('TXT', "Text"), ('CB', 'Checkbox'), ('DD', 'DropDown') ) id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) title = models.CharField(max_length=100) type = models.CharField(max_length=200, choices=FIELD_TYPE, default='TXT') workflow = models.ManyToManyField('Workflow') created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title Each field is associated with a workflow. Here is my workflow model class Workflow(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) name = models.CharField(max_length=200) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name I have a project model. class Project(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) title = models.CharField(max_length=100) workflow = models.ManyToManyField('Workflow') created_on = models.DateTimeField(auto_now_add=True) Now say there are 4 projects. Each project is associated with a workflow Project 1 : Workflow 1 Project 2 : Workflow 1 Project 3 : Workflow 2 Project 4 : Workflow 3 I want each project to have it's information (metadata). The metadata fields for every project should come from the fields created (in field model) for the associated workflow. It is like a form where the relevant fields are coming from the created fields and user can enter the value for each of those fields. How do I write a model to store this metadata? Will I have to … -
Django Using iex api from via model field
Hello so i will post my code, because I hope it explains my situation better than i can do :) Im struggeling with the views.py part because i dont know how I can use an argument for the iexcloud_watchlist. So if sb can explain how I am able to connect my api.py iexcloud_watchlist and watchlist_one from views.py correctly, I would be very thankful. I tried it with ticker = iexcloud_watchlist(query) , but thats not working bc it gave me the error watchlist_one() missing 1 required positional argument: 'ticker' models.py from django.db import models from django.contrib.auth.models import User class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=20, unique=True) description = models.CharField(max_length=50, null=True) updated = models.DateTimeField(auto_now=True) ticker = models.CharField(max_length=10, default='') def __unicode__(self): return str(self) api.py import requests def iexcloud_watchlist(ticker): response = requests.get(f'https://cloud.iexapis.com/stable/stock/{ticker}/quote? displayPercent=true&token=mytoken') try: return response.json() except Exception as e: e = "Error" views.py def watchlist_one(request, pk, ticker): Watchlist.objects.get(id=pk) model = Watchlist.objects query = model.all().values_list('ticker', flat=True) ticker = iexcloud_watchlist(query) context = { 'list_ticker':query, 'ticker':ticker, } return render(request, 'App1/watchlist_one.html', context) -
Loop through Django context values
How do I render a context value as a key-value list in template? def random_view(request): my_context = { "name": "turkey", "fly": "no", "run": 20 } return render(request, 'test/test.html', my_context) If this is the views the views then how can I loop through the values and render a list in test.html using a loop? -
How to use "has_object_permission" to check post request before saving to database?
How can I use a condition like this to validate data before it is written to the database? I am using django rest framework class WarehouseIsMemberOfCompany(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated: return True return False def has_object_permission(self, request, view, obj): if request.user.company.id == obj.warehouse.company.id: return True return False -
How can I calculate Position based on another field of Django model instances?
I have a Django model that looks like this: class Image(models.Model): name = models.CharField(max_length=60) description = models.CharField(max_length=60, null=False) clicks = models.IntegerField(default=0) views = models.IntegerField(default=0) @property def weight(self) -> float: return round((self.clicks * 0.7 + self.views * 0.3), 2) Based on weight, I'd like to estimate a position field of Image. It should give a position based on weight of all instances of Image. The higher the weight, the higher the position (position 1 - highest weight, position 2 - second highest, etc.) How can I create a function that would take ALL the Image instances I have in the DB and calculate position for all of them? -
organizations.OrganizationGroups has no ForeignKey to 'auth.User'
The following exception has been appearing randomly in my Django admin installation. OrganizationGroups does not have a ForeignKey to auth.User. This exception is also appearing in different apps of the system, and it is always organizations.OrganizationGroups has no ForeignKey to 'app.Model' I'm currently running: Django Version: 3.2.13 Python Version: 3.9.2 OrganizationGroups model: class OrganizationGroups(models.Model): id = models.BigAutoField(primary_key=True) organization = models.ForeignKey( Organization, models.DO_NOTHING, null=True, blank=True ) group = models.ForeignKey(Group, models.CASCADE, blank=True, null=True) class Meta: db_table = 'organization_groups' unique_together = (('organization', 'group'),) def __str__(self) -> str: return self.organization.name Traceback (most recent call last): File “/usr/local/lib/python3.9/dist-packages/django/core/handlers/exception.py”, line 47, in inner response = get_response(request) File “/usr/local/lib/python3.9/dist-packages/django/core/handlers/base.py”, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File “/usr/local/lib/python3.9/dist-packages/django/contrib/admin/options.py”, line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File “/usr/local/lib/python3.9/dist-packages/django/utils/decorators.py”, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File “/usr/local/lib/python3.9/dist-packages/django/views/decorators/cache.py”, line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File “/usr/local/lib/python3.9/dist-packages/django/contrib/admin/sites.py”, line 232, in inner return view(request, *args, **kwargs) File “/usr/local/lib/python3.9/dist-packages/django/contrib/admin/options.py”, line 1660, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File “/usr/local/lib/python3.9/dist-packages/django/utils/decorators.py”, line 43, in _wrapper return bound_method(*args, **kwargs) File “/usr/local/lib/python3.9/dist-packages/django/utils/decorators.py”, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File “/usr/local/lib/python3.9/dist-packages/django/contrib/admin/options.py”, line 1540, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File “/usr/local/lib/python3.9/dist-packages/django/contrib/admin/options.py”, line 1604, in _changeform_view … -
How to get the value within the a tag
<td> <a href="/Codes/A">'A' Codes</a> </td> <td> <a href="/Codes/B">'B' Codes</a> </td> <td> <a href="/Codes/C">'C' Codes</a> </td> I want to get the values A, B, and C from the tag -
Set default value Django Models
I need to set a date to Enddate if the user didn't enter it by taking the value from Starting input, Let's say I have this Model: class DataSet(models.Model): Event = models.CharField(max_length=50,blank=True ,null=True) Starting = models.DateField() Enddate = models.DateField(blank=True ,null=True) Times = models.PositiveIntegerField(max_length=4,blank=True ,null=True) postdate = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.Stating class Meta: ordering = ('-Enddate',) and the form is; class DataSet_F(forms.ModelForm): Event = forms.CharField(label='Event') Starting = forms.DateField(label='Start date',widget=forms.DateInput(attrs={"class":"form-control", 'type':'date'})) Enddate = forms.DateField(label='End date',required =False,widget=forms.DateInput(attrs={"class":"form-control", 'type':'date'})) Times = forms.IntegerField(label='Time',required =False) class Meta: model= DataSet fields=['Event','Starting','Enddate','Times'] How I set Enddate equal to Starting when the user didn't enter the value, then set Times equal to 1. Many thanks -
Nginx is showing 400 Bad Request No required SSL certificate was sent
I'm trying to establish SSL connection and I'm getting 400 No required SSL certificate was sent response from the server. I used this tutorial for it I tried everything to solve this issue, but it seems that there is something wrong with the cloudflare certificate because when I disable ssl_verify_client it is working (with security alert). Here is my nginx configuration: server { listen 443 ssl http2; listen [::]:443 ssl http2; ssl_certificate /etc/ssl/cert.pem; ssl_certificate_key /etc/ssl/key.pem; ssl_client_certificate /etc/ssl/cloudflare.crt; ssl_verify_client on; server_name example.com www.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/username/www/exampleproject; } location /media/ { root /home/username/www/exampleproject; } location / { include proxy_params; proxy_pass http://unix:/home/username/www/exampleproject/exampleproject.sock; } } -
Formatting Django forms elements in html templates
I have a contact form that I'm trying to use in one of my Django templates. I created a class for it in forms.py: class ContactForm(forms.Form): name = forms.CharField(max_length=100) email_address = forms.EmailField(max_length=150) message = forms.CharField(widget = forms.Textarea,max_length=2000) and added it to my views.py: def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Website Inquiry" body = { 'name': form.cleaned_data['name'], 'email': form.cleaned_data['email_address'], 'message':form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail(subject, message, 'admin@example.com', ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect ("BobbleHead:home") form = ContactForm() return render(request, "BobbleHead/contact.html", {'form':form}) and am now trying to get the form to render with specific html formatting in my template (contact.html), but am having difficulties. Previously, I was using the built in Django capabilities to render, like this: <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> That worked fine, but I don't like the way it looks on my webpage and wanted to clean up the formatting. I want the form to render with specific formatting, like this: <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <div class="w3-col m6"> <form action="/home" target="_blank"> {% csrf_token %} <div class="w3-row-padding" style="margin:0 -16px 8px -16px"> <div class="w3-half"> <div class="fieldWrapper"> <input class="w3-input w3-border" type="text" placeholder="Name" required name="name"> </div> … -
Best Django method for multiple entries for the same field
A huge hello to the community! I am trying to figure out the best method to add multiple instances of the same field for a Recipe class I have created. When creating the new Recipe, I need to be able to add multiple instances of Ingredient, Measurement Unit, Unit Value. For example: ingredient = Lemon measurement_unit = ml unit_value = 100 I would then need to add another Ingredient and do the exact same thing. I would then be able to save the Recipe. What would be the best method to use to achieve this? -
Page Number and Total Pages in Header When Printing HTML to PDF
Background: I have a large HTML file that has 8 different pages. Some of the pages in the HTML can be larger than the 11in container size and the 11in stipulated in the @page CSS due to a lot of data in some of the tables. What am I trying to do?: I am trying to send in context data (written in Django / Python) to each table of unknown length. Once the data has been entered then I will use weasyprint to create the pdf. At the top of every page the page number and total number of pages should be added dynamically. The issue: When I print to PDF the header on the pages with a lot of rows (ones that are >11in) add the header but the header shows the same page number for of the split pages. In the example below it is on page 2 that is split into two pages and when you print to pdf the header on page 3 and 4 are incorrect. What have I tried?: Basically everything I could think of. At first I thought about just using paged media but I couldn't figure out how to put this complex … -
How to implement a database for storing parentId and a list of children?
I need to implement a POST request with data loading via two keys: "items" and "UpdateDate". But in the database with items it is necessary to store the parent (parentId) of the category /product and a list of children (children). and record the time from the "UpdateDate" key in the date field for all categories/products imported for this request The screenshots below show a detailed TT. I haven't been able to figure out how to implement a database on Django/Django Rest Framework for a week. Screens: class ShopUnit(models.Model): id = models.UUIDField(primary_key=True, verbose_name='Unique identifier', default=uuid.uuid4, editable=False, null=False) name = models.CharField(max_length=255, verbose_name='Category/Product name', null=False) date = models.ForeignKey('Date', on_delete=models.CASCADE, related_name='date', null=True, blank=True) parentId = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='сhilden', db_index=True) type = models.CharField(max_length=10, verbose_name='Element Type', choices=ShopUnitType.choices) price = models.PositiveIntegerField(null=True, blank=True, verbose_name='Цена') children = models.ForeignKey("self", null=True, blank=True, on_delete=models.SET_NULL, related_name='parent') There are small developments: https://i.stack.imgur.com/GdAaK.png https://i.stack.imgur.com/fzBdS.png https://i.stack.imgur.com/LRQIq.png https://i.stack.imgur.com/tssis.png -
I'm usin django allauth for authentication. I can't find iun the website the list of error returned by the framework
I want for example know all type of error that can be returned by allauth, where can I find this list please ? like this one : "non_field_errors": [ "Unable to log in with provided credentials." ] -
How to use OuterRef with _in filter
I've been trying to rework a query and I can't figure out the solution. Here is the setup (oversimplified): An object OrderLine with a quantity and a product, and the product itself with a stock class Product(models.Model): inventory_quantity = models.IntegerField() class OrderLine(models.Model): product_id = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() What I want to do is annotate Product to know the predicted inventory and use it later in the code. I had this code that was working in Django 2: subquery_projected_product = OrderLine.filter( product_id__in=OuterRef('id') ).annotate( qty=ExpressionWrapper( F('product__inventory_quantity') - OrderLine.sum_quantity_sql(), output_field=IntegerField() ) ).values('qty') products_queryset = Product.objects.all(). annotate( nb_projected=Subquery( subquery_projected_product, output_field=IntegerField() ) ) But after Django switch to version 3 I ran into this: https://code.djangoproject.com/ticket/31135. If I understand correctly, this is not the correct way to do the request and it`s not supported anymore. So to put it simple, how can I, for each product, annotate the sum of quantity of related orderlines ? Thanks and have a good day. -
vscode lint extensions problems caused by different extensions
I have a problem in vscode where I have a lot of extensions installed and a lot of problems are reported in the Problems view. I've created a new django python project - but I want to set things up in such a way that the linters I am interested in will output correct problems. So for html files I want to use monosans.djlint. The idea being that all developers working on the project have the recommended extensions installed and any obtrusive ones disabled - but only for the project/workspace. So given a basic html file, I see 14 problems reported - just to highlight the wider problem in my project. templates/test.html <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Test</title> </head> <body> <ul> {% for x in z %} <li>x</li> {% endfor %} </ul> <script type="text/javascript"> const x = {{ data | safe }}; const y = { foo: [{{ count_1 }}, {{ count_2 }}] }; </script> </body> </html> Problems The following screenshot is what I see in vsode: Is it possible to actually identify what extension the problem is from? I can see Microsoft Edge Tools - but not … -
How to provide request to unit tests
How to provide a context request in the serializer? Because i get this error: price = int(self.context.get('request').query_params.get('price', None)) AttributeError: 'NoneType' object has no attribute 'query_params' serializers.py class IpotekaSerializer(serializers.ModelSerializer): payment = serializers.SerializerMethodField() class Meta: model = Ipoteka fields = '__all__' def get_payment(self, obj) -> int: """ :return: Payment value. float | int :rtype: float | int :except ValueError, TypeError: Returns errors if URL parameters were incorrectly provided """ try: price = int(self.context.get('request').query_params.get('price', None)) deposit = int(self.context.get('request').query_params.get('deposit', None)) term = int(self.context.get('request').query_params.get('term', None)) if price == 0 or term == 0: return 0 return self._get_offer_result(price, deposit, term, obj) except (ValueError, TypeError): return 0 test_serializer.py class SerializerTestCase(TestCase): def test_ser(self): # some logic data = IpotekaSerializer([offer_1, offer_2], many=True).data self.assertEqual(data, expected_data) -
F expression conjunction with Sum() is not working as expected
class Order(): pass class OrderItems(): order = models.ForiegnKey(Parent, related_name="items") price = models.DecimalField() quantity = models.DecimalField() class OrderItemSalesTax(): order_item = models.ForiegnKey(OrderItems, related_name="sales_tax") name = models.CharField(max_length=255) percentage = models.DecimalField(max_digits=6, decimal_places=2) class OrderItemDiscount(): name = models.CharField(max_length=255) discount = models.DecimalField(max_digits=6, decimal_places=2) in_percentage = models.BooleanField() I am using this query to calculate the total amount, but also deducting discount and adding Sales tax. Sum(F('items__sales_tax__percentage')) value is 25, and I have verified it, querying the database. Right now I have only One order and two Items and Items and two Sales Taxes and One Discount I am trying to Sum the Sales taxes to apply on discounted price, but I am getting the wrong result results. If I manually write 25 by replacing Sum(F('items__sales_tax__percentage')) then results are correct, is there anything wrong with my query ? Order.objects.filter(customer__zone__distribution=get_user_distribution(request.user.id))\ .annotate( trade_price=Sum(F('items__trade_price') * F('items__quantity')), tax = Sum(F('items__sales_tax__percentage')), discounted_price = F('trade_price') * ExpressionWrapper(0.01 * (100 - Sum(F('items__discount__discount'))), output_field=DecimalField()), total = F('discounted_price') + F('discounted_price') * Sum(F('items__sales_tax__percentage')) / 100 ) -
Django ValueError invalid literal for int() with base 10: ''how i can solve the None type error
in Django forms when i am appending the values , from old_car field getting ValueError invalid literal for int() with base 10: '' the values of new_car and old_car are string and need to convert to integer for further conditions, i know if i remove int will solve the error :). how i can solve that django forms.py car = cleaned_data.get("user", ['AUTO']) if car[0] == 'AUTO': records = [] for i in range(count): new_car = int(self.data.get(f'cardefination_set-{i}-new_car', [])) old_car =int(self.data.get(f'cardefination_set-{i}-old_car', [])) records.append((new_car, old_car)) records = sorted(records, key=lambda record: record[1]) trcae back Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/wm_data_collection/scenario/345/change/ Django Version: 3.1.1 Python Version: 3.7.4 Installed Applications: ['whitenoise.runserver_nostatic', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'wm_data_collection', 'masterdata', 'django_admin_listfilter_dropdown', 'grappelli', 'nested_admin', 'django.contrib.admin', 'django_select2', 'users.apps.UsersConfig', 'rest_framework', 'rest_framework.authtoken', 'adminsortable2', 'more_admin_filters', 'debug_toolbar', 'django_extensions'] Installed Middleware: ['debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'wm_data_collection.middleware.DefaultCountryMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "D:\Users\hasanm2\.virtualenvs\wm3330-46yZ5NJh\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Users\hasanm2\.virtualenvs\wm3330-46yZ5NJh\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Users\hasanm2\.virtualenvs\wm3330-46yZ5NJh\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "D:\Users\hasanm2\.virtualenvs\wm3330-46yZ5NJh\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Users\hasanm2\.virtualenvs\wm3330-46yZ5NJh\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "D:\Users\hasanm2\.virtualenvs\wm3330-46yZ5NJh\lib\site-packages\django\contrib\admin\sites.py", line 233, in … -
Add page loading while scraping process
I created a view using django that displays a search engine to type in the name of the product to be scraped and starts the scraping process. Also, I created a view as a loading page that I want to be displayed when I start the scraping and disappear when the scraping finishes and display the datatable as mentioned in my code. Here is my view.py : def home_view(request): context = {} context ['form'] = Scraping() # if user inserted into form and validated the form if request.method =='POST': form= Scraping(request.POST) if form.is_valid(): # get variable (nom product) subject = form.cleaned_data['subject'] # remove space and replace it with a + sign sbjt = subject.replace(" ","+") # call scrapy command line with this variable os.chdir('C:/Users/aicha/Desktop/new_version/django_project/aliScrap/scraper/codes/aliscraper/') os.system("scrapy crawl aliproduct -a product=" + sbjt) # get results from database client = MongoClient("mongodb://localhost:27017/") db = client["aliexpress"] col = db["listproducts"] products = col.find() context = {'products' : products} return render(request,'datatable.html', context) # default page return render(request,'index.html', context) Page loading view : def loading_view(request): return render(request,'loading.html') Knowing that I have already prepared the html of my loading page. The issue is that I don't know how to integrate my loading page after starting the scraping. It … -
How to implement an Api made with Django on kivy app
Hi everyone I followed the tutorial on the official docs here (https://www.django-rest-framework.org/tutorial/quickstart/) to make my authentification (sign up) and now If i am right with my api, I want to implement it on my kivy app. Aand I don't know how to do. Thanks for answering ! -
Can I add charset from utf-8 to utf8mb4 in django databases
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '{{projectName}}', 'USER': 'root', 'PASSWORD': 'root', 'HOST'strong text: 'localhost', 'PORT': '3306', } } How i can add or update charset, For Options Key i kept charset key i am getting error like below conn = Database.connect(**conn_params) TypeError: 'charset' is an invalid keyword argument for this function For my sql database there is option like this -
Django Form specify table to use for field
For the field cast in the Movie object I want to use the table Cast_movie generated which is movies_cast_movie instead i get an error that movies_movie_cast doesn't exist movies/models.py from django.db import models from .models import * class Movie(models.Model): cast = models.ManyToManyField('Cast_movie', related_name='cast_movies') class Cast_movie(models.Model): movie = models.ForeignKey('movies.movie', on_delete = models.CASCADE, blank=True, null=True) cast = models.ForeignKey('casts.cast', on_delete = models.CASCADE, blank=True, null=True) role = models.ForeignKey('casts.role', on_delete = models.CASCADE, blank=True, null=True) def __str__(self): return self.cast How do i specify the table to use? -
accessing one domain causes logout another domain in load balanced mutliple domain system
I have a elastic beanstalk application which is load balanced. It's a django multitenant application. I am facing a weird problem. If i just access a domain(loading a login page),other domain is getting logging out. I tried different window, different browser even different network. It's logging of. It's working for non load balanced single instance. Need help.