Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Typeerror: Metaclass conflict
I received this error via my console: it points out the problem to be this view: Please how do I solve this issue?Thanks -
how to fetch and return a template in django-javascript
I made a fetch post that includes information i need to handle on my server. So i'm doing: def prepricing(request): if request.method == "POST": if json.loads(request.body): content = json.loads(request.body) return render(request, "letter/pricing.html", { "mail":content['mail'], "name":content['name'], "content2":content['content'] }) This is what is running when the fetch post is done. Clearly this is not working. It's not returning anything. I should be doing instead: return JsonResponse(content) But I want to render that template and pass those variables. Should I return the JsonResponse and handle the template return in JavaScript? How can i do this? I just need to return that template with the values from the fetch POST. -
pytest: How to DRY up similar model manager method tests
What I have Manager and Model With the manager I can get those cases that are fulfilled, caducated or prescribed. from datetime import date class CaseManager(models.Manager): """Define a manager for Case model.""" def fulfilled(self): """Get all cases that will fulfill soon.""" return self.get_queryset().filter(fulfillment=date.today()) def caducated(self): """Get all cases that will caducate soon.""" return self.get_queryset().filter(caducity=date.today()) def prescribed(self): """Get all cases that will prescribe soon.""" return self.get_queryset().filter(prescription=date.today()) class Case(models.Model): """Representation of a legal case.""" fulfillment = models.DateField(verbose_name=_("Fulfillment"), default=date.today) caducity = models.DateField(verbose_name=_("Caducity"), default=date.today) prescription = models.DateField(verbose_name=_("Prescription"), default=date.today) objects = CaseManager() Factory Create fake cases for testing. class CaseFactory(DjangoModelFactory): """Define Case Factory""" fulfillment = Faker("date") caducity = Faker("date") prescription = Faker("date") class Meta: model = Case What I've tried Tests class TestCasesManagers: def test_fulfilled(self): case = CaseFactory(fulfillment=date.today()) assert case in Case.objects.fulfilled() def test_caducated(self): case = CaseFactory(caducity=date.today()) assert case in Case.objects.caducated() def test_prescribed(self): case = CaseFactory(prescription=date.today()) assert case in Case.objects.prescribed() Problem With this approach I have to repeat almost the same test for all the methods of my manager that are similar which is not scalable. What I want Create cases and change the keyword args that are passed to the factory to create a fake model. Call the different methods of the manager in … -
Django password form assign widget doesn't work
I'm creating a registration form for my website and everything functions, except the 'password1' and 'password2' won't recognize the widgets I assign to them. Below is a part of my code, which should be relevant to the issue from my forms.py file. Note the email part works correctly. fields = ['password1', 'password2', 'email'] widgets = { 'password1': forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Wachtwoord'} ), 'password2': forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Wachtwoord'} ), 'email': forms.EmailInput( attrs={'class': 'form-control', 'placeholder': 'E-mailadres'} ), } Below is a part of the registration.html in which the form is drawn. The top part is from the last name part which functions normally, the bottom part is from password1 which doesn't function: <div class="col-md-6"> <label for="last_name" class="text-info"> {{lid_form.last_name.label}}</label> {{lid_form.last_name}} </div> </div> <div class="row"> <div class="col-md-6"> <label for="password1" class="text-info"> {{user_form.password1.label}}</label> {{user_form.password1}} </div> Picture Example -
I want to display random blog views so that users will see different types of posts not according to time uploaded
I want my users to be able to view little info of other posts while in one but I don't get on how to make it work. Here is my views.py def blog_detail_view(request, slug): template_name = 'blog_details.html' instance = get_object_or_404(Blog, slug=slug) initial_data = { 'content_type':instance.get_content_type, 'object_id': instance.id, } share_string = quote_plus(instance.Content) #latest_blog_list = Blog.objects.order_by("?").first()[:5] latest_blog_list = Blog.objects.random().order_by('-publish_date')[:5] context = {'blog' : instance, "latest_blog_list":latest_blog_list, "share_string": share_string} return render(request, template_name, context) Here is my models.py file too from django.db import models from django.db.models.signals import post_save from django.utils import timezone from django.dispatch import receiver app_name='blog' # Create your models here. class Blog(models.Model): Your_Post_Title = models.CharField(max_length=2000) slug = models.SlugField(unique=True) publish_date = models.DateTimeField(auto_now_add=True) Content = models.TextField() def __str__(self): return self.slug If anyone can help me, with would be greatly appreciated -
How to make a like button with jquery inside a form so that it will save it to database and also change the style of like button?
I am working on a django project and I want to add a like button to the posts. this is my template: <form action="{% url 'like' post.id %}" method="GET" name="liked" class="l-form"> {% csrf_token %} <button style="display: inline;" class="like__btn"> <i class="like__icon fa fa-heart" style="display: inline;"></i> </button> </form> <script> $('.like__btn').on('click', function(){ $('.like__icon.fa-heart.fa').toggleClass("liked"); }); </script> All I want to do this, when user clicks on a heart icon, it will submit the form. But also change the icon color to red. (liked class is basically, color:red) When I click on the button it submits the form, increases the like count, but then it refreshes the page so my heart icon doesn't stay red. If I add type="button" this time it doesn't refresh the page, change the color of the icon but doesn't submit the form. I tried to do another button to submit the form and make it hidden but whenever the form is submitted it refreshes the page and goes back to the white heart. Also tried to return false; in jquery but it doesn't submit the form again. I am stuck for hours, so any advice would be great! -
Should race conditions be handled in form or view?
Lets suppose I have to withdraw money from a specific wallet object. So I first check if x amount of money is in wallet.. Then I lock wallet object in form clean() method, then check it. If the wallet has enough money, form is valid and we proceed to the view. In the view the withdraw action happens but in the view, the wallet object won't be locked anymore.. If two threads manage to reach to the view at the same time, race condition may occur. should the transfer action happen in the clean() form method where the wallet object will be locked or validate the amount of money of the wallet in the view? -
Hello, I need update delete and read function in my code
#1. Read Function should open the image in XL size and there should be a item name and item price and description should appear. #2. When i click order, the row data (data which is there in that row-id) in the table should be stored in other database. Picture shows the Views, URL, HTML, Model, Pitures https://photos.app.goo.gl/v1b8PU9m1vFH8RxZ6 -
How to prevent websockify process spawned by Django process does not get killed when restarting UWSGI?
I have the following oversimplified code: def openvnc_connection(request): Popen(['websockify', ...]) ... Problem is when I deploy the code, involves restarting the uwsgi service, the websockify process gets killed as well, resulting any active vnc connection gets dropped. I am aware the websockify process is the child of the django process and it gets killed because of that. I have tried the double-fork or similar stuff like detaching the child process but they don't seem to work. -
limit_choices_to with Q objects not working in production
I have these models where a Person can be a player, and if so, can be added to a team. I had the following code working in development, but in production it raises the error (requirements are exactly the same, but production as python 3.6.9 and development has python 3.7.3): Cannot resolve keyword 'is_active' into field. Choices are: players, < and the remaining fields of Team> The code models.py class Role(models.Model): role = models.CharField(max_length=30, verbose_name='Função') is_active = models.BooleanField(default=True, blank=False, null=False, verbose_name='Ativo') class Person(models.Model): name = models.CharField(max_length=150, verbose_name='Nome Próprio') roles = models.ManyToManyField(Role, blank=True, verbose_name="Funções") is_active = models.BooleanField(default=True, blank=False, null=False, verbose_name='Ativo') #...other non relevant fields class Team(models.Model): #...other non relevant fields players = models.ManyToManyField('Person', blank=True, verbose_name='Jogadores', limit_choices_to=Q(roles__role__startswith='player', roles__is_active=True, is_active=True )) # The above Q means Person's whose role starts with 'player' AND the role is active AND the Person is also active This works great in development but not in production... Any tips? Thanks! EDIT: Production server is an EC2 instance, with gunicorn, nginx and postgres, it was working ok before -
Why is the Django Admin bad for multiple users
I'm trying to find out why Django Admin is bad to use for users around > 10000 users and why people insists that I should serialize with for example Django REST API and use JavaScript on frontend to handle the data. Why is that? Why do I need to focus on that when the Django Admin is functioning well enough for my and the users needs? -
Is it possible to create an alias for deep joins/relationships?
I am adding some functionality to an app where a user can sort records in a table on the frontend (react) by passing additional url parameters to the backend. We use this in several places, and have a Mixin for pagination. In the pagination mixin I have the following: def get_queryset(self): order_by_field = self.request.GET.getlist("order_by") if order_by_field: return super().get_queryset().order_by(*order_by_field) else: return super().get_queryset() This works great, I can pass urls like {app_base_path}/{some_resource}/?order_by=title to get it to sort the returned query set by the queried model's title field. It also works with multi-sort (e.g. {app_base_path}/{some_resource}/?order_by=title&order_by=date). However, this looks very ugly and reveals unneccessary information to the end user for deeply nested relationships. For instance if I want to sort by a related field through an intermediary table: {app_base_path}/{some_resource}/?order_by=intermediary_model__related_model__field_of_interest. Is there a way I can make this nested relationship an alias on the model I am querying? Something like: class MyModel(models.model): # other model fields, etc. @property def alias(): return "intermediary_model__related_model__field_of_interest" -
Cannot resolve keyword 'last_activity' into field
As title says I was trying to sort a list of posts using the django order_by method and since the field I used was later added to the list (The field was not created inside the model) it failed. Is there anything I can do about it other than adding the field to the model which is something I really don't wanna do? Here is the model code class post(models.Model): title = models.CharField(max_length=236) content = models.TextField() post_board = models.ForeignKey(board, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) release_date = models.DateField(auto_now_add=True) views = models.IntegerField(default=0) def __str__(self): return self.title The function that adds the extra field: def forumdisplay(request, boardslug=None): context = { 'board': None } if boardslug: context['board'] = board.objects.all().filter(slug=boardslug).first() if context['board']: context['posts'] = post.objects.all().filter(post_board=context['board']) for eachpost in context['posts']: eachpost.reply_count = len(reply.objects.all().filter(reply_to=eachpost)) eachpost.last_activity = eachpost.release_date if eachpost.reply_count: eachpost.last_activity = reply.objects.all().filter(reply_to=eachpost).order_by('release_date').first().release_date context['posts'] = context['posts'].order_by('last_activity') alter_posts(context['posts']) else: pass return render(request, "board/forumdisplay.html", context) The error I got: Request Method: GET Request URL: http://127.0.0.1:8000/forumdisplay/news/ Django Version: 3.0.4 Exception Type: FieldError Exception Value: Cannot resolve keyword 'last_activity' into field. Choices are: author, author_id, content, id, post_board, post_board_id, release_date, reply, title, views``` -
React/Django: how to get label of models.TextChoices in React
I have the following Model in Django: class Expense(models.Model): class ExpenseTypes(models.TextChoices): FOOD = 'FOOD', 'Food' HOUSE = 'HOUS', 'Home' SPORT = 'SPRT', 'Sport and exercices' TRANSPORT = 'MOVE', 'Transportation' EVERYDAY = 'EVER', 'Everyday Expenses' ENTERTAINMENT = 'ENTE', 'Entertainment' CLOTHING = 'CLOT', 'Clothes' INVESTMENTS = 'INVE', 'Investments' EDUCATION = 'EDUC', 'Education' SAVING = 'SAVE', 'Saving' HOLIDAYS = 'HOLI', 'Holidays' DEBT = 'DEBT', 'Debt' TAXES = 'TAXS', 'Taxes' user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=32) amount = models.DecimalField(max_digits=10, decimal_places=2) expense_type = models.CharField( max_length=4, choices=ExpenseTypes.choices, default=ExpenseTypes.FOOD, ) time = models.DateTimeField(default=timezone.now) with a simple serializer and view: class ExpenseSerializer(serializers.ModelSerializer): class Meta: model = Expense fields = ('id', 'user', 'title', 'amount', 'expense_type', 'time') class ExpenseViewSet(viewsets.ModelViewSet): queryset = Expense.objects.all() serializer_class = ExpenseSerializer authentication_classes = (TokenAuthentication, ) permission_classes = (IsAuthenticated,) In React when I fetch the Data: const [expenses, setExpenses] = useState<Expense[]>([]); useEffect(() => { function formatExpense(expense: any): Expense { return { id: expense.id, title: expense.title, amount: expense.amount, user: expense.user, type: expense.expense_type, time: new Date(expense.time), }; } async function loadExpenses() { try { const response = await fetch("http://127.0.0.1:8000/api/Expenses/", { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'xxx' } }) const Expenses = await response.json() setExpenses(Expenses.map((expense: any) => formatExpense(expense))); } catch (err) { console.log(err); }; } loadExpenses(); }, … -
Invalid block tag on line 11: 'endblock'. Did you forget to register or load this tag?
Invalid block tag on line 11: 'endblock'. Did you forget to register or load this tag? 1 {% extends 'base.html'%} {%block title%}{{post.title}}{%endblock%}{%block 2 content%} 3 <h1>{{post.title}}</h1> 4 5 <small>Written by: {{post.author}}</small> 6 <br /> 7 <hr /> 8 {{post.body}} 9 <br /> 10 <a href="{% url 'home'%}" class="btn btn-success">Back</a> 11 {%endblock%} 12 -
Get related field names in serializer when ForeignKey is pointed to 'self'
I have a category model which has a field parent. This field can be null, and point to other categories from the same model. I'm having trouble serializing the category, and getting a list of its children using django rest framework. models.py class Category(models.Model): ... name = models.CharField( _('category name'), max_length=255, unique=True ) slug = models.SlugField( _('slug'), max_length=50, help_text=_( 'A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs.' ), ) parent = models.ForeignKey( 'self', on_delete=models.CASCADE, related_name='category', blank=True, null=True ) ... serializers.py class CategoryChildrenSerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() class Meta: model = Category fields = ['children'] def get_children(self, instance): if instance.parent is not None: queryset = Category.objects.filter(parent=instance.parent.id) return queryset class CategoriesNavigationSerializer(serializers.ModelSerializer): children = CategoryChildrenSerializer(many=True, read_only=True) class Meta: model = Category fields = ('name', 'children') Ideally i want the response to look something like: { name: Category 1, children: [ { name: Category 2, slug: ... }, { name: Category 3, slug: ... }, ] } It also important to note that i want to stop on the second child level, even if the parent has grandchildren. I have tried children = serializers.StringRelatedField(source='parent', read_only=True) and also doing the get_children method inside the … -
Can you put a context list inside a context in Django and cycle through it?
Currently, my project is taking grouped, query-sorted posts and displaying a for loop of each one. It is a hassle to put down every single for loop. I want to cycle through all the context without copy-and-pasting them in Jinja2. Can I do something like this? parent_context = { 'context': child_context } child_context = { 'object1': object1, 'object2': object2, ... } -
React Native API request
I'm using Django Rest Framework in my React Native App, so I'm fetching some data, but one field of that data is a foreign key. How can I retrieve that foreign keys data? item.owner displays http://127.0.0.1:8000/api/users/90/ but I want it to be the owners name which I guess needs to be fetched again. const renderItem = ({item}) => ( <> <Text>{item.owner}</Text> <Text>{item.title} : {item.category}</Text> <Image source={{uri:item.book_pic_src}} /> </> -
How to Navigate from other pages to index page specific tag?
I have multiple Options on navbar i.e home team contact store etc. So I have question that if I visited the store page and I want to come back to index.html on a specific tag like team how will I do that? I tried the following code but it didn't work for me base.html <li class="nav-item"> <a class="nav-link" href="{% url 'home:index'%}#team">Team</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'home:index'%}">Testimonial</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'home:index'%}#contact">Contact</a> </li> -
How do I make another variable available in views?
I am trying to add another section to a webpage. the first half works but I cant get the second half to render. The first half runs of a function called pageFour, it has a variable for blog. I created another function called pageFourBlogs that defines a variable for blogs. However it is still not showing up, what am I doing wrong? Thanks in advance for your efforts. urls.py from django.shortcuts import render, get_object_or_404 from .models import Blog def all_blogs(request): blogs = Blog.objects.order_by('?') return render(request, 'blog/all_blogs.html', {'blogs': blogs}) def Entertainment(request): blogs = Blog.objects.filter(category='Entertainment') return render(request, 'blog/Entertainment.html', {'blogs': blogs}) def Technology(request): blogs = Blog.objects.filter(category='Technology') return render(request, 'blog/Technology.html', {'blogs': blogs}) def Culture(request): blogs = Blog.objects.filter(category='Culture') return render(request, 'blog/Culture.html', {'blogs': blogs}) def pageOne(request, blog_id): blog = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/pageOne.html', {'blog': blog}) def pageTwo(request, blog_id): blog = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/pageTwo.html', {'blog': blog}) def pageThree(request, blog_id): blog = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/pageThree.html', {'blog': blog}) def pageFour(request, blog_id): blog = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/pageFour.html', {'blog': blog}) def pageFourBlogs(request): blogs = Blog.objects.order_by('?') return render(request, 'blog/pageFour.html', {'blogs': blogs}) pageFour.html {% extends 'blog/navBarFooter.html' %} {% block content %} <h1 class="text-center mt-3" id="blogdetailtitle">{{ blog.title }}</h1> <h5 class="text-center mt-3" id="blogdetailtitle">By: {{ blog.by }} | {{ … -
Django Plotly Dash
I have learned plotly and Dash, which are data visualisations library in python. Though i have got their core concepts and also i am well versed in django python as well, i dont know to integrate dash and plotly in django rest framework. I have searched everywhere but it seems there is a lack of resources on this topic. I want to create a dashboard using the same , just like we create dashboards using front end languages. Please help, i have been searching but not able to get any resources for help. -
DRF - api that lists nested objects but accepts foreign keys during creation
I'm fresh in drf and django overall but i'm working on application that uses drf as backend and react as fronted And currently i'm struggling with crated model serializer for transactions that will allow me to serialize nested objects on GET requests (as i need to refere to is eg. names to show in table) and create transaction with provided foreign keys(creating vie form with dropdowns), as reference to related child objects. Im wondering what would be best approach to achieve it, so for i consider: creating separate fields for getting and saving objects customising create method on view /and serilizer creating separate serializers for listing and creating transaction object I've done some research in drf documentation and here, but so far couldn't find any solutions that would meets\ my needs or be simple enough. Could you give me any advice? Now I'm getting the following error { "category": [ "This field is required." ], "tag": [ "This field is required." ], "transaction_type": [ "This field is required." ], "payment_target": [ "This field is required." ], "payment_source": [ "This field is required." ] } views.py class BaseViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin): """ A simple base viewset for creating and editing """ authentication_classes … -
Unable to set up SSL for Django in Docker
I have a django app which will be run using waitress and nginx is used for reverse proxy. Now i need to enable ssl for the site (localhost as of now). The certificates are self signed and i'm unable to enable ssl for the site. Docker doesn't start nginx with error : nginx: [emerg] "ssl_certificate" directive is not allowed here in /etc/nginx/conf.d/django.conf:22 Tried with most of the solutions available and failed.I'm novice to docker. Any sort of help is really appreciated. folder structure : docker-compose.yml file : version: '3' services: nginx: image: nginx:alpine container_name: ng01 ports: - "443:443" volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - ./webapp/static:/static - ./certs:/etc/ssl depends_on: - web networks: - nginx_network web: build: . command: python ./webapp/server.py volumes: - .:/code - ./webapp/static:/static networks: - nginx_network networks: nginx_network: driver: bridge django.conf file : upstream web { ip_hash; server web:443; } client_max_body_size 100M; server { listen 80; server_name localhost; return 301 https://$server_name$request_uri; } server { listen 443 ssl; server_name localhost; location /static { alias /static; } location / { proxy_pass https://web/; ssl_certificate /etc/ssl/localhost.crt; ssl_certificate_key /etc/ssl/localhost.key; add_header Strict-Transport-Security "max-age=31536000" always; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 900; proxy_send_timeout 900; proxy_read_timeout 900; } } Dockerfile : FROM … -
Can't communicate between django and selenium docker containers
I'm trying to setup a CI environment where I can test my Django application with selenium where both are running in docker. My test is setup with the following: from time import sleep from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium.webdriver.remote.webdriver import WebDriver class MySeleniumTests(StaticLiveServerTestCase): port = 8000 @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver("http://selenium:4444", desired_capabilities={'browserName': 'chrome'}) cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() def test_login(self): self.selenium.get('%s:%s%s' % ('http://web', self.port, '/')) greeting = self.selenium.find_element_by_id("greeting") self.assertEqual(greeting.text, 'hello world') I then try to run this on gitlab with this CI setup in my .gitlab-ci.yml: image: name: docker/compose:1.26.2 entrypoint: ['/bin/sh', '-c'] services: - docker:dind variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 stages: - test before_script: - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY build: stage: test script: - docker build --tag django . - docker network create selenium-net - docker run -d --network selenium-net --name selenium selenium/standalone-chrome:4.0.0-alpha-6-20200730 - docker run --network selenium-net --name web --expose 8000 django dindselenium/manage.py test myapp On my local machine the connection WebDriver setup succeeds but then Selenium fails to connect to the web app. On the CI environment I can't even connect to Selenium from the web app. I've setup an example repo here: https://gitlab.com/oskarpersson/dind-selenium/, and an example of a failing job: https://gitlab.com/oskarpersson/dind-selenium/-/jobs/705523165 -
Djanogo CoinMarketCap API is not updating prices(django.db.utils.OperationalError: database is locked)
I have a website that displays cryptocurrency prices with an SQLite db but unfortunately the prices have stopped updating for some reason. I get an django.db.utils.OperationalError: database is locked error when I run coin_update.py I tried adding 'OPTIONS': { 'timeout': 20, } to my settings.py but the error presists This is what my coin_update.py file looks like: import os, django, sys os.environ['DJANGO_SETTINGS_MODULE']='website.settings' django.setup() import datetime print("Cron Script for coinmarketcap API initialized") from requests import Session from requests.exceptions import ConnectionError, Timeout, TooManyRedirects import json from cryptocracy.models import Coin, CoinHistory url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest' parameters = { 'start': '1', 'limit': '5000', 'convert': 'USD', } headers = { 'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': 'aa817498-b4b3-48da-9774-eb54c26d846b', } session = Session() session.headers.update(headers) try: response = session.get(url, params=parameters) data = json.loads(response.text) coin_data=data except (ConnectionError, Timeout, TooManyRedirects) as e: print(e) coin_data=e integrity_error_count=0 api_length=len(coin_data['data']) for coin in coin_data['data']: update_coin=Coin.objects.filter(ticker=coin['symbol']) if update_coin: is_coin=True if coin['quote']['USD']['percent_change_24h']: change24h=coin['quote']['USD']['percent_change_24h'] else: change24h=0 if coin['quote']['USD']['volume_24h']: volume=coin['quote']['USD']['volume_24h'] else: volume=0 if coin['quote']['USD']['price']: price=coin['quote']['USD']['price'] else: price=0 if coin['circulating_supply']: supply=coin['circulating_supply'] else: supply=0 if coin['max_supply']: max_supply=coin['max_supply'] else: max_supply=0 if coin['total_supply']: total_supply=coin['total_supply'] else: total_supply=0 if coin['quote']['USD']['market_cap']: market_cap=coin['quote']['USD']['market_cap'] else: market_cap=0 if coin['platform']: is_coin=False save_history=update_coin[0] CoinHistory.objects.create(coin=save_history, price=save_history.price, supply=save_history.supply, volume=save_history.volume, total_supply=save_history.total_supply, max_supply=save_history.max_supply, market_cap=save_history.market_cap, change24h=save_history.change24h) update_coin.update(price=price, supply=supply, volume=volume,total_supply=total_supply, max_supply=max_supply, market_cap=market_cap, change24h=change24h) else: integrity_error_count=integrity_error_count+1 continue print("There are " + …