Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
configure django app to receive Apple App Store notification (refundNotification) and test it
I would like to configure my application to receive App Store Notifications in case of refund action. First of all I have to configure my server to support App Transport Security (ATS). Let’s assume that I have a django application hosted on ingenx or apache server. How can I configure my server to support ATS protocol? Does supporting ATS Portocol means that I should use HTTPS protocol for my APIs? Or do I need to configure NSAppTransportSecurity in the middleware in Django settings? How would I support ATS in Django? After supporting ATS in Django, I would like to test the new configurations. Thus, I have to configure a subscription status URL for my app in App Store Connect. Then, I have to wait until the next app version is released on App store in order to activate the newly registered URL in the App Store Connect. How would I test, that I am receiving the REFUNDNotification without waiting until the next version to be released on App Store? Any suggestions would be highly appreciated. Thanks in Advanced -
Reverse for 'view_post' with keyword arguments '{'pk': 5}' not found. 1 pattern(s) tried: ['post/(?P<post_id>[0-9]+)/$']
I searched about that problem, but don't find anything, and this is the first time I ask for help. This problem happened when I started to make a detail view of post. This site write:'It looks like your post is mostly code; please add some more details.', but I don't know what to write. Don't blame me) #urls.py from django.urls import path from .views import * urlpatterns = [ path('', home, name='home'), path('category/<int:category_id>/', get_category, name='category'), path('company/<int:company_id>/', get_company, name='company'), path('post/add_post/', add_post, name='add_post'), path('post/<int:post_id>/', view_post, name='view_post'), ] #views.py from django.shortcuts import render, redirect from .models import * from .forms import ProductsForm from django.urls import reverse def home(request): products = Products.objects.all() categories = Category.objects.all() companies = Company.objects.all() context = { 'products': products, 'categories': categories, 'title': 'Products', 'companies': companies } return render(request, template_name='shop/home.html', context=context) def get_category(request, category_id): products = Products.objects.filter(category_id=category_id) categories = Category.objects.all() category = Category.objects.get(pk=category_id) return render(request, 'shop/category.html', {'products': products, 'categories': categories, 'category': category}) def get_company(request, company_id): products = Products.objects.filter(company_id=company_id) companies = Company.objects.all() company = Company.objects.get(pk=company_id) return render(request, 'shop/company.html', {'products': products, 'company': company, 'companies': companies}) def add_post(request): if request.method == 'POST': form = ProductsForm(request.POST) if form.is_valid(): Products.objects.create(**form.cleaned_data) return redirect('home') else: form = ProductsForm() return render(request, 'shop/add_post.html', {'form': form}) # вторым аргументом ф-ция должна … -
can we pass a list to a permission_required?
I need to check a few permissions in a class based view. is there a way to pass a list (multiple permissions) to a permission_required? (we were include a PermissionRequiredMixin) -
it seems that has "polls/urls.py " but i dont get what
i dont know why there is bug even it seems not... i post my githuub. https://github.com/Angelheartha/tera in ther termional, i did python.py shell later from django.test import Client from django.test.utils import setup_test_environment setup_test_environment() create an instance of the client for our use client = Client() response = client.get(reverse('polls:index')) the result was this in the end Internal Server Error: /polls/ Traceback (most recent call last): raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. i dont understand the problem here. -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/index.html/
im trying to create simple todo list. I've found a little issue. During deleting todo task I'm getting error (this from topic), but task is actually deleting. How to get rid of this error? urls.py from django.urls import path, include from .views import DeleteTodo from . import views app_name = 'todoxd_app' urlpatterns = [ path('', views.index, name='index'), path('todo/', views.todo, name='todo'), path('new_todo/', views.new_todo, name='new_todo'), path('delete/<int:pk>/', DeleteTodo.as_view() ,name='delete_todo'), ] delete_todo.html Title {% extends 'todoxd_app/base.html' %} {% block content %} {% csrf_token %} Are you sure you want to delete this task? DELETE TASK {% endblock content %} views.py from django.shortcuts import render, redirect from django.urls import reverse_lazy from .models import Task from .forms import TaskForm from django.views.generic import DeleteView def index(request): return render(request, 'todoxd_app/index.html') def todo(request): objekt = Task.objects.all() context = {'objekt': objekt} return render(request, 'todoxd_app/todo.html', context) def new_todo(request): if request.method != 'POST': form = TaskForm() else: form = TaskForm(data=request.POST) if form.is_valid(): form.save() return redirect('todoxd_app/new_todo') context = {'form': form} return render(request, 'todoxd_app/new_todo.html', context) class DeleteTodo(DeleteView): model = Task template_name = 'todoxd_app/delete_todo.html' success_url = '/index.html/' If you will find other issue, give me feedback, I'm just a begginer. Thanks! -
Django apply migrate for inherit models
I have a base model BaseStage and two inherit models TestSpend , StageSpend class BaseStage(models.Model): name = models.CharField date = models.DateField ....... class TestSpend(BaseStage): direction = models.CharField class StageSpend(BaseStage): direction = models.CharField Now Im try to add constraints field to Meta class Meta: verbose_name = '' verbose_name_plural = '' constraints = [ models.UniqueConstraint( fields=['direction', 'name', 'date'], name='unique_name' ) ] to both models. Successfully running the makemigrations command, but when run migarte got django.db.utils.ProgrammingError: column "name" named in key does not exist -
how to use the same base code for different customers on the same server- django
i have a customer , he has two hotels , and he wants set both hotels on the same server , but each of them has different data , i tried to use django-tenant-schemas here is my settings.py SHARED_APPS = [ 'tenant_schemas', 'users', 'rosetta', 'widget_tweaks', 'import_export', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TENANT_APPS = [ 'rooms', 'vistors', 'booking', 'costs', 'payments', 'cancel', ] INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] TENANT_MODEL= "rooms.Hotel" #db engine 'ENGINE': 'tenant_schemas.postgresql_backend', my models.py class Hotel(TenantMixin): hotel_name = models.CharField(max_length=40,unique=True) def __str__(self): return self.hotel_name class Room(models.Model): room_no = models.IntegerField() #others and i have more models but all of them inherited from models.Model ,in the public schema it only created tables for SHARED_APP apps , TENANT_APP not created and i try manage.py migrate_schemas it raise this error if public_schema_name in tenants: TypeError: argument of type 'TenantQueryset' is not iterable is there another way to achieve it please ? i need something like this : home page shows two hotels name : Hotel A and Hotel B when i click on Hotel A shows all data which owns by Hotel A and both has same menu but they are different in contents … -
Django Trying to re-use same webpage for several different listviews
Just stared with python /django. But trying to be more clever than I have competence for. So if someone has the time to educate me, I would appreciate it. I have a main model to handle "work orders". Then I have subsets of data that is linked to each order. I have then generated a html template where I can see an order and all subsets of data in a list view. Now I'm trying to generate one generic HTML-template for the list views of all type (model) of data, instead of creating one HTML-template for each model of data. I thought I could define the variables through context_data. Even if not complete I think you understand what I'm trying to do with the below code. Otherwise the HTML-template and the views are working. Views.py class WO_TravelView(ListView): template_name = 'TravelLaborPartsLists.html' model = WorkOrderTravel def get_context_data(self, **kwargs): id_ = self.kwargs.get('str') context = super().get_context_data(**kwargs) context['list'] = WorkOrderTravel.objects.filter(wo_num=id_).order_by('wo_travel_slug') context['page'] = 'Travel logged for' context['string'] = id_ context['label'] = 'Work order-instance / Start / Stop ' context['data1'] = 'item.wo_travel_slug' context['data2'] = 'item.wo_travel_start' context['data3'] = 'item.wo_travel_stop' return context class WO_PartsView(ListView): template_name = 'TravelLaborPartsLists.html' model = WorkOrderParts def get_context_data(self, **kwargs): id_ = self.kwargs.get('str') context = super().get_context_data(**kwargs) … -
Django - Image gets uploaded after every save()
I have a custom upload path for any users avatar. I call a function to set the upload path to "avatar/" + str(self.username) + "/" + filename. My problem is everytime the user change e.g. email and save changes, the avatar gets saved again with the same upload path. models.py def _upload_path(instance, filename): return instance.get_upload_path(filename) def reduce_image_size(avatar): img = Image.open(avatar).convert('RGB') thumb_io = BytesIO() img.save(thumb_io, 'jpeg', quality=50) new_image = File(thumb_io, name=avatar.name) return new_image class User(AbstractUser): avatar = models.ImageField(upload_to=_upload_path, blank=True, null=True) def get_upload_path(self, filename): return "avatar/" + str(self.username) + "/" + filename def save(self, *args, **kwargs): new_image = reduce_image_size(self.avatar) self.avatar = new_image When first upload image the url is /media/avatar/username/the_uploaded_image.jpg and after updating any value it changes to /media/avatar/username/avatar/username/the_uploaded_image.jpg I tried to check if a path already exsist but it wasnt working. if self.avatar and not os.path.exists(settings.MEDIA_URL + self.get_upload_path(self.avatar.name)): new_image = reduce_image_size(self.avatar) self.avatar = new_image Do I miss something? -
can't upload image from database in django server
in my project i am trying to save image in database and next i want to get that image from database in my dashborad everything working well, imgs where saved in db but when i am trying to get url from db and asign it to img src="" chrome says that 404 (Not Found) this is my model class Id(models.Model): first_name = models.CharField(max_length=100, null=True) image = models.ImageField(default='defaut.jpg', upload_to='document_pics') def __str__(self): return self.first_nam img savinig in documents_pics folder then i am trying to in views.py get data from db and send it to home.html def home(request): context = { 'posts': Id.objects.all(), 'title': 'Home' } return render(request, 'blog/home.html', context) home.html {% extends 'blog/base.html' %} {% block content %} {% for post in posts %} <article class="media content-section"> <img src="{{ post.image }} " width="200" height="200" </article> {% endfor %} {% endblock content %} and than i am getting 404 error -
Getting JSON parse error using FETCH, but not when using PostMan
I have set up an API endpoint using Django and django-rest-framework to submit a form using a POST request. When sending the request with PostMan, the backend works fine and adds the data to the DB. However, when I use fetch the backend returns {"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}. The frontend is a react webpack setup. This is the code I am using to make the request: let csrftoken = getCookie('csrftoken') const jsonString = JSON.stringify(data,null, ' ') console.log(jsonString) const response = await fetch(baseURL + 'jobs/',{ method: 'POST', mode: 'same-origin', cache: 'no-cache', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'Accept': '*/*', 'X-CSRFToken': csrftoken, 'Accept-Encoding': 'gzip, deflate, br' }, body: jsonString }); return response.json() } Here is the print of jsonString: { "data": "asdf", "mode": "text", "node": "sdaf", "species": "asdf", "model_type": "proto", "dry_run": false, "single_fam_mode": false, "mail_address": "" } I also used wireshark to capture both the PostMan and the fetch request. Here is the postman request, with the successful response: [1 bytes missing in capture file].POST /api/jobs/ HTTP/1.1 Content-Type: application/json User-Agent: PostmanRuntime/7.28.3 Accept: */* Postman-Token: 8c4b0ff0-5430-4420-8785-e965a808db5c Host: localhost:8000 Accept-Encoding: gzip, deflate, br Connection: keep-alive Content-Length: 184 { "data": "asdsadad", "mode": "text", "node": "katten", "model_type": "both", … -
django get_object() getting called many times
I have a model- Article, and this code snippet class ArticleDetailView(HitCountDetailView): model = Article # some code... def get_object(self): article = super(ArticleDetailView, self).get_object() slug = self.kwargs['slug'] article = get_object_or_404(Article, slug=slug) print(article.some_count.counts) return article this code is line printing the value of article.some_count_counts 3 times, it means the function get_object() is getting called 3 times. But why so? that's my question. -
Couldn't access API root after using rest_framework_api_key library
I applied 'rest_framework_api_key' library and give my viewset permissions of using APIKey or the user is authenticated. When I log in with the admin user and access API root URL at localhost:8000/api/ it gives me an error ' You do not have permission to perform this action.' Viewset class CustomerViewSet(viewsets.ModelViewSet): """Endpoint for Customer""" queryset = Customer.objects.all() serializer_class = CustomerSeralizer permission_classes = [HasAPIKey | IsAuthenticated] URLS urlpatterns = [ path('api/', include(router.urls)), ] Django Rest Framework Settings REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework_api_key.permissions.HasAPIKey', ], } -
File upload button not visible in django (visible in django admin panel though)
I don't see file upload button in my front-end part and it's coming as a drop down list but it is visible in the admin panel, I'm new to Django, can you please help me to point out what is the mistake I'm making? [Thank You in advance :)]. [1]: Front-End Image: https://i.stack.imgur.com/MWU0s.png [2]: Back-End Image: https://imgur.com/a/J3R2k1P -
DeserializationError: ['“F(view_count) + Value(1)” value must be an integer.']
I am using Django 3.2 I am using F values to increment a field value (to avoid potential race conditions). Here is a snippet of my code (section that throws exception): def __update_fields(self, interaction_type): if interaction_type == Engagement.VIEW: self.view_count = F('view_count') + 1 I get this error: DeserializationError: ['“F(view_count) + Value(1)” value must be an integer.']: (poll.poll:pk=10) field_value was 'F(view_count) + Value(1)' Here is the full stack trace: Internal Server Error: //path/to/example Traceback (most recent call last): File "/path/to/myproj/env/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1836, in to_python return int(value) ValueError: invalid literal for int() with base 10: 'F(view_count) + Value(1)' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/path/to/myproj/env/lib/python3.8/site-packages/django/core/serializers/python.py", line 144, in Deserializer data[field.name] = field.to_python(field_value) File "/path/to/myproj/env/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1838, in to_python raise exceptions.ValidationError( django.core.exceptions.ValidationError: ['“F(view_count) + Value(1)” value must be an integer.'] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/path/to/myproj/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/path/to/myproj/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/path/to/myproj/env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/path/to/myproj/env/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/path/to/myproj/env/lib/python3.8/site-packages/django/views/generic/detail.py", line 107, in get context = self.get_context_data(object=self.object) File … -
VScode unittest test discovery settings for django app
I have a django app with some unittests. I want to run\debug them in VScode v.1.59.1. My ./vscode/settings.json looks like this: { "python.testing.unittestArgs": [ "-v", "-s", "./routes/tests", "-p", "test*.py" ], "python.testing.pytestEnabled": false, "python.testing.nosetestsEnabled": false, "python.testing.unittestEnabled": true, } When I try to run\discover tests I have this output: ImportError: Failed to import test module: test_utils ... django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. When I try to run tests in regular django way with command: python manage.py test the tests working fine. Please help me setup my VScode to run django unittests. P.S: I can not install pytest, this should be done without installation of any new modules. -
django.db.utils.ProgrammingError: relation "django_content_type" does not exist raised by psycopg2
I accidently removed django_content_type while migrating databse to postgreSQL to solve the following error: django.db.utils.IntegrityError: duplicate key value violates unique constraint (base, product) already exists it was raised when i tried load data from datadump.json to postgreSQL database Is there any way to create this table again I used command DROP TABLE public.django_content_type CASCADE; now i can't make the dumpdata.json it giving the following error django.db.utils.ProgrammingError: relation "django_content_type" does not exist and its raised by psycopg2 package I have reinstalled django, psycopg2 and started a new django project and its still giving the same error whenever i tried to migrate or create dumpdata.json for backup I tried this query to create django_content_type table CREATE TABLE public.django_content_type ( id integer NOT NULL DEFAULT nextval('django_content_type_id_seq'::regclass), app_label character varying(100) COLLATE pg_catalog."default" NOT NULL, model character varying(100) COLLATE pg_catalog."default" NOT NULL, CONSTRAINT django_content_type_pkey PRIMARY KEY (id), CONSTRAINT django_content_type_app_label_model_76bd3d3b_uniq UNIQUE (app_label, model) ) WITH ( OIDS = FALSE ) TABLESPACE pg_default; this query also giving error in djangoshell ERROR: relation "django_content_type_id_seq" does not exist -
Django - __init__() got an unexpected keyword argument 'headers'
I am trying to download a CSV when a button is clicked, however, I am getting the error: __init__() got an unexpected keyword argument 'headers this is my view: def download_file(request): response = HttpResponse( content_type='text/csv', headers={'Content-Disposition': 'attachment; filename="somefilename.csv"'}, ) return response this is the trackback: Traceback: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/Users/matthewkaye/Eflux/Argus/app/views.py" in download_file 74. response = HttpResponse( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/http/response.py" in __init__ 289. super().__init__(*args, **kwargs) Exception Type: TypeError at /Download Exception Value: __init__() got an unexpected keyword argument 'headers' -
Problem with referencing auth_user table in Django with raw query
I need to make an inner join on my tables and I need the users last name and first name from the auth_user table whose are added to a project. Projects are collected in another table (Project) that is connected to a Profile model with which I extended my User model. Yet I'm using SqLite3 so I wrote a query that works well in SqLite Viewer: SELECT username, projekt_id FROM 'auth_user' INNER JOIN stressz_profile ON stressz_profile.user_id = auth_user.id WHERE projekt_id=1 I adopted the query to Django like this: resztvevok = Profile.objects.raw('SELECT username, projekt_id FROM auth_user AS resztvevok INNER JOIN stressz_profile ON stressz_profile.user_id = auth_user.id WHERE projekt_id=1') But when I refresh the browser it says: no such column: auth_user.id models.py class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) projekt = models.ForeignKey(Projekt, on_delete=models.CASCADE, default=3) ... -
getting error while posting data of uid and token ( 'WSGIRequest' object has no attribute 'post' )
I created class based view to access uid and token . Here I create one web page which have one button of activate user. I am sending one uid and token to user email . now I want to post that uid and token when user click on button. I create this code in view for post uid and token. But getting error on posting (WSGIRequest' object has no attribute 'post) views.py class ActivationView(View): def get (self, request, uid, token): print('get called in activate_user') return render(request, 'activate.html') def post (self, request, uid, token): print('UID : ', uid) print('Token : ', token) payload = json.dumps({'uid': uid, 'token': token}) print("payload : " , payload) protocol = 'https://' if request.is_secure() else 'http://' web_url = protocol + request.get_host() + '/' post_url = web_url + ACTIVATION_BASE_ROUTE print('post_url : ' + post_url) response = request.post(post_url, data = payload) return HttpResponse(response.text) activate.html <form action="" method="post"> {% csrf_token %} <td ><button type="submit">Click Here For Activate Account</button></td> </form> How can I post it on same page ? -
django database TypeError
i am trying to make manytomanyfield so everything going well but when i created Department and assign user (Ids) i get error Field 'id' expected a number but got <Id: luka>. from django.db import models # Create your models here. class Id(models.Model): first_name = models.CharField(max_length=100, null=True) last_name = models.CharField(max_length=100, null=True) date_of_birth = models.CharField(max_length=100, null=True) date_of_expire = models.CharField(max_length=100, null=True) date_of_issue = models.CharField(max_length=100, null=True) CHOICES = [('Male', 'Female'), ('Female', 'Male')] gender = models.CharField(max_length=30, choices=CHOICES) # gender = models.CharField(max_length=10) address = models.TextField(null=True) country = models.CharField(max_length=30,null=True) city = models.CharField(max_length=30,null=True) card_no = models.CharField(max_length=30,null=True) personal_number = models.CharField(max_length=30,null=True) image = models.ImageField(default='defaut.jpg', upload_to='document_pics') def __str__(self): return self.first_name class Departments(models.Model): name = models.CharField(max_length=30, null=True) users = models.ManyToManyField(Id) def __str__(self): return self.name -
Preventing user from creating new Tags
I am building a BlogApp and I am trying to implement a feature so user cannot create new tags And can only use existing tags, So I am checking the form at the time of submit If blog post tags is in existing tags than Save the Post But if tags are not in existing tags than show an Error. For Example:- Existing tags are health, books and if user typed one of them then post will save And If user typed playing, health than it will show an error. But When i save the form with existing tags than it is showing error every time. models.py from taggit.managers import TaggableManager class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30, default='') description = models.CharField(max_length=30, default='') tags = TaggableManager() views.py from taggit.models import Tag def new_blog_post(request): existingTags = Tag.objects.all() if request.method == 'POST': form = BlogPostForm(request.POST, request.FILES) if form.is_valid(): blog_tags = form.cleaned_data['tags'] new_post = form.save(commit=False) new_post.post_owner = request.user if blog_tags in existingTags: new_post.save() else: messages.error(request,'You cannot create a New Tags') return redirect('qa:questions') else: form = BlogPostForm() context = {'form': form} return render(request, 'new_blog_post.html', context) I have also tried by looping the tags query like :- for extTags in existingTags: if blog_tags … -
Django - Model Form with ManyToManyField - how to calculate field?
I have this code in my views.py: from django.shortcuts import render from .helpers import * from .forms import OrderForm def create_order(request): if request.method == 'POST': form = OrderForm(request.POST) if not request.POST._mutable: request.POST._mutable = True if form.is_valid(): obj = form.save(commit=False) obj.total_price = calculate_total_price_obj(obj) obj.save() else: form = OrderForm() return render(request, 'create_order.html', {'form': form}) I have this in my helpers.py: def calculate_total_price_obj(obj) -> float: """ Calculate the total_price of the order. This function has to be called after the Order has been created and saved. """ prices_of_ordered_foods = obj.ordered_foods print(prices_of_ordered_foods) return sum(prices_of_ordered_foods) What I'm trying to achieve is: Get the form the user sent. Calculate field total_price based on the prices of chosen meals/foods by the user when he was filling up the forms (this is a ManyToManyField in my models.py). After calculation is performed, save the form. (Calculation is a simple sum() method.) However, this does not work. I am getting this error: <MyOrderObject> needs to have a value for field "id" before this many-to-many relationship can be used. Any ideas how to fix it? Thank you -
Unexpected result while using two matplotlib chart at the same time
I am using matplotlib for doing chart for my web project. There is two view functions. One for Pie chart and other for Bar chart. I get the desire chart while calling each chart one at a time. but while I tried to calling both function at the same time. I got unexpected result. Like both bar chart and pie chart produce identical figure, or one or both unfinished chart. I have added my code bellow. view.py from .utils import draw_piechart,draw_barchart # # Pie Chart def piechart(request): products = Product.objects.all() draw_piechart(products) return render(request,'store/piechart.html') def barchart(request): draw_barchart() return render(request,'store/barchart.html') utils.py import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import numpy as np # from random import random, randint import random # Pie Chart def draw_piechart(products): # Pie chart, where the slices will be ordered and plotted counter-clockwise: # labels = 'Sale', 'Purchase', 'Test' labels = [] for i in products: if i.category not in labels: labels.append(i.category) sizes = [random.randint(10,30), random.randint(30,50)] # explode = (0.1, 0) # only "explode" the 2nd slice (i.e. 'Hogs') explode = None fig1, ax1 = plt.subplots(1) ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.savefig('media/piechart.png',dpi=100, … -
Queries from Django unittests to Postgres are arbitrarily not being performed while staying on active mode
I'm developing ETLs with Django ORM and while running unittests either from my local env or from jenkins the query sometimes just stays active in the DB without being completed. I'm not always able to recreate the issue. I'm using Django 3.1.7 and the test are running within a Django "TestCase", so each test is running within a transaction. Im using a google cloud hosted Postgres (Postgres 12) DB server. When I run the ETL not in unittests everything runs smoothly. When run the generated query separately it work just fine and runs very fast. models.py definition for the tables: class DiseaseTarget(models.Model): id = models.AutoField(primary_key=True, db_index=True) gene = models.ForeignKey(Gene, on_delete=models.CASCADE, related_name='disease_target_gene', db_index=True) disease = models.ForeignKey(Disease, on_delete=models.CASCADE, related_name='disease_target_disease', db_index=True) dev_stage = models.TextField() class Meta: managed = True db_table = 'disease_target' unique_together = (('gene', 'disease'),) class Gene(models.Model): entity = models.OneToOneField(Entity, on_delete=models.CASCADE, primary_key=True, related_name='genes', db_index=True) symbol = models.TextField(null=True, db_index=True) class Meta: managed = True db_table = 'gene' class Entity(models.Model): id = models.AutoField(primary_key=True, db_index=True) entity_id = models.TextField(db_index=True) TYPES = [ ('cellnode', 'cell'), ('gene', 'gene'), ('geneset', 'geneset') ] type = models.TextField(choices=TYPES, db_index=True) name = models.TextField(default=entity_id) description = models.TextField(blank=True, null=True) class Meta: managed = True db_table = 'entity' index_together = [ ("id", "type"), ] unique_together = …