Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
A model field for storing an ordered list of ForeignKeys with duplicates
I have two models A and B, and B would like to keep an ordered list of As that can contain duplicates. class A(models.Model): ... class B(models.Model): As = models.OrderedOneToManyWithDuplicatesField(A) Where OrderedOneToManyWithDuplicatesField is mythical. I imagine that it might be a ManyToManyField with a custom through model that keeps a and ordering key, but am not sure if and how that would support the same A appearing more than ones in a given B.As. class A(models.Model): ... class B(models.Model): As = models.ManyToManyField(A, through=A_List) class A_List(models.Model): A = models.ForeignKey(A) B = models.ForeignKey(B) index = models.PositiveIntegerField() I guess I haven't found any documentation clearly stating this yet, nor made time to test it (which I will do), and I am wondering if anyone has experience to share in the interim. I guess the question boils down to whether A_list can can contain multiple rows that have the same A and B but a different index. Which in turn may boil down to: How Django keys that model (if it has an independent AutoField primary key, implicit or explicit) for example. That is, A and B are not together a unique key. Whether the manager(s) have any built-in premises about through table uniqueness … -
How do i save multiple files and prevent multiple entry to database
I am trying to save multiple files to a database. The problem however is that whenever I upload, two entries are created. Here is an example of what i am saying and models.py COLLECTION=( ("FICTION", "Fiction"), ("NON-FICTION", "Non-Fiction"), ("AUTOBIOGRAPHY", "Autobiography"), ("BIOGRAPHY", "Biography"), ) def validate_book_extension(value): import os from django.core.exceptions import ValidationError ext = os.path.splitext(value.name)[1] # [0] returns path+filename valid_extensions = [".pdf", ".epub"] if not ext.lower() in valid_extensions: raise ValidationError("Unsupported file extension.") class Books(models.Model): """ This is for models.py """ book_title = models.CharField(max_length=255, default="", primary_key=True) collection = models.CharField(max_length=255, choices=COLLECTION, default="") # book_author = models.CharField(max_length=255, default="") # publication_year = models.CharField(max_length=4, default="") # isbn = models.CharField(default="", max_length=25) book = models.FileField(default="", upload_to="media/books", validators=[validate_book_extension], verbose_name="book Name") class Meta: verbose_name_plural = "Books" def __str__(self): return self.book_title forms.py class Book(forms.ModelForm): class Meta: model = Books exclude = ["book_title"] widgets = { "book_title":forms.TextInput(attrs={"placeholder":"How"}), "book":forms.ClearableFileInput(attrs={"multiple":True}) } views.py def books(request): form = Book() if request.method == "POST": form = Book(request.POST, request.FILES) files = request.FILES.getlist("book") if form.is_valid(): for f in files: names = str(f) name = names.strip(".pdf") file = Books(book=f, book_title=name) file.save() form.save() return redirect(index) else: form = Book() return render(request, "books.html", {"form":form}) So basically, what i want to achieve is to be able to save a file without creating multiple … -
Django check if object in post method have specific value
I'm using DRF and have object with ManyToMany field. I'd like to check if object that user sent on server contains any pk in that field. Then i want to set boolean field to true in linked object to that ManyToMany. Models: class Parent(models.Model): child_link = models.ManyToManyField(child, related_name="child") class Child(models.Model): in_use = models.BooleanField(default=False) Views: class ParentView(viewsets.ModelViewSet): serializer_class = ParentSerializer authentication_classes = (SessionAuthentication, ) def get_queryset(self): user = self.request.user return Parent.objects.filter(user=user) class ChildView(viewsets.ModelViewSet): serializer_class = ChildSerializer authentication_classes = (SessionAuthentication, ) def get_queryset(self): user = self.request.user return Child.objects.filter(user=user) Serializers: class ParentSerializer(serializers.ModelSerializer): class Meta: model = Parent fields = __all__ class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = __all__ -
Export an html to PDF in Django application with charts
I have a Django application, and I want to provide 'export to pdf' functionality on all pages, (Note: all pages have images). I saw multiple tutorials on the topic, there are two ways: either write your pdf on your own or provide an HTML file path and context dictionary (which is difficult for me to provide). I need something like the following: button -> some_url -> some_view_function -> get all content from requesting page -> show the pdf content to the user in a separate window so the user can save it. -
Can't access images via web with Azure storage and Django
I want to access the path of the image/blog in the browser, I am using Django rest API and the package Azure storage, I tried to make the container storage public, but still had no luck in accessing the image, what could be wrong? This is an example of the image I want to access, it's there in the storage but can't access it : https://guiomentor-staging.azurewebsites.net/media/blog_images/images_3.jpeg -
How to send an Javascript object to be processed on a Django Backend
I had asked this question but I found out it was a bit complicated. I have simplified the question here. I am doing payment processing with a javascript API. I get the results, but I want to send it to a Django backend to be processed. I am not too familiar with this Javascript/Django interaction, hence my issue. The following are the files. Subscription.py It's a simple page that lets users choose their subscription. @csrf_exempt @login_required(login_url='login') def subscription(request): user = request.user user_organization = OrganizationUser.objects.get(user=user) company = Company.objects.filter(name = user_organization.organization.name).first() today = datetime.date.today() form = CompanyForm(request.POST) subscription = Subscription.objects.all() if user_organization.is_admin == True: context = {'user_organization': user_organization, 'form': form, 'subscription': subscription, 'company': company, 'today': today,} return render(request, 'registration/subscription.html', context) else: return HttpResponse('You are not authorised to view this page') Here is the corresponding Subscription.html {% block content %} <div class="columns is-centered"> <div class="column is-5 box"> {% if company.paid_till < today %} <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="content"> <h1 class="title is-4"> <i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Account is not active </h1> Your company <strong>{{user_organization.organization}}</strong> is not active. Please renew the subscription.<br> </div> {% else %} <p class="label">We have great subcription options for you. Choose from our list either for monthly … -
Can't get information from codeforces API in Django
in my project, I need to show the name of the contest site. I can't hardcode the name as I have to load the name & details of various websites as per user need. I need to show the Contest site name, contest name, contest date & time(found in UNIX format in the API which has to be converted), contest URL (which is in the list of return items but not showing while I open the API) I am so new in Django and working for the first time with API I wrote the function in views.py def homepage(request): response = pip._vendor.requests.get('https://codeforces.com/api/contest.list').json() return render(request,'home.html',response) and in HTML I did this to get the name of all contests <div class="box"> {% for i in response %} {{i.name}} {% endfor %} </div> -
Error while working with two databases in Django: sqlite3.IntegrityError: NOT NULL constraint failed: wagtailcore_page.draft_title
I'm working on a Django Project with Wagtail which uses two databases. The first one is the standard sql lite database for all django models (called db_tool.sqlite3), the other one is also sql lite but for a wagtail integration (called db.sqlite3). I wanted to migrate to the db_tool.sqlite3 with the following command python manage.py make migrations python manage.py migrate --database db_tool but now I get the following error message regarding wagtail, which I never got before. django.db.utils.IntegrityError: NOT NULL constraint failed: wagtailcore_page.draft_title First of all: I don't understand this, because I named the db_tool in particular and I wonder, why the wagtail integration raises an error when I try to migrate to db_tool. Second: I see no particular field at my wagtail-pages called draft_title and I don't have any draft page at the moment. Third: the error message also relates to a migration file of wagtail that can be found in the side-packages (see below). So maybe this is the root of the error, but I don't understand the correlation to the other error message, because since now it worked fine and I changed nothing exept of some content of my wagtail pages. File "C:\Users\pubr\.conda\envs\iqps_web\lib\site-packages\wagtail\core\migrations\0001_squashed_0016_change_page_url_path_to_text_field.py", line 23, in initial_data root … -
How can I add an Image to a Django Custom User Model (AbstractUser)?
I am trying to add 'image' to a class that extends AbstractUser. I would like to know how I could use fetch api to make a post request (vuejs) so that it calls on an views.py api and specifically uploads an image for a user. I understand how this would work when it comes to frontend but I do not know what my django views.py api would do assuming I only want it to take a file object and just add to the appropriate user. I have followed the below tutorial, however, they assume DRF is being used as opposed to an api simply made in views.py. This is why I am unsure about what my api will need to do with the image object I pass over using formData https://www.youtube.com/watch?v=4tpMG6btI1Q I have seen the below SO post but it does not directly address what my views.py api would do. That is, will it just store an image in a certain format? A URL? Add Profile picture to Django Custom User model(AbstractUser) class CUser(AbstractUser): image = models.ImageField(upload_to='uploads/', blank=True, null=True) def __str__(self): return f"{self.first_name}" -
how to Don't repeat div into for loop in django template
i have questions and answers into for loop in django template that repeats itself from dictionary, and a button that i don't want to be repeated into the for loop, i searched everywhere on documentation but i found nothing, an exemple : {% for question in questions %} {{question}} {% for reps in questions %} {{reps}} {% endfor %} <div><input type="button" value="Next question"></div> {% endfor %} i want to don't repeat the input button into the for loop -
Django when I upload a image is not saved
I'm trying to create an auction system with django. But when I create a new item for the auction, the image is not saved, but the rest of the item does. But the media folder isn't created. SETTINGS.PY MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") URLS.PY urlpatterns = [ path("admin/", admin.site.urls), path("", include("core.urls")), path("users/", include("users.urls")), path("users/", include("django.contrib.auth.urls")), path("auction/", include("auction.urls")), ] if settings.DEBUG: """ With that Django's development server is capable of serving media files. """ urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) MODELS.PY class Auction(models.Model): object = models.CharField(max_length=50) description = models.CharField(max_length=256, default="") image = models.ImageField(upload_to="media/", null=True, blank=True) open_date = models.DateTimeField(auto_now_add=True) close_date = models.DateTimeField() total_bet = models.IntegerField(default=0) open_price = models.FloatField( default=0, ) close_price = models.FloatField(default=0) winner = models.CharField(max_length=256, default="") active = models.BooleanField(default=True) json_details_file = models.TextField(default="") tx = models.CharField(max_length=256, default="") def __str__(self): return self.object FORMS.PY class ItemForm(forms.ModelForm): class Meta: model = Auction fields = ["object", "description", "image", "close_date", "open_price"] widgets = { "close_date": DateTimeInput(attrs={"placeholder": "YYYY-MM-DD HH:MM"}) } VIEW.PY @login_required(login_url="login") def new_item(request): """ A function that will create a new item for te auction """ if request.method == "POST": form = ItemForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, "Item create") return redirect("homepage") else: form = ItemForm() return render(request, "auction/new_item.html", {"form": form}) new_item.html {% extends "base.html" %} {% … -
Get average of multiple ratings values from different model instances (Django)
I'm working on this web-app that lets a project manager rate a vendor after finishing a task/job. Here is the models.py content: class Rating(models.Model): RATE_CHOICES = [ (1, 'Below Expectation greater than 0.02'), (2, 'Meet Expectaion 0.02'), (3, 'Exceed Expectaions less than 0.02'), ] reviewer = models.ForeignKey(CustomUser, related_name="evaluator", on_delete=models.CASCADE, null=True, blank=True) reviewee = models.ForeignKey(Vendor, null=True, blank=True, related_name="evaluated_vendor", on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE, null=True, blank=True, related_name='jobrate') date = models.DateTimeField(auto_now_add=True) text = models.TextField(max_length=200, blank=True) rate = models.PositiveSmallIntegerField(choices=RATE_CHOICES) class Job(models.Model): title = models.CharField(null=True, blank=True, max_length=100) project_manager = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name="assigned_by") startDate = models.DateField(blank=True, null=True) deadlineDate = models.DateField(blank=True, null=True) status = models.CharField(choices=STATUS, default='In Preparation', max_length=100) evaluated = models.BooleanField(default=False) #Related Fields purchaseOrder = models.ForeignKey(PurchaseOrder, blank=True, null=True, on_delete=models.CASCADE) project = models.ForeignKey(Project, blank=True, null=True, on_delete=models.CASCADE, related_name="Main_Project") assigned_to = models.ForeignKey(Vendor, blank=True, null=True, on_delete=models.CASCADE, related_name="Job_owner") class Vendor(models.Model): #Basic Fields. vendorName = models.CharField(null=True, blank=True, max_length=200) addressLine1 = models.CharField(null=True, blank=True, max_length=200) country = models.CharField(blank=True, choices=COUNTRY_CHOICES, max_length=100) postalCode = models.CharField(null=True, blank=True, max_length=10) phoneNumber = models.CharField(null=True, blank=True, max_length=100) emailAddress = models.CharField(null=True, blank=True, max_length=100) taxNumber = models.CharField(null=True, blank=True, max_length=100) mother_language = models.CharField(blank=True, choices=LANGUAGE_CHOICES, max_length=300) Here is my view.py: @login_required def vendors(request): context = {} vendors = Vendor.objects.all() context['vendors'] = vendors if request.method == 'GET': form = VendorForm() context['form'] = form return render(request, … -
Storing different types of data in a single django database column
I have a problem that I can't quite fix, I have a table built on the basis of a model: class MessageData(models.Model): messageID = models.IntegerField() fieldID = models.IntegerField() value = models.CharField(max_length=60) class Meta: verbose_name = 'MessageData' verbose_name_plural = 'MessagesData' I need to somehow, when creating a request, in some posts, in the value field, transfer the file and then save it to the media folder, and in some posts, the text is simply taken from the textarea, Meybe someone knows a simple method to implement this without adding new fields to the model? The data i get from this template using this method: def clientPage(request, link_code): if request.method == 'POST': files = request.FILES req = request.POST.copy() print(files) print(req) {% block content %} <div class="card bg-dark"> <div class="card-header"> <h5 class="text-light">From associate: {{ message }}</h5> </div> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <fieldset> <div class="card-body"> <div class="form-group"> <label for="subjectInput" class="form-label mt-4 text-light">Subject</label> <input class="form-control" id="subjectInput" placeholder="Enter subject" name="subject"> </div> <div class="form-group"> <label for="Textarea" class="form-label mt-4 text-light">Text Area</label> <textarea class="form-control" id="Textarea" rows="3" name="textArea"></textarea> </div> <div class="form-group"> <label for="formFileMultiple" class="form-label">Multiple files input</label> <input class="form-control" type="file" id="formFileMultiple" name="file" multiple/> </div> </div> <div class="card-footer"> <button class="btn btn-success" type="submit">Send Data</button> </div> </fieldset> </form> </div> {% endblock %} -
How to disable transaction in Django Admin?
I used @transaction.non_atomic_requests for the overridden save() in Person model as shown below: # "store/models.py" from django.db import models from django.db import transaction class Person(models.Model): name = models.CharField(max_length=30) @transaction.non_atomic_requests # Here def save(self, *args, **kwargs): super().save(*args, **kwargs) And, I also used @transaction.non_atomic_requests for the overridden save_model() in Person admin as shown below: # "store/admin.py" from django.contrib import admin from .models import Person from django.db import transaction @admin.register(Person) class PersonAdmin(admin.ModelAdmin): @transaction.non_atomic_requests # Here def save_model(self, request, obj, form, change): obj.save() But, when adding data as shown below: Transaction is used as shown below. *I used PostgreSQL and these logs below are the queries of PostgreSQL and you can check On PostgreSQL, how to log queries with transaction queries such as "BEGIN" and "COMMIT": And also, when changing data as shown below: Transaction is also used as shown below: So, how can I disable transaction in Django Admin? -
how to add data to a list of dictionary
a = list(request.POST.getlist('users')) b = get_participants['participants'] output=[] for i in b: for k in a: if k in i: print(k) c={ "participants" : k, "attendance" : "Present" } # output.append(c) else: c={ "participants" : i, "attendance" : "Absent" } output.append(c) print(output) This is my code I have to add participants with respect to their attendance . In "a" Im getting list of participants those are present. In "b" Im getting all participants My logic wasnt going right plz correct me. a = list(request.POST.getlist('users')) b = get_participants['participants'] output=[] for i in b: for k in a: if k in i: print(k) c={ "participants" : k, "attendance" : "Present" } # output.append(c) else: c={ "participants" : i, "attendance" : "Absent" } output.append(c) print(output) I have tried this Output: [{'participants': 'rajesh.gupta@atmstech.in', 'attendance': 'Present'}, {'participants': 'rajesh.gupta@atmstech.in', 'attendance': 'Absent'}, {'participants': 'pranay.gharge@atmstech.in', 'attendance': 'Absent'}, {'participants': 'pranay.gharge@atmstech.in', 'attendance': 'Present'}] expected output: [{'participants': 'rajesh@gamil.in', 'attendance': 'Present'}, {'participants': 'pranay@gmail.in', 'attendance': 'Present'}] -
Django imagefield repeat
I added an index.html carousel for my django project. When I try to pull the database from django admin, there are a lot of pictures and it repeats one picture? [enter image description here](https://i.stack.imgur.com/CJXFa.png) [enter image description here](https://i.stack.imgur.com/p7OKh.png) [enter image description here](https://i.stack.imgur.com/gjTcy.png) Can you tell me where is the problem? -
Can a mobile application backend be built using Django & python?
Me and my friend are trying to create a mobile application. We'll be using flutter in the frontend. There are some doubts we've regarding the backend of the application. Can we create the backend using Django and python? We're planning to access the backend with the Api's. Did some googling where some said it is not possible to build because Django is a web framework also were some said it can be done if we're using it with Api. Our Stack: Frontend: Flutter Backend: (Python-Django) or (Nodejs-Express) Database: MongoDB NOTE: I want to keep my backend as clean as possible as in don't want to keep extra things which I will not be using in my project! -
Match student's time with TA's time slot to make a scheduling table
I'm trying to make a scheduling system for TAs and students at my school. The logic is every TA has an open period (from start_time to end_time on some days of the week, and 15-minute slots during that period. (I figured out how to output that in HTML already.) Every student also has a time they want to meet with an available TA whose time slot match with the student's time on the same day of the week. I'm having trouble with how to match student's time with TA's time slot and put student's name beside TA's time slot. Can anyone help, please? Thanks!! Here's my models, views.py, HTML, and web output. -
Django UpdateView Two Seperate Form Save (included inlineformset_factory)
I have a specific problem with my forms. I think it would be better to share my codes instead of explaining the problem in detail. However, to explain in a nutshell; inside my model I have field OneToOneField and model of that field has inlineformset_factory form. My new model also has a form and I want to save both forms. I get the following error when I want to save the offer update form: TypeError at /ru/mytarget/offer-update/T2GTTT053E9/ AdminOfferUpdateView.form_invalid() missing 2 required positional arguments: 'request_form' and 'request_item_formset' Models: request.py class RequestModel(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="customer_requests") id = ShortUUIDField(primary_key=True, length=10, max_length=10, prefix="T", alphabet="ARGET0123456789", unique=True, editable=False) status = models.BooleanField(default=True) request_title = models.CharField(max_length=300) delivery_time = models.CharField(max_length=50) shipping_country = models.CharField(max_length=50) shipping_address = models.CharField(max_length=300) preferred_currency = models.ForeignKey(Currency, on_delete=models.CASCADE) shipping_term = models.ForeignKey(ShippingTerm, on_delete=models.CASCADE) delivery_term = models.ForeignKey(DeliveryTerms, on_delete=models.CASCADE) request_statuses = models.ForeignKey(RequestStatus, on_delete=models.CASCADE, blank=True, default=1) is_accepted = models.BooleanField(default=False) is_rejected = models.BooleanField(default=False) is_offer_created = models.BooleanField(default=False) updated_on = models.DateTimeField(auto_now=True) published_date = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.request_title) class Meta: verbose_name_plural = "Requests" verbose_name = "Request" def get_absolute_url(self): return reverse('mytarget:customer_request_details', kwargs={'pk': self.id}) class RequestItem(models.Model): request_model = models.ForeignKey(RequestModel, on_delete=models.CASCADE, related_name="request_items") product_name = models.CharField(max_length=300) product_info = models.TextField(max_length=2000, blank=True) target_price = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) price = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) quantity = models.DecimalField(max_digits=10, decimal_places=2) … -
Send data from google sheet to a webhook url in json format on trigger column
Is there a way to trigger an action (i.e convert row data into json format and send it to a webhook URL) from googlesheets based on column values like dates? Triggers like when todays date equals date in column? WEBHOOK REQUEST EXAMPLE DATA { "data": { "header_image_url": "https://..." }, "recipients": [ { "whatsapp_number": "+91XXXXXXXXXX", "attributes": { "first_name": "James", "last_name": "Bond" }, "lists": [ "Default" ], "tags": [ "new lead", "notification sent" ] } ] } I am new to webhooks and API stuff, there form do not know much. -
what is the best way to use has_usable_password in Django 3 templates?
I would like to add condition in my template to see if user password is set or not. Something like this doesn't work for me because I cannot put it in my html: >>> a = User.objects.create_user('user1', 'user1@example.com') >>> b = User.objects.create_user('user2', 'user2@example.com', password='secret') >>> a.has_usable_password() False >>> b.has_usable_password() True I tried to put has_usable_password in html as template tag but it doesn't work: {% if user.has_usable_password == True %} password ok {% else %} password not set {% endif %} Something like this is also not working {% if user.has_usable_password %} passord ok {% else %} password not set {% endif %} But if I go to admin panel I see password not set -
Use filterset class in a nested route in Django REST Framework
We have a REST API created with Django and Django REST Framework. With the package django-filter I've created a FilterSet class which I want to use in a nested route. For illustration, we have model classes User, Post, Tag. A Post has one author (User) and can have many (or none) Tags. The following endpoints are present: /users/[id]/ /posts/[id]/ /users/[id]/posts/ The FilterSet class looks like this: class PostFilterSet(filters.FilterSet): tags = filters.ModelChoiceFilter(queryset=Tag.objects.all()) class Meta: model = Post fields = ("tags",) We use it in the viewset for Posts: class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() filter_backends = [filters.DjangoFilterBackend] filterset_class = PostFilterSet Now this is working well and the list of posts can be filtered by tag, like this: /posts/?tags=some_tag In the UserViewSet we have a nested route created with the decorator action: class UserViewSet(viewsets.ReadOnlyModelViewSet): @action(methods=["get"], detail=True) def posts(self, request, pk): # logic to fetch posts for the given user return Response(serializer.data) We want to filter the list of posts for a given user (author) tagged by some tag: /users/[id]/posts/?tags=some_tag I want to use the PostFilterSet class in the nested route above. Is this possible? If yes, how should it be done? -
Unable to understand why the error is occurring
I have been trying to concatenate two strings and assign them to a cell in an excel sheet. I am however unable to understand why the below-shown error is occurring as I cannot find any error in the functioning of the rest of the code the error shown is: Traceback (most recent call last): File "C:\Users\AdvaitSNambiar\Desktop\Myfolder\SUTT task\Final\task1test-2-final.py", line 63, in <module> ws['D' + str(i) ].value = ws['D' + str(i)].value + '+ EEE' TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' if (h2 == 'A3'): ws['D' + str(i) ].value = ws['D' + str(i)].value + '+ EEE' this was the concatenation I tried to perform my code is given below import openpyxl from openpyxl import load_workbook wb = load_workbook('names.xlsx') ws = wb.active i = 0 while(i<24): i = 2 while(i<24): idnum = ws['A' + str(i)] idnum1 = idnum.value idnum2 = idnum1[4:8] if (idnum2 == 'AAPS'): ws['D' + str(i)] = 'ECE' if (idnum2 == 'ABPS'): ws['D' + str(i) ] = 'Manu' if (idnum2 == 'A1PS'): ws['D' + str(i)] = 'chemical' if (idnum2 == 'A2PS'): ws['D' + str(i) ] = 'civil' if (idnum2 == 'A3PS'): ws['D' + str(i) ] = 'EEE' if (idnum2 == 'A4PS'): ws['D' + str(i)] = 'Mech' if (idnum2 == … -
Pass html in to another html
Hello dear community, First of all, I've been trying to solve the problem for x hours, but so far I've failed transiently. You are Tmm a last opening. I am currently involved in a project where we are developing a quiz game. I am responsible for the backend. We want users to be able to add questions to the game as well, but when a user adds a question, it should be saved to the database before the question. As soon as the user adds a question, the admin gets an email: "A new question has been received", and the email contains a link that leads to an html page (approve_question.html). Up to here everything works. However, the link only leads to an empty html page. I want added question then show on approve_question.html so admin can save in database after check so question will show in game then. my problem is i can't find question.html page (the question with four answers can then be entered here), with the content forward to approve_question.html. I'll add some more code to make it clearer. The question.html has one field for the questions and four for the answers. I would like to fill … -
While paginating my results of dictionary values in djnago I am getting an error as unhashable type: 'slice'
I am trying to paginate my results(dictionary values) to html page. While doing I am getting an error unhashable type: 'slice' views.py from django.shortcuts import render import urllib.request import json from django.core.paginator import Paginator def display(request): cities=['vijayawada','guntur','tenali','rajahmundry','amaravathi','Bengaluru','Mangaluru','Chikkamagaluru','Chennai'] data = {} for city in cities: source = urllib.request.urlopen( 'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=metric&appid=APIID').read() list_of_data = json.loads(source) data[city] = { "country_code": str(list_of_data['sys']['country']), "coordinates": { 'latitude': str(list_of_data['coord']['lat']), 'longitude': str(list_of_data['coord']['lon']) }, "temp": str(list_of_data['main']['temp']) + ' °C', "pressure": str(list_of_data['main']['pressure']), "humidity": str(list_of_data['main']['humidity']), 'main': str(list_of_data['weather'][0]['main']), 'description': str(list_of_data['weather'][0]['description']), 'icon': list_of_data['weather'][0]['icon'], } p = Paginator(data,3) page = request.GET.get('page') d = p.get_page(page) context = {'data': d} return render(request, 'display.html', context) Please help me to paginate the values in a dictionary I expect the paginated results of my dictionary values