Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Registration information not saving to database in Django
The registration part of the code does not work. After creating a new user it just redirects to the registration page and I can not figure out why. Also is there a way to edit the username and password elements in the RegisterForm like I did with the email element? forms.py from django import forms from django.contrib.auth import authenticate, models from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm class RegisterForm(UserCreationForm): email = forms.EmailField(max_length=100, required=True, widget=forms.EmailInput(attrs={'class': 'form_control', 'name': 'email', 'id': 'email', "placeholder": 'Your class Meta: model = User fields = ( 'username', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegisterForm, self).save(commit=False) user.username = self.cleaned_data user.email = self.cleaned_data user.password1 = self.cleaned_data if commit: user.save() return user views.py def addUser(request): if request.method == 'POST': form = RegisterForm(request.POST or None) if form.is_valid(): form.save() return redirect('home') else: form = RegisterForm() args = {'form': form} return render(request, 'login_register/register.html', args) register.html <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Register</title> <!-- Font Icon --> <link rel="stylesheet" href="{% static 'login_register/fonts/material-icon/css/material-design-iconic-font.min.css' %}" /> <!-- Main css --> <link rel="stylesheet" href="{% static 'login_register/css/style.css' %}" /> </head> <body> <div class="main"> <!-- Sign up form --> <section class="signup"> <div … -
Nginx isn't Serving Django Static Files Correctly Because of Trailing Slash
Currently, I have a Django web app being served by Gunicorn. Gunicorn does not serve static file requests so I am using Nginx in front of Gunicorn to serve static file requests. I am able to containerize the app fine with Docker and can successfully serve application requests but Nginx cannot serve the static file requests correctly because Django appends a trailing slash to static file requests. After running the Docker container with Django, Nginx, and Postgres services, I navigate to the home page of the web app and the first request is fine. HTTP Request 200 The rest of the incoming requests after navigating to the home page of the web app are static file requests all with 404 error codes. HTTP Request 404 The 404 error codes indicate that the server cannot find the static files but I can verify that my static files are stored in the correct location and are present. The 404 error codes are happening because Django static file requests append a trailing slash to the request. So, after reading the Nginx documentation, I discovered that Nginx treats all static file requests with trailing slashes as requests for directories and thus searches for an … -
Is sometimes single complicate query worse than two separate query?
I just came into the article on Django that says, when the amount of data is so huge it's better to split it and send them separately. I'm not really sure about this, because as far as I know, DBMS itself is so optimized and the networking is what causes the greatest portion of the latency. Are there really any cases like this? -
Django: Can't redirect to list page after clicking Submit button
Sorry for the long-ass post. I have a problem with my "update_fisher" view. It doesn't redirect to the "list_fishers" view after clicking the "Submit" button. What wonders me more is that "create_fisher" view uses the same html file for submitting forms, but it executes successfully. Here is the code for more details: fishers/views.py ... @ staff_member_required def create_fisher (request): form = FisherForm(request.POST or None) if form.is_valid(): form.save() form = FisherForm() return HttpResponseRedirect(reverse("fishers:list_fishers")) template_name = "fisher_form.html" context = {'form' : form} return render (request, template_name, context) @ staff_member_required def update_fisher (request, fisher_id): items = get_object_or_404(Fishers, fisher_id = fisher_id) form = FisherForm(request.POST or None, instance = items) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("fishers:list_fishers")) template_name = "fisher_form.html" context = {'fishers' : items, 'form' : form} return render (request, template_name, context) ... fishers/urls.py from django.urls import path from . import views # this is responsible for the "namespace" in admin > urls.py app_name = 'fishers' # urlpatterns = [ path('', views.list_fishers, name = "list_fishers"), path('add_fisher/', views.create_fisher, name = "create_fisher"), path('update_fisher/<int:fisher_id>', views.update_fisher, name = "update_fisher"), fishers/templates/fisher_form.html {% extends "base.html" %} <title> {% block title %} Add/Update Information {% endblock %} </title> {% block content %} <div class = "page-header"> <h2> Fisher's Information </h2> </div> <form method … -
How to optimize django-import-export?
I have a data in Excel around 20,000 records. I using django-import-export extension for import data.I tried to import data but very slow about 10 minute. I think one thing to make it slow that is django-import-export render 20,000 records on preview table. I want to know how to speedup ? -
requests.post from python script to my Django website hosted using Apache giving 403 Forbidden
My Django website is hosted using Apache server. I want to send data using requests.post to my website using a python script on my pc but It is giving 403 forbidden. import json url = "http://54.161.205.225/Project/devicecapture" headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'content-type': 'application/json'} data = { "nb_imsi":"test API", "tmsi1":"test", "tmsi2":"test", "imsi":"test API", "country":"USA", "brand":"Vodafone", "operator":"test", "mcc":"aa", "mnc":"jhj", "lac":"hfhf", "cellIid":"test cell" } response = requests.post(url, data =json.dumps(data),headers=headers) print(response.status_code) I have also given permission to the directory containing the views.py where this request will go. I have gone through many other answers but they didn't help. I have tried the code without json.dumps also but it isn't working with that also. How to resolve this? -
Retrieve Form Field Values With Ajax in Django
I have two forms. 1st form is CreateQuoteForm, which is used to create a Quote object - the user will fill this out first. The 2nd form is CreateProformaForm, which is used to create a Proforma object this will be completed second. I would like for the user to have the ability to select a Quote object from a select box and upon the click of a button, populate the CreateProformaForm fields with the data where there is overlap between the two models. Please see below for further illustration: models.py class Quote(models.Model): Name = models.CharField(max_length=30, null=True, blank=True) Shipment = models.ForeignKey(Shipment, null=True) Exporter = models.CharField(max_length=100, null=True, blank=True) QuoteNo = models.CharField(max_length=30, null=True, blank=True) class Proforma(models.Model): Name = models.CharField(max_length=30, null=True, blank=True) Shipment = models.ForeignKey(Shipment, null=True) Exporter = models.CharField(max_length=100, null=True, blank=True) QuoteNo = models.CharField(max_length=30, null=True, blank=True) Date = models.CharField(max_length=30, null=True, blank=True) Consignee = models.ForeignKey(Customer, null=True) As you can see, the models have similar fields. So after selecting the Quote in the selectbox, the fields Name, Shipment, Exporter, QuoteNo should populate in CreateProformaForm while Data and Consignee remain blank. Also to be clear - this should be an option for this user only, the form should be initialized blank. I am sure that this will … -
Uploading multiple csv files in Django using multiple file field form
I have tried uploading one csv file using Django file field form and it works well. However, switching the file field form into multiple file field form yields to an error when trying to read the csv file. What I initially tried for single csv file: in forms.py class UploadForm(forms.Form): file_field = forms.FileField(allow_empty_file = False) in views.py input_file = request.FILES['file_field'] data_set = input_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) model_list = [] for row in csv.reader(io_string, delimiter = ',', quotechar = "|"): #create Django model object based on the row and append it to model_list Sample_Model.objects.bulk_create(model_list) What I currently try for multiple csv files: in forms.py: class UploadForm(forms.Form): file_field = forms.FileField(allow_empty_file = False, widget=forms.ClearableFileInput(attrs={'multiple': True})) in views.py: input_files = request.FILES.getlist('file_field') for file in input_files: data_set = file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) model_list = [] for row in csv.reader(io_string, delimiter = ',', quotechar = "|"): #create Django model object based on the row and append it to model_list Sample_Model.objects.bulk_create(model_list) I got a Stop Iteration error at the next(io_string) line. Upon browsing for its meaning and analysing the code, it seems data_set = file.read().decode('UTF-8') is the source of the problem as it does not work properly now. Thank you! -
Static files moved to a STATIC_ROOT but still none are being shown
Trying to deploy my site and everything is working fine except that the CSS in the admin page is non-existent. I have looked through all of the other posts where people have had this issue but i have already done the steps most of them forgot. I have the static files directed to the base directory with STATIC_ROOT = os.path.join(BASE_DIR, 'static'), when I ran python manage.py collectstatic, they all seemed to move into the base DIR just fine. Heres the code/file structure: In settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' Then the structure that this created after collectstatic: Obviously something isn't right or I wouldn't be here but Im stuggling to figure out what is incorrect. All help is appreciated. Thank you! -
FOREIGN KEY constraint failed - Django, SQLite3
My application allows Tenantprofiles to apply for Property viewings that are listed by Landlord profiles. I can't seem to link the two tables together I can't get past FOREIGN KEY constraint failed error. views.py from django.shortcuts import render, redirect from projects.models import Properties, Property_Applications, Property_Reviews from users.models import Landlord_Profile, Tenant_Profile from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import CreatingListingForm, ListingApplicationForm def property_apply(request, pk): project = Properties.objects.get(pk=pk) applyButton = ListingApplicationForm(request.POST) profile = request.user.tenant_profile if request.method == "POST": link = applyButton.save(commit=False) link.tenant_apply = profile link.listing=project link.save() messages.success(request, f'You have applied!') return redirect('/tenantportal/') else: link = applyButton context = {'project': project, 'applyButton': link} return render(request, 'application_submit.html', context) models.py - projects from django.db import models from PIL import Image from django.contrib.auth.models import User from django.contrib.auth import get_user_model from django.conf import settings from users.models import Landlord_Profile, Tenant_Profile class Property_Applications(models.Model): tenant_apply = models.ForeignKey(Tenant_Profile, on_delete=models.CASCADE, default=1) property_owner = models.ForeignKey(Landlord_Profile, on_delete=models.CASCADE,default=1) listing = models.ForeignKey('Properties', on_delete=models.CASCADE) app_description = models.TextField(default='app description') created = models.TextField(default=1) class Properties(models.Model): User = settings.AUTH_USER_MODEL landlord = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=100) rentPrice = models.FloatField() description = models.TextField() bedRooms = models.IntegerField() bathRoom = models.IntegerField() tenantCondtions = models.CharField(max_length=100) image = models.ImageField(upload_to='house_preview/') models.py - users from django.db import models from django.contrib.auth.models import User from PIL … -
expired confirmation email to return a JSON response in django-rest-auth
using Django-rest-auth and Django-allauth to handle email verification and signup in my rest api. When a user tries to verify their email after the link has expired, I get an unpleasant error page. ---> I would like to get a JSON response saying the email has expired. Below is the error message I get when I confirm the expired verification email. -
custom form validation errors in template
how can i pass custome form validation errors in template? forms.py '''' def clean_username(self): inputusername = self.cleaned_data['username'] if len(inputusername) < 6: raise forms.ValidationError('Sorry, your username must be between 6 and 30 characters long.') else: return inputusername '''' views.py '''' def signup(request): signup_form = CreateUserForm() if request.method == 'POST': signup_form = CreateUserForm(request.POST) if signup_form.is_valid(): signup_form.save() context = {'signup_form':signup_form} return render(request, 'formvalidationapp/signupform.html', context) '''' temlate '''' <form method="post" action="{% url 'signup' %}"> {% csrf_token %} <div class="row"> <div class="col-sm-6"> <h1>Sign Up</h1> </div> </div> <div> #i want to pass error here </div> '''' -
Why can't my user can't check their inbox?
So I am attempting to query and display messages between two users in an inbox. I am running into a problem where no messages are appearing for request.user's inbox. It's showing as empty when there are messages. However, when I go into an inbox for another user that my request.user has messaged while still logged in to request.user, I can see the messages from both parties there and displayed correctly. For the life of me, I don't understand why this is happening. Hell, request.user.username is passed through the template and my user's username actually prints. Yes, django.template.context_processors.request is already in my context processor. I tried doing if msg.receiver_id == request.user but that still doesn't work. What the hell am I doing wrong here? views.py/messages def messages(request, profile_id): messages = InstantMessage.objects.filter(Q(sender_id=request.user, receiver_id=profile_id,) | Q(sender_id=profile_id, receiver_id=request.user,) ).\ values('sender_id','receiver_id', 'message', 'date', ).\ order_by('date',) return render(request, 'dating_app/messages.html', {'messages': messages,}) messages.html {% for msg in messages %} {% if msg.receiver_id == user.id %} <li class="text-right list-group-item">{{ msg.message }}<br/>{{ msg.date }}<br/>{{ request.user.username }}</li> {% elif msg.sender_id == user.id %} <li class="text-left list-group-item">{{ msg.message }}<br/>{{ msg.date }}</li> {% endif %} {% empty %} {%endfor %} urls.py/messages path('messages/<int:profile_id>/', views.messages, name='messages') models.py class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): … -
how to fix "Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL" Error?
public static void main(String[] args) throws Exception { // check if the user enter the right args from the command line. if(args.length != 2){ System.out.println("Usage: java Reverse " + "http://<location of your servlet/script> " + "string_to_reverse");// display the error. System.exit(1); // exit the program. } /**the sting that will be reversed may contain spaces or other * non-alphanumeric characters. These characters must be * encoded because the string is processed on its way to the server. * the URLEncoder class methods encode the characters.*/ String stringToReverse = URLEncoder.encode(args[1], "UTF-8"); // create object for the specified url for the command line. URL url = new URL(args[0]); // sets the connection so that it can write to it. URLConnection connection = url.openConnection(); connection.setDoOutput(true); // I tried the follow things to fix the error but still not working. //connection.setRequestProperty("http.agent", "Chrome"); //connection.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); // connection.setRequestProperty("User-agent", "Mozilla/5.0"); // connection.setRequestProperty("User-agent", "Mozilla"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); // The program then creates an output stream on the connection // and opens an OutputSteamWriter on it; OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream()); // the program writes the required information t the output // stream and closes the stream. out.write("string = " … -
Django user model. 1 admin account, 1 customer account with the same email and different password
Im trying to handle a use case where i have 2 roles. (admin , customer) There will be an admin portal and a customer portal (2 different login pages ). An admin can invite a customer An admin can be a customer as well , can invite himself into the customer portal An admin account must not share the same password as the customer account. Email is used as the unique field for both admin and customer account. For example : Admin account - customer@email.com /password1 Customer account - customer@email.com /password2 Solution 1: - Permission. Having 1 account with admin permission and customer permission. (This cant work to fit the bussiness use case) Based on this article: https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html Solution 2: - Creating 2 django projects. One for each user model since both accounts cant share password. The reason for separating into 2 projects is because resources such as session,login, logout will not be shared. So each portal(admin,customer) has their own resource. A create Customer API to allow admin to create a customer account in customer django project. A shared db to share related data This is the only way i can think of to handle the use case. Please let … -
How to test a Django+Celery application with multiple queues
I am wondering if it is feasible to write functional tests for a Django application using multiple Celery queues. For a single queue, I used the solution explained here, and it worked great. What I would basically want to do is the following: from celery.contrib.testing.worker import start_worker from django.contrib.staticfiles.testing import StaticLiveServerTestCase from mysite.celery import app class MyTestCase(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.celery_worker1 = start_worker(app, perform_ping_check=False, queue="myqueue1") cls.celery_worker1.__enter__() cls.celery_worker2 = start_worker(app, perform_ping_check=False, queue="myqueue2") cls.celery_worker2.__enter__() @classmethod def tearDownClass(cls): super().tearDownClass() cls.celery_worker1.__exit__(None, None, None) cls.celery_worker2.__exit__(None, None, None) This code has two problems: I get the message /home/user/.local/lib/python3.7/site-packages/kombu/pidbox.py:74: UserWarning: A node named gen18391@Machine is already using this process mailbox! which leads me to think that multiple workers aren't handled properly. The "queue" argument isn't in the documentation and is likely not parsed at all. Consequently, the task sent to the second queue isn't being executed. -
What is the best practice for an internal API call in django
I've developed a chess API in django. I intend to develop a client for it as well. What would be the best practice for a client? Develop the client as another app in the same project in django, and perform internal API calls using requests(Is it better than calling the API externally performance wise? ) Develop the client as another app in the same project in django, and call the API's views using Django. (How would I do this, as the API expects JSON data in request) Develop the client as a standalone. -
django // conditional settings depend on aws instance server
Environment django 2.2 python 3.6 AWS EC2 ubuntu instance gunicorn nginx My setting Now I'm using one production server aws ubuntu instance. I separated settings.py depond on local and production server as follows. # local : Project/setting/dev.py DEBUG = True ALLOWED_HOSTS = ['localhost'] database = { ..skip.. } # production : Project/setting/real.py DEBUG = False ALLOWED_HOSTS = ['~real_server_host of ec2~'] database = { ..AWS RDS instance for real.. } # manage.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project.settings.dev") # wsgi.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project.settings.real") Question I have to operate one more aws instance for test before deploy to real. So I made same EC2 instance and RDS instance(dumped from real rds) for test. But I don't have any nice idea how to seperate os.environ.setdefault in wsgi.py Once I made one more settings file for test server. # Project/setting/test.py DEBUG = True ALLOWED_HOSTS = ['~test_server_host of ec2~'] database = { ..AWS RDS instance for test.. } I expect the code below to work. # wsgi.py if realserver: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project.settings.real") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project.settings.test") and I have to use another api url depend on real or test. # views.py if real: get_data = requests.get(real_api.apiurl.com) else : get_data = requests.get(test_api.apiurl.com) How do I? -
How can I solve this problem SMTPAuthenticationError? [django]
I uploaded my website on the free host on Heroku and now when I click on forget password and send theSMTPAuthenticationError (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials l189sm7124459qkd.112 - gsmtp') I don't completely understand what is going on anybody can explain this issue -
DJANGO FORM RETURN HTML RAW CODE IN BROWSER
So im new in django and im learning to use django form i already try several tutorial but m django form return html raw code and idk where i did wrong please help # Create your views here. from django.shortcuts import render from django.http import HttpRequest from django.http import HttpResponse from .forms import SettingForm from django import forms def setting(request): form = SettingForm(request.POST or None) if form.is_valid(): form.save() context = { 'form' : form } return render(request, 'setting.html', {'name': 'Navin'}, context) this is my view from django import forms from .models import myform class SettingForm(forms.ModelForm): class Meta: model = myform fields = '__all__' my django forrms.py {% load static %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript %} <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>WOMBASTIS</title> <style> .hidden{ display:none; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> function myFunction() { var x = document.getElementById("myDIV"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> </head> <body> <h1>Hello {{name}}</h1> <form> {% csrf_token %} {{ form }} </form> </body> </html> the return was exactly that raw code in browser page -
Can one use Django for web scraping into a database?
I have a seemingly rare problem as I cannot find any resources on my issue. I have a fully functioning Django Rest-API framework backend that interacts with a database. I need to continuously scrape live data from the web and feed it into the same database for my application to work. I have already built a multi-threaded python web-scraping script (using Selenium) that runs in a "while True:" loop meant to never stop running, but I am unsure whether to add this code to my existing Django project, a separate and new Django project, or a separate file altogether. Since my database is made up of Django's object oriented models, my scraping script would run best inside of a Django framework as it can feed the database with ease. I am however, open to other methods. Note, I plan to push all of this to Amazon Web Service soon. My question is: Is Django fast enough for my purposes? Or is there a better way to do this? Thank you for your ideas in advance. -
(Rest framework, Django) __init__() takes 1 positional argument but 2 were given
I'm trying to create a new API file with django-rest-framework and use serializers, but for some reason I keep getting this error even if i do everything exactly as the tutorials(yes, I've tried more than one and they all lead to the same error). my basic model (Models.py @blog): class BlogPost(models.Model): title=models.CharField(max_length=12) description=models.TextField() name=models.IntegerField(default=0) def __str__(self): return self.title Serializers.py @blog.api: class BlogPostserializer(serializers.ModelSerializer): class Meta: model=BlogPost fields=('title','description','name') viewsets.py @blog.api class BlogPostView(viewsets.ModelViewSet): queryset=BlogPost.objects.all() serializer_class= BlogPostserializer Thanks in advance. -
Navbar toggle doesn't show icons after click on small screen
Django, Bootsrap 4; I have this navbar with toggle: <nav class="navbar navbar-expand-lg navbar-dark fixed-top bg-dark white scrolling-navbar" role="navigation"> <div class="container"> <a class="navbar-brand waves-effect" href="{% url 'product-list' %}"> <img src="../../../media/Logo.png" width="40" class="d-inline-block align-top"> <strong class="blue-text">Marche Saluk</strong> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <!-- Left of navbar --> <ul class="navbar-nav mr-auto"> {% if request.user.is_staff %} <li class="nav-item active"> <a class="nav-link waves-effect" href="{% url 'product-create' %}"> <span class="clearfix d-none d-sm-inline-block"> <i class="fa fa-plus-square-o" aria-hidden="true"></i> Create Product </span> </a> </li> {% endif %} {% if request.user.is_staff or request.user|has_group:"limited_staff" %} <li class="nav-item active"> <a class="nav-link waves-effect" href="{% url 'orders-view' %}"> <span class="clearfix d-none d-sm-inline-block"> <i class="fa fa-list-ul" aria-hidden="true"></i> Orders <span class="badge badge-pill badge-danger">{% orders_count request.user %}</span> </span> </a> </li> {% endif %} </ul> <!-- Right of navbar --> <ul class="navbar-nav nav-flex-icons"> {% if request.user.is_authenticated %} <li class="nav-item active"> <a class="nav-link waves-effect" href="{% url 'product-list' %}"><span class="clearfix d-none d-sm-inline-block"> <i class="fa fa-bars" aria-hidden="true"></i> Products List </span> </a> </li> <li class="nav-item active"> <a href="{% url 'cart-view' %}" class="nav-link waves-effect"> <span class="clearfix d-none d-sm-inline-block" style="color: greenyellow;"> <i class="fa fa-shopping-cart" aria-hidden="true"></i> Cart </span> <span class="badge badge-pill badge-danger">{% cart_items_count request.user %}</span> </a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" … -
Caching base.html only in Django
My base.html template, which is extended in nearly all of my pages, contains a header that I never want to be cached since it contains the username of the current user. I have two pages where it keeps getting cached though. I tried adding a {% cache 0 base request.user.username %} for the header, but to no avail. I don't want to have to add a @never_cache since I want to keep most of the DOM cached. Is there a way to add a never_cache decorator/functionality to my extended base.html only? -
Cannot resolve keyword 'slug' into field. Choices are: ... in django
hello guys is searched a lot and test the changing slug_url_kwarg but still problem does not solved! can anyone say why this error happening? here is my model.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #additional blood_type = models.CharField(max_length=2,blank=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) description = models.TextField(blank=True) case =models.CharField(max_length=30,blank=True) def __str__(self): return self.user.username and here is my views.py: basically I want to set a view that shows every person that has same blood_type to the person who loged in and case field is for whether a person is a donor or reciver and we want to match this people so i need the opposite case of the person who loged in for example if the loged in person is "reciver" with "blood type" : A+ i need a detail views of all the "blood donor" with "blood type" A+ class ProfileDetailView(DetailView,LoginRequiredMixin): model = UserProfile template_name = 'basicapp/detail_view.html' context_object_name = 'pro_detail' def get_queryset(self): user = UserProfile.objects.get(user=self.request.user) bloodType = user.blood_type Case = user.case return UserProfile.objects.filter(blood_type__exact=bloodType and ~Q(case__exact=Case)) and here is my url.py: urlpatterns = [ path('',views.index, name='index'), path('register/', views.register,name='register'), path('<slug:slug>/',views.ProfileDetailView.as_view(),name='detail_view') ]