Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ProgrammingError at /admin/order/order/ relation "order_order" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "order_order"
I'm working with django rest framework and I have a app named order. I wanted to change my order logic and I changed order app's models. but when I want to open order and order_item models in admin panel I have this error: ProgrammingError at /admin/order/order/ relation "order_order" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "order_order" and also when i run migrate command it doesn't migrate well and doesn't create the order and OrderItem tabels in the database. I'm using postgres db. there is my code: models: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) # products = models.ManyToManyField(OrderItem) created_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.full_name def total_price(self): total = 0 for order_item in self.products.all(): total += order_item.get_final_price() return total class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='products') ordered = models.BooleanField(default=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.product.name}" def get_total_item_price(self): return self.quantity * self.product.price def get_total_discount_item_price(self): return self.quantity * self.product.discount def get_amount_saved(self): return self.get_total_item_price() - self.get_total_discount_item_price() def get_final_price(self): if self.product.discount: return self.get_total_discount_item_price() return self.get_total_item_price() admin: class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'ordered_date', 'created_date', 'total_price' ] list_display_links = ['user', ] … -
sum values from database in DJANGO templatetags
''' {% for d in pointss %} {{ d.points }} {% endfor %} ''' I have such a recurrence i know you need to use a ‘sum’ filter for this ''' from django import template register = template.Library() def summing(value): return register.filter("sum", summing) ''' I don't know how to use it here -
Django - how can i return a json response error?
I created a simple API endpoint using Django Rest Framework and i created a very basic logic where if the user doesn't provide any filter, the API needs to return a custom error, something like {'error': 'no parameter provided'}. The problem with my code is that i keep getting this error: object of type 'JsonResponse' has no len(). Here is my code: class WS_View(viewsets.ModelViewSet): pagination_class = StandardResultsSetPagination http_method_names = ['get'] serializer_class = WS_Serializer def get_queryset(self): valid_filters = { ... } filters = {valid_filters[key]: value for key, value in self.request.query_params.items() if key in valid_filters.keys()} #If there are filters, execute the query if len(filters) > 0: queryset = WS.objects.filter(**filters) return queryset #If there isn't any filter, return an error else: return JsonResponse({"error": "no parameter required"}) Now i know i'm getting this error because i'm supposed to return a Queryset, and JsonResponse is not a Queryset of course, but i don't know how to actually solve this. Any advice is appreciated! -
Filtering by category
I want to filter by categories. I have a lot of categories and they are translated into 3 languages. They also can be added dynamically. Now I am filtering by primary key and it seems to work fine, but I need to have the category 'All' which will be selected by default. How can I avoid hardcode values for this category? def autocomplete(request): if 'term' in request.GET: term = request.GET.get('term') qs = Article.objects.all() if 'category_id' in request.GET: category_id = request.GET.get('category_id') # 4 stands for all category if category_id != '4': qs = qs.filter(category__pk=category_id) qs = qs.filter(name__istartswith=term) names = [] for article in qs: names.append(article.name) return JsonResponse(names, safe=False) return render(request, 'home.html') Thank you! -
How do I use django models.py classes in my own python programs?
So, I want to make some changes in the database using python outsite Django, but I am unable to. I'm trying to import the model from models.py but i'm unable to. from models import NumberInfo There is this error: Traceback (most recent call last): File "/home/sagan/p/matematika/matematika/mnumbers/prime_insert.py", line 1, in <module> from models import NumberInfo File "/home/sagan/p/matematika/matematika/mnumbers/models.py", line 5, in <module> class NumberInfo(models.Model): File "/home/sagan/.local/lib/python3.9/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/home/sagan/.local/lib/python3.9/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/home/sagan/.local/lib/python3.9/site-packages/django/apps/registry.py", line 135, in check_apps_ready settings.INSTALLED_APPS File "/home/sagan/.local/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/sagan/.local/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/sagan/.local/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'matematika'``` -
A clear resource to understand django-helpdesk
I'm not sure if this is a valid question for this community, but I've linked my django website with django-helpdesk as its ticketing system, I'm facing an issue with uploading attachments, as they are not being saved, and wanted to read about the right way to upload an attachment, I've only found this documentation link https://django-helpdesk.readthedocs.io/en/0.2.x/install.html which explains absolutely nothing. Is there another resource I'm missing?? -
AttributeError at /admin/blog/post 'list' object has no attribute 'lower'
I have a simple blog code in Django , I write the error and my codes: there is my codes models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() def __str__(self): return self.title views.py from django.views.generic import ListView from .models import Post class BlogListView(ListView): model = Post template_name = 'home.html' urls.py from django.urls import path from .views import BlogListView urlpatterns = [ path('', BlogListView.as_view(), name= 'home') ] and home.html {% extends 'base.html' %} {% block content %} {% for post in object_list %} <div class="post-entry"> <h2><a href="">{{ post.title }}</a></h2> <p>{{ post.body }}</p> </div> {% endfor %} {% endblock content %} There is Error message after running code: AttributeError at /admin/blog/post 'list' object has no attribute 'lower' Request Method: GET Request URL: http://127.0.0.1:8000/admin/blog/post Django Version: 3.1.5 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'lower' Exception Location: C:\Users\nilaroz\.virtualenvs\blog-Keg_c4F1\lib\site-packages\django\utils\http.py, line 295, in is_same_domain Python Executable: C:\Users\nilaroz\.virtualenvs\blog-Keg_c4F1\Scripts\python.exe Python Version: 3.8.6 Python Path: ['D:\\MyDjangoProject\\blog', 'c:\\program files (x86)\\python38-32\\python38.zip', 'c:\\program files (x86)\\python38-32\\DLLs', 'c:\\program files (x86)\\python38-32\\lib', 'c:\\program files (x86)\\python38-32', 'C:\\Users\\nilaroz\\.virtualenvs\\blog-Keg_c4F1', 'C:\\Users\\nilaroz\\.virtualenvs\\blog-Keg_c4F1\\lib\\site-packages'] Server time: Sun, 31 Jan 2021 19:53:08 +0000 why? I don't make any list! what's mean "'list' object has no attribute 'lower'"? I think … -
Dynamic urls for hierarchy tree on django
I would like to build a hierarchy tree of content with no depth limits. models.py: class Element(models.Model): name = models.CharField(verbose_name="Nombre", max_length=250) parent = models.ForeignKey("self", on_delete=models.CASCADE) slug = models.TextField(verbose_name="Slug", blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Element, self).save(*args, **kwargs) .../element_n-1/element_n/element_n+1/... How do i have to write the path in urls.py to get this functionality? Thanks in advanced. -
Django modal forms with ajax tables
I am using modal forms with django ajax tables: https://pypi.org/project/django-bootstrap-modal-forms/ https://pypi.org/project/django-ajax-tables/ How can I update data asychronously by the modal form? Here is some example code: Registered Views: def index(request): return render(request, 'proto/index.html') class BookTableView(View): model = Books my_table = BooksTable def get(self, request): data = self.model.objects.all() #filtering table = self.my_table(data) RequestConfig(request, paginate = {"per_page": 6, "paginator_class": LazyPaginator}).configure(table) return HttpResponse(table.as_html(request)) class BookUpdateView(BSModalUpdateView): model = Books template_name = 'proto/books/update_book.html' form_class = BookModelForm success_message = 'Success: Book was updated.' success_url = reverse_lazy('index') Table: class BooksTable(tables.Table): column1 = tables.TemplateColumn(verbose_name='Read', template_name='proto/columns/column1.html', orderable=False) column2 = tables.TemplateColumn(verbose_name='Update', template_name='proto/columns/column2.html', orderable=False) class Meta: model = Books Column2 html template button <button type="button" class="update-book btn btn-sm btn-primary" data-form-url="{% url 'update_book' record.id %}" onclick="updateBookModalForm()"> <span class="fa fa-pencil"></span> Close update buttons on update_book.html modal form <button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="update_books_id('', '/proto/books')"> <span aria-hidden="true">&times;</span> </button> ... <div class="modal-footer"> <button type="button" class="submit-btn btn btn-primary">Update</button> </div> Calling ajax tables on index.html and javascript for modals : ... <div class="col-12 mb-3"> {% ajax_table "books_id" "books" %} </div> <script> function updateBookModalForm() { $(".update-book").each(function () { $(this).modalForm({ formURL: $(this).data("form-url"), asyncUpdate: true, asyncSettings: { closeOnSubmit: false, successMessage: asyncSuccessMessageUpdate, dataUrl: "books/", dataElementId: "#books-table", dataKey: "table", addModalFormFunction: updateBookModalForm } }); }); } updateBookModalForm(); </script> Surprisingly this works and appears … -
xhtml2pdf heroku can't load font
I'm creating a PDF based on xhtml2pdf (Django). In my localhost I need to provide absolute path for font 'D:\user\folder1\folder2\project\static\fonts\DejaVuSansMono.ttf' because reference of {% static 'fonts/DejaVuSansMono.ttf' %} doesn't work. My font isn't loading. If i provide absolute path, it is working fine. But it isn't working when I publish my app on Heroku. I don't know how to do. I know that the xhtml2pdf has reference only on xhtmlpdf catalog (please correct me if I'm wrong). What should I do that the font will be working on localhost and Heroku too? I've tried to do something like that but it isn't working as well. base_url = "{0}://{1}{2}".format(request.scheme, request.get_host(), request.path) My app in heroku return only /static/fonts/DejaVuSansMono.ttf -
Create a nested Form in Django
I've been pondering a lot, but I'm still not sure how best to implement it. I want to get a nested Formular(a real Formular, not a Django Form) in Django. What I mean with nested is, that there are categorys and if the user ticks the boxes there appear subcategorys and so on. The filling of the form can be over several pages. I'm happy about every inspiration, it doesn't have to be full guide. -
How to filtering in Django use specific user
I try to filtering django some specific user. I try with list but it not working. Do you have any solution. list = ['bill gates','elon musk','aamir khan','larry page'] allPosts = Post.objects.filter(author=list) When I change list filter can work dynamically -
Why ajax returns the latest variable of a loop in html template?
I have a html file as bellow: <div id="preview_updated_notifications"> {% for lst in unread_list %} <div > <span data-notification-item="{{ lst.id }}" id="_mark_as_read_id"> ●</span> </div> {% endfor %} </div> and in js file: $(document).on('click', "#_mark_as_read_id", function() { var object_id = $('#_mark_as_read_id').data('notification-item'); console.log('--------------object_id:------------') console.log(object_id) console.log('--------------------------') $.ajax({ type: "GET", url: "{% url '_mark_as_read' object_id %}", dataType: 'json', data: { 'object_id': object_id, }, dataType: 'json', success: function (data) { $('#preview_updated_notifications').html('**TEST**'); } }); event.preventDefault(); }); But the problem is that this always prints the latest value of loop, while I expect after clicking on each item ● retrieve the relative id! -
Why is the delete button for a Heroku app greyed out?
I want to delete an Django app and found two solutions: Use the delete button in settings, or from the command line. The delete button doesn't work (the "prohibited" icon shows up). I started a console from within the app to use the command heroku destroy apps --app MyApp, but the command "isn't found". This app has never been set up, so I get lots of "failed" notifications. So I want to remove it. How can I delete this app? -
Upload file at Wagtail bakerydemo
I can't make file upload form field work. My references are: https://github.com/lb-/bakerydemo/blob/stack-overflow/61289214-wagtail-form-file-upload/bakerydemo/base/models.py https://dev.to/lb/image-uploads-in-wagtail-forms-39pl The field was added to admin and appear correctly on my site, but when I try to send the form: if the field is required, the form is reloaded without any error if the field is not required, the form is sent but the file is not uploaded What am I doing wrong? I've been working on this for 3 days and can't find any error message pointing what's wrong. When I get some error message it's always too generic. Please help! :) My models.py inside bakerydemo/bakerydemo/base from __future__ import unicode_literals import json from os.path import splitext from django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.utils.html import format_html from django.urls import reverse from django import forms from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.admin.edit_handlers import ( FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel, PageChooserPanel, StreamFieldPanel, ) from wagtail.core.fields import RichTextField, StreamField from wagtail.core.models import Collection, Page from wagtail.contrib.forms.forms import FormBuilder from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormSubmission, AbstractFormField, FORM_FIELD_CHOICES from wagtail.contrib.forms.views import SubmissionsListView from wagtail.images import get_image_model from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.images.fields import WagtailImageField from wagtail.search import index from wagtail.snippets.models import register_snippet from .blocks import BaseStreamBlock from django.core.validators … -
Django DEBUG = True xlsx files do not work
I have faced a strange problem. I have a button that creates xlsx file. For example, firstly file is empty and when I press the button it becomes full of information from the database( PostgreSQL ). And now what is wrong: When DEBUG is TRUE in settings.py file everything works pretty fine and the document creates. When DEBUG is FALSE it do not change the file. I really appreciate all answers, thanks! -
how i can handel date in path
i want test api of my project. i have model Article that have DateField that fill automatic and certainly each time save date.today() so if i run this line of test code today it run correctly but future days will run incorrectly response=self.client.get("/api/v1.0.0/blog/archive/en-2021-01/") how i can change the date part of above line of code dynamically.I mean part "en-2021-01" of the above code .I also tested it with a variable but it did not work.like this edate=str(date.today()) response=self.client.get("/api/v1.0.0/blog/archive/en-edate/") i do not know how changed it to work Thanks for trying to help me -
How could I show placeholder inside html inputs?
I want to set placeholder inside text inputs, and I still don't know how to do this. I tried to add attributes but they didnt work and text is still showing above inputs. Here's my code: forms.py class LoginForm(forms.Form): username = forms.Charfield(widget = forms.TextInput), password = forms.Charfield(widget = forms.PasswordInput) and that form is creating something like this: html <div class="row"> <div class="col-8"> </div> <div class="col-4"> <p><span style="font-size:50px; color:#ac3b61;">Welcome!</span></p> <form action="/account/login/" method="post"> <p><label for="id_username">Username:</label> <input type="text" name="username" autofocus="" autocapitalize="none" autocomplete="username" maxlength="150" required="" id="id_username"></p> <p><label for="id_password">Password:</label> <input type="password" name="password" autocomplete="current-password" required="" id="id_password"></p> <input type="hidden" name="csrfmiddlewaretoken" value="gkh34TNSATaWHP3f3c9Qmp1msf6nazSd9hAoKsTPlHtMWFN4nNIYOwkpx9iXcCer"> <input type="hidden" name="next" value="/account/"> <p><input type="submit" value="Login"></p> <p><a href="/account/password_reset/">Forgot your password?</a></p> <p>Don't have an account? Register <a href="/account/register/">here</a>. </p> </form> </div> </div> -
Django testing (TestCase) with multiple database is failing
I use 2 databases on my django app - the first is MySQL and the second is Mongo (using the [djongo][1] engine). I started writing some tests using the TestCase and i want to use sqlite3 engine. My DBs configuration: (You can see that i have assigned TEST DBs on sqlite] #settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': DEFAULT_NAME, 'USER': DEFAULT_USER, 'PASSWORD': DEFAULT_PASSWORD, 'HOST': 'my-host-here', 'PORT': '3306', 'TEST': { 'NAME': 'test_dev' } }, 'mongoDB': { 'ENGINE': 'djongo', 'CLIENT': { 'host': 'mongodb+srv://{}:{}@{}/?retryWrites=true&w=majority'.format( username, password, host), 'username': username, 'password': password, 'name': name, 'authSource': authSoruce, 'ssl':ssl, 'authMechanism': 'SCRAM-SHA-1', } } } # If django runs unittests - run on a local sqlite DB if 'test' in sys.argv: DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase', 'SUPPORTS_TRANSACTIONS': True } DATABASES['mongoDB'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase2', 'SUPPORTS_TRANSACTIONS': True } When i run the tests, I get failures when Django is trying to create the mongoDB TEST database. error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: release_notes_releasenotesformmodel (release_notes_releasenotesformmodel is the only model i have in the mongoDB) test script: databases = '__all__' def SetUp(self): self.client = Client() self.dummy_test = EdisonAbTestsListModel.objects.create( test_id=DUMMY_TEST_ID_1 ) def run_test(self): ## here is my test logic...``` [1]: https://github.com/nesdis/djongo -
Get certain parameter on a fetch request
I'm developing a twitter-like app where users are able to make posts. I want to make a div containing the Username posting, the post content, and the date. Since the username is a ForeignKey, I had some errors until I was able to fetch the whole User table. I only need to get the username field, which seems to be a dictionary inside and list, as I'll show below. Below, you may find the codes: The Models class User(AbstractUser): pass class PostData(models.Model): active = models.BooleanField(default=True) # In case I want to add a delete feature in the future post_content = models.CharField(max_length=360) date_post_created = models.DateTimeField(auto_now_add=True) user_posting = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userposting") def __str__(self): return f"{self.post_content}" def serialize(self): return { "post_content": self.post_content, "user_posting":serializers.serialize("json", User.objects.all()), "date_post_created": self.date_post_created } The views.py def all_posts(request): # Get posts. posts = PostData.objects.all() #Return in reverse chronological order posts = posts.order_by("-date_post_created").all() return JsonResponse([post.serialize() for post in posts], safe=False) The posts.js (which has the code to feed the html) function load_posts(){ fetch('allposts') .then(response => response.json()) .then(posts => { posts.forEach(element => { console.log(element.post_content); console.log(element.user_posting); console.log(element.date_post_created); (...) The current output: from console.log(element.post_content); teste teste teste ** from console.log(element.user_posting); ** [ {"model": "network.user", "pk": 1, "fields": {"password": "pbkdf2_sha256$216000$C13hJOjD4ojv$AW5a0AFEisWO7IG0MkVNQ8k6+OnfN0CljEV8lnfEaKE=", "last_login": "2021-01-29T00:01:37.127Z", "is_superuser": false, "username": … -
django extended page not rendering values from registration page (User django Model)
I extended the user model and created one to one relationship from users to a Customer model. However, whenever I'm calling the Customer Page the fields from the user model are not rendered there. It's only rendering one field, the username in the Customer Model in the field name instead of rendering the first name as name, last name and email address, and so on. How can I achieve that? I need the customer form to fill in using information from the user's registration whichever is available. Makes sense? Or the implementations I'm trying to do is wrong. Thank you in advance. Please see below the code for models.py and views.py models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.auth.models import Group # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True,on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True, blank=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) city = models.CharField(max_length=200, null=True) address_1 = models.CharField(max_length=200, null=True) zip_code = models.CharField(max_length=5, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.name) #return self.name # Using signals to post_save data def customer_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='customer') instance.groups.add(group) Customer.objects.create( user=instance, name=instance.username, ) … -
convert json string to datetime format dd/mm/yyyy in django template
After using json.loads to get data and show it on django template, it give these results Contract Name Debt Createat 20150307-500000-0009 AAA 2 2020-12-13T14:25:35Z 20170221-0007429 BBB 3 2020-12-13T14:25:35Z I try to convert date time on createat column to dd/mm/yyyy, like this Contract Name Debt Createat 20150307-500000-0009 AAA 2 13/12/2020 20170221-0007429 BBB 3 13/12/2020 In my view contract_posts = serializers.serialize('json', Contracts.objects.all()) contract_posts = json.loads(contract_posts) request.session['contract_posts'] = contract_posts context = {'contract_posts': contract_posts} return render(request, 'customer2.html', context) in my template {% for contract in contract_posts%} <tr> <td>{{ contract.fields.contract }}</td> <td>{{ contract.fields.name }}</td> <td>{{ contract.fields.debt }}</td> <td>{{ contract.fields.created_at}} </tr> {% endfor %} I try <td>{{ contract.fields.created_at|date:"d m Y"}} or <td>{{ contract.fields.created_at|date:"SHORT_DATE_FORMAT"}} But it just show empty cell in result Contract Name Debt Createat 20150307-500000-0009 AAA 2 20170221-0007429 BBB 3 -
How to get current user information in django admin template?
I have the following Profile model which relates the user using a OneToOneField and also has a theme field with two choices light & dark. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile') theme = models.CharField(max_length=20, choices=USER_THEME, default='light') history = HistoricalRecords() def __str__(self): return self.user.username I access the current logged In user theme in my templates using the following: {{ user.user_profile.theme }} Now I want to access the same thing in my overriden django admin template named base_site.html. I did the following but even though the theme of the current user is light it still loads the dark.css file from /static/css/admin/. base_site.html {% extends "admin/base.html" %} ...... {% block extrahead %} <!-- Problem is here --> {% if user.is_authenticated %} {% if user.user_profile.theme == 'dark' %} <link href="{% static '/css/admin/dark.css' %}" rel="stylesheet"> {% endif %} {% endif %} {% endblock %} I don't know what I'm doing wrong here and I appreciate some help. I'll improve my question if more information needed. Thanks in Advance! -
Matching cards in Django, html and js
good evening everyone. I have a list of random questions and answers, they're not very much different than matching cards. I'm making them using Django library in python. And I can't manage to make it to work, using html, js. I tried couple of scripts but they all failed. Here's the code: views.py: def homePage(request): objects = QuestionsAndAnswers.objects.values('question', 'answer', 'id') objects = sample(list(objects), 10) context = { 'QuestionsRandom' : sample(list(objects), 10), 'AnswersRandom' : sample(list(objects), 10), } return render(request, 'homepage.html', context=context) homepage.html: <div class='column1'> {% for result in QuestionsRandom %} <p><button class="questionCard" id="Q{{result.id}}" onclick="setColorQuestion('Q{{result.id}}')"> <p style="color:black;margin: center;">{{forloop.counter}}</p> <p style="color:#4CAF50;font-size: 23px;text-align: center;">{{result.question}}</p> </button></p> {% endfor %} </div> {% for result in AnswersRandom %} <p><button class="answerCard" id="A{{result.id}}" onclick="setColorAnswer('A{{result.id}}')"> <p style="color:black">{{forloop.counter}}</p> <p style="color:rgb(228, 72, 72); font-size: 23px;padding: inherit;">{{result.answer}}</p> </button></p> {% endfor %} I make the question's id and the answer's id invisible, so I can call them in the js script to check if they're the same then count a point to the team that opened the question card and the answer card correctly. <script> function checkingCard(choosedCardID) { var button = document.getElementById(choosedCardID); var style = getComputedStyle(button); var color = style['background-color']; if (choosedCardID.startsWith('Q') && color == 'rgb(0, 0, 0)') { console.log('entering question, rgb is black'); … -
How do I pass in a value (kwargs?) through the URL for Django DayArchiveView?
Okay, So I have a club model which has many booking slots. I want to be able to use Django DayArchiveView but pass in additional parameters which correspond to the club. This is what I tried but I get the error "NoReverseMatch at /book/club/5/2021/jan/1/ Reverse for 'archive_book_day' with keyword arguments '{'year': '2020', 'month': 'dec', 'day': '31'}' not found. 1 pattern(s) tried: ['book/club/(?P[0-9]+)/(?P[0-9]+)/(?P[^/]+)/(?P[0-9]+)/$']" urls.py urlpatterns = [ # Example: club/5/2012/nov/10/ path('club/<int:clubid>/<int:year>/<str:month>/<int:day>/', BookingArchiveView.as_view(), name="archive_book_day"), ] views.py class BookingArchiveView(DayArchiveView): ..... You see it works perfectly fine when I only use 'int:year/str:month/int:day/' but I want to be able to add a parameter to represent the club. Can anyone help me or tell me how I should go about doing this.