Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Mail is not sent
Email is not sent. What is interesting... before (like 3 mos ago) entire code worked perfectly fine. Settings: DEBUG = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT: 587 EMAIL_HOST_USER = 'xyz@gmail.com' EMAIL_HOST_PASSWORD = 'xyz' EMAIL_USE_TLS = True ALLOWED_HOSTS = [] view.py: def index(request): """The home page.""" # Send a message. if request.method != 'POST': # No data submitted; create a blank form. form_email = EmailForm() form_message = EmailMessageForm() else: # POST data submitted; proecess data. form_email = EmailForm(data=request.POST) form_message = EmailMessageForm(data=request.POST) if form_email.is_valid() and form_message.is_valid(): try: email = Email.objects.get(text=request.POST['text']) except: form_email.save() email = Email.objects.last() message_db = form_message.save(commit=False) message_db.email = email message_db.save() message_owner = ( f'New email on your website from {request.POST["text"]}', f"Email has been sent from: {request.POST['text']}\n\n" f"Full message:\n\"{request.POST['message']}\"", 'settings.EMAIL_HOST_USER', ['my@gmail.com',], ) message_guest = ('Your email has been sent', "Many thanks for getting in contact with me. Your message was " "successfully sent. I will reach out to you as soon as possible." f"\n\nYour message:\n\"{request.POST['message']}\"", 'settings.EMAIL_HOST_USER', [request.POST['text'],], ) send_mass_mail((message_owner, message_guest), fail_silently=False) return redirect('home:contact_thank_you') # Display a blank or invalid form. context = {'form_email': form_email, 'form_message': form_message} return render(request, 'home/index.html', context) Traceback: Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.1.5 Exception Type: TimeoutError Exception Value: [WinError 10060] Raised during: home.views.index C:\Users\danie\Desktop\python_work\page\home\views.py, line … -
Django - How to control 'add another' links in django-nested-admin areas
I have a very complicated object structure that the django admin section handles like a champ. As you can see below there are sub-references to other objects or even the same object. In many cases the sub objects are created in a certain pattern and I'd like to be able to generate stubs for that pattern. What i'd like to be able to do is I guess customize what happens when you click on the 'Add another Crafted Item' link, or add another link that will add multiple sub-item stubs. Right now if you click on that link, you get ONE stub with default values in it from the model object. I wanna do the same thing, but I want to be able to do more than one and be able to specify different default values than what are specified in the model object. Does anyone have any idea how I can tap into that functionality? Is there a name for it or something? thanks for the assistance, EK -
What is causing `tzlocal` to throw `Please use a timezone in the form of Continent/City. tzlocal() does not support non-zoneinfo timezones like UTC`?
Please use a timezone in the form of Continent/City. tzlocal() does not support non-zoneinfo timezones like UTC This was raised by requests.raise_for_status() My settings.py: USE_TZ = True TIME_ZONE = 'UTC' What is causing tzlocal to throw this? I couldn't find this error in other places. It usually complains about specific timezones but not 'UTC' -
Open ListView with foreignkey from anotherlist view using a slug in django
I was able to do basically what this article - link - says, and in the comments the person says that it would be beneficial to use a slug. How would I go about implementing the above article but with a slug. I understand how slug:pk works, I'm just not sure how to link that to a foreign key and have it filter by that pk, and then how to have it passed into the url as well. I don't really know where to start trying to figure this out, so any help at all is appreciated, Thanks(: -
Wagtail Sporadic 502 Errors in Image Admin
I am getting a 502 error when uploading new images to wagtail (this after uploading successfully many times since last update). The site runs on nginx. Sometimes, this leads to 502 error on the main image admin page, but these often clear with refreshing. This is the related error get in my Wagtail error log: Wagtail AttributeError: type object 'RequestContext' has no attribute 'locale' I expected this to resolve with reloading nginx and gunicorn and rebooting ubuntu. Unfortunately nothing works. I've also tried running a search for corrupt images and deleting all offenders. The problem remains. Have also tried uploading problematic images directly via SFTP which solves the problem temporarily, but doesn't allow for new uploads. I am using Django>=4.1,<4.2, wagtail>=5.0,<5.1 -
How to handle django static files for production
I am a newbie django developer and this is the django project i will be deploying. Everything works in development but I am been having issues in production. PS: I am using shared hosting for the deployment. First, the website loads but images are not showing. I tried using whitenoise but keeps getting the error File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/publishm/PUBLISHMYCRAFT/learnwithjdd/index/urls.py", line 12, in <module> path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('images/favicon_io/favicon.ico'))), File "/home/publishm/virtualenv/PUBLISHMYCRAFT/learnwithjdd/3.9/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 203, in url return self._url(self.stored_name, name, force) File "/home/publishm/virtualenv/PUBLISHMYCRAFT/learnwithjdd/3.9/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 182, in _url hashed_name = hashed_name_func(*args) File "/home/publishm/virtualenv/PUBLISHMYCRAFT/learnwithjdd/3.9/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 513, in stored_name raise ValueError( ValueError: Missing staticfiles manifest entry for 'images/favicon_io/favicon.ico' part of my urls.py from . import views from django.urls import path from . views import BlogHomeView, BlogDetailsView, AddPostView, EditPostView, DeletePostView, AddCategoryView, DraftsListView, AddDraftPostView, DraftPostDetailsView, EditDraftPostView, DeleteDraftPostView from django.views.generic.base import RedirectView from django.contrib.staticfiles.storage import staticfiles_storage app_name = 'index' urlpatterns = [ path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('favicon.ico'))) ] part of the settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" I tried using the whitenoise and play around with the path but the static files and the ckeditor are not working. The error disppears and … -
for loop for search engine not working properly
similar_entries = [] for entry in all_entries: for letters in entry: if letters in entry: if entry not in similar_entries: similar_entries.append(entry) This code is for a search engine but it is displaying all elements of the list instead of a showing strings with the same couple of words. all entries is a list I was stuck on this problem for so long -
Pytest doesn't find tests written in django project
I am learning about test-driven development and am using pytest-django to conduct unit tests for my django project. I wrote a few tests, but when I run pytest, it says that it collected 0 items and that a file or directory wasn't found. Terminal text: mariojerez@Marios-MacBook-Pro zhulimoon % pytest ============================================================================== test session starts =============================================================================== platform darwin -- Python 3.9.6, pytest-7.3.0, pluggy-1.0.0 django: settings: zhulimoon.test_settings (from ini) rootdir: /Users/mariojerez/Documents/coding/ZhuLi Moon/zhulimoon configfile: pytest.ini plugins: django-4.5.2 collected 0 items ============================================================================= no tests ran in 0.00s ============================================================================== ERROR: file or directory not found: #After mariojerez@Marios-MacBook-Pro zhulimoon % tests.py file inside the django app: import pytest from .models import * @pytest.fixture(scope='module') @pytest.mark.django_db def create_project_no_framework(): yield Project.objects.create(name="The Bikini Bottom", description="Model of the Spongebob Universe") @pytest.fixture(scope='module') @pytest.mark.django_db def create_node_type_in_project(): yield NodeType.objects.create(name="character", project=Project.objects.get(name="The Bikini Bottom")) @pytest.fixture(scope='module') @pytest.mark.django_db def create_node_in_project(): yield Node.objects.create(name="Spongebob", description="The protagonist of the show", nodeType=NodeType.objects.get(name="character"), project=Project.objects.get(name="The Bikini Bottom")) @pytest.fixture(scope='module') @pytest.mark.django_db def create_node_type_property(): yield Property.objects.create(type="physical", name="height", description="height of character", dataType="dec", unit="cm") @pytest.mark.django_db def test_create_project_no_framework(create_project_no_framework): create_project_no_framework project = Project.objects.get(name="The Bikini Bottom") assert str(project) == "The Bikini Bottom" @pytest.mark.django_db def test_create_node_type_in_project(create_node_type_in_project): create_node_type_in_project nodeType = NodeType.objects.get(name="character") assert str(nodeType.project) == "The Bikini Bottom" assert nodeType in NodeType.objects.filter(project=Project.objects.get(name="The Bikini Bottom")) assert str(nodeType) == "character" @pytest.mark.django_db def test_create_node(create_node_in_project): create_node_in_project node = Node.objects.get(name="Spongebob") assert … -
Django, extraction problem when i use SELECT2 for two comboboxes contained in two different models
I'm trying to use Select2 in Django. I saw a guide on the official site, but it doesn't show how to use it when there are two or more comboboxes (dropdown) in the same model (here), because the official site shows how to use Select2 with one combobox for each model. In my case I have only one model with 2 comboboxes inside. I would like to make the country combobox dependent on the voyage combobox models.py class NextVoyage(models.Model): country = models.CharField(max_length=30) departure = models.CharField(max_length=30) destination = models.CharField(max_length=30) def __str__(self): voyage = f"{self.departure}-{self.destination}" return voyage forms.py This is the base code with which I normally display the contents of combobx. This works and displays correctly (when they are not dependent) class Form_SelectVoyage(forms.Form): country = forms.ModelChoiceField(queryset=NextVoyage.objects.values_list('country', flat=True).distinct()) destination = forms.ModelChoiceField(queryset=NextVoyage.objects.all()) In Select2, I try to make them dependent like this, but it does not work. The comboboxes are empty. It doesn't work because as you can see I have 2 comboboxes in the same model, but the example on the official site shows how to make 2 comboboxes dependent in 2 different models. Can anyone help me? Thank you class Form_SelectVoyage(forms.Form): country = forms.ModelChoiceField( queryset=NextVoyage.objects.values_list('country', flat=True).distinct(), label="Country", widget=ModelSelect2Widget( model=NextVoyage, search_fields=['name__icontains'], ) … -
Writing forms in django generates duplicated rows when using save() method
I'm building a form based on different models using django and I was struggling because I was generating duplicates rows and I fixed it with the code below but I'm interested in hearing suggestions to write this code better: #views.py def make_customer(request, id): # Get the customer object or return a 404 response if it doesn't exist customer = get_object_or_404(Customer, pk=id) print(request.POST) if request.method == 'POST': contact_form = ContactForm(request.POST) address_form = AddressForm(request.POST) company_form = CompanyForm(request.POST) if contact_form.is_valid() and address_form.is_valid() and company_form.is_valid(): if customer.company: # Update existing company, contact, and address company = customer.company print(company_form.cleaned_data) company.name = company_form.cleaned_data['name'] company.customer_information_file_number = company_form.cleaned_data['customer_information_file_number'] company.contact.name = contact_form.cleaned_data['name'] company.contact.email = contact_form.cleaned_data['email'] company.contact.cc_email = contact_form.cleaned_data['cc_email'] company.address.street = address_form.cleaned_data['street'] company.address.city = address_form.cleaned_data['city'] company.address.postal_code = address_form.cleaned_data['postal_code'] company.contact.save() company.address.save() company.save() else: # Create a new company if it doesn't exist contact = contact_form.save() address = address_form.save() company = Company.objects.create( name=company_form.cleaned_data['name'], customer_information_file_number=company_form.cleaned_data['customer_information_file_number'], contact=contact, address=address ) customer.company = company customer.save() messages.success(request, 'Customer saved successfully') return redirect('view_customers') else: # GET request contact_form = ContactForm( instance=customer.company.contact) if customer.company else ContactForm() address_form = AddressForm( instance=customer.company.address) if customer.company else AddressForm() company_form = CompanyForm( instance=customer.company) if customer.company else CompanyForm() context = { 'contact_form': contact_form, 'address_form': address_form, 'company_form': company_form, } return render(request, 'invoices/form_customer.html', context) This is the … -
Django multiple databases and multiple apps
I have an app_login that I want to store the information in the default database and I have a folder with the name client where there will be several clients one of them is flowon all the models of app_flowon I want it to stay in the app_flowon database, but I'm having difficulty making it work, or I'm migrating all the models to the default database or everything is going to the app_flown database, I don't want to mix the models, I want to leave everything separate, I want the models of the app_login to be in default and the models from app_flowon is in app_flowon database, what can i do? -
How to combine Django and Next.js to deploy under a single domain?
My goal is to create a website with Django as a backend, and React/Nextjs as a frontend. At the moment, I have found a perfect example of a repository which fits for the purpose, but it combines React and Django: https://github.com/techwithtim/Music-Controller-Web-App-Tutorial/tree/main/Tutorial%207 I was wondering if is possible to add Next.js to it. If it is possible, how can it be done? I tried a naive approach of replacing the frontend with nextjs app, didn't work. Then i tried installing next.js as a package and using it's features except for routing, did not work either. Due to me being not well versed with bundling and tranpiling tools such as Webpack and Babel, I am unsure how to configure them to attain the intended result. When I tried to replace frontend with next.js app, the frontend became decoupled from the backend. Then I tried to install next as a package and use 'next/link' feature, both approaches didn't work. What I was expecting is that the code written using next package would be added to the generated static main.js file from the example: https://github.com/techwithtim/Music-Controller-Web-App-Tutorial/tree/main/Tutorial%207/frontend/static/frontend -
Error : This queryset contains a reference to an outer query and may only be used in a subquery
This might be a very easy to spot mistake but I am not the most familiar with the Django queries so I have been breaking my head for hours trying to solve that. I have a Django Rest app and there I have 2 models: class Student(models.Model): name = models.CharField(max_length=20) status = models.CharField(max_length=4, blank=True, default="UNK", choices=STATUS_TYPES) started_date = models.DateTimeField(null=False, auto_now_add=True) class StudentStatusHistory(BaseTimestampModel): """Table of status changes for Students""" student = models.ForeignKey( "core.Student", on_delete=models.CASCADE, related_name="StatusHistory" ) status = models.CharField( max_length=4, blank=True, default="UNK", choices=STATUS_TYPES ) created_on = models.DateTimeField(null=False, auto_now_add=True) For reference: STATUS_TYPES = [("UNK", "Unknown"), (“PASS", “Passed"), (“FAIL", “Failed")] I am trying to write a query that calculates for how many students their status changed to Pass within the time window of a week or less. So for example if a Student.started_date is 2023-07-15 12:22:22 and the StudentStatusHistory.created_on field is 2023-07-21 12:22:22, for a student with Student.status that equals PASS, I want to count this student because they passed in less than a week (in 6 days in this example). Additionaly, I want to calculate this count only for students that started the current month. What I have so far is: current_month_start = datetime(datetime.today().year, datetime.today().month, 1) # Subquery to filter StudentStatusHistory objects … -
In Django, when a function in views.py returns a JsonResponse, how can it render a web page at the same time?
I am trying to write a webpage in Django that obtains real-time input from the user and gives some responses back to the user. However, when the function in views.py returns a type of JsonResponse, my HTML file in the template cannot be showed properly. How can I fix this issue? My HTML: <!DOCTYPE html> <html> <head> <title>Real-time Input Text</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <input type="text" id="input-box"> <div id="output"></div> <script> $(document).ready(function() { $("#input-box").on("input", function() { var inputText = $(this).val(); // Get the current value of the input box $.ajax({ url: "/update_text/", method: "POST", data: { text: inputText }, success: function(response) { $("#output").text(response); } }); }); }); </script> </body> </html> My function in views: from django.shortcuts import render from django.http import JsonResponse def update_text(request): if request.method == "POST": text = request.POST.get("text", "") return JsonResponse(text, safe=False) else: return JsonResponse({}, status=400) -
How to do custom truncation of date in Django ORM?
I have two sql queries which which does some specific truncation on dates. I have posted the truncation portion below import datetime from datetime import timedelta time_diff_in_minutes = 60 * 24 start_time = datetime.datetime.utcnow() end_time = current_time - timedelta(minutes=time_diff_in_minutes) # 4 days interval (created_at, cost are columns in db) sql = "select date_trunc('month', created_at) + (date_part('day', created_at)::int - 1) / 4 * interval '4 day' AS custom_gran, avg(cost) from some_table where created_at between '{}' and '{}' group by zoom_gran order by zoom_gran;".format(start_time, end_time) # 4 hours interval (created_at, cost are columns in db) sql = "select date_trunc('day', created_at) + date_part('hour', created_at)::int / 4 * interval '4 hour' AS custom_gran, avg(cost) from some_table where created_at between '{}' and '{}' group by zoom_gran order by zoom_gran;".format(start_time, end_time) Now in django models I know basic truncation such as hours, days, months etc. So If I had to write a daily truncation or hourly truncation, this is how I would do it # daily truncation result = SomeTable.objects.filter(created_at__gte=start_time, created_at__lte=end_time) .annotate(daily=Trunc("created_at", "day")).values_list("daily") .annotate(avs=Avg("cost")) # hourly truncation result = SomeTable.objects.filter(created_at__gte=start_time, created_at__lte=end_time) .annotate(hourly=Trunc("created_at", "hour")).values_list("hourly") .annotate(avs=Avg("cost")) I found a Stack overflow question regarding this (Custom TruncFunc in Django ORM) but I didn't quite understand the solution (even the … -
Django ElasticSearch DSL How to sort by another document
In Django, I have 2 models Keyword and KeywordPopularity. class Keyword(models.Model): name = models.CharField(max_length=50) class KeywordPopularity(models.Model): keyword = models.ForeignKey(Keyword, on_delete=models.CASCADE, related_name='popularities') date = models.DateField(auto_now_add=True) popularity = models.IntegerField() I run a script to detect the popularity of each keyword once a month, so a keyword has multiple popularities (with different date of couse). I set up elasticsearch dsl to search keywords by query and it worked fine. @registry.register_document class KeywordDocument(Document): class Index: name = 'keywords' class Django: model = Keyword fields = ['name'] when I search for a query, i used this command and it works: KeywordDocument.search().query('match', name=query)[fromOffset:toOffset] My question is: how to search for a query then sort by popularity in a given date range. What I'm doing right now is to get all keywords that match the query then find each one popularity then sort. But it is very slow: keywords = KeywordDocument.search().extra(size=10000).query('match', name=query).to_queryset() result = [] for keyword in keywords: popularities = keyword.popularities.filter(date__gte=startDate, date__lte=endDate).order_by('date') data = KeywordSerializer(keyword).data data['popularity'] = popularities.last().popularity if popularities.count() > 0 else -1 result.append(data) result = sorted(result, key=lambda keyword: -keyword['popularity']) Could you please help me optimize the above snippet? Thank you very much! -
Docker Compose run, how to map ports defined in docker-compose.yml?
I am trying to run Django server inside a docker container, but the localhost:port is not working. I tried to achieve this by running the following commands: 1. docker compose -p dev run --entrypoint /usr/bin/fish shop-backend 2. docker compose --project-name dev run -p8000:8000 --entrypoint /usr/bin/fish shop-backend 3. docker-compose --project-name dev run --service-ports --entrypoint /usr/bin/fish shop-backend and once I am inside the docker container I start the Django server using this command: python3 src/manage.py runserver but I am not able to reach the localhost:8000. In shortcut my docker-compose.yml look like this: ... services: shop-backend: container_name: ${COMPOSE_PROJECT_NAME}-shop-backend build: context: . dockerfile: Dockerfile.${COMPOSE_PROJECT_NAME} volumes: - ./:/app/ stdin_open: true tty: true ports: - "8000:8000" # HOST:CONTAINER depends_on: - shop-db env_file: .env.${COMPOSE_PROJECT_NAME} ... Can you please provide some examples, of what I need to do to reach localhost:8000, if I want to run Django server from the docker container and get into the docker container I want to use the docker compose run command? -
When I try to use a dynamic URL from my 'articulos application in my template, I encounter a NoReverseMatch error at /
`The dynamic URLs work perfectly in the core app, but when I try to do exactly the same in the articulos app, I get an error, and I don't know what the cause is. This is the part of the template that is causing the error. <a href="{% url 'articulos:create-article' %}" class="btn btn-success mb-3">Crear un nuevo artículo</a> This is the URLs.py of the app: from django.urls import path from .views import * app_name = 'articulos' urlpatterns = [ path('create-article/', CrearArticuloView.as_view(), name='create-article'), path('list-articles/', ListaArticulos.as_view(), name='list-articles'), ] "This is my view:" from django.shortcuts import render from django.views import generic from .models import Articulo from .forms import CrearArticuloForm from django.urls import reverse # Create your views here. class CrearArticuloView(generic.CreateView): model = Articulo template_name = 'blog/create_article.html' form_class = CrearArticuloForm def get_success_url(self): return reverse('articulos:list-articles') def form_valid(self, form): f = form.save(commit=False) f.autor_id = self.request.user.id return super().form_valid(f) class ListaArticulos(generic.ListView): model = Articulo template_name = 'blog/articles.html' context_object_name = 'articulos' paginate_by = 25 And this is the error: NoReverseMatch at / Reverse for 'create-article' not found. 'create-article' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'create-article' not found. 'create-article' is not a … -
Match value with range value in column
I am having table with column registration year with values like '2017-2019' and '2014-2016. If my input value is 2018 then what will be my SQL query to get that record which is in between '2017-2019'. id registration_year 1 2014-2016 2 2017-2019 above is DB table and my input is 2018. Then it should return id 2. What will be my sql query. Thanks in advance -
Google allauth with django
when i do it in the local it work perfectly but when i host it's show this error : NoReverseMatch at /login Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name. Request Method: GET Request URL: Django Version: 4.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name. Note : in the local host it work and doesn't show this type of error i try to edit the domaine in google cloud but the same error -
DataTable -> Python ->Django -> Expanded Row / Colspan problem / Searching, etc. does not work
I have a problem because I am trying to make a datatable with a drop down when I click on a row and everything works. But then I lose the functionality of the datatable and can't search etc. I have already searched half the internet and can't figure it out, maybe there is someone who could help? Script: `$(document).ready(function () { // Ukryj wszystkie rozwinięte wiersze $(".expanded-row").hide(); // Po kliknięciu w wiersz, rozwinięty wiersz staje się widoczny, a reszta zostaje ukryta $(".expandable-row").click(function () { $(this).next(".expanded-row").toggle(); $(".expanded-row").not($(this).next(".expanded-row")).hide(); }); });` Table: ` <table style="width: 100%;" class="table table-hover table-striped table-bordered dataTable dtr-inline" id="clients_list"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Phone</th> </tr> </thead> <tbody> {% for c in clients_list %} <tr class="expandable-row"> <td><a href="{% url 'client' c.id %}">{{ c }}</a></td> <td>{{ c.email }}</td> <td>{{ c.phone }} <i class="fa fa-fw" aria-hidden="true" title="Copy to use phone"></i> </td> </tr> <tr class="expanded-row"> <td colspan="10"> <div class="row"> <div class="col-md-6"> <div class="widget-chat-wrapper-outer"> <b> <div class="widget-title text-center opacity-10 text-uppercase"> Basic information </div> </b> <div tabindex="-1" class="dropdown-divider"></div> <div class="table-responsive-sm"> <table class="table table-nowrap mb-0 table-borderless" style="table-layout: auto; width: 100%"> <tbody> <tr> <th>Name & lastname:</th> <td>{{ c }} ({{ c.name }})</td> <th>Register date:</th> <td>{{ c.reg_time }}</td> </tr> </tbody> </table> </div> </div> </div> <div class="col-md-6"> <div class="card-body"><h5 … -
How can I change label to span tag using Django filters
I am using django_filters to filter objects. My site displays filter fields with the following code: <div class="inputBoxTEST"> <label for="id_name__icontains">Name contains:</label> <input type="text" name="name__icontains" id="id_name__icontains"> <label for="id_brand__icontains">Brand contains:</label> <input type="text" name="brand__icontains" id="id_brand__icontains"> <label for="id_cloth_type">Type:</label> <select name="cloth_type" class="form-control" id="id_cloth_type"> </div> django_filters generates inputs and labels. I need to change label tag with span tag. How can i do that? My code: views.py class WardrobeView(ListView): model = Clothes template_name = "wardrobe_TEST.html" context_object_name = "clothes" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["filter"] = ProductFilter( self.request.GET, queryset=self.get_queryset() ) return context 'filters.py` import django_filters from django import forms class ProductFilter(django_filters.FilterSet): cloth_type = django_filters.ModelChoiceFilter( queryset=ClothType.objects.all(), label='Type', widget=forms.Select(attrs={'class': 'form-control'}), ) class Meta: model = Clothes fields = { 'name': ['icontains'], 'brand': ['icontains'], } 'wardrobe.html' <div class="filter_form"> <form method="GET"> <div class="inputBoxTEST"> {{ filter.form }} </div> <button type="submit" style="--clr:#1644C9"><span>Submit</span><i></i></button> </form> </div> -
send jwt to Vue front end
I have a Django app and a vue app that work together. The Django part are a few pages including a log in page. Once logged in you are directed to the Vue app where I would like to log the user in automatically because he is already logged in on the Django side. I am sending an encrypted token to the Vue side and I encrypted the token using: encoded_token = jwt.encode({'token': token}, os.environ['SECRET_KEY'], algorithm='HS256') Now I want to use the token on the Vue side to log the user in and get his data. How do I do that because every library I have tried gives me an error: import VueJwtDecode from 'vue-jwt-decode'; Could not find a declaration file for module 'vue-jwt-decode'. '/mnt/500GB/website/frontend/node_modules/vue-jwt-decode/dist/lib/vue-jwt-decode.min.js' implicitly has an 'any' type. this also Could not find a declaration file for module 'jsonwebtoken'. Really new to this so would appreciate some help -
Python Manage.py runserver Failed
I have virtual environment of window 10 of company laptop. I am trying to execute python manage.py or python manage.py runserver Not getting error and it just shows output like this- enter image description here I expect the runserver start in my virtual environment. -
when running server, django always displays error
im only learnin python and django, i tried running server but only it shows error that says Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\theta\AppData\Local\Programs\Python\Python39\lib\site- packages\django\urls\resolvers.py", line 717, in url_patterns iter(patterns) TypeError: 'module' object is not iterable django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'app_advertisements' from ' C:\\Users\\theta\\PycharmProjects\\advertisements\\app_advertisements\\__init__.py' >' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app_advertisements')), ] and an app\urls.py from django.urls import path from .views import index urlpatterns = [ path('user/', index), ]