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!
Related
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.
I am creating a quiz application using a guide. My application works perfectly fine in development with both sqlite3 and postgresql databases. But when pushed to production, I am faced with errors using a postgresql database. So I tried using my development sqlite3 database in production to test things out. My sqlite3 database works fine in production, but postgresql does not work in production. Initially, I thought the error is on the views level, but now I am seeing the error coming from the postgresql. Could be errors in my views or models schema. I really can't tell. The corresponding error I get when using a postgresql database in production using a linux server with gunicorn and nginx is here below, and the whole models design and views are here below too. Thanks, I appreciate your time in giving me a suitable answer to my question.
models.py
from django.db import models
import random
from account.models import Profile
from django.urls import reverse
import datetime
from django.utils import timezone
from ckeditor_uploader.fields import RichTextUploadingField
class PublishedBookManager(models.Manager):
def get_queryset(self):
return super(PublishedBookManager, self).get_queryset().filter(publish_book=True)
class Book(models.Model):
name = models.CharField(max_length=120)
description = models.TextField()
created_by = models.ForeignKey(Profile, default=1, null=True, on_delete=models.SET_NULL)
number_of_questions = models.IntegerField()
number_of_sections = models.IntegerField()
time = models.IntegerField(help_text="duration of the quiz in minutes")
required_score_to_pass = models.IntegerField(help_text="required score in %")
start_date = models.DateTimeField(default=timezone.now)
publish_book = models.BooleanField(default=False)
date_created = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)
objects = models.Manager()
published = PublishedBookManager()
def __str__(self):
return f"{self.name}"
def get_absolute_url(self):
return reverse('quiz:book-detail-view', args=[self.pk])
class PublishedQuizManager(models.Manager):
def get_queryset(self):
return super(PublishedQuizManager, self).get_queryset().filter(publish_quiz=True)
class Quiz(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE, blank=True, null=True)
name = models.CharField(max_length=120)
description = models.TextField()
created_by = models.ForeignKey(Profile, default=1, null=True, on_delete=models.SET_NULL)
number_of_questions = models.IntegerField()
time = models.IntegerField(help_text="duration of the quiz in minutes")
required_score_to_pass = models.IntegerField(help_text="required score in %")
completed_users = models.ManyToManyField(Profile, blank=True, related_name='completed_users_quiz')
publish_quiz = models.BooleanField(default=False)
start_date = models.DateTimeField(default=timezone.now)
deadline_date = models.DateTimeField(default=timezone.now)
date_created = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)
objects = models.Manager()
published = PublishedQuizManager()
def __str__(self):
return f"{self.book.name} = {self.name}"
def get_questions(self):
questions = list(self.question_set.all())
random.shuffle(questions)
return questions[:self.number_of_questions]
class Meta:
verbose_name_plural = 'Quizes'
def get_absolute_url(self):
return reverse('quiz:quiz-view', kwargs={'book_pk': self.book.pk, "pk": self.pk})
class Question(models.Model):
# text = models.TextField()
text = RichTextUploadingField(unique=True)
second_text = models.TextField()
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.text)
def get_answers(self):
return self.answer_set.all()
# def get_absolute_url(self):
# return reverse('quiz:quiz-view', kwargs={'question_pk': self.pk,})
class Answer(models.Model):
text = models.CharField(max_length=255)
correct = models.BooleanField(default=False)
question = models.ForeignKey(Question, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"question: {self.question.text}, answer: {self.text}, correct: {self.correct}"
class Result(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
user = models.ForeignKey(Profile, on_delete=models.CASCADE)
score = models.FloatField()
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.pk)
views.py
def save_quiz_view(request, pk, book_pk):
# if request.user in
quiz = Quiz.objects.get(pk=pk)
# Submition of result only occurs if a user is not in the completed users field. If they are already
# in the completed users ManyToMany field, then it won't save. But if not, it will save.
if request.is_ajax() and not request.user.profile in quiz.completed_users.all():
questions = []
data = request.POST
data_ = dict(data.lists())
data_.pop('csrfmiddlewaretoken')
for _k in data_.keys():
if Question.objects.all():
# print('key: ', k)
k = _k
question = Question.objects.get(text=k)
questions.append(question)
user = request.user.profile
quiz = Quiz.objects.get(pk=pk)
if request.user.is_authenticated:
if not user in quiz.completed_users.all():
quiz.completed_users.add(user)
score = 0
multiplier = 100 / quiz.number_of_questions
results = []
correct_answer = None
for q in questions:
a_selected = request.POST.get(q.text)
if a_selected != "":
question_answers = Answer.objects.filter(question=q)
for a in question_answers:
if a_selected == a.text:
if a.correct:
score += 1
correct_answer = a.text
else:
if a.correct:
correct_answer = a.text
results.append({str(q): {'correct_answer': correct_answer, 'answered': a_selected}})
else:
results.append({str(q): 'not answered'})
score_ = score #* multiplier
Result.objects.create(quiz=quiz, user=user, score=score_)
if score_:#>= quiz.required_score_to_pass:
return JsonResponse({'passed': True, 'score': score_, 'results': results})
else:
return JsonResponse({'passed': False, 'score': score_, 'results': results})
Error
django#UniqueAsf2:~/src$ python3 manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
October 26, 2021 - 03:57:12
Django version 3.2.8, using settings 'asf.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
[26/Oct/2021 03:57:18] "GET /quiz/1/1/ HTTP/1.1" 200 8065
Not Found: /quiz/1/1/assets/vendors/boxicons/css/boxicons.min.css
[26/Oct/2021 03:57:18] "GET /quiz/1/1/assets/vendors/boxicons/css/boxicons.min.css HTTP/1.1" 404 5612
[26/Oct/2021 03:57:18] "GET /quiz/1/1/data/ HTTP/1.1" 200 101
Internal Server Error: /quiz/1/1/save/
Traceback (most recent call last):
File "/home/django/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/django/.local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/django/src/quiz/views.py", line 108, in save_quiz_view
question = Question.objects.get(text=_k)
File "/home/django/.local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/django/.local/lib/python3.9/site-packages/django/db/models/query.py", line 435, in get
raise self.model.DoesNotExist(
quiz.models.Question.DoesNotExist: Question matching query does not exist.
Your data in Question is not stored in simple text because you are using RichTextUploadingField which converts text into HTML format for handling text fomatting. Because of this you can't directly compare two strings or run search over it.
Try using icontains for checking string in your field. This might not work in all cases so you'll have to handle that accordingly.
questions = Question.objects.filter(text__icontains=k)
for question in questions:
# Handle questions here
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))
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')
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.