Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store information from javascript into a Django model?
I currently have an app which uses HTML/CSS/JQuery. As of right now all my data is saved in Jquery (and therefore not saved between sessions), but I am learning Django and want to learn how I would save that JQuery data into Django models. So how do javascript and django communicate in order to save information from one to the other? -
Django admin search_fields for ForeignKey CustomUser
I am using this model class Project(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False) name = models.CharField(max_length=20, editable=False) total = models.DecimalField(max_digits=7, decimal_places=2, default=0) created = models.DateTimeField(auto_now_add=True, editable=False, null=False, blank=False) # new fields comission_owed = models.DecimalField(max_digits=7, editable=False, decimal_places=2, default=0) comission_paid = models.DecimalField(max_digits=7, editable=False, decimal_places=2, default=0) def __str__(self): return self.name Which has CustomUser as a Foreign Key for user from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass I am trying to do a search on name and user (Which is a foreign key) using this admin config from django.contrib import admin from .models import Project class ProjectAdmin(admin.ModelAdmin): readonly_fields = ('id','user','name','created','comission_owed','comission_paid') # new list_display = ('user', 'name','comission_owed','comission_paid') search_fields = ( 'name','user') ordering = ('user',) admin.site.register(Project, ProjectAdmin) However I am getting this error: Exception Type: FieldError Exception Value: Related Field got invalid lookup: icontains I tried varius things such as Users__username in my search field or CustomUser__user to no avail, how could I have my user field as a searchable field? Thanks -
how to i reset password if user forget his password, checking a valid user id and mobile number
I want to first ask user to enter his user id and mobile number, if it is correct then render a new form to capture new password and update the password in DB views.py file def forgot_password(request): if request.method=="POST": data=request.POST user_name=data['user_id'] mobile_number=data['mobile_number'] print('user name is: ',user_name) print('mobile number is: ',mobile_number) queryset = MyAccount.objects.filter(username=user_name,mobile_number=mobile_number).values('email', 'mobile_number','username') if not queryset.exists(): messages.warning(request, 'Please enter valid email id and mobile number') fm=ForgotPassword() form={'form':fm} return render(request,'account/forgot_uid_pass.html',form) else: #render new form to enter password by user and change/update password in DB #queryset.set_password('Comedy@124') #queryset.save() else: print('need to generate password change form') fm=ForgotPassword() form={'form':fm} return render(request,'account/forgot_uid_pass.html',form) forms.py file class Register(UserCreationForm): class Meta: model=MyAccount fields=['email','username','mobile_number'] class ForgotPassword(forms.Form): #this will used to provide the user id and mobile number, if they are user_id = forms.CharField(max_length = 200) #valid the will render form to provide new password mobile_number = forms.IntegerField(help_text = "Enter 6 digit mobile number") class CapturePasswordForm(forms.Form): #this form will be used for capture new password by user new_password=forms.CharField(min_length=8) confirm_password=forms.CharField(min_length=8) -
How to specify the type of http request in django
I am writting a view named index. I want to specify that it can handle not only get requests but also post. In flask it was done by decorator, how to achieve it using django? I use Django 1.9.5 -
How to get a non-pk value to be the value by which a post request is made in django rest framework
As the question states, I'd like to be able to instead of having to pass a PK inside my JSON file in the post request I could pass a different value, like a username "bob" instead of 1. here are my relevant models: class UserModel(models.Model): MEMBERSHIP_TYPE = [ ('NM', 'NORMAL'), ('PT', 'PLATA'), ('OR', 'ORO'), ('PL', 'PLATINO'), ] id = models.AutoField(primary_key=True) username = models.CharField(max_length=100, unique=True) photo = models.ImageField(upload_to='images/', blank=True) address = models.TextField() client_type = models.CharField(max_length=2, choices=MEMBERSHIP_TYPE, default= 'NM') def __unicode__(self): return self.name class ArticleModel(models.Model): id = models.AutoField(primary_key=True) code = models.IntegerField(unique=True) description = models.TextField() def __str__(self): return str(self.code) class SupplierModel(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) address = models.TextField() articles = models.ManyToManyField(ArticleModel) def __str__(self): return self.name class OrderModel(models.Model): id = models.AutoField(primary_key=True) client = models.ForeignKey('UserModel', on_delete=models.CASCADE) gen_time = models.DateTimeField(auto_now_add=True) gen_supplied = models.DateTimeField(null=True, blank=True) urgent = models.BooleanField() order_to = models.ForeignKey('OrderToModel', on_delete=models.CASCADE) article = models.ForeignKey('ArticleModel', on_delete=models.CASCADE) quantity= models.IntegerField() and Serializer: class OrderCreateSerializer(serializers.ModelSerializer): # order_to = OrderToPolymorphicSerializer() class Meta: model = OrderModel fields = ('client', 'urgent', 'article', 'quantity', 'order_to') Help is much appreciated. Thank you in advance. -
How to create nexting columns with bootstrap grid
I'm trying to create nexted columns with bootstrap grid, but the result I'm getting isn't nexted {% for home in home %} <div class="container"> <div class="row"> <div class="col-sm-6 col-md-3 med_trend bg-light shadow m-4 rounded"> <h3 class="text-center text-info">{{ home.title }}</h3> <li><i class="fas fa-check text-info mr-2"></i>{{ home.first_point }}</li> <li><i class="fas fa-check text-info mr-2"></i>{{ home.second_point }}</li> <li><i class="fas fa-check text-info mr-2"></i>{{ home.third_point }}</li> <li><i class="fas fa-check text-info mr-2"></i>{{ home.fourth_point }}</li> </div> </div> </div> {% endfor %} -
Change a view varible file with the html file
Im making an online store and I add to it the Stripe Checkout for payments, everything works correct, the problem is that the view fuction only manage one price, it looks like this def charge(request): # new if request.method == 'POST': charge = stripe.Charge.create( amount=179900, currency='mxn', description='Bota Caballero', source=request.POST['stripeToken'] ) return render(request, 'charge.html') the amount says the price, In my html homepage i have a select tag, it define the cost of the product <select id="modelo" onchange="modelo()" class="select__option" required> <option>Selecciona Modelo...</option> <option>$1799</option> <option>$1299</option> <option>$1199</option> </select> i would like to change the amount variable of the view file depending on what is selected in the select tag. Any idea? -
Superuser doesn't work after unapplying migrations in Django
I was having some trouble (errors) with old migrations in my auction site project, so I decide to run python manape.py migrate auctions zero to unapply all the migrations and apply new ones, and it worked. However, after I did it I couldn't use my superuser account to manipulate the models in the admin/ url anymore. In fact, I couldn't use any other account -- this website I'm working on allows the creation of profiles by the user, and before I unapply all the migrations it worked perfectly. But now, if I try to log in with an existing account created for testing purposes, I receive this error message (that I wrote): But I was expecting that to happen, since I (if I understood well) cleared the user database when I unapplied the migrations. But when I try to create a new user, no matter the username or password, I get this error (that I also wrote): How can the username be already taken if it is completely new? These errors appears no matter what I do, even when I try to login with the superuser. When I try to create a new superuser I also have problems, like this … -
Could someone please provide a link to a Django + Javascript basic project?
Could someone please provide a link to a sample Django project that I can download and build off. To be specific, I am going to create a website used for a business application on a mobile device. The web page will have a login. When logged in, the user will be presented with a few menu options. The user can click between the menus without the page reloading. All will be done with Ajax. The user will enter data, scan/search and submit forms. The submitted data will be sent to an external application (ERP system). I have created several projects in the past, but they become difficult to scale and manage. In my previous apps, I used Flask and had everything in a single html file including the javascript. It works, but it isn't great. I'm trying to take things to the next level. I have spent a bunch of time researching google but find several different directions to take. I learn best, by having a basic example and then reverse engineering how it works. -
How to read shapefile in Django view helper function?
As part of my view logic I need to check if Latitude and Longitude points are withing city boundaries. To do that, I am using city shapefiles with geopandas. It all works ok locally in plain python code. However, when I run the following code in Django: LA_geo_df = gpd.read_file('./City_Boundaries/City_Boundaries.shp') I get the error: DriverError at / ./City_Boundaries/City_Boundaries.shp: No such file or directory What is the proper Django way of loading such files? -
How do I display videos in template from inline formset?
I have a form that includes an inline formset and I am having trouble displaying the videos in the template that were uploaded from the form. What would I add to the html line in the template as the source so that the video uploads are displayed? Thanks. models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) bio = models.TextField(max_length=150, null=True) phone_number = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.user.username class MultipleFileUpload(models.Model): file_uploads = models.ForeignKey(Profile, on_delete=models.CASCADE) video = models.FileField(null=True, blank=True, upload_to='videos') def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_profile_signal(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py: class EditProfile(forms.ModelForm): class Meta: model = Profile fields = ['bio', 'phone_number'] class ProfileUpdateFormset(forms.ModelForm): class Meta: model = MultipleFileUpload fields = ['video'] views.py: def edit(request, id): all_objects = get_object_or_404(Profile, id=id) ProfileFormset = inlineformset_factory(Profile, MultipleFileUpload, fields=('video',), can_order=False, can_delete=True, extra=1) if request.method == 'POST': form1 = EditProfile(request.POST or None, instance=all_objects) formset = ProfileFormset(request.POST, request.FILES, instance=all_objects) if form1.is_valid() and formset.is_valid(): form1.save() formset.save() return HttpResponseRedirect(".") form1 = EditProfile(instance=all_objects) formset = ProfileFormset(instance=all_objects) context = { 'form1': form1, 'formset': formset, } return render(request, 'accounts/edit.html', context) html: <video width="350" height="200" source src="{{ user.profile.file_uploads.video.url }}" controls></video></p> -
Updating two models with a foreign key at the same time
Below are my codes and I get the error ValueError at /inventory/stock/1/edit Cannot assign "'1'": "Stock.category" must be a "Category" instance. in model.py class Category(models.Model): name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.name class Stock(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE,blank=True) item_name = models.CharField(max_length=100, blank=True, null=True) quantity = models.IntegerField(default='0',blank=True, null=True) class StockHistory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE,blank=True) item_name = models.CharField(max_length=100, blank=True, null=True) quantity = models.IntegerField(default='0',blank=True, null=True) in view.py def UpdateStock(request, pk): stock = Stock.objects.get(id=pk) stock_form = StockForm(instance = stock) history_form = StockHistoryForm(instance = stock) if request.method == 'POST': stock_form = StockForm(request.POST, instance = stock) history_form = StockHistoryForm(request.POST, instance = stock) if stock_form.is_valid() and history_form.is_valid(): stock = stock_form.save() history = history_form.save() return redirect('inventory') context = { 'stock_form': stock_form, 'history_form': history_form } return render(request, 'inventory/edit.html', context) -
AttributeError: 'CharField' object has no attribute 'stream_block'
I'm really new to Python3, Django & Wagtail and am trying to create an ArticlePage Model with a StreamField block used in it, and have run into problems and am getting an error: AttributeError: 'CharField' object has no attribute 'stream_block' error. I have no idea what I'm doing wrong? I'm obviously doing something wrong but have no idea what? Here's the model.py code: articles/models.py: from modelcluster.fields import ParentalKey from wagtail.core import blocks from wagtail.core.models import Page, Orderable from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel, MultiFieldPanel, InlinePanel from wagtail.core.fields import StreamField from streams import blocks from wagtail.core.fields import RichTextField from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.search import index ### Flexible Page # Create your models here. class ArticlePage(Page): subtitle = models.CharField() body = RichTextField() date = models.DateField("Article date") team_member = models.CharField() feed_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) search_fields = Page.search_fields + [ index.SearchField('body'), index.FilterField('date'), index.FilterField('subtitle'), ] template = "articles/article_page.html" #ToDo: add StreamFields content = StreamField( [ ("team_member", blocks.TeamMembersBlock()) ], null=True, blank=True, ) subtitle = models.CharField() content_panels = Page.content_panels + [ FieldPanel("subtitle"), FieldPanel('date'), FieldPanel('body', classname="full"), InlinePanel('related_links', label="Related links"), StreamFieldPanel("team_member"), ] promote_panels = [ MultiFieldPanel(Page.promote_panels, "Common page configuration"), ImageChooserPanel('feed_image'), ] # Parent page / subpage type rules parent_page_types = ['articles.ArticleIndex'] subpage_types = [] … -
How can i Fix this problem in Python Django?
enter image description hereClass 'User' has no 'objects' memberpylint(no-member) i don't understand -
Create a waiting room for users django
I would like to create something like FaceTime on a website based of the tastes of the users. I thought about creating a waiting room where all users will be. Then a matching algorithm will try to pair two of the users and take them to a private room where they will be able to chat. I tried to see for a solution on internet but I didn’t find any great answers. If you guys have any great ressources on how to do that it would be awesome :) PS: I use Django with python and rest framework for the backend. Thanks -
Template doesn't overwrite
I render a template and return it. Program seems to render template only once and then even though i change input arguments, return the first rendered template. The function named getNumber works properly and return different data. My template: <head> <meta charset='UTF-8'> <title>file uploader</title> </head> <body> <form id='selectForm'> <input id='selectInput' type='file' name='files' multiple> <div>Files:</div> <table id='selectTable'></table> </form> <script> ... </script> <p> Solution: {{ solution }} </p> </body> </html>``` Function that return HttpResponse in views.py resolving '/' url: ```def index(request): if request.method == 'POST': uploadFile1 = request.FILES['file1'] uploadFile2 = request.FILES['file2'] text1 = '' text2 = '' with open('file1', 'wb+') as file1: text1 = uploadFile1.read() with open('file1', 'wb+') as file2: text2 = uploadFile2.read() data = calcpy.views.getNumber(str(text1), str(text2)) print(data['number']) template = loader.get_template('main.html') context = {'solution' : data['number']} template.render(context); return HttpResponse(template.render(context)) template = loader.get_template('main.html') context = {'solution' : 0} return HttpResponse(template.render(context))``` Code in settings.py responsible for templates. I suppose here is the mistake. ```TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True }, ] # Application definition INSTALLED_APPS = ( 'version', 'current', 'calcpy', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ) I use django 1.9.5 and I can't really change the version. -
How to reverse an url from APIView in DRF for testing
I'm trying to test my view but when I try to reverse the URL I get: django.urls.exceptions.NoReverseMatch: Reverse for 'list_task' not found. 'list_task' is not a valid view function or pattern name. I'm not sure how to do it since I've seen people doing it the way I am and yet it does not work for me. Here is my view: from rest_framework import generics, filters from todo import models from .serializers import TaskSerializer from django_filters.rest_framework import DjangoFilterBackend #lists, creates and filters tasks class ListTask(generics.ListCreateAPIView): queryset = models.Task.objects.all() serializer_class = TaskSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ['date'] search_fields = ['description'] #allows to see detail of a task class DetailTask(generics.RetrieveUpdateDestroyAPIView): queryset = models.Task.objects.all() serializer_class = TaskSerializer And here is my test view: from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase class CreateTaskTest(APITestCase): def setUp(self): self.data = {'title': 'title', 'description': 'desc', 'completed': False} def test_can_create_task(self): response = self.client.post(reverse('list-task'), self.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) -
Update database instance with specific form fields using Django (modify_personal_info)
I am quite new to Django, and I am working on a project, and I am trying to create a page to modify user data (code down below). What I am trying to do is allow the user to change one or more field, and not necessarily all the fields at the same time, and then update the user instance, I tried using multiple conditions on each field so I won't have an empty field in the database later, but nothing happens. Here's the corresponding view: ``` @login_required def profile(request, id_user): try: user = Account.objects.get(pk=id_user) if request.method == 'POST': form= request.POST if form.get('first_name'): user = Account(first_name=form.get('first_name')) user.save() if form.get('last_name'): user = Account(last_name=form.get('last_name')) user.save() if form.get('email'): user = Account(email=form.get('email')) user.save() if form.get('username'): user = Account(username=form.get('username')) user.save() if form.get('adress'): user = Account(adress=form.get('adress')) user.save() if form.get('phone'): user = Account(phone=form.get('phone')) user.save() except Account.DoesNotExist: user = None raise Http404("User does not exist") return render(request, "profile.html") And this is a snippet from the template: {% csrf_token %} Informations du compte Nom d'utilisateur Email Prénom Nom Informations de contact Adresse Télephone Appliquer ``` -
Slow requests whenever Psycopg2 reconnects to DB
I'm currently facing a very strange issue. I did some optimizations in my queries, which improved quite a lot the overall performance for my Django application's GET requests. However, I'm still facing a few very slow ones (1000ms or more). Checking on Elastic APM, I noticed that for all those cases, there was a DB reconnection. While it's obvious those requests would take more time, it's still takes WAY more time than the amount required for the reconnection itself. I have set the DB_CONN_MAX_AGE to None, therefore the connections themselves shouldn't be closed at all. Which makes me think the reason for the disconnection itself could also indicate the cause for this. The blue bars represent the amount of time a given transaction took. The total amount of time for this particular request was 1599ms. The DB reconnection took 100ms, the the queries about ~20ms. Adding those up, gives a total time of 120ms. I'm a bit clueless how to find out where the rest of the 1479ms. I did some load tests locally, but couldn't reproduce this particular issue. Of course is serializations, middlewares, authentication and other things that might add up some time to requests, but not nearly … -
Is it not possible to set ALLOWED_HOSTS as an environment variable in Django?
I have a Django app deployed on Heroku. During initial development, I defined ALLOWED_HOSTS manually in the settings.py file ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] Before deploying to Heroku, I changed various settings to environment variables. In my application, I used the environs[Django] package to identify variables and I defined the variables in Heroku using "Config Vars" in app's settings tab. in my Django app, the environment variables looked like this... SECRET_KEY = env("DJANGO_SECRET_KEY") SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) During the initial deployment to Heroku, I also set ALLOWED_HOSTS as an environment variable using the same approach as described above. In my settings.py file, the variable looked like this... ALLOWED_HOSTS = env("ALLOWED_HOSTS") Long story short: This didn't work, so after a bit of trial and error, I manually defined the ALLOWED_HOSTS in the settings.py file as I had done during development. ALLOWED_HOSTS = [.herokuapp.com, etc...] I'm back to setting up ALLOWED_HOSTS as an environment variable, but in a development environment, with no luck. The message I get is... Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS Haven't found anything online regarding this. The documentation says very little regarding ALLOWED_HOSTS as an environment variable, mainly in regards to DEBUG. At … -
Django Error - MultiValueDictKeyError at /new_bid/5 'total_bid.' (Beginner help appreciated)
I'm creating a page on a site to allow users to 'bid' on items similar to ebay. When I try to enter a number (dollar amount) on the item on the site (to enter a bid) I get the error: MultiValueDictKeyError at /new_bid/5 'total_bid.' The problem seems to be total_bid = request.POST["total_bid"] and I think the system believes it's None. I'm not sure why it thinks it's None because when entering the bid on the site, a number really is in the box, so if I type 100 meaning $100 bid, maybe the code is not actually taking in that number? So on POST it thinks there is nothing there? I also tried total_bid = request.POST.get["total_bid"] with the .get part and also received an error. I also tried adding something like "if total_bid is not none:" but I'm not sure how to do that with the syntax because I would need to declare total_bid = to something first. I'm new to Django so additional information on how this works would be so helpful. I've already read a lot of posts on this site about this and similar errors but I'm having some trouble understanding. views.py def new_bid(request, listingid): if request.method … -
update existing row in model with django forms
//i have a model class WerknemerCV(models.Model): bedrijfsnaam = models.CharField(max_length=50) werknemer = models.ForeignKey('auth.user', related_name='werknemer', null='False', blank='False', on_delete=models.CASCADE) def __str__(self): return self.bedrijfsnaam //my form based on the model class Create_CV(forms.ModelForm): bedrijfsnaam = forms.CharField(max_length=50) werknemer = forms.ModelChoiceField(queryset=User.objects.all()) class Meta: model = WerknemerCV fields = '__all__' //my view to create an instance with the form def maakCV(request): user = request.user if request.method == "POST": user = request.user form = Create_CV(request.POST) if form.is_valid(): form.save() return redirect(reverse("maak_cv")) else: print("form is not valid") form = Create_CV(initial={'werknemer': user}) return render(request, 'users/maak_cv.html', {"form": form}) //my html template snippet of the DETAIL view {% if user.is_authenticated %} <dt style="margin-left: 20px">Gewerkt in de functie van {{ object.functie }}.</dt> <dd style="margin-left: 20px">{{ object.omschrijving }}</dd> //my question ?, i want to update the existing instance of the model created with the form. I want to to this on the detail page. so, http://....../detail_view/1/. See my comment in the code below //my update code in view def updateCV(request): user = request.user if request.method == 'GET': cv_id = request.GET.get('cv_id', None) print('cv id', cv_id) if request.method == 'POST': cv = WerknemerCV.objects.get(pk=/////Here i want the pk of the detail, but i dont know how. form = Create_CV(request.POST,instance=cv) if form.is_valid(): form.save() return redirect(reverse("cv_detail")) else: print("form is not valid") … -
call parent dispatch before child dispatch django
I have a mixin which beside other things simplifies call of request.user object. class MyMixin(LoginRequiredMixin, View): ... leader = False employee = False def dispatch(self, request, *args, **kwargs): self.leader = request.user.is_leader() self.employee = request.user.is_employee() return super().dispatch(request, *args, **kwargs) ... And I have a heir of DetailView which has it's own dispatch method. class MyDetailView(MyMixin, DetailView): def dispatch(self, request, *args, **kwargs): if not self.leader: raise PermissionDenied return super().dispatch(request, *args, **kwargs) But as you could've told it ain't working. Is there a way to elegantly call parent dispatch method from it's heir? -
Django multiple annotation counts on a single queryset
I need to count the number of tasks pending, in progress and completed for each company at any given time. Using the code below I am able to achieve this however it is repeating the company name on each row instead of doing it once. Models.py class Company(models.Model): company = models.CharField(max_length=40) class Period(models.Model): period = models.CharField(max_length=7) class Status(models.Model): option = models.CharField(max_length=40) class Task(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, default=None, blank=True, null=True) period = models.ForeignKey(Period, on_delete=models.CASCADE, default=None, blank=True, null=True) status = models.ForeignKey(Status, on_delete=models.CASCADE, default=1) Views.py if request.method == 'POST': if form.is_valid(): periods = Period.objects.get(period=form.cleaned_data['period']) status = Task.objects.filter(period=periods).values('period', 'company__compnay', 'status__option', 'status').annotate(count_all=Count('status__option')) args = {'form': form, 'periods': periods, 'status': status} Template {% if status %} <table class="table table-striped"> <thead> <tr> <th scope="col">Company</th> <th scope="col">Tasks Pending</th> <th scope="col">Tasks In Progress</th> <th scope="col">Tasks Completed</th> </tr> </thead> <tbody> {% for stat in status %} <tr> <td>{{stat.company__company}}</td> <td>{{stat.status__option}}</td> <td>{{stat.count_all}}</td> </tr> {% endfor %} </tbody> </table> {% endif %} Results Company Pending Tasks In Progress Tasks Completed Tasks Apple Completed 1 Apple In Progress 1 Apple Pending 2 Microsoft Completed 2 Microsoft In Progress 5 Microsoft Pending 5 Expected Result Company Pending Tasks In Progress Tasks Completed Tasks Apple 2 1 1 Microsoft 5 5 2 -
How to add real time date & time in a Djago app
I want to add date and time to the navbar of my Django app, so I added the following javascript code (reference) in the header of my base.html <script type="text/javascript"> var timeDisplay = document.getElementById("time"); function refreshTime() { var dateString = new Date().toLocaleString("en-US", {timeZone: "Indian/Christmas"}); var formattedString = dateString.replace(", ", " - "); timeDisplay.innerHTML = formattedString; } setInterval(refreshTime, 1000); </script> and the below HTML in the navbar: <p id="time"></p> I even tried putting this in the main content of my index.html file but it don't seem to work for me, what am I doing wrong? or is there any other way to add real time date and time in the navbar of my Django app?