Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run node things in docker (Django, Angular)
A have a frontend(angular) project inside a backend(django) project with this structure [structure][1] compose.yml services: db: image: postgres:13-alpine container_name: db restart: always env_file: .env.dev environment: - POSTGRES_HOST_AUTH_METHOD=trust - POSTGRES_USER=stage - POSTGRES_PASSWORD=stage - POSTGRES_DB=stage volumes: - postgres_data:/var/lib/postgresql/data/ web: build: context: . dockerfile: Dockerfile image: web container_name: web env_file: .env.dev environment: - POSTGRES_USER=stage - POSTGRES_PASSWORD=stage - POSTGRES_DB=stage restart: always volumes: - ./:/leostudy links: - db depends_on: - db ports: - "8000:8000" command: "python manage.py runserver 0.0.0.0:8000" redis: image: "redis:alpine" expose: - 6379 celery: restart: always build: context: . command: celery -A students worker -l info env_file: - ./.env.dev volumes: - ./:/leostudy/ depends_on: - db - redis - web volumes: postgres_data: Dockerfile # set work directory WORKDIR /proj # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev libffi-dev openssl-dev RUN apk --update add \ build-base \ jpeg-dev \ zlib-dev # install dependencies COPY ./requirements.txt . RUN pip install --upgrade pip \ && pip install -U pip setuptools \ && pip install -r requirements.txt # copy project COPY . . # run entrypoint.sh RUN ["chmod", "+x", "./entrypoint.sh"] ENTRYPOINT ["./entrypoint.sh"] So, I need to somehow build static with gulp … -
Django for loop data not displaying in template
I am not saving data in my data base. I am using an api service and I don't want to to save those api data in my data base. I just want to display those data in my html template. The problem only first data of for loop showing in template where I can see all for loop data from my terminal. I want to display my all for loop data in my html template. here is my code: views.py: for i in results[search_type]: if search_type == "organic_results": title = i["title"] print(title) context = {"title":title} I know I can use append method but it's showing all data together in my template as list. I want to so theme in my template using for loop like this: html {%for i in title %}{{i}}{%endfor%} my terminal result: Facebook - Log In or Sign Up https://www.facebook.com/ Newsroom | Meta - Facebook https://about.fb.com/news/ Facebook - Apps on Google Play https://play.google.com/store/apps/details?id=com.facebook.katana&hl=en_US&gl=US Facebook - Wikipedia https://en.wikipedia.org/wiki/Facebook Facebook Careers | Do the Most Meaningful Work of Your ... https://www.facebookcareers.com/ Facebook - Twitter https://twitter.com/facebook why only first data of for loop showing in my template? -
django.db.utils.OperationalError: fe_sendauth: no password supplied despite having supplied password in settings.py
I am trying to do python manage.py migrate to do migrations for my django app but i keep getting this error even though i have supplied the db name, user, password in settings.py. Any help will be appreciated. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'accountant', 'USER': 'json', 'PASSWORD': '******', 'HOST': 'localhost', 'PORT': '5432' } } Full stacktrace: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/loader.py", line 47, in __init__ self.build_graph() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/loader.py", line 191, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/backends/base/base.py", line 162, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/backends/base/base.py", line 135, in _cursor self.ensure_connection() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/utils.py", line 98, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/backends/base/base.py", line 130, in … -
Middleware in django keeps redirecting, visiting admin-site not possible
I am writing a django project where I need to separate the pages and the accounts. Do to so, I wrote a LoginCheckMiddleWare. The problem is that I am not able to visit the django-admin site anymore, because it keeps redirecting me. I don't what I did wrong. I also have an EmailBackEnd.py file, that I use for logging in with the email and not the username. LoginCheckMiddleWare.py from django.http.response import HttpResponseRedirect from django.urls import reverse from django.utils.deprecation import MiddlewareMixin class LoginCheckMiddleWare(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): modulename = view_func.__module__ user = request.user if user.is_authenticated: if user.user_type == '1': if modulename == 'user.views' or modulename == 'django.views.static': pass elif modulename == 'user.log_views': pass else: return HttpResponseRedirect(reverse('user:admin_index')) elif user.user_type == '2': if modulename == 'instructor.views' or modulename == 'django.views.static': pass elif modulename == 'user.log_views': pass else: return HttpResponseRedirect(reverse('instructor:instructor_index')) elif user.user_type == '3': if modulename == 'student.views' or modulename == 'django.views.static': pass elif modulename == 'user.log_views': pass else: return HttpResponseRedirect(reverse('student:student_index')) else: return HttpResponseRedirect(reverse('user:login_user')) else: if request.path == reverse('user:login_user') or modulename == 'django.contrib.auth.views': pass else: return HttpResponseRedirect(reverse('user:login_user')) EmailBackEnd.py from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model class EmailBackEnd(ModelBackend): def authenticate(self, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: … -
django multiple form separated in the html, merge again with submit
there is a formmodel like: class foo(forms.ModelForm): a = forms.BooleanField(label='a', required=False) b = forms.BooleanField(label='b', required=False) c = forms.BooleanField(label='c', required=False) d = forms.BooleanField(label='d', required=False) e = forms.BooleanField(label='e', required=False) f = forms.BooleanField(label='f', required=False) g = forms.BooleanField(label='g', required=False) h = forms.BooleanField(label='h', required=False) #... further there are multiple instances of foo in a list: L = [] L.append(foo(instance=object_1)) L.append(foo(instance=object_2)) L.append(foo(instance=object_3)) #... L.append(foo(instance=object_n)) this is shown on the html in different tables in different columns. The problem now is to send the data back correctly with subbmit. I have to put the tables and lines back together correctly. I was thinking of something like this: <form class="form-inline" action ="{% url 'bla:blo' %}" method="post"> Table #1 | ID of Form | Value #1 | Value #2 | Value #3 | Value #4 | | ---------- | -------- | -------- | -------- | -------- | <form id=1>| 1 | a1 | b1 | c1 | d1 |</form> <form id=2>| 2 | a2 | b2 | c2 | d2 |</form> <form id=3>| 3 | a3 | b3 | c3 | d3 |</form> <form id=4>| 4 | a4 | b4 | c4 | d4 |</form> Table #2 | ID of Form | Value #1 | Value #2 | Value … -
Django correct way to place form in template
this is my test model form class FieldForm(forms.ModelForm): class Meta: model = Field fields = ( 'title', 'url', ) It has two fields but for design reasons I need each input in a seperate DIV in the template like so (just an example) <form> <div> <input spellcheck="false" autocorrect="off" type="email" required="" name="re_email"> </div> <div> <input spellcheck="false" autocorrect="off" type="email" required="" name="re_email"> </div> </form> When I just add {{ form }} every input is in the form without a surrounding container. What is there correct way 2022 (not a Django 1.1 or 2016 tutorial) to place inputs manually in the template and then connect it with the model? -
AttributeError: type object 'x' has no attribute 'view'
i'm doing a project and I'm trying to incorporate the spotify API with it. Anyhow, i'm receiveing this error and really don't know how to get past it. Thanks in advanced, here is the code from views.py: from django.shortcuts import render from .credentials import REDIRECT_URI, CLIENT_SECRET, CLIENT_ID from rest_framework.views import APIView from requests import Request, post from rest_framework import status from rest_framework.response import Response class AuthURL(APIView): def get(self, request, format=None): scopes = 'user-read-playback-state user-modify-playback-state user-read-currently-playing' url = Request('GET', 'https://accounts.spotify.com/authorize', params={ 'scope': scopes, 'response-type': 'code', 'redirect_uri': REDIRECT_URI, 'client_id': CLIENT_ID }).prepare().url return Response({'url': url}, status=status.HTTP_200_OK) Here's the code of urls.py: from django.urls import path from .views import AuthURL urlpatterns = [ path('get-auth-url', AuthURL.view()), ] -
Can I override default CharField to ChoiceFoeld in a ModelForm?
I have a (horrible) database table that will be imported from a huge spreadsheet. The data in the fields is for human consumption and is full of "special cases" so its all stored as text. Going forwards, I'd like to impose a bit of discipline on what users are allowed to put into some of the fields. It's easy enough with custom form validators in most cases. However, there are a couple of fields for which the human interface ought to be a ChoiceField. Can I override the default form field type (CharField)? (To clarify, the model field is not and cannot be constrained by choices, because the historical data must be stored. I only want to constrain future additions to the table through the create view). class HorribleTable( models.Model): ... foo = models.CharField( max_length=16, blank=True, ... ) ... class AddHorribleTableEntryForm( models.Model) class Meta: model = HorribleTable fields = '__all__' # or a list if it helps FOO_CHOICES = (('square', 'Square'), ('rect', 'Rectangular'), ('circle', 'Circular') ) ...? -
React GET request from Django API is not working and how to solve this?
I am trying to build django-react application. I used netlify for react deployment and herokuapp for django api deployment. My api endpoint is working perfectly but my react can't fetch them from the actual endpoint. In localhost it fetch from my actual api [ http://cylindercommerce.herokuapp.com/api/products/ ] but in production it is trying to fetch from it's own url then end point [https://modest-knuth-50c56b.netlify.app/api/products] this one but it should fetch from [http://cylindercommerce.herokuapp.com/api/products/] this endpoint. I didn't change any code. so what is the problem here check the screenshot here -
How can I customize image properties in ckeditor using django
I want when I click on upload images I am directed directly to select images rather than being shown image properties box. Kindly help -
How do I update the records stored in my db using an html form as input?
I am very new to django and I have made an app that displays a different timetable for different user. I am stuck at this point where I can delete the records stored in my db but I am unable to update them through my html form. Is there a way to do this? Here are my files, models.py from pickle import TRUE from django.db import models from datetime import date from django.conf import settings class Timetable(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default = "", on_delete=models.CASCADE) subject = models.CharField(max_length=100) room_no= models.IntegerField() date = models.DateField(default=date.today) time = models.TimeField() semester = models.TextField() day = models.CharField(max_length=10, default="") views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm from django.contrib.auth.decorators import login_required from .models import Timetable # Create your views here. def register(request): if request.method=='POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created, you are now able to login!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def tt(request): if request.user.is_authenticated: tt = Timetable.objects.filter(user=request.user).order_by('day') return render(request, 'users/time_table.html', {'tt': tt}) else: return render(request, 'homepage/home.html') @login_required def tt_add(request): return render(request, 'users/tt_add.html') @login_required def newPage(request): user=request.user sem = request.POST.get("semester") sub = request.POST.get("subject") room_no = … -
Conditional query in django [closed]
Am worried that it may cause any problem, as am using conditional querying paramters. Here is my query: data = Project.objects.filter(user=user if user.role == 1 else user.staff_to_id) In this, staff_to_idis just a self reference to a user to represents that this is a staff. So if Role == 1 then Projects will be fetched using "user" and when Role == 2 or something else it will Project will be fetched using "user.staff_to_id" Is this a bad practice ? -
Revisions not creating in TestCase ( Django, django-reversion, tests)
Trying to cover with tests django-reversion functionality for my model, but versions are not created in test db, in manual creation from admin interface everything works fine. Model: @reversion.register() class RuleSet(ModeratedBase, AdminUrlMixin): """Ruleset of a given type of contest related to the contest""" name = models.CharField( max_length=64, help_text="Short name of the ruleset.", unique=True ) rules = models.JSONField( default=dict, help_text="Base rules dict for Ruleset", blank=True, null=True, ) default_for = models.ManyToManyField( "ci_contest.ContestType", help_text="Field specifies content types ruleset is default for", related_name="default_ruleset", null=True, blank=True, ) def __str__(self): return self.name def get_versions(self): return Version.objects.get_for_object(self) Test: class RulesetTestCase(TestCase): fixtures = ["core-defaults", "gamer-defaults", "ledger-defaults", "contest-defaults"] def setUp(self): call_command("createinitialrevisions") self.ruleset = RuleSetFactory() def test_ruleset_get_versions(self): self.assertFalse(self.ruleset.get_versions().exists()) self.ruleset.rules = str(fake.pydict()) self.ruleset.save() print(self.ruleset.get_versions()) self.assertTrue(self.ruleset.get_versions().exists()) Print Output: <VersionQuerySet []> -
I get an error when installing django with pipenv
I am trying to install django=4.0.1 on my mac with pipenv. (1) my python: /usr/bin/python3 (3.7.3) (2) my pipenv version: version 2022.1.8 (3) I just updated 'pip' But I get a message below [pipenv.exceptions.InstallError]: ERROR: Could not find a version that satisfies the requirement django==4.0.1 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 1.11.13, 1.11.14, 1.11.15, 1.11.16, 1.11.17, … -
Django python manage.py runserver is giving an error [closed]
I haven't been running my django project, which runs smoothly, for a month now. Now python manage.py i get these errors when i run runserver. What should I do? enter image description here -
Problem to transfer data from Django template to vue.js app
I am trying to make Django and Vue talk. I installed Vue-Cli with Vue3. Vue app is well displayed into the Django template, but I can't transfer data (Django data but also a simple string for testing) to the vue app. App.vue <template> <h1>{{ msg }} world</h1> </template> <script> export default { name: 'App', props: { msg: { type: String, default: 'test' } } } </script> <style scoped> </style> main.js import { createApp } from 'vue' import App from './App.vue' createApp(App).mount('#app') This code shows "test world", instead of "Hello world". Thank you in advance for your help. -
How to add an image along with a post in Django from the admin panel so it'll show in my templates
I created a model for the post, I don't have issues with the body(blog post)but with the images how should I do it such that it'll reflect at the template class Post(models.Model): title = models.CharField(max_length=100) body = models.CharField(max_length=1000000) created_at = models.DateTimeField(default=datetime.now, blank=True) posted_by = models.CharField(max_length=50, default=False) image1 = models.ImageField(upload_to='images/', default=False) image2 = models.ImageField(upload_to='images/', default=False) image3 = models.ImageField(upload_to='images/', default=False) def __str__(self): return str(self.title) -
Object of type Response is not JSON serializable in rest framework
I'm trying to call one method response into another method in Django rest framework. views.py: @api_view(['GET','POST']) def GetCurrentRunningActivityForAudit(request, UserID): if request.method == 'GET': print("current running activity--userid--", UserID) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,)) result_set = cursor.fetchall() data = [] for row in result_set: TaskId=row[0] TaskName = row[1] Source = row[2] SID = row[3] type = row[4] data.append({ "TaskId": TaskId, "TaskName":TaskName,"Source":Source, "SID":SID, "type":type, "IsActive":GetCurrentSubTaskSTatus(TaskId)}) return Response(data[0]) return Response(data) I'm passing this method response to the above method response i.e.,. GetCurrentRunningActivityForAudit but it's show as Object of type Response is not JSON serializable def GetCurrentSubTaskSTatus(taskid): cursor = connection.cursor() cursor.execute('EXEC [dbo].[USP_GetCurrentTaskStatus] @taskid=%s',(taskid,)) result_set = cursor.fetchall() for row in result_set: IsActive =row[0] return Response({"IsActive":IsActive}) -
Why does bitbucket pipeline not find tests that run inside local docker container?
I have a repo that holds two applications, a django one, and a react one. I'm trying to integrate tests into the pipeline for the django application, currently, the message I'm getting in the pipeline is: python backend/manage.py test + python backend/manage.py $SECRET_KEY System check identified no issues (0 silenced). --------------------------------------------------------------- Ran 0 $SECRET_KEYS in 0.000s However, running the same command in my local docker container finds 11 tests to run. I'm not sure why they aren't being found in the pipeline My folder structure is like this backend/ - ... - app/ -- tests/ - manage.py frontend/ - ... bitbucket-pipelines.yml and my pipelines file: image: python:3.8 pipelines: default: - parallel: - step: name: Test caches: - pip script: - pip install -r requirements.txt - python backend/manage.py test -
Django custom editable email template with variable and saving db by users
I have started to learn 3 month ago django and I am newbie. I couldn't find thing anywhere that I want to do. I want to make custom email template form to editable and savable to db but at the same time user can use variable when create email template. How could I do that ? Thank you. enter image description here -
how to generate random passwords that change every 24 hours in Django
I'm trying to create a Django application in which only people with a pin number can enter. Is there a way in Django to generate a random pin every 24 hours and make this pin appear in the admin panel. -
How to fix "ERROR: Command errored out with exit status 1:" when I try to install web3
When I try to install web3, there is a error. How can I fix? enter image description here Thanks everybody for the support! -
Disabling and reassigning a new django token
I am planning to use "RestFrame TokenAuthentication" for django API requests. I want to give the Bearer Token to my client for accessing the API. The token needs to be disabled based on payment module. On a succesful payment, i needs to create a new token programatically and give it to the client. Is it possible to deactivate and renew with a new token when necessary ? Is it the best practice to use "RestFrame TokenAuthentication" for such a scenario ? -
Django: Create a Model from parsing a different model's field
I have a model A with several fields. One of the fields ("results") is a a dict-like string in my database (which is hardly readable for a human being). Can I create a separate Model that would basically parse that "results" field into its own fields, so I can have a separate table with fields corresponding to the keys and values from my "results" field from model A? Final goal is to make a Results table that shows all the information in a pretty and easy-to-read manner. class ModelA(models.Model): language = models.CharField(max_length=30) date = models.DateTimeField() results = models.CharField(max_length=255) This is how "results" field looks in my database (I cannot change this format): OrderedDict([('Name', 'Bob'), ('Phone', '1234567890'), ('born', '01.01.1990')]) I want to create something like this: class Results(models.Model): name = model.Charfield(max_length=100) phone= model.IntegerField() born = model.DateTimeField() What is the best way to do this? How do I take the info from the "results" field from ModelA and "put" it into the Results model? -
WSGIRequest is not callable 'blockchain project'
I'm working on a blockchain project, but I had a problem that I could not solve myself, and here I share all the details of the project. Mining a new block def mine_block(request): if request.method == 'GET': previous_block = blockchain.get_last_block() previous_nonce = previous_block['nonce'] nonce = blockchain.proof_of_work(previous_nonce) previous_hash = blockchain.hash(previous_block) blockchain.add_transaction(sender = root_node, receiver = node_address, amount = 1.15, time=str(datetime.datetime.now())) block = blockchain.create_block(nonce, previous_hash) response = render(request({'message': 'Congratulations, you just mined a block!', 'index': block['index'], 'timestamp': block['timestamp'], 'nonce': block['nonce'], 'previous_hash': block['previous_hash'], 'transactions': block['transactions']})) return render(JsonResponse(response)) ``` # Getting the full Blockchain ``` def get_chain(request): if request.method == 'GET': response = render(request({'chain': blockchain.chain, 'length': len(blockchain.chain)})) return render(request,JsonResponse(response)) Checking if the Blockchain is valid def is_valid(request): if request.method == 'GET': is_valid = blockchain.is_chain_valid(blockchain.chain) if is_valid: response = render(request({'message': 'All good. The Blockchain is valid.'})) else: response = render(request({'message': 'Houston, we have a problem. The Blockchain is not valid.'})) return render(request,JsonResponse(response)) Adding a new transaction to the Blockchain @csrf_exempt def add_transaction(request): #New if request.method == 'POST': received_json = json.loads(request.body) transaction_keys = ['sender', 'receiver', 'amount','time'] if not all(key in received_json for key in transaction_keys): return 'Some elements of the transaction are missing', HttpResponse(request(status=400)) index = blockchain.add_transaction(received_json['sender'], received_json['receiver'], received_json['amount'],received_json['time']) response = render(request({'message': f'This transaction will be …