Error when trying to write to database Django - django

I am still learning Python via Django and have been doing most of my methods in views. I have been told that it is better practice to put them in my models under a Manager. I have the following code grabbing the product info and I believe the id to fill my model. but its throwing an error. Any help would be great.
Updated error after moving stuff in to model. Now it does't regonize request.session
Traceback:
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\exception.py" in inner
42. response = get_response(request)
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\dbhol\Desktop\blackbelttest ver 1\blackbelttest\apps\blackbeltapp\views.py" in create
43. viewsResponse = Myblackbelt.objects.add_product(request.POST)
File "C:\Users\dbhol\Desktop\blackbelttest ver 1\blackbelttest\apps\blackbeltapp\models.py" in add_product
9. secreteid= User.objects.get(id=request.session['loguser_id'])
Exception Type: NameError at /blackbelt/create
Exception Value: global name 'request' is not defined
Html matters
<form class="" action="{% url 'blackbelt:create' %}" method="post">
{% csrf_token %}
<p>Product: <input type="text" name="product" value=""></p>
<input type="submit" name="" value="Create">
</form>
view.py that matters
def create(request):
viewsResponse = Myblackbelt.objects.add_product(request.POST)
return redirect ('blackbelt:index')
Models in full
from __future__ import unicode_literals
from django.db import models
from ..logReg.models import User
class ProductManager(models.Manager):
def add_product(self, postData):
print 'dog here'
secreteid= User.objects.get(id=request.session['loguser_id'])
Myblackbelt = self.create(product = postData['product'], creator=secreteid)
class Myblackbelt(models.Model):
product = models.CharField(max_length = 70)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
loguser = models.ManyToManyField(User, related_name='loguser')
creator = models.ForeignKey(User, related_name='creator')
objects = ProductManager()

Your code is not well structure and it'll break soon. However, to overcome the MultiValueDictKeyError error write these:
# views.py
def create(request):
if request.method == 'POST':
viewsResponse = Myblackbelt.objects.add_product(request.POST)
secreteid= User.objects.get(id=request.session['user_id'])
return redirect ('blackbelt:index')
class ProductManager(models.Manager):
def add_product(self, postData):
# always set a default value if dict key is not found
# of course you must (also) check if postData is of type dict
product = postData.get('product', None)
creator_id = postData.get('loguser_id', None)
if product is not None and creator_id is not None:
creator = User.objects.get(id=creator_id)
Myblackbelt = self.create(product=product, creator=creator)
print 'dog here'

Related

AttributeError at / 'int' object has no attribute 'get'

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/deprecation.py", line 138, in __call__
response = self.process_response(request, response)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/middleware/clickjacking.py", line 27, in process_response
if response.get("X-Frame-Options") is not None:
AttributeError: 'int' object has no attribute 'get'
Here is my code,
#views.py
class BookList(generic.View):
model = Book
def get(self, request, *args, **kwargs):
books = Book.objects.all()
if request.GET.get('Add') == 'Add':
query = request.GET.get('hidden-book')
book = Book.objects.filter(pk=query).update(moved=True)
return book
context = {'books': books}
return render(request, 'main.html', context)
#main.html
<form method="GET" action="">
<input type="hidden" name="hidden-book" value="{{ book.id }}/>
<input type="submit" name="Add" value="Add"/>
</form>
#models.py
class Book(models.Model):
moved = models.BooleanField(default=False)
When the user presses the 'Add' input button, it should change the moved attribute in book to True. For background, I have an application that has a list of books, each with their own add button, that upon clicking an add button, the book is added to another list of books. My code works, but when I click the add button an AttributeError at / 'int' object has no attribute 'get' is raised. When I go back to 127.0.0.1:8000/, the book has been moved from the first to second list.
Since I don't know what's causing the error, I assumed it was the query = request.GET.get('hidden-book') line because it's getting an id which is an int. I tried putting this in a try/except block, but nothing changed. I also tried to change {{ book.id }} to {{ book }} to get a string instead, but it also didn't work.
the root cause is
return book
get() needs to return a http response like
return render(...)
some lines below, not a query object
this should do it:
class BookList(generic.View):
model = Book
def get(self, request, *args, **kwargs):
if request.GET.get('Add') == 'Add':
query = request.GET.get('hidden-book')
book = Book.objects.filter(pk=query).update(moved=True)
books = Book.objects.all()
context = {'books': books}
return render(request, 'main.html', context)

MultiValueDictKeyError at /search/ when using post request in django

I am Unable to get query, which user is searching for from a POST request
Template file
<!-- search bar -->
<form action="{% url 'search' %}" method="post">{% csrf_token %}
<div class="container py-3 row">
<div class="col-md-8 offset-2">
<div class="input-group">
<input name="searchfieldText" type="text" class="form-control" placeholder="Search">
<button class="btn btn-danger" type="submit">Search</button>
</div>
</div>
</div>
</form>
urls.py
......
path('search/', views.search,name='search'),
.....
views.py
def search(request):
usr_qry= request.POST['searchfieldText']
print(usr_qry)
# and some more code which is irrelavent to paste here
.....
Complete views.py
from django.db.models.query_utils import Q
from App_wfi_Community import signals, urls
from django.shortcuts import render
from django.http import request, HttpResponseRedirect, HttpResponse
# import the models
from .models import Question, Answer, Comment, Upvote, DownVote, Upvote_record
# import paginator for pagination
from django.core.paginator import Paginator
# import forms
from .forms import Write_Answer_form, CommentForm
# import user
from django.contrib.auth.models import User
# import timezone for update function
from django.utils import timezone
# reverse for efficient url redirecting
from django.urls import reverse
from django.shortcuts import redirect
# import helper functions
from App_wfi_Community.view_helpers import *
# custom middleware
from App_wfi_Community.decorators import authentication_required, welcome_user_auth
# Create your views here.
# functions to called in views
def getPageObject(request, all_qns):
"""Returns the page object of Questions"""
paginator = Paginator(all_qns, 4, orphans=3)
pageNo = request.GET.get('page')
def getTags(RequestedQuestion):
"""Returns the Tags with comma seprated(if available)"""
# get tags from Question model
Question_tags = RequestedQuestion.Tags
# check if tag are not empty
if Question_tags != None:
Tags = Question_tags.split(',')
else:
Tags = Question_tags
# return the tags
return Tags
def get_save_form_data(RequestedQuestion, request, fom):
"""get data from form & save to DB"""
related_question = RequestedQuestion
detail = fom.cleaned_data['detail']
ansGiver = User.objects.get(pk=request.user.id)
ans = Answer(AnsGiver=ansGiver,
related_question=related_question, detail=detail)
ans.save()
# functions to process and send data to templates
#welcome_user_auth
def index(request):
# check if user is typing something
all_qns = Question.objects.all().order_by('-id')
# passing all questions to paginator with 4 question for one page
paginator = Paginator(all_qns, 6, orphans=2)
# get page no from home.html element with name= 'page'
page_number = request.GET.get('page')
# making page object
page = paginator.get_page(page_number)
# get all answer objects
all_ans = Answer.objects.all()
# get the username to display on home
username = request.user.username
# pass all the data to dictionary
data = {'all_ans': all_ans, 'all_qns': all_qns,
'page_object': page, 'username': username}
return render(request, 'home.html', data)
#authentication_required
def detail(request, questionID):
# get the Question from ID
RequestedQuestion = Question.objects.get(id=questionID)
# get the tags
Tags = getTags(RequestedQuestion)
# get the Answer
ans_A = Answer.objects.filter(related_question=RequestedQuestion)
# get the comment form
commentform = CommentForm()
# pass the info to data
data = {
'RequestedQuestion': RequestedQuestion,
'ans_A': ans_A,
'Tags': Tags,
'commentForm': commentform,
}
return render(request, 'detail.html', data)
#authentication_required
def writeAns(request, questionID):
# get the Question from ID
RequestedQuestion = Question.objects.get(id=questionID)
# check if there is a post request from template
if request.method == 'POST':
# get all the form data with post request into a variable
fom = Write_Answer_form(request.POST)
if fom.is_valid():
get_save_form_data(RequestedQuestion, request, fom)
# make a string url to pass as a arguments
url = '/detail/' + str(questionID)
return HttpResponseRedirect(url)
else:
return HttpResponse('you write the answer incorrectly')
else:
# send blank form to template
fom = Write_Answer_form()
data = {'form': fom}
return render(request, 'writeAns.html', data)
#authentication_required
def saveComment(request, ansID, questionID):
if request.method == 'POST':
fom = CommentForm(request.POST)
if fom.is_valid():
answer = Answer.objects.get(id=ansID)
commented_By = User.objects.get(pk=request.user.id)
detail = fom.cleaned_data['detail']
comment = Comment(
answer=answer, commented_By=commented_By, detail=detail)
comment.save()
# redirect the user to previous page
url = '/detail/' + str(questionID)
return HttpResponseRedirect(url)
# update the Answer
#authentication_required
def update(request, ansID):
if request.method == 'POST':
fom = Write_Answer_form(request.POST)
if fom.is_valid():
answer = Answer.objects.filter(id=ansID)
# getting data for saving
ansGiver = User.objects.get(pk=request.user.id)
related_question = answer[0].related_question
detail = '[Edited] ' + fom.cleaned_data['detail']
post_time = timezone.now()
# saving to database (for update we need to add all fields including answer id and post time)
ansObj = Answer(id=ansID, AnsGiver=ansGiver,
related_question=related_question, detail=detail, post_time=post_time)
ansObj.save()
# getting question id for redirecting the url
question = Question.objects.get(title=related_question)
url = '/detail/' + str(question.id)
return HttpResponseRedirect(url)
else:
fom = Write_Answer_form()
data = {'form': fom}
return render(request, 'update.html', data)
# delete the answer
#authentication_required
def deleteAns(request, ansID):
answerOb = Answer.objects.get(id=ansID)
question = Question.objects.get(title=answerOb.related_question)
answerOb.delete()
# url for redirection
url = '/detail/'+str(question.id)
return HttpResponseRedirect(url)
# search function
#authentication_required
def search(request):
usr_qry= request.GET['searchfieldText']
print(usr_qry)
# for use with postgre
# search_res1= Question.objects.filter(detail__icontains=usr_qry).order_by('id')
# search_res2= Question.objects.filter(title__icontains=usr_qry).order_by('id')
# final_res= search_res1.union(search_res2)
final_res= Question.objects.filter(Q(title__icontains=usr_qry) or Q(detail__icontains=usr_qry))
print('the search res are:',final_res)
pag_ob= Paginator(final_res,per_page=3)
print(f"Total no of question found with search are: {pag_ob.count}")
print(f"Total no of pages found with the question are: {pag_ob.num_pages}")
print(f"The Page range is: {pag_ob.page_range}")
print('the item in the page 1 are:',pag_ob.page(1).object_list)
return HttpResponse('chk terminal')
def downVote(request, ansID, quesID):
url= "/detail/"+str(quesID)
usr= User.objects.get(pk= request.user.id)
ansob= Answer.objects.get(id=ansID)
if chk_downvote_record(usr,ansob) == "yes":
print('this ans is already downvoted by: ',usr)
elif chk_downvote_record(usr,ansob) == "no":
save_to_downvote_record(usr,ansob)
update_downvote(ansob)
signals.delete_upVote.send(sender=None,ans=ansob,usr=usr)
return HttpResponseRedirect(url)
def upvote(request, ansID, quesID):
url = "/detail/"+str(quesID)
usr = User.objects.get(pk=request.user.id)
ans_ob = Answer.objects.get(id=ansID)
if check_upvote_record(usr, ans_ob) == "yes":
pass
elif check_upvote_record(usr, ans_ob) == "no":
save_to_upvt_rec(usr, ans_ob)
update_upvote(ans_ob)
signals.delete_downvote.send(sender=None,ans=ans_ob,usr=usr)
return HttpResponseRedirect(url)
Traceback
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/search/?searchfieldText=window
Django Version: 3.2.2
Python Version: 3.9.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'App_wfi_Community',
'django.contrib.humanize',
'askQuestion',
'authentiCation']
Installed 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']
Traceback (most recent call last):
File "C:\Users\saurav\Documents\GitHub\WFI-Community\venv\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__
list_ = super().__getitem__(key)
During handling of the above exception ('searchfieldText'), another exception occurred:
File "C:\Users\saurav\Documents\GitHub\WFI-Community\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\saurav\Documents\GitHub\WFI-Community\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\saurav\Documents\GitHub\WFI-Community\App_wfi_Community\decorators.py", line 7, in wrapper_func
return func_arg(request, *args, **kwargs)
File "C:\Users\saurav\Documents\GitHub\WFI-Community\App_wfi_Community\views.py", line 178, in search
usr_qry= request.POST['searchfieldText']
File "C:\Users\saurav\Documents\GitHub\WFI-Community\venv\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__
raise MultiValueDictKeyError(key)
Exception Type: MultiValueDictKeyError at /search/
Exception Value: 'searchfieldText'
i want to get user search query or whatever user is searching for.. initially i am trying to print user search query in Terminal but it gives me:
MultiValueDictKeyError at /search/
'searchfieldText'
if i use get method then it works fine but i want to use post method & i don't know what is going wrong here.
As I see in traceback, your browser sent GET request
Request Method: GET
Request URL: http://127.0.0.1:8000/search/?searchfieldText=window
Did you reload the page after changing template?

Having a problem with the follower system, I am following myself in Django and also this error shows ValueError at /accounts/users/2/accept_follower/

Hey guys I am trying to send a follow request through the django notifications and the person at the other end will be either accepting or rejecting the request. But I have a problem that when the person at the other end accepts the request, this error is showing
ValueError at /accounts/users/2/accept_follower/
The view accounts.views.accept_follow_request didn't return an HttpResponse object. It returned None instead.
and he is following himself. I tried printing out the current_user and user in send_follow_request function and it is showing the 2 users correctly, but in the accept_follow_request function, both the users are same! How to change that?
This is the code I have now.
def send_follow_request(request, id):
current_user = request.user
user = Account.objects.get(id=id)
notify.send(request.user, recipient=user, verb='has sent you a follow request', target=user)
return redirect('posts:userprofile', user.username)
def accept_follow_request(request, id):
current_user = request.user
user = Account.objects.get(id=id)
contact, created = Contact.objects.get_or_create(user_from=request.user, user_to=user, follow_status='AC')
if user != request.user:
create_action(request.user, 'started following', user)
notify.send(request.user, recipient=user, verb='started following you')
return redirect('all_user_notifications')
This is the notification view
class AllNotificationsList(LoginRequiredMixin, NotificationViewList):
def get_queryset(self, *args, **kwargs):
if get_config()['SOFT_DELETE']:
qset = self.request.user.notifications.active()
else:
qset = self.request.user.notifications.all()
return qset
Can anyone tell me where the problem is?
This is the form I have in the notificaion template:
{% if notice.target == user %}
<form action="{% url 'accept_follow_request' user.id %}">
<button class="btn-sm btn-success" type="submit">Accept</button>
Cancel
</form>
This is the model I have
class Contact(models.Model):
user_from = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_from_set', on_delete=models.CASCADE)
user_to = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_to_set', on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True, db_index=True)
follow_status = models.CharField(choices=FOLLOW_STATUS, max_length=10)
#USER_FROM IS THE ONE WHO IS FOLLOWING AND USER_TO IS ONE BEING FOLLOWED
class Meta:
ordering = ('-created',)
def __str__(self):
return f'{self.user_from} follows {self.user_to}'
following = models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)
#adding the above field to User Model class
user_model = get_user_model()
user_model.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers',
symmetrical=False))
url:
path('<int:id>/accept_follower/', views.accept_follow_request, name='accept_follow_request'),
Traceback:
C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py in inner
response = get_response(request) …
▼ Local vars
Variable Value
exc
ValueError("The view accounts.views.accept_follow_request didn't return an HttpResponse object. It returned None instead.")
get_response
<bound method BaseHandler._get_response of <django.core.handlers.wsgi.WSGIHandler object at 0x039FC6E8>>
request
<WSGIRequest: GET '/accounts/users/2/accept_follower/'>
C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py in _get_response
raise ValueError( …
▼ Local vars
Variable Value
callback
<function accept_follow_request at 0x04D19E80>
callback_args
()
callback_kwargs
{'id': 2}
middleware_method
<bound method CsrfViewMiddleware.process_view of <django.middleware.csrf.CsrfViewMiddleware object at 0x03A2B3D0>>
request
<WSGIRequest: GET '/accounts/users/2/accept_follower/'>
resolver
<URLResolver 'socialwebsite.urls' (None:None) '^/'>
resolver_match
ResolverMatch(func=accounts.views.accept_follow_request, args=(), kwargs={'id': 2}, url_name=accept_follow_request, app_names=[], namespaces=[], route=accounts/users/<int:id>/accept_follower/)
response
None
self
<django.core.handlers.wsgi.WSGIHandler object at 0x039FC6E8>
view_name
'accept_follow_request'
wrapped_callback
<function accept_follow_request at 0x04D19E80>
Thanks!
It does seem that user == request.user as in that case you are not returning any response ( you have if but not else)
I would guess that constructed URL for accept_follower has wrong id in URL ( notified user instead of id of user that requested follow)
This would be reason you are following yourself
contact, created = Contact.objects.get_or_create(user_from=request.user, user_to=user, follow_status='AC')
so something in a line of following ( instead user.id (its the target) send id of sender ):
{% if notice.target == user %}
<form action="{% url 'accept_follow_request' notice.actor.id %}">
<button class="btn-sm btn-success" type="submit">Accept</button>
Cancel
</form>

Test of form containing ImageField resulting in type error

I'm trying to test a form that contains an ImageField and I'm getting an error. I've tried stepping through the Django code but I keep getting lost and I can't see the problem. I've researched how this is supposed to be done and I thought I was doing everything correctly.
Here's the error which occurs at the assertTrue statement in my test:
TypeError: is_valid() takes exactly 2 arguments (1 given)
Here are my files:
# forms.py
class UploadMainPhotoForm(forms.Form):
photo = forms.ImageField(error_messages={'required': err_msg__did_not_choose_photo})
def is_valid(self, request):
# Run parent validation first
valid = super(UploadMainPhotoForm, self).is_valid()
if not valid:
return valid
if request.FILES:
photo_file = request.FILES['photo']
file_name, file_ext = os.path.splitext(photo_file.name)
else:
self._errors['photo'] = 'You forgot to select a photo.'
return False
# Return an error if the photo file has no extension
if not file_ext:
self._errors['photo'] = err_msg__photo_file_must_be_jpeg
return False
return True
# upload_photo.html (template)
<form method="post" enctype="multipart/form-data" action=".">{% csrf_token %}
<input type="file" name="photo" />
<input type="submit" name="skip_photo" value="Skip Photo" />
<input type="submit" name="upload_photo" value="Upload Photo">
</form>
# form_tests.py
class TestUploadMainPhotoForm(TestCase):
def initial_test(self):
post_inputs = {'upload_photo': '[Upload Photo]'}
test_photo = open('photo.jpg', 'rb')
file_data = {'file': SimpleUploadedFile(test_photo.name, test_photo.read())}
self.assertTrue(UploadMainPhotoForm(post_inputs, file_data).is_valid())
Here:
def is_valid(self, request):
You have defined is_valid method with a parameter request and while calling it,
self.assertTrue(UploadMainPhotoForm(post_inputs, file_data).is_valid())
You have not specified the parameter. Hence the error.
You can make use of the RequestFactory to get the request object in the unittest.
from django.utils import unittest
from django.test.client import RequestFactory
class TestUploadMainPhotoForm(TestCase):
def setUp(self):
self.request = RequestFactory()
def initial_test(self):
post_inputs = {'upload_photo': '[Upload Photo]'}
test_photo = open('photo.jpg', 'rb')
file_data = {'file': SimpleUploadedFile(test_photo.name, test_photo.read())}
self.assertTrue(UploadMainPhotoForm(post_inputs, file_data).is_valid(self.request))

Django: IndexError at /customerList/ tuple index out of range

Can anyone help me with this. I don't understand this error
IndexError at /customerList/
tuple index out of range
and it came from this code
self.Customer = get_object_or_404(customer, name__iexact=self.args[0])
I want to be able to do ListView some of the fields from two forms that is from customerForm (F_NAME, L_NAME) and buildingForm (B_USE, B_TYPE). Any help is very much is very very much appreciated. Thank u.
Traceback:
File "c:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "c:\Python27\lib\site-packages\django\views\generic\base.py" in view
48. return self.dispatch(request, *args, **kwargs)
File "c:\Python27\lib\site-packages\django\views\generic\base.py" in dispatch
69. return handler(request, *args, **kwargs)
File "c:\Python27\lib\site-packages\django\views\generic\list.py" in get
114. self.object_list = self.get_queryset()
File "f:\iqgit\amon\amonsolution\solution\views.py" in get_queryset
59. self.Customer = get_object_or_404(customer, name__iexact=self.args[0])
Exception Type: IndexError at /customerList/
Exception Value: tuple index out of range
views.py
class customerListView(ListView):
template_name = "customerList.html",
model = customer
context_object_name = "customer_list"
def get_queryset(self):
self.Customer = get_object_or_404(customer, name__iexact=self.args[0])
return building.objects.filter(Customer=self.Customer)
def get_context_data(self, **kwargs):
context = super(customerListView, self).get_context_data(**kwargs)
context['building_list'] = building.objects.all()
return context
forms.py
class customerForm(forms.ModelForm):
F_NAME = forms.CharField(widget=forms.TextInput()
L_NAME = forms.CharField(widget=forms.TextInput()
EMAIL = forms.CharField(widget=forms.TextInput()
ADD = forms.CharField(widget=forms.TextInput()
class Meta:
model = customer
class buildingForm(forms.ModelForm):
CUSTOMER = forms.CharField(widget=forms.TextInput()
B_FLOORSPACE = forms.CharField(widget=forms.TextInput()
B_YEAR = forms.CharField(widget=forms.TextInput()
B_USE = forms.ChoiceField(widget=forms.RadioSelect(), choices=c.Use)
B_TYPE = forms.ChoiceField(widget=forms.RadioSelect(), choices=c.Type)
class Meta:
model = building
exclude = ('CUSTOMER',)
urls.py
url(r'^customerList/',customerListView.as_view(), name= "customerList_view"),
customerList.html
...some of code...
{% for customer in customer_list %}
<tr class = {% cycle "row_even" "row_odd" %}>
<td>{{ customer.id }}</td>
<td class ="name"> {{ customer.F_NAME }} {{ customer.L_NAME }}</td>
<td class ="b_use"> {{ building.B_USE }}{{ building.B_TYPE }}</td>
...some of code...
You are trying to call a positional argument (self.args[0]) passed from the URL conf but you haven't added any positional arguments to your actual url. If you look at how a request is processed, you will notice that:
4 . Once one of the [url] regexes matches, Django imports and calls the given view, which is a simple Python function. The view gets passed an HttpRequest as its first argument and any values captured in the regex as remaining arguments.
You aren't passing any arguments (neither positional or named) to your view so there is nothing in self.args or self.kwargs. You need to change your URL to something like:
url(r'^customerList/(\w+)/',customerListView.as_view(), name= "customerList_view"),
or ideally make use of named arguments such as:
url(r'^customerList/(?P<name>\w+)/',customerListView.as_view(), name= "customerList_view"),
so that you can instead use self.kwargs.get("name", None)