Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'HTTP status code must be an integer' error in Django view
i have small scraping view in my Django website, but i get an error 'HTTP status code must be an integer' in line: 'return HttpResponse(request, 'scrapingscore.html', {'original_link':original_link}) ' def scraping(request): rootlink = 'https://www.transfermarkt.pl' link = 'https://www.transfermarkt.pl/schnellsuche/ergebnis/schnellsuche?query=' if request.method == 'POST': data = request.POST.get("textfield") if data == '': empty = 'Data is empty' return HttpResponse(request, 'scrapingscore.html', {'empty':empty}) else: data = data.replace(" ", "+") search = link + data + '&x=0&y=0' req = Request( search, data=None, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' } ) req = urlopen(req).read() soup = BeautifulSoup( req, features="lxml" ) anchor = soup.find("a",{"class":"spielprofil_tooltip"}) link = anchor.get("href") original_link = rootlink + link return HttpResponse(request, 'scrapingscore.html', {'original_link':original_link}) return render(request, 'scraping.html') I don't know why i get an error 'HTTP status code must be an integer'. I have one argument in dict in this line with error and i don't know how to repair it, i thought it will work but it is not. When user input is blank, i also get this error in line 'return HttpResponse(request, 'scrapingscore.html', {'empty':empty})'. -
Can't use validation error for a form in django
I have a birthday field in a model and when i try to validate the form i want it so that the age should be 13+ to validate the form . I have set up something like this .forms.py class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=60, help_text='Add a valid email') today = date.today() class Meta: model = Account fields = ('email','username', 'password1', 'password2', 'first_name','last_name','addresse','birthday','city','profil_pic') def clean_birth(self): birthday = self.cleaned_data['birthday'] if int((today-birthday).days / 365.25) < 18: raise forms.ValidationError("Users must be 18+ to join the website")` template <form method="post"> {% csrf_token %} {{registration_form.as_p}} {% if registration_form.errors %} {% for field in registration_form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in registration_form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} <button type="submit">zef</button> </form> But this only show the main errors of django like wrong email and passwords not matching -
HeaderParseError Invalid Domain
I am getting this error when i try to invoke an email to be sent to an Admin when a staff applies for leave. Below are my email settings and the server stack trace. Any thoughts why am getting this and how to fix it, thanks. email settings: EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'jacmuhuri@gmail.com' #test EMAIL_HOST_PASSWORD = '*******'#test EMAIL_PORT = 587 EMAIL_USE_TLS = True stacktrace: Internal Server Error: /dashboard/leave/apply/ Traceback (most recent call last): File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Projects\hr_app\humanresource\src\dashboard\views.py", line 575, in leave_creation leave_application_email(leave_obj=instance) File "C:\Projects\hr_app\humanresource\src\leave\emails.py", line 85, in leave_application_email template="leave_application", File "C:\Projects\hr_app\humanresource\src\leave\emails.py", line 61, in send_email return msg.send(fail_silently=True) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\mail\message.py", line 291, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\mail\backends\smtp.py", line 110, in send_messages sent = self._send(message) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\mail\backends\smtp.py", line 122, in _send from_email = sanitize_address(email_message.from_email, encoding) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\mail\message.py", line 119, in sanitize_address address = Address(nm, addr_spec=addr) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\email\headerregistry.py", line 42, in __init__ a_s, rest = parser.get_addr_spec(addr_spec) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\email\_header_value_parser.py", line 1631, in get_addr_spec token, value = get_domain(value[1:]) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\email\_header_value_parser.py", line 1604, in get_domain raise errors.HeaderParseError('Invalid Domain') email.errors.HeaderParseError: Invalid Domain -
Django Teamplate Error name 'Post_title' is not defined
I'm trying to render index HTML and get post title from database but I'm getting error. I define in views post database but still getting error name 'Post_title' is not defined my app/views.py from django.shortcuts import render, get_object_or_404 from django.shortcuts import reverse from .models import BlogPost,comments def index(request): Post_list = BlogPost.objects.all() template_name = 'front/index.html' return render(request, template_name,{Post_title:"Post_title",}) def post_detail(request): return render(request, 'front/post_detail.html') my app/urls.py from django.urls import path from .import views urlpatterns = [ path('', views.index, name = 'index'), path('<int:BlogPost_id>/', views.post_detail, name='Post Detail') ] my project/urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static from froala_editor import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('froala_editor/', include('froala_editor.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my index.html template <div class="col-md-8 mt-3 left"> {% for post in Post_list %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title">{{ post.Post_title }}</h2> </div> </div> {% endfor %} </div> -
Pyodbc - Calling Store procedure from Django application
I have an MsSQL strore procedure which is getting executed by the command : EXEC proc_CreateProblemTicket @CurrentDate='2020-03-08'. Now I have a python django application where I need to call the store proc and passing the dynamic date. In the above example, the date is hard coded but I would like this is to dynamic. Everyday when the store proc gets executed, it should have current day. Please suggest how to do this. -
Login with oAuth2 in django using email or phone number
I am trying to implement login with oauth2 in django. Currently I am using TokenView for logging user in. But that uses username. I tried to override the default TokenView by writing something like this: class TokenView(OAuthLibMixin, View): server_class = oauth2_settings.OAUTH2_SERVER_CLASS validator_class = oauth2_settings.OAUTH2_VALIDATOR_CLASS oauthlib_backend_class = oauth2_settings.OAUTH2_BACKEND_CLASS @method_decorator(sensitive_post_parameters("password")) def create_token_response(self, request): email = request.POST.get('email', None) contact = request.POST.get('contact', None) if email or contact: username = get_user_model().objects.filter(Q(email__iexact=email)).first() | get_user_model().objects.filter(Q(contact__iexact=contact)).first() request.POST['email'] = username return super(TokenView, self).create_token_response(request) and here is my user model: class User(AbstractUser): email = models.EmailField(unique=True) contact = models.CharField(max_length=10, unique=True) username = None But I am getting an error like this AttributeError: This QueryDict instance is immutable And I get it that I cant change the value of POST request. So how can I achieve this? -
How to save and restore filters with django-filter
how can I save and restore filters with django_filters? I'm using django_filters like so: f = MyFilter(request.POST, queryset=MyModel.objects.all()) Now, I would like to be able to save my filter. That's what I tried: request.session['myfilter'] = f.form.cleaned_data I use the pickled session backend so I do not expect any trouble from there. If I try to rebuild the filter afterwards it doesn't work: f = MyFilter(request.session['myfilter'], queryset=MyModel.objects.all()) No error is displayed, but RangeFilter seem to be ignored. Of course, I could just store request.POST but this seems very ugly to me because it contains unverified data. Also, storing the queryset (f.qs) doesn't work for me because I need to be able to show the form again for editing. How to do it right? Thank you very much! -
HomeView is missing a QuerySet. Define HomeView.model, HomeView.queryset, or override HomeView.get_queryset()
i have got this error and i'm following this [tutorial][1] this is urls.py from django.urls import path from .views import HomeView urlpatterns = [ path('home/', HomeView.as_view(), name ='blog-home') ] this is my views.py from django.shortcuts import render from django.views.generic import ListView from .models import Entry class HomeView(ListView): models = Entry template_name = 'entries/index.html' -
How to upload a pre populated DataBase on Heroku?
I am making a django app and it and I am using selenium for automatically scraping the data from a site and populating my database with it. But I can't seem to find a way to run selenium on heroku. So I thought if there was any possible way by which I can populate the database on my local machine and then upload it to Heroku. -
django boto3: NoCredentialsError -- Ubale to locate credentials
I am running django website which is served by IIS on an amazon ec2 instance(windows 10) and I'm using boto3 module to send an email. I installed awscli and ran aws configure and set up my aws access keys My email sending code looks like this: import boto3 from botocore.exceptions import ClientError from django.shortcuts import redirect, render from django.http import HttpResponseRedirect def sendEmail(request): if request.method == 'POST': SENDER = "Sender Name <xxx>" RECIPIENT = "xxx" AWS_REGION = "eu-west-1" # The subject line for the email. SUBJECT = "Amazon SES Test (SDK for Python)" # The email body for recipients with non-HTML email clients. BODY_TEXT = ("Amazon SES Test (Python)\r\n" "This email was sent with Amazon SES using the " "AWS SDK for Python (Boto)." ) # The HTML body of the email. BODY_HTML = """<html> <head></head> <body> <h1>Amazon SES Test (SDK for Python)</h1> <p>This email was sent with <a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the <a href='https://aws.amazon.com/sdk-for-python/'> AWS SDK for Python (Boto)</a>.</p> </body> </html> """ # The character encoding for the email. CHARSET = "UTF-8" # Create a new SES resource and specify a region. client = boto3.client('ses', region_name=AWS_REGION) try: # Provide the contents of the email. response = client.send_email( Destination={ 'ToAddresses': … -
how to handle the Post request with many to many relation in django
I have 3 models and i want to save them they have a relation between them you are welcome to change anything and i have another issue that i'm using js function clone to add as much item as I want in the template form class Item (models.Model): name = models.CharField(("Item"), max_length=50) description = models.TextField(("Description"),blank=True, null=True) category_id = models.ForeignKey(ItemCategory, on_delete=models.CASCADE,blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class RFQ (models.Model): title = models.CharField(("Title"), max_length=100) # qty = models.CharField(("Quantity"), max_length=50) project = models.ForeignKey(Project, on_delete=models.CASCADE) item = models.ManyToManyField(Item, through='RFQItem') note = models.TextField(("Note"),blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class RFQItem (models.Model): RFQ = models.ForeignKey(RFQ, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) price =models.FloatField(("Price"), blank=True) qty = models.FloatField(("Quatity"), blank=True) note I'm using HTML and bootstrap in the template, not Django form how could I handle that in the view and save it I try something like this but it gives me an error and could not save this this is my view code def create_RFQ(request, project_id): context = {} print('aaaaaaaaaaa') if request.method == 'POST': print(request.POST) print(project_id) if not request.user.is_authenticated: return redirect("login") items = Item.objects.all() # context = {} if request.method == 'POST': print('*-*-*-*-') form1 = RFQCreate(request.POST) … -
Django, How can i count how much student every group?
i can not filter my models ,for example i need show in result, please help, thank you date group 110 students 23 date group 111 students 9 models class Group(models.Model): title = models.CharField(max_length=200, default=0) date_pub = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) def __str__(self): return self.title def datepublished(self): return self.date_pub.strftime('%d.%m.%Y') class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE,default=0) rating = models.CharField(default='5', max_length=200) date_pub = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) def __str__(self): return self.user.username views def groups(request): groups = Group.objects.all() context = { 'groups': groups } return render(request, 'panel/panel_groups.html', context) html {% for i in groups %} <tr> <td>{{ i.datepublished }}</td> <td>{{ i.title }}</td> <td>count</td> <td> <a href="{% url 'groups_detail' i.id %}" class="btn btn-secondary"> <i class="fas fa-angle-double-right"></i> Details </a> </td> </tr> {% endfor %} -
In need of clear explanation the usage of get_form_kwargs method in django
i have been working with django for quite a while now, trying to deepen my knowledge. Hence started using Generic Class Base Views, overriding some django methods and its been fun. However, i haven't been able to understand get_form_kwargs() method and its implementation. Will be most grateful if someone could share what it all entails succinctly or drop a link that perfectly explains its implementations and usage. -
Exception Value: name 'start_date' is not defined
I'm getting this error during my admin testing on save of a habit in my Habit app. I don't know what to add to this code that would satisfy a definition of 'start_date'. Will you please show me where I've gone wrong. Exception Value: name 'start_date' is not defined Exception Location: //models.py in duration, line 20 which is, a = datetime.strptime(str(start_date), date_format) class Habit(models.Model): name = models.CharField(max_length=60) goal_nbr = models.IntegerField(default=0, null=True, blank=True) goal_description = models.CharField(max_length=60, null=True, blank=True) start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey( User, related_name="habit", on_delete=models.CASCADE) @property def duration(self): date_format = "%m/%d/%Y" a = datetime.strptime(str(start_date), date_format) b = datetime.strptime(str(end_date), date_format) delta = b - a return f'{ delta } days' def __str__(self): return f"Goal Name: {self.name} Goal Target: {self.goal_nbr} Description: {self.goal_description} Duration: {self.duration} days Beginning: {self.start_date} Ending: {self.end_date}" -
how to display uploaded files or images on template in django3
I only see the file path in the template. I can't see the file itself. (django 3.x) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') model.py class EkleModel (models.Model): aKaydi = models.CharField(max_length=50, verbose_name='A KAYDI') bKaydi = models.CharField(max_length=50, verbose_name='B KAYDI') cKaydi = models.CharField(max_length=50, verbose_name='C KAYDI') upload = models.FileField(upload_to='media/%Y/%m/%d/', verbose_name='DOSYA YÜKLE') yuklemeTarihi =models.DateTimeField(default =timezone.now) views.py def index(request): girdiler = EkleModel.objects.filter(yuklemeTarihi__lte=timezone.now()).order_by('-yuklemeTarihi') return render(request, 'sayfalarUygulamasi/index.html', {'girdiler': girdiler}) index.html <img class="card-img-top" src="girdi.upload"> <h4 class="card-title">{{girdi.aKaydi}}</h4> <h4 class="card-title">{{girdi.bKaydi}}</h4> <h4 class="card-title">{{girdi.cKaydi}}</h4> <h4 class="card-title">{{girdi.yuklemeTarihi}}</h4> -
Django, error in manage.py when run migrate
I have the following message error when I try to run "python manage.py migrate, I don't understand where is my problem, someone could help me????": (v_env) C:\Users\Federico\Desktop\Prova test\mysite>python manage.py migrate Operations to perform: Apply all migrations: admin, app, auth, contenttypes, sessions Running migrations: Applying app.0004_income_date...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) ..... To help you to identify the problem I have attached below my setting.py. I don't identify any issue or code error: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1.5. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '!60gpatqgt*q&6da*u3m@0nq&ml-^c7d#$bijk_5ge%b7p@r0b' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'djmoney', 'django_tables2', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = … -
How To add Linebreak on specific characters in django?
I Want To add Linebreaks after specific characters but i don't know how to do that! Here is the image Look at this image i want to add line breaks after 50 characters Here is my HTML FILE: {% extends 'blog/base.html' %} {% block content %} <div class="container mt-3"> <h3>{{ post.title }}</h3> <hr> {% if post.blog_img %} <div class="card-image" style="background-image: url({{ post.blog_img.url }}); height: 370px;background-size: cover;background-repeat: no-repeat;background-position: center center;"></div> <hr> {% endif %} <p>{{ post.content }}</p> <hr> <p>About <a href="{% url 'category' slug=post.category.slug %}">{{ post.category.name }}</a> By <a href="{% url 'profile' username=post.author.username %}">{{ post.author.username }}</a> Posted At: <strong>{{ post.timestamp|timesince }}</strong></p> </div> {% endblock %} Here is my views.py def detail(request,slug=None): post = get_object_or_404(Post,slug=slug) if post.status == 'published': context = {'post':post,} return render(request,'blog/detail.html',context) else: return redirect(index) -
Error while installing mysqlclient in py3
rohit@rohit:~/Desktop/django_project$ pip3 install mysqlclient Collecting mysqlclient==1.3.12 Using cached https://files.pythonhosted.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "", line 1, in File "/tmp/pip-build-6bic4vtr/mysqlclient/setup.py", line 17, in metadata, options = get_config() File "/tmp/pip-build-6bic4vtr/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-build-6bic4vtr/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-6bic4vtr/mysqlclient/ I've also tried install with version pip3 install mysqlclient==1.3.12, it shows same error. -
Which one is better Dot net or django
I am a fresher in IT sector so i am confused to choose dot net or django .Please give me advise what i will choose. In both of them which have more jobs and more salary. Please compare them in accordance of jobs and salary to. -
ValueError at /basic_app/register/
The view basic_app.views.register didn't return an HttpResponse object. It returned None instead. ... Please Help me I am tired to solve or find out this error even couldn't understand this that where it's located The view basic_app.views.register didn't return an HttpResponse object. It returned None instead. views.py from django.shortcuts import render # from django.http import HttpResponse from basic_app.forms import UserForm, UserProfileInfoForm # Create your views here. def index(request): return render(request, 'basic_app/index.html') def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'basic_app/registration.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): # user = models.OneToOneField(User) user = models.OneToOneField(User, on_delete=models.CASCADE) # user = models.ForeignKey(User,models.SET_NULL,blank=True,null=True) # user = models.ForeignKey(User, on_delete=models.PROTECT) # additional profile_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics', blank=True) def __str__(self): return self.user.username -
How to create a 'Text to HTML' generator app in Django?
I want to create this app but I have no clues on how I can get it done. I have tried googling for a solution but can't find any. Anyone help? -
I have configured every thing but django says page not found
can any one help me with this problem? this is my blog/urls.py: from django.urls import path from .views import * urlpatterns = [ path("/testTemplate", template_testing, name="testtemplate"), ] and this is my website/urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and this is blog/views.py: from django.shortcuts import render # Create your views here. def template_testing(request): return render(request, "blog/index.html", {}) every things looks OK but when I want to go to this url: 127.0.0.1:8000/testTemplate I get a page not found error. What is going wrong here? please help me! -
What *args, **kwargs doing in this save method overriding
I'm new to Django. I understand what are the usage of *args and **kwargs. And also know how to use them in method overriding. But, I don't understand what purpose they serve while overriding the save() method in a model class. My observation is that no number of arguments, either non-keyworded or keyworded, were assigned to them anywhere. Still why do I must use them and how. Have this example: class DemoModel(models.Model): title = models.CharField(max_length = 200) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.title) super(DemoModel, self).save(*args, **kwargs) Please explain. -
Use self in ModelForm fields
I have a Formview and pass the pk to the ModelForm. In the ModelForm i am not able to use self.pk in the queryset i define for the field: views.py [...] def get_form_kwargs(self): # Pass extra kwargs to DetailProductForm kwargs = super(DetailProduct, self).get_form_kwargs() kwargs.update({'pk': self.kwargs['pk']}) return kwargs forms.py class DetailProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): # get the pk from the FormView at set it as self.pk self.pk = kwargs.pop('pk', None) super(DetailProductForm, self).__init__(*args, **kwargs) # use self.pk in my queryset (there are more fields who use self.pk, this is just one as an example) field = forms.ModelChoiceField(queryset=Configuration.objects.filter(product__pk=self.pk), widget=forms.RadioSelect) class Meta: model = Configuration fields = ['field'] NameError: name 'self' is not defined How can i use self.pk for the fields? -
Replacing templates in [os.path.join(BASE_DIR, 'templates')]
Since I don't have a Template folder with all my HTML, I cant use 'template in 'DIRS': [os.path.join(BASE_DIR, 'templates')], I place all my HTML directly in the site folder. MySite ├── MySite │ └── settings.py <--`'DIRS': [os.path.join(BASE_DIR, 'templates')],` └── index.html How can I change the 'templates' in 'DIRS': [os.path.join(BASE_DIR, 'templates')], to take the HTML files directly from my site folder?