Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check if data from input exist in QuerySet - Django
Can I check if a data from input html is in QuerySet? exemple: <div> <input type="tel" id="phone-number"> {% if input in client %} -
how can i get the "post id"(foreign key field connected with comment model) to the django comments form without post_detail page in django
i am creating a single page blog site how can i get the post id to the comments form , i created django forms with necessary field but the problem is ,i have to select the post id from a drop down menu manually while commenting, for that i passed post object as an input value of a form to views.py file but django needs instance to save in database what should i do now note :i am not using post_detail models.py class comments(models.Model): name=models.CharField(max_length=255) content=models.TextField() post=models.ForeignKey(blog,related_name="comments",on_delete=models.CASCADE) #blog is the model to which comment is related date=models.DateTimeField(auto_now_add=True) forms.py class commentform(ModelForm): class Meta: model=comments fields=('name','content','post') widgets={ 'name' : forms.TextInput(attrs={'class':'form-control','placeholder':'type your name here'}), 'content' : forms.Textarea(attrs={'class':'form-control'}), 'post' : forms.Select(attrs={'class':'form-control'}) } Html <form method='POST' action="comment_action" class='form-group'> {%csrf_token%} {{form.name}} {{form.content}} <input type="text" id="objid" name="objid" value="{{objs.id}}" hidden> <button class="btn btn-primary btn-sm shadow-none" type="submit">Post comment</button> views.py def comment_action(request): name=request.POST.get('name') content=request.POST.get('content') objid=request.POST.get('objid') to_db=comments.objects.create(name=name,content=content,post=objid) print(name,content,objid) return redirect('/homepage') return render(request, 'index.html') ERROR : Exception Type: ValueError Exception Value: Cannot assign "'48'": "comments.post" must be a "blog" instance. -->48 is my blog id i know that database will only accept instance post field because that was a foreign key my question is how to pass it ? -
How can I turn Tag to List ? or How can I use tags in for loop ? (Django)
I want to show some tags product part of the homepage. How can I do with for loop ? Thats my index func. can I turn tags in product to list ? I try like : example_tag = Tag.objects.filter('example') but not working def index(request,): category = Category.objects.all context = { 'products': products, 'category': category, } return render(request, 'index.html', context ) -
Static Files and Upload, process, and download in Django
I've made a desktop app in Python to process .xls files with openpyxl, tkinter and other stuff. Now i'm looking to run this App on www.pythonanywhere.com. I was expecting to make an app to upload the file to the server, process it and then retrieve it changed to the user. But after long months struggling with Django i`ve reached the problem of static media. As I understood Django doesn’t serve files in production mode. Does this means that I can’t upload-process-download as I was planning? Or I can run in the view function the process algorithm on the request.file and then retrieve it changed, regardless of not serving static files? Am I missing something? Does Flask has the same issue? What’s the optimal solution? Apologize me for the many doubts. PD: I took the time to read many similar questions and seems to be possible to upload and download, but then im missing something on handling static files and what that means -
Trying to get the no of (count) of questions of specific data and used this information to validate the input field value in Django template
in my project, I have a table having questions of specific topics and subtopics. I want to count the no of questions of each subtopic for a particular topic id. here I have a query named subtopics which contains the information about subtopics of a particular topic and the other one is a list named totall which contains total questions of subtopics that are present in query named subtopics . in models.py the question table class Questions(models.Model): grade = models.ForeignKey(Add_Grade,on_delete=models.CASCADE, default = 1) topic = models.ForeignKey(Add_Topics, on_delete= models.CASCADE , default = 1) sub_topic = models.ForeignKey(Sub_Topics, on_delete= models.CASCADE, default = 1) question = models.CharField(max_length=100) image= models.URLField(null=True) difficulty=models.CharField(max_length=100, default='') class Meta: db_table = 'questions' in views.py def showassess(request): if request.method=='POST': classname=request.POST.get("classname") topicid=request.POST.get("topicid") topicname=request.POST.get("topicname") print(topicname,topicid) gradeid=request.POST.get("gradeid") subtopics=Sub_Topics.objects.filter(topic__id=topicid) print(subtopics) listt=list(Sub_Topics.objects.values_list('id',flat=True).filter(topic__id=topicid)) q=0 totall=[] for p in listt: if q <= len(listt): totalques=Questions.objects.filter(sub_topic__id=listt[q]).count() totall.append(totalques) q=q+1 #totalques=Questions.objects.filter(sub_topic__in=listt) print(listt) print(totall)#list contain no of questions of each subtopic having specic topic_id context={ 'totall':totall, 'topicid':topicid, 'topicname':topicname, 'classname':classname, 'gradeid':gradeid, 'subtopics':subtopics, } return render(request,"assessment.html",context) output is [1, 2, 3, 4]-->list (contains subtopic id ) [3, 2, 1, 1]-->totall (total no of questions of subtopics mentioned above[eg: subtopic having id=1 has total 3 questions ,subtopic of id=2 have 2 questions] in the template, … -
Limit choices to a user attribute
I have a series of Models which are connected by foreign keys. General SETUP APP class Company(HistoryBaseModel): code = models.CharField(max_length=3) name = models.CharField(max_length=50) user_company = models.ManyToManyField(User, through="UserCompany", through_fields=("company", "user")) class Meta(BaseModel.Meta): verbose_name = "Company" verbose_name_plural = "Companies" ordering = ('code',) def __str__(self): return f'{self.name} ({self.code})' class UserCompany(HistoryBaseModel): company = models.ForeignKey(Company, on_delete=models.PROTECT, verbose_name="Company", related_name="%(app_label)s_%(class)s_company") user = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="User", related_name="%(app_label)s_%(class)s_user") class Meta(BaseModel.Meta): verbose_name = "User's Company" verbose_name_plural = "User's Companies" constraints.UniqueConstraint(fields=['company', 'user'], name='unique_user_company') def __str__(self): return f'{self.user} ({self.company})' class MachineTypes(HistoryBaseModel): manufacturer = models.CharField(max_length=50) family = models.CharField(max_length=20) type = models.CharField(max_length=10) series = models.CharField(max_length=10) company_machine_types = models.ManyToManyField(Company, through = 'CompanyMachineTypes', through_fields=('type_series', 'company')) class Meta(BaseModel.Meta): verbose_name = "machine Type" verbose_name_plural = "machine Types" constraints.UniqueConstraint(fields=['family', 'type', 'series'], name='unique_type_series') ordering = ('manufacturer', 'type', 'series') def __str__(self): return f'{self.manufacturer} {self.type}-{self.series}' # Unique: Type, Series class CompanyMachineTypes(HistoryBaseModel): company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_company") type_series = models.ForeignKey(MachineTypes, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_type_series", verbose_name='Type/Series') class Meta(BaseModel.Meta): verbose_name = "Company machine Types" verbose_name_plural = "Company machine Types" constraints.UniqueConstraint(fields=['company', 'machineTypes'], name='unique_company_typeSeries') def __str__(self): return f'{self.company} ({self.type_series})' class Machine(HistoryBaseModel): type = models.ForeignKey(MachineTypes, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_type") company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_company") registration = models.CharField(max_length=10, unique=True) sn= models.CharField(max_length=10, unique=True) class Meta(BaseModel.Meta): verbose_name = "machine" verbose_name_plural = "machine" ordering = ('company', 'type', 'sn') def __str__(self): return f'{self.company} {self.registration} ({self.sn})' Power Source … -
Using SweetAlert2 in Django
I'm using SweetAlert to have better javascript alerts. In the documentation of sweetalert, says this: A HTML description for the popup. [Security] SweetAlert2 does NOT sanitize this parameter. It is the developer's responsibility to escape any user input when using the html option, so XSS attacks would be prevented. I know that Django autoescapes by default to prevent XSS attacks. My question is if django autoescapes automatically the HTML written by javascript. -
JSONDecodeError in Django project
I'm a beginner. I do everything as in the django ecommerce website course from the link, but it does not work for me. I also tried other stack overflow solutions but they didn't help. I have this error when i go to /update_item/ and the data is not showing up in the terminal: Expecting value: line 1 column 1 (char 0) error png tutorial link cart.js var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) }) } function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json(); }) .then((data) => { location.reload() }); } views.py def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) return JsonResponse('Item was added', safe=False) -
how to call api in android using retrofit?
I want to call login api(django) when user click on login button.I have created apiinterface and apiclient also.but when I Click on login button it shows me text: ***Failed to connect to /my ip address:8000.***I am using pgadmin.Server is already runnig and api works fine in postman,I don't know why it is not connecting and gives me message failed to connect??Please help me out!! public class ApiClient { private static final String BASE_URL="http://192.168.0.102/auth/"; private static ApiClient mInstance; private Retrofit retrofit; private ApiClient(){ retrofit=new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } public static synchronized ApiClient getInstance(){ if (mInstance==null){ mInstance=new ApiClient(); } return mInstance; } public ApiInterface getApi(){ return retrofit.create(ApiInterface.class); } } public interface ApiInterface { @FormUrlEncoded @POST("registeruser") Call<ResponseBody>performUserSignIn(@Field("username") String username, @Field("full_name") String full_name , @Field("password") String password, @Field("confirm_password") String confirm_password); @FormUrlEncoded @POST("loginuser") Call<ResponseBody>performUserLogin( @Field("username") String username ,@Field("password") String password ); } Call<ResponseBody> call=ApiClient.getInstance().getApi().performUserLogin(username,password); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { String s =response.body().string(); Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Toast.makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_SHORT).show(); } }); } -
Share files with other users (Django)
Description About the application: The main idea of this app is to create projects and share uploaded files with other users with permission. So: after creating the project( which is a Project module also), When any user uploads his file to the Django database, he can make this file visible to other users or not(this depends on his choice). This is the models: class File(models.Model): file_name = models.CharField(max_length=100) file = models.FileField(storage=file_storage, max_length=100) project_owner = models.ForeignKey(Project, on_delete=models.CASCADE,related_name='project_owner') projects_accessed = models.ManyToManyField(Project) And this is the Project Module also: class Project(models.Model): name = models.CharField(max_length=30) task = models.ForeignKey(Task, on_delete=models.SET_NULL, null=True, blank=True) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) This is the kind of prototype i want to create!! Image Proto type So, please any ideas or how can solve this kind of problem? Thank you in advance !! -
How do I setup Django Allauth with the new Sign in With Google?
Recently I realize that there is a signin with google that easier to use: no redirect to Google Singin page. For example the below Sign to Kayak with Google will popup kinda seamlessly when I open kayak.com I usually use django-allauth for social signin: but I think it still use the old Google Login UX. So, how do I use this new Sign int With Google using Allauth? -
Django Class Based View (update view)
I want to update the labels of images using Update view(Class-based-views). I can update labels of one image at a time but I would like to update labels of multiple images at once. Will passing a list of Image IDs to update view work? (How to pass a list of ids in Url pattern?) Can someone please help me with the methods I should be using in update view?? Here is my models.py class DataFile(models.Model): projectinfo= models.ForeignKey(ProjectInfo, on_delete=models.SET_NULL, null=True, blank=True) image = models.ImageField(null=False, blank=False) label = models.ForeignKey( LabelName, on_delete=models.SET_NULL, null=True, blank=True ) def __str__(self): return str(self.label) if self.label else '' -
Django list class instances matching parent
I'm new to Django, so any help is appreciated. I have one class Gym and a second class Route (rock climbing gym and climbing routes). Each gym can contain multiple routes, but each route can only belong to one gym. I can list available gyms and click on one to go to the gym page, but I want to list all of the routes that belong to it and can't figure out how. # /gym/models.py from django.db import models from django.shortcuts import reverse class Gym(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='gym', default='default_route.jpg') address = models.CharField(max_length=200) def get_absolute_url(self): return reverse('gym:detail', kwargs={'pk': self.pk}) def __str__(self): return self.name # route/models.py from django.db import models from .utils import generate_qrcode class Route(models.Model): Gym = models.ForeignKey('gym.Gym', on_delete=models.CASCADE, null=True) grade = models.CharField(max_length=10) hold_color = models.CharField(max_length=20, default='') rating = models.PositiveIntegerField() date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='routes', default='default_route.jpg') def __str__(self): return str(self.pk) # gym/views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView from .models import Gym from route.models import Route def gym_list_view(request): # Can filter this for specific gyms qs = Gym.objects.all() return render(request, 'gym/index.html', {'gym_list': qs}) def gym_detail_view(request, pk): gym_obj = Gym.objects.get(pk=pk) # This is where I don't know how to get the routes that belong … -
How to filter a table based on data from another table
there are three tables: class Course(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) start_date = models.CharField(max_length=255) end_date = models.CharField(max_length=255) def get_count_student(self): count = CourseParticipant.objects.filter(course=self.id) return len(count) def __str__(self): return f'{self.name}' class Student(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255) def __str__(self): return f'{self.first_name}' class CourseParticipant(models.Model): course = models.ForeignKey(Course, related_name='course', on_delete=models.CASCADE) student = models.ForeignKey(Student, related_name='student', on_delete=models.CASCADE) completed = models.BooleanField(default=False) I want to get students who do not participate in specific courses, I fulfill the following request potential = Student.objects.exclude(courseparticipants__course=pk) where in pk I indicate the id of the course, in response I get: django.core.exceptions.FieldError: Cannot resolve keyword 'courseparticipants' into field. Choices are: email, first_name, id, last_name, student -
How can I save the name of the selected option?
How can I save the name of the selected option in a select input? If i select plan and i sumbit i want to in select option stay plan option not selected option. <form method="get"> <!-- filtro por carpeta --> <label for="carpeta">Carpeta</label> <select id="carpeta" class="form-control" name="carpeta"> <option disabled selected>Selecciona una opcion</option> <option>Plan</option> <option>Gestion</option> </select> <br /> {% block buscador %} Nombre:<br /> <input class="form-control" type="text" value="{{ request.GET.buscar }}" name="buscar" /> <br /> {% endblock buscador %} <!-- fin filtro por carpeta --> <button type="submit" class="btn btn-primary btn-sm">Buscar</button> </form> -
POST request does not writes data to field from another model
Hello Guys, Huge Respect for all devs I have one model called field in one app, and I connected this field with the model in the same and from another app. User and Course models. User model is from usersapp. In this model, I am trying to make sign up on API, but if send data in array type, It is not written. It shows empty array in admin panel. How can I write this here is my models.py file from users app from django.db import models from courses.models import Field from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class CustomAccountManager(BaseUserManager): def create_superuser(self, email, username, first_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, username, first_name, password, **other_fields) def create_user(self, email, username, first_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, username=username, first_name=first_name, **other_fields) user.set_password(password) user.save() return user class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=32 , verbose_name="Login", unique=True, ) email = models.EmailField(unique=True) first_name = models.CharField(max_length=64, verbose_name="Ismingiz", blank=False, null=False) second_name = models.CharField(max_length=64, verbose_name="Familyangiz", blank=False, null=False) # … -
How to create a system used in facebook, linked in that suggest a friend or connection to connect
How to create a system used in facebook, linked in that suggest a friend or connection to connect I need to do it using python and django -
Django - Cannot query username, must be instance of Tagulous_Post_season
Good afternoon everyone, I'm just wondering if anyone could provide any guidance or tips on how to resolve the following error: Cannot query [username], Must be instance of Tagulous_Post_season I am trying to return two different filters within my PostListView class but when attempting to get the list of Tagulous tags which have been assigned my user's previous posts, I am getting an error as quoted above. Views.py class PostListView(LoginRequiredMixin, ListView): model = Post template_name = 'core/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = PAGINATION_COUNT def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) all_users = [] data_counter = Post.objects.values('author')\ .annotate(author_count=Count('author'))\ .order_by('-author_count')[:6] for aux in data_counter: all_users.append(User.objects.filter(pk=aux['author']).first()) # if Preference.objects.get(user = self.request.user): # data['preference'] = True # else: # data['preference'] = False data['preference'] = Preference.objects.all() # print(Preference.objects.get(user= self.request.user)) data['all_users'] = all_users print(all_users, file=sys.stderr) return data def get_queryset(self): user = self.request.user qs = Follow.objects.filter(user=user) follows = [user] instance = Post() #taguser = Post.objects.filter(season=self.request.user) taguser = Post.season.tag_model.objects.all() for obj in qs: follows.append(obj.follow_user) return Post.objects.filter(author__in=follows).filter(season__author=user).order_by('-date_posted') Models.py class Post(models.Model): content = models.TextField(max_length=1000) date_posted = models.DateTimeField(default=timezone.now) image = models.ImageField(default='default.png', upload_to='srv_media') author = models.ForeignKey(User, on_delete=models.CASCADE) likes= models.IntegerField(default=0) dislikes= models.IntegerField(default=0) title = tagulous.models.SingleTagField(initial="Mr, Mrs, Miss, Ms") season = tagulous.models.TagField( autocomplete_view='swaptags_season_autocomplete' ) def __str__(self): return self.content[:5] img = Image.open(self.image.path) if … -
Nuxt JS + Django(DRF) Deploy on Heroku
I'm a beginner, I want to deploy a project on Next and Django on Heroku, but I don't know how to do it correctly. Link on repo (https://github.com/akozyreva/recipe-app) -
Django URLField ErrorDetail "Please enter a valid URL"
Im currently working on a webApp for a client. I never used URLField cause i always use my own URL validator inside JS, but this time i wanted to use it. The problem is that when i test the app and i pass a url like this: tests.py url = "https://www.youtube.com/watch?v=9P1HtbpGSCk" data = {..., "img": img, "url":url} response = client_superuser.post(url, data,format="multipart") This error arraise: {'error': {'url': [ErrorDetail(string='Please enter a valid URL.', code='invalid')]}, 'status': 422} I also tried with different URLs but nothing change. Reading on other questions , like this, Im testing locally, so that may be the problem. On the other hand, ¿how can i make something like this?: url = models.URLField(verify_exists=False) Or, in other words, ¿how can i turn off the URL validator?, maybe it's stupid having a URLField without validators but i don't understand with Django Docs how to properly disable some validators. -
django , node js, php website hosting and domain information
I would like to about Django, node js, and PHP hosting along with MySQL database. how can we host them online, please suggest to me some websites for that? can I host the Django website with MySQL on GoDaddy, Bluehost or do I need to use cloud services like AWS Azure, etc? how to set up a domain for these websites. what is the difference in hosting the website using can you host these website on a Cpanel and is there any other way also to host -
How to return Json data in django
Instead of rendering the html page, I want to return Json data from the following blocks of code but I don't know how to implement it. I don't want to use the rest_framework. When I use render the page renders but when I use JsonResponseit throws back an error. views.py from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.core.mail import send_mail def contact_us(request): if request.method == "POST": name = request.POST.get("name") email = request.POST.get("email") title = request.POST.get("title") message = request.POST.get("message") data = { "name": name, "email": email, "title": title, "message": message } message = ''' New message: {} From: {} '''.format(data["message"], data['email']) send_mail(data["title"], message, '', ['mine@gmail.com']) return JsonResponse(request, 'contact_us/contact_us.html', safe=False) contact.html <form action="" method="POST" class="contact_us"> {% csrf_token %} <div> <div>Name</div> <input type="text" name="name"> </div> <div> <div>Email</div> <input type="text" name="email"> </div> <div> <div>Title</div> <input type="text" name="title"> </div> <div> <div>Message</div> <textarea name="message" cols="30" rows='10'></textarea> </div> <div> <input type="submit", value="submit"> </div> </form> -
How to get list of fields instead of one field in `Mymodel.objects.values()`
in Django models you can filter the field that you want but how to get a list of fields instead of one field. data = Mymodel.objects.values('id','username','other_field') print(data) -
How to pass email verification account in allauth, while seeding database
Cant find the way how to create user inside seed.py with passed verification( I have email verification in my project which is set up as mandatory). User creation works, but i want activated account. I am using django-allauth package.Setting up verificated/is_active = True does not help. Here is my seed.py: def add_arguments(self, parser): parser.add_argument( "--create_user", action="store_true", help="Create user", ) def handle(self, *args, **options): if options["create_user"]: # ToDo: find the way to pass account verification user = CustomUser.objects.create_user( first_name="A", last_name="A", email="test@test.com", password="Password123", ) for _ in range(2): EventFactory.create( is_checked_by_admin=True, private=False, host=user, event_starts=datetime(1987, 8, 15, 9, 51, 25), ) EventFactory.create( is_checked_by_admin=True, private=False, host=user, ) Here is account_manager: class CustomUserManager(BaseUserManager): def create_user( self, email, first_name, last_name, password, ): if not email: raise ValueError(_("User must have an email")) if not password: raise ValueError(_("User must have a password")) if not first_name: raise ValueError(_("User must have a first name")) if not last_name: raise ValueError(_("User must have a last name")) email = self.normalize_email(email) custom_user = self.model( email=email, first_name=first_name, last_name=last_name, ) custom_user.set_password(password) custom_user.save() return custom_user Thank you for any help! -
embed plot animation in a django project
I followed this tutorial to create a chart animation using matplotlib. Now I want to embed the chart in a django project, and I followed this tutorial that display a static image and instead I want a dynamic image. I'm very knew with matplotlib and this is what I wrote in the utilis.py import matplotlib.pyplot as plt import base64 from io import BytesIO import cryptocompare from datetime import datetime from matplotlib.animation import FuncAnimation def get_graph(): buffer = BytesIO() plt.savefig(buffer, format='svg') buffer.seek(0) image_svg= buffer.getvalue() graph = base64.b64decode(image_svg) graph = graph.decode('utf-8') buffer.close() return graph #get price of cryptocurrency def get_crypto_price(cryptocurrency,currency): return cryptocompare.get_price(cryptocurrency,currency=currency)[cryptocurrency][currency] #get fullname of the cryptocurrency def get_crypto_name(cryptocurrency): return cryptocompare.get_coin_list()[cryptocurrency]['FullName'] # set style plt.style.use('seaborn') #X: datetime objects, Y: price x_vals = [] y_vals = [] #animate function evry second def animate(i): plt.switch_backend('AGG') plt.figure() x_vals.append(datetime.now()) y_vals.append(get_crypto_price('ETH', 'EUR')) plt.cla() #specify plot title plt.title(get_crypto_name('ETH') + 'Price live plotting') plt.gcf().canvas.set_window_title('Live Plotting ETH') plt.xlabel('Date') plt.ylabel('Price (EUR)') #actual plottib plt.plot_date(x_vals,y_vals,linestyle="solid",ms=0) plt.tight_layout() graph = get_graph() return graph #call animate function ani = FuncAnimation(plt.gcf(), animate, interval=1000) this is the views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .utilis import animate def index_view(request): chart = animate() return render(request, 'cryptochart/index.html', {'chart': chart}) And this …