Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test Django class base View method with pytest Client?
I am using Django to build a website and now I am running unittest with pytest, but I could't test my class base view method with pytest Client, I did it with RequestFactory but I want to run it also with Client. This is my test case Class. import pytest from django.contrib import auth from django.contrib.auth.models import User from django.forms import modelform_factory from django.urls import reverse, is_valid_path from company.models import Company from company.views import CompanyView @pytest.mark.django_db class TestCompanyView: @pytest.fixture def company_form(self): yield modelform_factory(Company, fields='__all__') @pytest.fixture def user(self, db): yield User.objects.create_user(username='admin', password='admin') @pytest.fixture def login_pass(self, client): yield client.login(**{'username': 'admin', 'password': 'admin'}) @pytest.fixture def login_fail(self, client): yield client.login(**{'username': 'admin', 'password': 'admi'}) def test_company_view_require_login_failed(self, client): path = reverse('companyview') assert is_valid_path(path) response = client.post(path, data={'saveForm': '-1', 'name_english': 'ITTech', 'mobile_number': 89897}) assert response.status_code == 302 # status_code will be 302 if login failed assert response.context is None def test_company_view_require_login_pass(self, client, user): path = reverse('companyview') assert is_valid_path(path) client.login(**{'username': 'admin', 'password': 'admin'}) response = client.post(path, data={'saveForm': '-1', 'name_english': 'ITTech', 'mobile_number': 89897}) assert response.status_code == 200 # status_code will be 200 if login pass assert '_auth_user_id' in client.session # checks that auth_user_id is in client session user = auth.get_user(client) assert user.is_authenticated # checks that logged in user is … -
Django : input field dropdown for receiver customized based on sender
I am trying to make my dropdown list for the receiver in which the sender's id/name won't be included. I guess this is not a case of chained dropdown which has been answered previously. Maybe ajax is needed to be used here, but I am not understanding the exact code of ajax, if it is to be used. Below are my template file, views.py file and models.py file. home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'Bank_App/css/styles.css' %}" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"> </script> </head> <body> <div class="container"> <center> <h2>Customer Details</h2> </center> <table> <tr> <th>Sr. No.</th> <th>Customer Id</th> <th>Customer Email</th> <th>Account Balance</th> <th>Send Money</th> </tr> {% for customer in customer_details %} <tr> <td id="customer_pk">{{customer.pk}}</td> <td id="customer_id">{{customer.customer_id}}</td> <td id="customer_email">{{customer.customer_id.email}}</td> <td id="customer_acc_balance">{{customer.account_balance}}</td> <td> <center><button type="button" class="btn btn-primary btnDemo" data-bs-toggle="modal" data-bs-target="#exampleModal" id="send" data-name={{customer.customer_id}} data-balance={{customer.account_balance}}> Send Money </button> </center> </td> </tr> {% endfor %} </table> </div> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Transfer Money</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <h6 id="modal_body"></h6> <center> <form … -
color p tags different colors based off for loop in Django template
Im creating an application where answers to multiple quizes are displayed on one page. To do this i have a for loop which loops through each one and within that loop use if tags to color the correct answer green. However all quizes get teh same answered color, because the css style doesnt stick between each for loop. How can i stop this? {% for quiz in Quizes %} <div class="question-Card"> <p id="a"> A:{{choice1}} <p id="b"> A:{{choice2}} <p id="c"> A:{{choice3}} <p id="d"> A:{{choice4}} {% if quiz.answer == 'a' %} <style> #a { color: green; } </style> {% endif %} **this then continues for the other choices but the code isnt the issue, so i will save you the read** </div> {% endfor %} The issue is that if the last quiz to be 'read' is colored c then they are all colored c and it doesnt do each one indivisually, please help -
Changes not reflecting in local server of vue project
I have a project built on Vue js. I cloned it and setup in my local machine. I changed the base url from the staging to my local django server. The picture is here. But when I run the vue developemtn server and call the api, it is still calling the staging/production backend. The changes are not reflecting. I can see it is calling the staging backend like here. -
How to pass choises from views.py in forms.ChoiceField?
I want to make a form for online tests, but I can't figure out how to make radio buttons (forms.ChoiceField or similar) with the transfer of the selection value not from forms, but from views. Why can't you get from models directly in the form? because I do not know in advance which pk is needed. Please tell me an option that will help you create a form for online testing. I ask with examples to make it easier to understand. Thanks in advance. -
Reverse for 'bans' with keyword arguments '{'user': 1}' not found. 1 pattern(s) tried: ['bans/(?P<pk>[0-9]+)/$']
I am building a GroupApp and I am trying to add some group members in premium_members(ManyToManyField). In Brief :- I made a Group model for group creation and adding members and I made another GroupPosts with ForeignKey of Group for post creation in the particular Group with id or pk. It means i am accessing all the groups in one page and when someone opens a group then blogposts are showing of the clicked group, Like group_1 has 6 posts and group_2 has 2 posts. AND I am trying to add post_creater in premium_members which is a instance in Group Model. The Problem :- BUT When i click on add_premium_member in the group's post's User. Then post creater is not adding in premium_members. No error is showing. BUT NOT ADDING. models.py # For Group Creation class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') premium_members = models.ManyToManyField(User, related_name='premium_members', blank=True) def get_absolute_url(self): return reverse('group_detail_view',kwargs={'pk':self.pk}) # For Post Creation in Particular Group class GroupPosts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) post_title = models.CharField(max_length=30,default='') views.py # For show the group details and posts in one page (group_detail_view) def group_detail_view(request,pk): data = get_object_or_404(Group,pk=pk) posts = GroupPost.objects.filter(group=data) context = {'data':data,'posts':posts} return render(request, 'group_detail_view.html',context) # … -
How to access a legacy database without creating a new table in it in Django
I was given access to a database to use on one of my Django projects. I set everything up and went to migrate the new models and I got an error. "Unable to create the django_migrations table ((1142, "CREATE command denied to user 'MyDatabaseName' for table 'django_migrations'"))" After looking into it, I see its because Django is trying to create a new table in that database. I don't have write access and I do not want it because I am pretty new at this and do not want to mess anything up. I am also not sure the owner would give it to me. Is there a way to get to use the legacy database without having to create a new table in it? -
how to make requirements.txt work while using circle ci with django
I have the following configuration crashing using CIRCLE CI / DJANGO FOLDER STRUCTURE .circleci |____ config.yml djangoproject |____ djangoproject |____________ settings.py ...etc |____ manage.py Circle CI config.yml file jobs: build: working_directory: ~/someproject docker: - image: circleci/python:3.8 auth: username: mydockerhub-user password: $DOCKERHUB_PASSWORD environment: PIPENV_VENV_IN_PROJECT: true DATABASE_URL: postgresql://root@localhost/circle_test - image: circleci/postgres auth: username: mydockerhub-user password: $DOCKERHUB_PASSWORD environment: POSTGRES_USER: admin POSTGRES_DB: $POSTGRES_DB POSTGRES_PASSWORD: $POSTGRES_PASSWORD steps: - checkout - run: sudo chown -R circleci:circleci /usr/local/bin - run: sudo chown -R circleci:circleci /usr/local/lib/python3.8/site-packages - restore_cache: key: deps9-{{ .Branch }}-{{ checksum "requirements.txt" }} - run: name: Wait for db to run command: dockerize -wait tcp://localhost:5432 -timeout 1m - run: name: Install Python Dependencies command: | pip3 install virtualenv python3 -m venv env . env/bin/activate pip3 install -r requirements.txt - save_cache: key: deps9-{{ .Branch }}-{{ checksum "requirements.txt" }} paths: - "env" - "/usr/local/bin" - "/usr/local/lib/python3.8/site-packages" - run: name: run tests command: | . env/bin/activate pytest -s -v mkdir test-results pytest --junitxml=test-results/junit.xml --html=test-results/pytest_results.html --self-contained-html - store_test_results: path: test-results - store_artifacts: path: test-results workflows: build_and_test: jobs: - build When i push a change to github, Circle CI crash with the following error: #!/bin/bash -eo pipefail pip3 install virtualenv python3 -m venv env . env/bin/activate pip3 install -r requirements.txt Requirement … -
Django - filtering on foreign key usin an attribut
i have 2 foreingkey , one from the User and the other one from Device. class checkn(models.Model): user = models.ForeignKey(User, null=True,on_delete= models.SET_NULL) devices = models.ForeignKey(Device, null=True,on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) ch = models.CharField(max_length=1000, null=True) he's using the Device ID for the search and i want to use the IP adresse : this is the device model : class Device(models.Model): hostname = models.CharField(max_length=200, null=True) password = models.CharField(max_length=200, null=True) type = models.CharField(max_length=200,choices=dtype, null=True) ipadress = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) any advices ? -
Customizing model fields by user
I am making a CRM, and I ran into one task: I want to make a “Client” model, with all possible fields, and give an opportunity for users to “enable” only those “Client” fields that he needs. I have little experience and unfortunately I have not been able to find a solution for this for a long time. I would be grateful if someone can show me an example of how this is done (or a link to a repository with a similar method). -
Setting Up Logins For Users with Django
I am trying to use Django's built in user authentication for login/allowing users to create an account and login. I think there's something wrong with my urls or where files are placed in the project. Can anyone help? I know the login.html file is supposed to be inside a folder called 'registration.' I think the fact that my templates are then in a sub folder called 'capstone' might be causing issues. I just don't know how to point to the right file when someone clicks to login. In urls.py under 'weather' I have the following. In two tutorials I saw it should say 'accounts/' but I'm a bit confused as to why. urlpatterns = [ path('admin/', admin.site.urls), path('', include('capstone.urls')), # medium site says to do this path('accounts/', include('django.contrib.auth.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is how my files are set up in Visual Studio Code: -
Django how to add admin page without using model
I needed to create a admin page which is not associated with any model. I have followed the below documentation. https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls So my admin.py looks like this, class MyModelAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() my_urls = [ path('statistic/', self.my_custom_view), ] return my_urls + urls def my_custom_view(request): . . . return HttpResponse(html) When I login to admin site, I am not able to see the link for this view. Then I added below line to the above code, admin.site.register(MyModelAdmin) It is not working. Please advise what I am doing wrong. -
Request deleting an appointment?
I'm trying to build an appointment system. If a user decided to delete his appointment it must be through request where the admin decides to accept/reject his deleting request. after that the user will receive an email that his deleting request got approved/rejected.. how do I implement that? Where should I start reading about it? Any help is appreciated! -
Docker: Unable to send task from Django to Celery
I have been working recently with Docker and I was able to set up certain services to be able to use Async functions but when I try to send a task to Celery from Django using RabbitMQ it never reachs. When I run the code outside Docker by running several commands on console everything runs perfectly. Not sure whats going on. Any help would appreciated. version: "3.7" services: rabbit: hostname: rabbit container_name: rabbitmq image: 'rabbitmq:3.7-management' environment: RABBITMQ_ERLANG_COOKIE: "SWQOKODSQALRPCLNMEQG" RABBITMQ_DEFAULT_USER: admin RABBITMQ_DEFAULT_PASS: admin RABBITMQ_DEFAULT_VHOST: "/" RABBITMQ_VM_MEMORY_HIGH_WATERMARK: 0.5 CELERY_BROKER_URL: "amqp://admin:admin@172.23.240.1:5672" ports: - "15672:15672" - "5672:5672" expose: - "5672" restart: on-failure networks: rabbitmq_net: aliases: - rabbitmq_host custom_app: build: . container_name: custom_app command: python manage.py runserver 0.0.0.0:8000 volumes: - static:/code/static - .:/code depends_on: - rabbit environment: - CELERY_BROKER='amqp://admin:admin@172.23.240.1:5672' - CELERY_BACKEND='amqp://admin:admin@172.23.240.1:5672' networks: - rabbitmq_net links: - rabbit nginx: image: nginx:1.13 container_name: nginx ports: - 8000:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static:/code/static volumes_from: - custom_app depends_on: - custom_app networks: - rabbitmq_net celery: build: . container_name: celery command: celery -A djangoapp worker --loglevel=info -P eventlet debug volumes: - .:/code depends_on: - rabbit networks: - rabbitmq_net volumes: .: postgres_data: static: networks: rabbitmq_net: name: rabbitmq_network driver: bridge -
Django CKEditor - youtube embeded video disappear after saving at admin panel
There is no problem with uploading. But when I lookup to the article for editing then I can't see youtube video Before saving: After Saving: But actually the iframe block at there. The problem is I can't see it at admin panel again settings.py CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'CMS', 'width': '100%', 'toolbar_CMS': [ ['Format', 'Styles', 'FontSize'], [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript'], ['TextColor', 'BGColor'], ['Link', 'Unlink'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Undo', 'Redo'], ['Copy', 'Paste', 'PasteText', 'PasteFromWord'], ['SelectAll', 'Find', 'Replace'], ['NumberedList', 'BulletedList'], ['Outdent', 'Indent'], ['Smiley', 'SpecialChar', 'Blockquote', 'HorizontalRule'], ['Table', 'Image', 'Youtube'], ['ShowBlocks', 'Source', 'About'] ], 'extraPlugins': 'youtube', 'contentsCss': ( '/staticfiles/ckeditor/customization-files/style.css', '/staticfiles/ckeditor/customization-files/bootstrap.css', ), }, } CKEDITOR_UPLOAD_PATH = 'content/ckeditor/' models.py class Article(models.Model): title = models.CharField(max_length=200) content = RichTextField( extra_plugins=['youtube'], null = False, blank=False, external_plugin_resources=[( 'youtube', '/staticfiles/ckeditor/extra_plugins/youtube/', 'plugin.js', )], ) updated = models.DateField(auto_now=True) created = models.DateField(auto_now_add=True) Django version: 3.2.3 django-ckeditor version: 6.1.0 Additionaly detail: When I click to "See HTML source" and save article then even the current video removing from database -
Django Form only show when i press Submit Button
my form is hide, its onlye display submit button, and when i click it the forms show. Crear Tarea= Create task. Its basically a crud for create task. Here are my Views: class Crear_Tarea(View): def get(self, request,*args,**kwargs): context = { 'form': TareaForm() } return render(request, "crear_tarea.html", context) def post(self, request,*args,**kwargs): context = { 'form': TareaForm() } formulario = TareaForm(request.POST or None) if formulario.is_valid(): formulario.save() messages.success(request, 'Tablero seleccionado con éxito!') context['crear_tarea']= formulario return render(request, "crear_tarea.html", context) My forms: class TareaForm(forms.ModelForm): class Meta: model = Tarea fields = ('nombre','descripcion','fecha_creacion','fecha_termino','user', 'id_columna' ,'id_tipo','detalle','id_documento','estado','estado_avance','posicion') def save(self, commit=True): user = super().save(commit=False) user.id = self.cleaned_data['user'] if commit: user.save() return user and my Models.py class Tarea(models.Model): id_tarea = models.AutoField(primary_key=True) nombre = models.CharField(max_length=99) descripcion = models.CharField(max_length=99) fecha_creacion = models.DateTimeField(null=True, blank=True) fecha_termino = models.DateTimeField(null=True, blank=True) user = models.ForeignKey(Usuario, on_delete=models.CASCADE) id_columna = models.ForeignKey('Columna', on_delete=models.CASCADE) id_tipo = models.ForeignKey('Tarea_tipo', on_delete=models.CASCADE) detalle = models.CharField(max_length=255) id_documento = models.ForeignKey('Documento', on_delete=models.CASCADE) estado = models.IntegerField(blank=True, null=True) estado_avance = models.IntegerField(blank=True, null=True) posicion = models.IntegerField(blank=False, null=False) def __str__(self): return self.nombre crear_tarea.html {% extends "base.html" %} {% load static %} <!doctype html> <html lang="en"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}Crear Tarea Ari-J{% endblock %}</title> {% block content %} <div class="container-fluid"> <div class="row mt-5"> <div class="col-12 my-5"> … -
How to change edges (lines) color when filtering by a drop down menu javascript
I have a folim map drawing by a python code.I have a drop down menu on the left of the map. When selecting the Lane (input) value : all edgs associated to a Lanes value=1 should be colored as "#FF0000" all edgs associated to a Lane value=2 should be colored as "#FFF933" Could you please help me? {% load static %} {% block content %} <div class="row h-100"> <div class="col-md-2" id="destinationDiv"> </div> <div class="col-md-10"> {% include 'visualization/visualization.html' %} </div> <div class="form-group w-75 mx-auto"> <label for="linkSelector" class="sr-only">Links</label> <select id="linkSelector" class="form-control"> <option value="none">Links...</option> <option value="lanes">Lanes (input)</option> <option value="length">Length (input)</option> </select> </div> </div> <script src="{% static '/js/api/changeMapData.js' %}"></script> {% endblock %} My Javascript code which will fetch the data from the api. function changeMapData(){ fetch("http://127.0.0.1:8000/api/edges/") .then(response => { return response.json() }) .then((data) => { var linkSelector = document.getElementById('linkSelector') switch (linkSelector.value) { case "Lanes(input)": if($(edges.lanes)==1){ // Set all edges color = "#FF0000" with number of lanes=1 edges.setStyle ({ 'fillColor': "#FF0000", 'color': "#FF0000" }); } if($(edges.lanes)==2){ // Set all edges color = "#FFF933", with number of lanes=2 edges.setStyle ({ 'fillColor': "#FFF933", 'color': "#FFF933" }); } } }); } My html page containing the map. -
How can i create / Check permission using Django ? Real example
I'm working on a small project using Django / Rest Framework, and now i try to add Groups / Permissions options i don't know from where to start to do permissions checking. I surfed a lot on Google and here, i can't find any tutorial that explain how to use Groups and Permissions ( programmatically ), now I arrived to create a group / permission. like that : from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from api.models import Project new_group, created = Group.objects.get_or_create(name='new_group') # Code to add permission to group ??? ct = ContentType.objects.get_for_model(Project) # Now what - Say I want to add 'Can add project' permission to new_group? permission = Permission.objects.create(codename='can_add_project', name='Can add project', content_type=ct) new_group.permissions.add(permission) Now how can i check if the user has X Permission or no ? where must i do this Logic ? also i heared some thing about default permission that any user has called ( Django Model Permission ) how can i use that ? my Goal is to create a Group and add user to a group, check if the user has the right permissions like any normal applciation can someone give me a small real example ? Thank you -
Get dynamic Form Value from Django Forms
I'm trying to get the totalPrice value from the changing value of the form field through JavaScript. My view part: if request.method == "POST": if (not closed): form = BookingForm(request.POST) if form.is_valid(): booking = form.save(commit=False) booking.author = user booking.hotelName = hotel.name booking.save() success = "Success!" else: return render(request, "hotels/hotel.html", { "form": form }) messages.info(request, success) return HttpResponseRedirect(reverse("hotel", args=(hotel.id,))) else: return render(request, "hotels/hotel.html", { "hotel": hotel, "closed": closed, "message": message, "form": BookingForm() }) My HTML + JS Code: {% if not closed %} <div class="container login"> <h2>Book Now!</h2> <form method="POST"> {% csrf_token %} <div class="form-group"> {{ form.as_p }} </div> <div class="form-group"> <input type="submit" name="button" id="submit" value="Book"> </div> </form> </div> {% endif %} <script> let price = 0; const check = (id) => { if(document.querySelector(`#${id}`).checked) { price += 300; document.querySelector('#totalPrice').value = `${price}`; } if(!document.querySelector(`#${id}`).checked) { if (!price <= 0) { price -= 300; document.querySelector('#totalPrice').value = `${price}`; } } } document.addEventListener('DOMContentLoaded', function() { document.querySelector("#breakfast").addEventListener('click', () => check("breakfast")); document.querySelector("#dinner").addEventListener('click', () => check("dinner")); }) </script> And, my form (through ModelForm): class BookingForm(ModelForm): class Meta: model = Booking fields = ['includeBreakfast', 'includeDinner', 'totalPrice'] labels = { 'includeBreakfast': 'Include Breakfast', 'includeDinner': 'Include Dinner', 'totalPrice': 'Total Price (in USD)' } #Visual stuff the totalPrice is a FloatField in … -
i am getting an error while i am trying to add a user to a defined group while registration in django
#views.py def sign_up(request): if request.method == "POST": fm= SignUpForm(request.POST) if fm.is_valid(): messages.success(request,'account created') fm.save() group = Group.objects.get(name='groupname') User.groups.add(group) else: fm = SignUpForm() return render(request,'signup.html',{'form':fm}) and,i am getting AttributeError like this below:- Django Version: 3.2.3 Exception Type: AttributeError Exception Value: 'ManyToManyDescriptor' object has no attribute 'add' -
How can I convert/export HTML code returned by django-ckeditor's RichTextUploadingField to a docx file?
I want to convert html received from django-ckeditor Field to a docx file, for which I'm using htmldocx. The html code returned by ckeditor uses a css file which contains styles like background-color. So htmldocx is able to recognise bold, italics and alignment but it is not recognising the highlight color. contents of views.py: def home(request): if request.method == 'POST': htd = HtmlToDocx() document = Document() htd.add_html_to_document(request.POST.get('file'), document=document) document.save(settings.MEDIA_ROOT+'TEST.docx') form = File() return render(request, 'home.html', {'form': form}) else: form = File() return render(request, 'home.html', {'form': form}) contents of models.py: class Document(models.Model): file = RichTextUploadingField(blank=True,null=True) For example: for submitted text "Hello World" , where say 'World' is both, highlighted and in italics, the html code returned is: <p>Hello <em><span class="marker">World</span></em></p> #styles of marker class are defined in a separate css file by ckeditor but upon converting the html to docx, the document loses highlight color. Is there any workaround to this issue? Also, ckeditor provides an export to word feature but only through npm. If somehow I could use that feature in django-ckeditor, things would become much easier. How can I implement that feature in django-ckeditor? -
Why do I get an 404 Error in part 4 of the Django tutorial "Writing you first Django app"
I am trying to complete the Django tutorial: Writing your first Django app. I am currently stuck on part 4. After updating my template polls/templates/polls/detail.html, rewriting my polls/views.py and creating a results.html located at polls/templates/polls/results.html, I ran the server and tried to go to http://127.0.0.1:8000/polls/1/, but I get this Error: Page not found (404) No Question matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/ Raised by: polls.views.detail Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ [name='index'] polls/ <int:question_id>/ [name='detail'] The current path, polls/1/, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I see that the error is raised by the html-file detail wich looks like this: <form action="{ url 'polls:vote' question.id }" method="post"> { csrf_token } <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> { if error_message }<p><strong>{{ error_message }}</strong></p>{ endif } { for choice in question.choice_set.all } <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> { endfor } </fieldset> <input type="submit" value="Vote"> </form> My other two templates (html-files) index and result looks like this: … -
Django form validation fails when dynamically creating form by overwriting __init__
I'm writing a prediction app in Django. At a basic level it pulls matches from an API, populates the database, and finally allows users to make predictions on matches that have not yet been played. As I don't know how many matches will be in a tournament before the fact, I wanted to create a form that dynamically adds as many fields as is required. I currently have a "working" version but it would create issues further down the line. Here's the working version: (Fair warning, this is me testing, so excuse the naming conventions) views.py def ftest(request, contest_id): matches_list = Matches.objects.filter( matches_contest_pk__id = contest_id ).filter( matches_complete = False ).order_by( '-matches_start_time' ) matches = [ f'{match.matches_team_1} vs. {match.matches_team_2}' for match in matches_list ] if request.method == 'POST': form = TestForm(form_fields = matches, data=request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: print(form.errors) else: form = TestForm(form_fields = matches) context = { 'form': form, } return render(request, 'predictions/test.html', context) forms.py from django import forms from .models import Matches class TestForm(forms.Form): def __init__(self, *args, **kwargs): form_fields = kwargs.pop('form_fields', None) super(TestForm, self).__init__(*args, **kwargs) for field in form_fields: self.fields[field] = forms.CharField(label = f'{field}', max_length = 100) As I said, this works but I would, ideally, like to … -
open html file and add data into it with iteration
I have a html file for Invoice. and i want to display some data from my database which can be in multiple rows of a table. how can i use iteration to show the data in my Invoice. for example: In an organisation 3 people used a coupon to do a payment. and when invoice would generate all of the three people's name with date and amount i want to display. <thead> <tr> <th class="col-4 border-0"><strong>Sites</strong></th> <th class="col-4 border-0"><span><strong>Mode</strong></span></th> <th class="col-4 border-0"><span><strong>Amount</strong></span></th> </tr> </thead> <tbody> <tbody> ---for loop here--- <tr> <td class="col-4 text-1 border-0"> {var 1} </td> <td class="col-4 border-0"><span> {var 2} </span></td> <td class="col-4 border-0"><span> {var 3} </span></td> </tr> </tbody> </table> The way i am passing data from views is: my_dict=[{'var1':'my site', 'var2': 'DIY', 'var3':'111'}, {'var1':'my site2', 'var2': 'DIY', 'var3':'222'}] with open(BACKEND_TEMPLATE + 'Invoice_base.html') as inf: txt = inf.read() val = txt.format(date=today, invoice_id=str(identity), domain=FRONTEND_DOMAIN, customer_name=(obj.customer.first_name + " " + obj.customer.last_name), company=obj.customer.company_name, contact=obj.customer.phone_number, my_dict=my_dict) how can i achieve that. The html file is not supporting template tags or may be i am not using it correctly. if there is an easy solution please help me out! -
sliding key in Django how to
i am fairly new to python programing language and this year i challenged myself to build our project's app. We want the app to display certain features. To start with, this is our pseudo code : ' Inputs: Desired Max Temperature Tmax Intensity (in %) On or Off Tsurface Outputs LED0 LED1 LED2 LED3 LEDRED Relay1 Relay2 When Settings are changed If device is at 0% Power (0W) LED1, LED2, and LED3 are off If device is at 0 to 39% power (2.5 W) LED 1 is on, LED2 and LED3 are off If device is at 40 to 79% power (5 W) LED 1 and LED2 are on, LED3 is off If device is at 80 to 100% power (7.5 W) LED 1, LED2 and LED3 are on Ton = Tcycle * Intensity / 100% Continuously happen with timing signals If Tsurface >Tmax Relay1, Relay2 are off LEDRED is on Else At t=0+Ton/2 Turn Relay1 off At t=Tcycle-Ton/2 Turn Relay 1 on At t=Tcycle/2 - Ton/2 Turn Relay 2 on At t=Tcycle/2 + Ton/2 Turn Relay 2 off ' Python code ' from django.contrib import admin from django.urls import path, include from .views import (home,led_off,led_on, increase_temp,decrease_temp) urlpatterns = [ …