__init__() got an unexpected keyword argument 'book_category' - python

Hi? I'm new to web development can you plz help me whats the problem with my file?
I don't know why is this, I have defined my category model properly and imported it. I have also defined book_category. Im stuck
views.py: the error is found here
class AddBookIndexView(View):
def get(self, request):
booksQS = Books.objects.all()
authorsQS = Author.objects.all()
categoryQS = Category.objects.all()
print(authorsQS)
print(categoryQS)
print(booksQS)
return render(request, 'addbook.html')
def post(self, request):
form = BooksForm(request.POST, request.FILES)
if form.is_valid():
book_category = request.POST.get('book_category')
firstname = request.POST.get('Firstname')
lastname = request.POST.get('Lastname')
author = Author.objects.filter(Q(firstname__icontains = firstname) & Q(lastname__icontains = lastname))
if author:
print(author)
else:
form = AuthorForm(firstname= firstname, lastname=lastname)
form.save()
category = Category.objects.filter(Q(book_category__icontains = book_category))
if category:
print(category)
else:
form = CategoryForm(book_category= book_category)#this is where the error
form.save()
author = Author.objects.filter(Q(firstname__icontains = firstname) & Q(lastname__icontains = lastname))
category = Category.objects.filter(Q(book_category__icontains = book_category))
for a in author:
print(a.book_author_id)
for c in category:
print(c.book_category_no)
book_title = request.POST.get('book_title')
book_cover = request.FILES.get('book_cover')
book_file = request.FILES.get('book_file')
book_year = request.POST.get('book_year')
book_tags = request.POST.get('book_tags')
book_summary = request.POST.get('book_summary')
form = Books(book_title = book_title, book_author_id = Author.objects.get(book_author_id = a.book_author_id), book_cover = book_cover,
book_file = book_file, book_year = book_year, book_summary = book_summary, book_category_no = Category.objects.get(book_category_no = c.book_category_no),
is_bookmarked = 0, is_downloaded = 0, is_read = 0, is_deleted = 0)
form.save()
return HttpResponse('Book Saved!')
else:
print(form.errors)
return HttpResponse('Not Valid')
This is what my models.py looks like:
from django.db import models
from django.utils import timezone
class Category(models.Model):
# book_category_no = models.CharField(primary_key=True, max_length=50)
book_category_no = models.AutoField(primary_key=True)
book_category = models.CharField(max_length=100)
class Meta:
db_table = "Category"
class Books(models.Model):
# book_id = models.CharField(primary_key=True, max_length=50)
book_id = models.AutoField(primary_key=True)
book_title = models.CharField(max_length = 100)
book_author_id = models.ForeignKey(Author, on_delete=models.CASCADE)
book_cover = models.ImageField(upload_to='media/')
book_file = models.FileField(upload_to='media/')
book_year = models.DateField()
book_tags = models.CharField(max_length = 100)
book_summary = models.CharField(max_length = 100)
book_category_no = models.ForeignKey(Category, on_delete=models.CASCADE)
date_added = models.DateField(default=timezone.now)
# book_info = models.CharField(max_length = 100, default="")
is_bookmarked = models.BooleanField()
is_downloaded = models.BooleanField()
is_read = models.BooleanField()
is_deleted= models.BooleanField(default=False)
class Meta:
db_table = "Books"
Traceback
File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py" in dispatch
97. return handler(request, *args, **kwargs)
File "C:\ARMS\projectarms\arms\views.py" in post
315. form = CategoryForm(book_category= book_category)
Exception Type: TypeError at /arms/addbook/
Exception Value: init() got an unexpected keyword argument 'book_category'
`

Most certainly your Category or CategoryForm model is missing a field book_category which you use here:
category = Category.objects.filter(Q(book_category__icontains = book_category))

Related

TypeError returning Model entry

I'm creating an ebay style website that auctions off items. I have a form that takes in the values for the listing required by the model. The form renders well but when I submit the form I get the error:
<class 'TypeError'> views.py 80 ("l = Listing(title=title, description=description, url=url, user=user_id, category=category)")
forms.py
class NewListingForm(forms.Form):
title = forms.CharField(max_length=200)
description = forms.CharField(max_length=500)
url = forms.URLField()
bid = forms.DecimalField(decimal_places=2, max_digits=10)
category = forms.ModelChoiceField(queryset=Category.objects.all())
views.py
** added around line that's throwing the error
def newListing(request):
try:
if request.method == "POST":
newListingForm = NewListingForm(request.POST)
if newListingForm.is_valid():
title = newListingForm.cleaned_data['title']
description = newListingForm.cleaned_data['description']
url = newListingForm.cleaned_data['url']
bid = newListingForm.cleaned_data['bid']
category = newListingForm.cleaned_data['category']
current_user = request.user
user_id = current_user.id
**l = Listing(title=title, description=description, url=url, user=user_id, category=category)**
l.save()
b = Bid(price=bid, bid_count=0)
b.listing.add(l)
b.save()
return HttpResponseRedirect(reverse("index"))
else:
newListingForm = NewListingForm()
return render(request, "auctions/newListing.html", {
'form': newListingForm
})
except Exception as exc:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
newListingForm = NewListingForm()
return render(request, 'auctions/newListing.html', {
'form': newListingForm
})
models.py
class Listing(models.Model):
title = models.CharField(max_length=200)
description = models.CharField(max_length=500)
url = models.URLField()
user = models.ForeignKey('User', on_delete=models.CASCADE, name='author')
category = models.ForeignKey('Category', on_delete=models.CASCADE, name='category', default="")
def __str__(self):
return f'{self.id}: {self.title}'
class Bid(models.Model):
price = models.DecimalField(decimal_places=2, max_digits=10)
bid_count = models.IntegerField()
listing = models.ForeignKey('Listing', on_delete=models.CASCADE, name='listing', default="")
def __str__(self):
return f'{self.slug} ({self.price})'
User is a keyword, so I was getting an error from that.

Cannot make the views counter

I'm Trying to create a Views Counter in my django blog. Their are 3 apps in the project. The views counter on the writings app works fine but on the blog app it throws an error 'NoneType' object has no attribute 'views' and shows the error at post.views+=1. However the same code works in the writings app. I cannot find where the problem lies. Maybe the code is returning a empty set that's why it's not working but if so then why the code works when I remove just this views counter code?
Here are the code snippets for Blog and Writings app.
Blog app Views.py:-
post = Post.objects.filter(slug=slug).first()
post.views +=1
post.save()
tech = Tech.objects.filter(slug=slug).first()
tech.views +=1
tech.save()
pcomments = BlogComment.objects.filter(post=post,parent=None)
preplies = BlogComment.objects.filter(post=post).exclude(parent=None)
#Creating Reply Dictionary and iterating it
preplyDict = {}
for reply in preplies:
if reply.parent.sno not in preplyDict.keys():
preplyDict[reply.parent.sno] = [reply]
else:
preplyDict[reply.parent.sno].append(reply)
tcomments = BlogComment.objects.filter(tech=tech,parent=None)
treplies = BlogComment.objects.filter(tech=tech).exclude(parent=None)
#Creating Reply Dictionary and iterating it
treplyDict = {}
for reply in treplies:
if reply.parent.sno not in treplyDict.keys():
treplyDict[reply.parent.sno] = [reply]
else:
treplyDict[reply.parent.sno].append(reply)
context = {'post': post,'tech': tech,'pcomments':pcomments,'tcomments':tcomments,'preplyDict':preplyDict,'treplyDict':treplyDict}
return render(request,'blog/blogPost.html',context)
Writings views.py:-
def wPost(request,slug):
w = Writing.objects.filter(slug=slug).first()
w.views = w.views+1
w.save()
comments = WComment.objects.filter(wpost=w, parent=None)
replies = WComment.objects.filter(wpost=w).exclude(parent=None)
#Creating Reply Dictionary and iterating it
replyDict = {}
for reply in replies:
if reply.parent.sno not in replyDict.keys():
replyDict[reply.parent.sno] = [reply]
else:
replyDict[reply.parent.sno].append(reply)
context = {'writings': w,'comments': comments,'user' : request.user,'replyDict' : replyDict}
return render(request,'writings/wPost.html', context)
Blog Models.py:-
class Post(models.Model):
sno= models.AutoField(primary_key=True)
title = models.CharField(max_length=200)
content = models.TextField()
views = models.IntegerField(default=0)
category = models.CharField(max_length=13)
author = models.CharField(max_length=100)
slug = models.CharField(max_length=150,default=" ")
timeStamp = models.DateTimeField(blank=True)
img = models.ImageField(upload_to="blog/", blank=True)
img2 = models.ImageField(upload_to="blog/", blank=True)
img3 = models.ImageField(upload_to="blog/", blank=True)
img4 = models.ImageField(upload_to="blog/", blank=True)
img5 = models.ImageField(upload_to="blog/", blank=True)
img6 = models.ImageField(upload_to="blog/", blank=True)
def __str__(self):
return self.title + ' by ' + self.author
class Tech(models.Model):
sno= models.AutoField(primary_key=True)
title = models.CharField(max_length=200)
content = models.TextField()
views = models.IntegerField(default=0)
category = models.CharField(max_length=13)
author = models.CharField(max_length=100)
slug = models.CharField(max_length=150,default=" ")
timeStamp = models.DateTimeField(blank=True)
img = models.ImageField(upload_to="blog/", blank=True)
def __str__(self):
return self.title + ' by ' + self.author
Writing Models.py
class Writing(models.Model):
sno= models.AutoField(primary_key=True)
title = models.CharField(max_length=200)
content = models.TextField()
views = models.IntegerField(default=0)
category = models.CharField(max_length=13)
author = models.CharField(max_length=100)
slug = models.CharField(max_length=150,default=" ")
timeStamp = models.DateTimeField(blank=True)
img = models.ImageField(upload_to="writings/", blank=True)
def __str__(self):
return self.title + ' by ' + self.author
Blog admin.py:-
admin.site.register(BlogComment)
#Add this media to the post while registering it.
#admin.register(Post)
class PostAdmin(admin.ModelAdmin):
class Media:
js = ("tinyinject.js",)
#admin.register(Tech)
class TechAdmin(admin.ModelAdmin):
class Media:
js = ("tinyinject.js",)
Writings admin.py:-
admin.site.register(WComment)
#admin.register(Writing)
class WriteAdmin(admin.ModelAdmin):
class Media:
js = ("tinyinject.js",)
Error Starctrace:-
None
Internal Server Error: /blog/learning-python
Traceback (most recent call last):
File "/home/skyrunner/django_blog/mendlife/blogenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/skyrunner/django_blog/mendlife/blogenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/skyrunner/django_blog/mendlife/blogenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/skyrunner/django_blog/mendlife/blog/views.py", line 18, in blogPost
post.views+=1
AttributeError: 'NoneType' object has no attribute 'views'
So after wasting hours I realised i made a very silly mistake there. As I'm using two models I just simply had to use an If statement. so I added this and it worked as desired
if post is None:
tech.views +=1
tech.save()
else:
post.views+=1
post.save()
Thank you for everybody's comments and feedbacks!

Problem with saving multiple records in JSON file to MySQL using django-rest-framework

I'm newbie in django I'm trying to save JSON record using Dango-rest-framework, here is my JSON file.
{
"result":{
"lists":[
{
"resAccountBalance":"0",
"resWithdrawalAmt":"0",
"commStartDate":"20190124",
"commEndDate":"20190724",
"resTrHistoryList":[
{
"resAccountTrDate":"20190723",
"resAccountTrTime":"070609",
"resAccountOut":"132795",
"resAccountIn":"0",
"resAccountDesc1":"",
"resAccountDesc2":"BC",
"resAccountDesc3":"카드출금",
"resAccountDesc4":"",
"resAfterTranBalance":"0"
},
{
"resAccountTrDate":"20190722",
"resAccountTrTime":"071125",
"resAccountOut":"0",
"resAccountIn":"17",
"resAccountDesc1":"",
"resAccountDesc2":"이자",
"resAccountDesc3":"2019년결산",
"resAccountDesc4":"",
"resAfterTranBalance":"132795"
},
{
"resAccountTrDate":"20190515",
"resAccountTrTime":"031314",
"resAccountOut":"0",
"resAccountIn":"180000",
"resAccountDesc1":"",
"resAccountDesc2":"타행이체",
"resAccountDesc3":"지원금",
"resAccountDesc4":"",
"resAfterTranBalance":"626109"
}
]
}
]
}
}
I want to save 3 records in resTrHistoryList to MySQL, but only the following is saved:
record({
"resAccountTrDate":"20190515",
"resAccountTrTime":"031314",
"resAccountOut":"0",
"resAccountIn":"180000",
"resAccountDesc1":"",
"resAccountDesc2":"타행이체",
"resAccountDesc3":"지원금",
"resAccountDesc4":"",
"resAfterTranBalance":"626109"
})
Here is my code.
model.py
class QuickQuiryBankKDB(models.Model):
result = models.TextField()
resAccountTrDate = models.CharField(max_length=20, default='1000')
resAccountTrDate = models.CharField(max_length=20, default='1000')
resAccountTrTime = models.CharField(max_length=20, default='1000')
resAccountOut = models.CharField(max_length=20, default='1000')
resAccountIn = models.CharField(max_length=20, default='1000')
resAccountDesc1 = models.CharField(max_length=20, default='1000')
resAccountDesc2 = models.CharField(max_length=20, default='1000')
resAccountDesc3 = models.CharField(max_length=20, default='1000')
resAccountDesc4 = models.CharField(max_length=20, default='1000')
resAfterTranBalance = models.CharField(max_length=20, default='1000')
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
def __unicode__(self): # __str__ on Python 3
return self.QuickQuiryBankKDB
serializers.py
class QuickQuiryBankKDBSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
many = kwargs.pop('many', True)
super(QuickQuiryBankKDBSerializer, self).__init__(many=many, *args, **kwargs)
class Meta:
model = QuickQuiryBankKDB
# fields = '__all__'
fields = ['result']
views.py
class QuickQuiryBankKDBViewSet(viewsets.ModelViewSet):
queryset = QuickQuiryBankKDB.objects.all()
serializer_class = QuickQuiryBankKDBSerializer
def perform_create(self, serializer_class):
if (serializer_class.validated_data['result'][2:8] == 'result'):
json_text = serializer_class.validated_data['result']
json_unpacked = json.loads(json_text)
for i in json_unpacked['result']['lists'][0]['resTrHistoryList']:
resAccountTrDate = i['resAccountTrDate']
resAccountTrTime = i['resAccountTrTime']
resAccountOut = i['resAccountOut']
resAccountIn = i['resAccountIn']
resAccountDesc1 = i['resAccountDesc1']
resAccountDesc2 = i['resAccountDesc2']
resAccountDesc3 = i['resAccountDesc3']
resAccountDesc4 = i['resAccountDesc4']
resAfterTranBalance = i['resAfterTranBalance']
serializer_class.save(resAccountTrDate=resAccountTrDate, resAccountTrTime=resAccountTrTime, resAccountOut=resAccountOut, resAccountIn=resAccountIn,
resAccountDesc1=resAccountDesc1, resAccountDesc2=resAccountDesc2, resAccountDesc3=resAccountDesc3, resAccountDesc4=resAccountDesc4,
resAfterTranBalance=resAfterTranBalance)
Hope to have a hint to solve the problem. Thank you!
Based on tips from #cagrias, I revised views.py as follow.
class QuickQuiryBankKDBViewSet(viewsets.ModelViewSet):
queryset = QuickQuiryBankKDB.objects.all()
serializer_class = QuickQuiryBankKDBSerializer
def perform_create(self, serializer_class):
serializer_class = QuickQuiryBankKDBSerializer(data=self.request.data, many=True)
if serializer_class.is_valid():
if (serializer_class.validated_data['result'][2:8] == 'result'):
json_text = serializer_class.validated_data['result']
json_unpacked = json.loads(json_text)
for i in json_unpacked['result']['lists'][0]['resTrHistoryList']:
resAccountTrDate = i['resAccountTrDate']
resAccountTrTime = i['resAccountTrTime']
resAccountOut = i['resAccountOut']
resAccountIn = i['resAccountIn']
resAccountDesc1 = i['resAccountDesc1']
resAccountDesc2 = i['resAccountDesc2']
resAccountDesc3 = i['resAccountDesc3']
resAccountDesc4 = i['resAccountDesc4']
resAfterTranBalance = i['resAfterTranBalance']
print('1')
serializer_class.save(resAccountTrDate=resAccountTrDate, resAccountTrTime=resAccountTrTime, resAccountOut=resAccountOut, resAccountIn=resAccountIn,
resAccountDesc1=resAccountDesc1, resAccountDesc2=resAccountDesc2, resAccountDesc3=resAccountDesc3, resAccountDesc4=resAccountDesc4,
resAfterTranBalance=resAfterTranBalance)
but serializer_class.validated_data gives nothing but blank list [], while self.request.data gives full records of data what I want. Do you have any idea for this?
In order to be able to save multiple objects in one request you need to init your serializer with many=True command. You are extending ModelViewSet class in your view and create method is the place where your serializers are initiated. So you need to edit your views.py such as:
class QuickQuiryBankKDBViewSet(viewsets.ModelViewSet):
queryset = QuickQuiryBankKDB.objects.all()
serializer_class = QuickQuiryBankKDBSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data, many=True)
if (request.data['result'][2:8] == 'result'):
json_text = request.data['result']
json_unpacked = json.loads(json_text)
for i in json_unpacked['result']['lists'][0]['resTrHistoryList']:
resAccountTrDate = i['resAccountTrDate']
resAccountTrTime = i['resAccountTrTime']
resAccountOut = i['resAccountOut']
resAccountIn = i['resAccountIn']
resAccountDesc1 = i['resAccountDesc1']
resAccountDesc2 = i['resAccountDesc2']
resAccountDesc3 = i['resAccountDesc3']
resAccountDesc4 = i['resAccountDesc4']
resAfterTranBalance = i['resAfterTranBalance']
serializer.is_valid(raise_exception=True)
self.perform_create(serializer, resAccountTrDate=resAccountTrDate, resAccountTrTime=resAccountTrTime, resAccountOut=resAccountOut, resAccountIn=resAccountIn,
resAccountDesc1=resAccountDesc1, resAccountDesc2=resAccountDesc2, resAccountDesc3=resAccountDesc3, resAccountDesc4=resAccountDesc4,
resAfterTranBalance=resAfterTranBalance)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
else:
return Response("error", status=status.HTTP_500_INTERNAL_SERVER_ERROR, headers=headers)
def perform_create(self, serializer_class, **args):
serializer.save(args)

object is not iterable - Django Modelform

I'm using Model forms to add a row to a table in Django,
here are my views and forms file
views.py
def add_ad_mod(request):
current_user = request.user
current_ip = get_client_ip(request)
selected = Temp.objects.filter(created_by_ip=current_ip).order_by('-created_at')[0]
selected_category = selected.cat
selected_town = selected.town
if request.method == 'POST':
add_ad_mod_form = AddAdModForm(request.POST, request.FILES, cat=selected_category, loc=selected_town)
if add_ad_mod_form.is_valid():
model_instance = add_ad_mod_form.save(commit=False)
model_instance.created_by = current_user.email
model_instance.category = selected_category
model_instance.town=selected_town
if request.user.is_superuser:
model_instance.is_active = True
else:
model_instance.is_active = False
add_ad_mod_form.save()
return redirect('dashboard')
else:
add_ad_mod_form = AddAdModForm(cat=selected_category, loc=selected_town)
context = {
'add_ad_mod_form': add_ad_mod_form,
'selected_category': selected_category,
'selected_town': selected_town,
}
return render(request, 'add_ad_mod.html', context)
I am using views.py to send a variable as you see to the form itself
forms.py
class AddAdModForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
current_categ = kwargs.pop('cat')
current_loc = kwargs.pop('loc')
super(AddAdModForm, self).__init__(*args, **kwargs)
self.fields['sub_category'] = forms.ModelChoiceField(label="Sniffer", queryset=SubCate.objects.filter(main_category=current_categ))
self.fields['sub_location'] = forms.ModelMultipleChoiceField (widget=forms.CheckboxSelectMultiple,label="Sniffer", queryset=SubLoc.objects.filter(main_town=current_loc))
title = forms.CharField(
widget=forms.TextInput(
attrs={
'placeholder': 'Ad Title here',
'style': 'width: 100%; max-width: 800px;'
}
)
)
description = forms.CharField(
widget=forms.Textarea(
attrs={
'placeholder': 'Ad description is here',
'style': 'width: 100%; max-width: 800px;'
}
)
)
image = forms.ImageField(required=True)
image2 = forms.ImageField(required=False)
image3 = forms.ImageField(required=False)
image4 = forms.ImageField(required=False)
image5 = forms.ImageField(required=False)
address = forms.CharField(max_length=100,
widget=forms.Textarea(
attrs={
'placeholder': 'Detailed Address is here ',
'style': 'width: 100%; max-width: 800px;'
}
)
)
class Meta:
model = Item
fields = ['title', 'sub_category', 'price', 'description', 'sub_location', 'address', 'image', 'image2', 'image3', 'image4',
'image5', 'phone']
And here is my models.py file:
class Category(models.Model):
category_name = models.CharField(max_length=60)
def __str__(self):
return self.category_name
class Town(models.Model):
town_name = models.CharField(max_length=300)
def __str__(self):
return self.town_name
class SubCate(models.Model):
sub_category_name = models.CharField(max_length=100)
main_category = models.ForeignKey(Category, on_delete=CASCADE)
def __str__(self):
return self.sub_category_name
class SubLoc(models.Model):
sub_location_name = models.CharField(max_length=100)
main_town = models.ForeignKey(Town, on_delete=CASCADE)
def __str__(self):
return self.sub_location_name
class Item(models.Model):
category = models.ForeignKey(Category, on_delete=CASCADE)
sub_category = models.ManyToManyField(SubCate)
title = models.CharField(max_length=250)
description = models.TextField(max_length=1200)
price = models.IntegerField(default=0)
town = models.ForeignKey(Town, on_delete=CASCADE)
sub_location = models.ManyToManyField(SubLoc)
address = models.TextField(max_length=100)
image = models.ImageField(upload_to='media/', null=False, blank=False)
image2 = models.ImageField(upload_to='media/', null=True, blank=True)
image3 = models.ImageField(upload_to='media/', null=True, blank=True)
image4 = models.ImageField(upload_to='media/', null=True, blank=True)
image5 = models.ImageField(upload_to='media/', null=True, blank=True)
created_by = models.CharField(max_length=600)
created_at = models.DateField(auto_now=True)
phone = models.IntegerField(default=0)
is_active = models.BooleanField(default=False)
is_deleted = models.BooleanField(default=False)
def __str__(self):
return self.title
Despite the items is added to the database and if I reloaded my website I can see the item posted - it gives me the error instead of redirecting normally (The error is not in the page user redirected to after submitting, as I can browse into it normally )
Traceback:
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\lito\Desktop\DJ\JEHLUM - Copy - Copy\web_site\views.py" in add_ad_mod
219. add_ad_mod_form.save()
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py" in save
457. self._save_m2m()
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py" in _save_m2m
439. f.save_form_data(self.instance, cleaned_data[f.name])
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related.py" in save_form_data
1619. getattr(instance, self.attname).set(data)
File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related_descriptors.py" in set
947. objs = tuple(objs)
Exception Type: TypeError at /add_ad/mod/
Exception Value: 'SubCate' object is not iterable
As I mentioned in the comments, it looks like both of these fields should be multiple choice, since they are both representing ManyToManyFields in the model.
self.fields['sub_category'] = forms.ModelMultipleChoiceField(label="Sniffer", queryset=SubCate.objects.filter(main_category=current_categ))
self.fields['sub_location'] = forms.ModelMultipleChoiceField (widget=forms.CheckboxSelectMultiple,label="Sniffer", queryset=SubLoc.objects.filter(main_town=current_loc))
Also as mentioned, you need to call save on the model instance, and save_m2m on the form:
if add_ad_mod_form.is_valid():
model_instance = add_ad_mod_form.save(commit=False)
...
model_instance.save()
add_ad_mod_form.save_m2m()
return redirect('dashboard')

Django Sitemap -- 'str' object has no attribute 'get_absolute_url' Error

I'm getting the 'str' object has no attribute 'get_absolute_url' error on my django project on my sitemap page. Any help is appreciated.
Here is my traceback:
Traceback:
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\sitemaps\views.py" in inner
16. response = func(request, *args, **kwargs)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\sitemaps\views.py" in sitemap
71. protocol=req_protocol))
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\sitemaps\__init__.py" in get_urls
111. urls = self._urls(page, protocol, domain)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\sitemaps\__init__.py" in _urls
120. loc = "%s://%s%s" % (protocol, domain, self.__get('location', item))
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\sitemaps\__init__.py" in __get
68. return attr(obj)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\sitemaps\__init__.py" in location
75. return obj.get_absolute_url()
Exception Type: AttributeError at /sitemap.xml
Exception Value: 'str' object has no attribute 'get_absolute_url'
my sitemaps.py file
from django.contrib import sitemaps
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
from deals.models import Deal
from blog.models import Post
class StaticViewSitemap(sitemaps.Sitemap):
priority = 1.0
changefreq = 'daily'
def items(self):
return ['about', 'contact', 'disclosure', 'terms', 'privacy', 'deals:deals', 'blog:blog']
class BlogSitemap(Sitemap):
changfreq = "daily"
priority = 1.0
location ='/blog'
def items(self):
return Post.objects.filter(status='Published')
def lastmod(self, obj):
return obj.created
class DealSitemap(Sitemap):
changfreq = "daily"
priority = 1.0
def items(self):
return Deal.objects.all()
def lastmod(self, obj):
return obj.date_added
and my two relevant models (Deal and Post) where i created a get_absolute_url methods since it had been generating an error on the sitemap prior:
class Deal(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=140, unique=True)
description = RichTextUploadingField(default='')
retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE)
image = VersatileImageField('deal image',
upload_to=deal_upload_path,
null=True,
blank=True)
link = models.URLField(max_length=2000, default='')
category = models.ForeignKey(Category, on_delete=models.CASCADE)
date_added = models.DateField(default=timezone.now)
date_expires = models.DateField(default=timezone.now)
price = models.CharField(max_length=140)
secondary_price = models.CharField(max_length=140, default='')
likes_total = models.IntegerField(default=1)
expired = models.BooleanField(default=False)
def __str__(self):
return "#{} ({})".format(self.title, self.retailer)
def _get_unique_slug(self):
slug = slugify(self.title)
unique_slug = slug
num = 1
while Deal.objects.filter(slug=unique_slug).exists():
unique_slug = '{}-{}'.format(slug, num)
num += 1
return unique_slug
def save(self, *args, **kwargs):
if not self.slug:
self.slug = self._get_unique_slug()
super().save()
def get_label(self):
if self.date_added > datetime.date.today() - datetime.timedelta(days=4):
return "<span class='"'notify-badge'"'>new</span>"
else:
return ''
def get_absolute_url(self):
return reverse('deals:deal_detail', kwargs={'slug': self.slug})
class Post(models.Model):
STATUS_CHOICES = (
('Published', 'Published'),
('Draft', 'Draft'),
)
title = models.CharField(max_length=100, unique=True)
body = RichTextUploadingField()
category = models.ForeignKey(BlogCategory, on_delete=models.CASCADE)
seo_title = models.CharField(max_length=60, blank=True, null=True)
seo_description = models.CharField(max_length=165, blank=True, null=True)
slug = models.SlugField(max_length=200, unique=True)
image = VersatileImageField('blog image',
upload_to='media/blog_images',
null=True,
blank=True)
created = models.DateTimeField(db_index=True, auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, default='Draft', choices=STATUS_CHOICES)
def get_absolute_url(self):
return reverse('blog:blog_post', kwargs={'slug': self.slug})
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def __str__(self):
return self.title
and my urls.py file with relevant info
from django.contrib.sitemaps.views import sitemap
sitemaps = {
'static': StaticViewSitemap,
'blog': BlogSitemap,
'deals': DealSitemap
}
path('sitemap.xml', sitemap,
{'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap'),
You haven't followed the example properly for the StaticViewSitemap. As the docs say, the elements returned from items() are passed to the location() method; since the items would normally be model instances, the default implementation of this method is to call the get_absolute_url() method of each instance. In your case you are passing URL names, so you need to redefine location() appropriately - again as the example does.
def location(self, item):
return reverse(item)
It's the location() function who request for get_absolute_url() method : here. If you are absolutly sur that your string is already an absolute path you can simply override it in your class by:
def location(self, item) :
return item
This will return your already setup absolut path.

Categories

Resources