Django get_absolute_url on sitemap.xml getting NoReverMatch error - django

models.py
def get_absolute_url(self):
return reverse('abc', kwargs={'slug': self.slug})
urls.py
from posts.views import xyz
from posts.sitemaps import PostSitemap
sitemaps = {
'posts': PostSitemap()
}
urlpatterns = patterns(
url(r'^posts/(?P<slug>[\w-]+)/$',xyz, name='abc'),
url(r'^sitemap\.xml$',sitemap, {'sitemaps': sitemaps}),
)
sitemaps.py
class PostSitemap(Sitemap):
changefreq = 'daily'
pirority = 0.5
def items(self):
return Post.objects.all()
I have not changed the default contib/sitemaps/templates/sitemap.xml and when I browse mysite/sitemap.xml it's throwing error:
Reverse for 'abc' with arguments '()' and keyword arguments '{'slug': u'my-slug-goes-here'}' not found. 0 pattern(s) tried: []

class PostSitemap(Sitemap):
changefreq = 'daily'
pirority = 0.5
def items(self):
return Post.objects.all()
def location(self, item):
return item.get_absolute_url()

Related

The current path, index.php, didn’t match any of these

**
Good day, please am new to Django and am facing some challenges
which have tried to resolve but am not yet resolve please i need
your help.
**
the error are below
Page not found (404)
Request Method: GET
Request URL: https://mydomain/pages/index.php**
Using the URLconf defined in dcitygate.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
blog/ [name='blog']
audio_messages/ [name='audio_messages']
imgc/ [name='imgc']
imgc/<int:id> [name='imgc_detail']
tsc/ [name='tsc']
tsc/<int:id> [name='tsc_detail']
word_prayer/ [name='word_prayer']
word_prayer/<int:id> [name='word_prayer_detail']
video_messages/ [name='video_messages']
contact_us/ [name='contact_us']
couple_meeting/ [name='couple_meeting']
kcc/ [name='kcc']
kcc/<int:id> [name='kcc_detail']
pages/streaming/ [name='streaming']
watchlive/ [name='watchlive']
<int:id> [name='audio_streaming_detail']
listenlive/ [name='listenlive']
blogs/
audio_msg/
^media/(?P<path>.*)$'''
*The current path, index.php, didn’t match any of these*
my Project.url
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from django.conf.urls import url
urlpatterns = [
path('admin/',admin.site.urls),
path('', include('pages.urls')),
path('blogs/', include('blogs.urls')),
path('audio_msg/', include('audio_msg.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MyApp.url
from django.urls import path, re_path
from django.conf.urls import url
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('blog/',views.blog, name='blog'),
path('audio_messages/', views.audio_messages, name='audio_messages'),
path('imgc/', views.imgc, name='imgc'),
path('imgc/<int:id>', views.imgc_detail, name='imgc_detail'),
path('tsc/', views.tsc, name='tsc'),
path('tsc/<int:id>', views.tsc_detail, name='tsc_detail'),
path('word_prayer/', views.word_prayer, name='word_prayer'),
path('word_prayer/<int:id>', views.word_prayer_detail, name='word_prayer_detail'),
path('video_messages/', views.video_messages, name='video_messages'),
path('contact_us/', views.contact_us, name='contact_us'),
path('couple_meeting/', views.couple_meeting, name='couple_meeting'),
path('kcc/', views.kcc, name='kcc'),
path('kcc/<int:id>', views.kcc_detail, name='kcc_detail'),
path('pages/streaming/', views.streaming, name='streaming'),
path('watchlive/', views.watchlive, name='watchlive'),
path('<int:id>', views.audio_streaming_detail, name='audio_streaming_detail'),
path('listenlive/', views.listenlive, name='listenlive'),
]
my view
from django.shortcuts import render, get_object_or_404
from blogs.models import Blog
from audio_msg.models import Audio_msg
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
# Create your views here.
def index(request):
blog_data = Blog.objects.order_by('-created_date')
audio_data = Audio_msg.objects.order_by('-created_date')
data = {
'blog_data': blog_data,
'audio_data': audio_data,
}
return render(request, 'pages/home.html', data)
def blog(request):
return render(request, 'pages/blog.html')
def audio_messages(request):
return render(request, 'pages/audio_messages.html')
def imgc(request):
blog_data = Blog.objects.order_by('-created_date').filter(category='IMGC')
paginator = Paginator(blog_data, 9)
page = request.GET.get('page')
paged_blog = paginator.get_page(page)
data = {
'blog_data': paged_blog,
}
return render(request, 'pages/imgc.html', data)
def imgc_detail(request, id):
blog_detail = get_object_or_404(Blog, pk=id)
data = {
'blog_detail': blog_detail,
}
return render(request, 'pages/imgc_detail.html', data)
def tsc(request):
blog_data = Blog.objects.order_by('-created_date').filter(category='TSC')
paginator = Paginator(blog_data, 9)
page = request.GET.get('page')
paged_blog = paginator.get_page(page)
data = {
'blog_data': paged_blog,
}
return render(request, 'pages/tsc.html', data)
def tsc_detail(request, id):
blog_detail = get_object_or_404(Blog, pk=id)
data = {
'blog_detail': blog_detail,
}
return render(request, 'pages/tsc_detail.html', data)
def word_prayer(request):
blog_data = Blog.objects.order_by('-created_date').filter(category='WAP')
paginator = Paginator(blog_data, 9)
page = request.GET.get('page')
paged_blog = paginator.get_page(page)
data = {
'blog_data': paged_blog,
}
return render(request, 'pages/word_prayer.html', data)
def word_prayer_detail(request, id):
blog_detail = get_object_or_404(Blog, pk=id)
data = {
'blog_detail': blog_detail,
}
return render(request, 'pages/word_prayer_detail.html', data)
def video_messages(request):
return render(request, 'pages/video_messages.html')
def audio_messages(request):
return render(request, 'pages/audio_messages.html')
def contact_us(request):
return render(request, 'pages/contact_us.html')
def couple_meeting(request):
return render(request, 'pages/couple_meeting.html')
def kcc(request):
blog_data = Blog.objects.order_by('-created_date').filter(category='KCC')
data = {
'blog_data': blog_data,
}
return render(request, 'pages/kcc.html', data)
def kcc_detail(request, id):
blog_detail = get_object_or_404(Blog, pk=id)
data = {
'blog_detail': blog_detail,
}
return render(request, 'pages/kcc_detail.html', data)
def streaming(request):
return render(request, 'pages/streaming.html')
def watchlive(request):
return render(request, 'pages/watchlive.html')
def listenlive(request):
return render(request, 'pages/listenlive.html')
def audio_msg(request):
audio_data = Audio_msg.objects.order_by('-created_date')
data = {
'audio_data': audio_data,
}
return render(request, 'pages/audio_msg.html', data)
def audio_streaming_detail(request, id):
audio_data = get_object_or_404(Audio_msg, pk=id)
data = {
'audio_data': audio_data,
}
**return render(request, 'pages/audio_streaming_detail.html', data)
please help**
I don't see any pages/index.php anywhere, and you shouldn't use .php on Django projects, it's not PHP
If you're trying to get to: path('', views.index, name='index') just try http://127.0.0.1:8000/
If you are trying to get to another view, what view?- ti should be in a urls.py
Thank you for this platform and everyone that have contributed to this question.
my solution to the problem was removing the default redirect code in .htaccess and use this code below.
# DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN
PassengerAppRoot "/home2/thecity2/church-project"
PassengerBaseURI "/"
PassengerPython "/home2/thecity2/virtualenv/church-project/3.9/bin/python"
# DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END
# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN
<IfModule Litespeed>
</IfModule>
# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION END

Reverse for 'new-quiz' with arguments '(11, '')' not found. 1 pattern(s) tried: ['course/(?P<course_id>[^/]+)/(?P<module_id>[^/]+)/quiz/newquiz$']

here is my code views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden
from quiz.forms import NewQuizForm, NewQuestionForm
from quiz.models import Answer, Question, Quizzes, Attempter, Attempt
from courses.models import Module
from completion.models import Completion
# Create your views here.
def NewQuiz(request, course_id, module_id):
user = request.user
module = get_object_or_404(Module, id=module_id)
if request.method == 'POST':
form = NewQuizForm(request.POST)
if form.is_valid():
title = form.cleaned_data.get('title')
description = form.cleaned_data.get('description')
due = form.cleaned_data.get('due')
allowed_attempts = form.cleaned_data.get('allowed_attempts')
time_limit_mins = form.cleaned_data.get('time_limit_mins')
quiz = Quizzes.objects.create(user=user, title=title, description=description, due=due, allowed_attempts=allowed_attempts, time_limit_mins=time_limit_mins)
module.quizzes.add(quiz)
module.save()
return redirect('new-question', course_id=course_id, module_id=module_id, quiz_id=quiz.id)
else:
form = NewQuizForm()
context = {
'form': form,
}
return render(request, 'quiz/newquiz.html', context)
def NewQuestion(request, course_id, module_id, quiz_id):
user = request.user
quiz = get_object_or_404(Quizzes, id=quiz_id)
if request.method == 'POST':
form = NewQuestionForm(request.POST)
if form.is_valid():
question_text = form.cleaned_data.get('question_text')
points = form.cleaned_data.get('points')
answer_text = request.POST.getlist('answer_text')
is_correct = request.POST.getlist('is_correct')
question = Question.objects.create(question_text=question_text, user=user, points=points)
for a, c in zip(answer_text, is_correct):
answer = Answer.objects.create(answer_text=a, is_correct=c, user=user)
question.answers.add(answer)
question.save()
quiz.questions.add(question)
quiz.save()
return redirect('new-question', course_id=course_id, module_id=module_id, quiz_id=quiz.id)
else:
form = NewQuestionForm()
context = {
'form': form,
}
return render(request, 'quiz/newquestion.html', context)
def QuizDetail(request, course_id, module_id, quiz_id):
user = request.user
quiz = get_object_or_404(Quizzes, id=quiz_id)
my_attempts = Attempter.objects.filter(quiz=quiz, user=user)
context = {
'quiz': quiz,
'my_attempts': my_attempts,
'course_id': course_id,
'module_id': module_id,
}
return render(request, 'quiz/quizdetail.html', context)
and quiz/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('<course_id>/<module_id>/quiz/newquiz', views.NewQuiz, name='new-quiz'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/newquestion', views.NewQuestion, name='new-question'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/', views.QuizDetail, name='quiz-detail'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/take', views.TakeQuiz, name='take-quiz'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/take/submit', views.SubmitAttempt, name='submit-quiz'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/<attempt_id>/results', views.AttemptDetail, name='attempt-detail'),
]
and template
<i class="material-icons"></i>Add new quiz
in the project urls.py
path('quiz/',include('quiz.urls')),
it says like this "Reverse for 'new-quiz' with arguments '(11, '')' not found. 1 pattern(s) tried: ['course/(?P<course_id>[^/]+)/(?P<module_id>[^/]+)/quiz/newquiz$']"which means it detect the first argument but not the others why???
Use single quotes in your template, so 'new-quiz' instead of "new-quiz":
<i class="material-icons"></i>Add new quiz

'Tribe' object has no attribute 'tribe_id'

I have a view which should redirect the user to the new tribe that he created. but I don't know how to get the tribe_id for it to work.
views.py
def tribeview(request, tribe_id):
tribe = get_object_or_404(Tribe,pk=tribe_id)
playlist = tribe.playlist_set.all()
context = { 'tribe': tribe, 'playlists':playlist }
return render(request, 'app/tribe.html', context)
class create_tribe(CreateView):
model = Tribe
form_class = TribeForm
template_name = 'app/create_tribe.html'
def form_valid(self, form):
tribe = form.save(commit=False)
tribe.chieftain = self.request.user
tribe.save()
return super().form_valid(form)
def get_success_url(self):
return reverse('app:tribe-view', args={'tribe': self.object.tribe_id})
urls.py
app_name = 'app'
urlpatterns = [
path('', views.index, name='index'),
path('tribe/<int:tribe_id>',views.tribeview,name='tribe-view'),
path('tribe/<int:tribe_id>/playlist/<int:playlist_id>',views.playlistview,name='playlist-view'),
path('new_tribe', login_required(create_tribe.as_view()), name="new-tribe"),
]
models.py
class Tribe(TimeStamped):
name = models.CharField(max_length=200,unique=True)
chieftain = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
tribe_members = models.ManyToManyField(Member)
def __str__(self):
return self.name[:80]

Why doesn't enter to the get method?

The function does not even enter the get method.
urls.py
from django.conf.urls import url
from django.contrib.auth.views import (
password_reset_done,
password_reset_complete,
PasswordResetDoneView,
PasswordResetConfirmView,
PasswordResetCompleteView
)
from django.views.generic import TemplateView
from registration.backends.model_activation.views import ActivationView
from .views import (
login, logout, password_reset_confirm,
auth_pass_email,
ProfileEditMain,
ProfileEditContacts,
ProfileEditInterests,
ProfileEditEducation,
ProfileEditCareer,
ProfileEditLifepos,
ProfileEditCompetencies,
PurseTransactionWeekListView,
AvatarUpdate,
People,
PopupSearchView, PopupSearchRefereeView,
registration, identification_view,
ReferralTop,
ProfileSettingsMainView,
profile_settings_notification_view,
PasswordResetView,
ReferralChart,
resend_activation_email
)
from communication.views import poll_choice_confirm
urlpatterns = [
url(r'^login/$', login, name='login'),
url(r'^login/success/$', login, name='login'),
url(r'^logout/$', logout, name='logout'),
url(r'^password-reset/$',
PasswordResetView.as_view(),
name='password_reset'),
url(r'^password-reset/done/$',
PasswordResetDoneView.as_view(),
name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$',
PasswordResetConfirmView.as_view(),
name='password_reset_confirm'),
url(r'^reset/done/$',
PasswordResetCompleteView.as_view(),
name='password_reset_complete'),
url(r'^pass/email/$', auth_pass_email,
name='auth_pass_email'),
url(r'^profile/edit/main/$',
ProfileEditMain.as_view(),
name='profile_edit_main'),
url(r'^profile/edit/contacts/$',
ProfileEditContacts.as_view(),
name='profile_edit_contacts'),
url(r'^profile/edit/interests/$',
ProfileEditInterests.as_view(),
name='profile_edit_interests'),
url(r'^profile/edit/education/$',
ProfileEditEducation.as_view(),
name='profile_edit_education'),
url(r'^profile/edit/career/$',
ProfileEditCareer.as_view(),
name='profile_edit_career'),
url(r'^profile/edit/position/$',
ProfileEditLifepos.as_view(),
name='profile_edit_life_position'),
url(r'^profile/edit/competencies/$',
ProfileEditCompetencies.as_view(),
name='profile_edit_competencies'),
url(r'^profile/settings/main/$',
ProfileSettingsMainView.as_view(),
name='profile_settings_main'),
url(r'^profile/settings/notification/$',
profile_settings_notification_view,
name='profile_settings_notification'),
url(r'^purse/(?P<period>week|month|year)/$',
PurseTransactionWeekListView.as_view(),
name='profile_purse'),
url(r'^referral/top/(?P<period>month|all)/$',
ReferralTop.as_view(),
name='referral_top'),
url(r'^referral/chart/(?P<period>month)/$',
ReferralChart.as_view(),
name='referral_chart'),
url(r'^profile/edit/avatar/$', AvatarUpdate.as_view(),
name='profile_edit_avatar'),
url(r'^people/$', People.as_view(),
name='people'),
url(r'^people/popup/$', PopupSearchView.as_view(),
name='people_popup'),
url(r'^people/popup_referee/$', PopupSearchRefereeView.as_view(),
name='people_popup_referee'),
url(r'^registration/$', registration,
name='registration'),
url(r'^registration/complete/$',
TemplateView.as_view(
template_name='registration/registration_complete.html'
),
name='registration_complete'),
url(r'^activate/(?P<activation_key>\w+)/$',
ActivationView.as_view(),
name='registration_activate'),
url(r'^activate/complete/$',
TemplateView.as_view(
template_name='registration/activation_complete.html'
),
name='registration_activation_complete'),
url(r'^identification/$',
identification_view,
name='identification_view'),
url(r'^poll_choice/$', poll_choice_confirm, name='poll_choice'),
url(r'^resend_activation_email/$', resend_activation_email, name='resend_activation_email'),
]
views.py
class ActivationView(TemplateView):
success_url = 'registration_activation_complete'
template_name = 'registration/activate.html'
def get(self, *args, **kwargs):
activated_user = self.activate(*args, **kwargs)
activated_user.email_approval_status = 'done'
activated_user.email_success = True
activated_user.save(update_fields=['email_success', 'email_approval_status', 'user_status'])
activated_user.email_success = False
activated_user.save(update_fields=['email_success'])
if activated_user:
signals.user_activated.send(
sender=self.__class__,
user=activated_user,
request=self.request
)
success_url = self.get_success_url(activated_user) if \
(hasattr(self, 'get_success_url') and
callable(self.success_url)) else \
self.success_url
try:
to, args, kwargs = success_url
return redirect(to, *args, **kwargs)
except ValueError:
return redirect(success_url)
return super(ActivationView, self).get(*args, **kwargs)
def activate(self, *args, **kwargs):
activation_key = kwargs.get('activation_key')
activated_user = RegistrationProfile.objects.activate_user(
activation_key
)
user_registration_log = UserRegistration.objects.get(user=activated_user)
parent = user_registration_log.get_parent()
ref_log = LogReferral.objects.get_or_create(
user=parent, enabled=True, created_at__date=now()
)
ref_log.count_reg += 1
ref_log.save(update_fields=['count_reg'])
activated_user.email_approval_status='done'
activated_user.save(update_fields=['email_approval_status'])
email_confirmed_status = Status.objects.filter(verification_done=False, identification_done=False, referred=False, email_confirmed=True).last()
visitor_status = Status.objects.filter(verification_done=False, identification_done=True, referred=False, email_confirmed=False).last()
if not activated_user.user_status or activated_user.user_status == visitor_status:
activated_user.user_status = email_confirmed_status
activated_user.save(update_fields=['user_status'])
return activated_user
You've imported the original ActivationView (from registration.backends.model_activation) rather than your version.

Django sitemap for static pages

I'm in the progress of creating a sitemap for my new site.
the site only contains static pages.
I'm trying to get this snippet working:
class StaticSitemap(sitemaps.Sitemap):
"""Return the static sitemap items"""
priority = 0.5
def __init__(self, patterns):
self.patterns = patterns
self._items = {}
self._initialize()
def _initialize(self):
for p in self.patterns:
if getattr(p, 'name', None) is not None:
print p.name
self._items[p.name] = self._get_modification_date(p)
def _get_modification_date(self, p):
template = getattr(p, 'template', None)
template_path = self._get_template_path(template)
mtime = os.stat(template_path).st_mtime
return datetime.datetime.fromtimestamp(mtime)
def _get_template_path(self, template_path):
for template_dir in settings.TEMPLATE_DIRS:
path = os.path.join(template_dir, template_path)
if os.path.exists(path):
return path
return None
def items(self):
return self._items.keys()
def changefreq(self, obj):
return 'monthly'
def lastmod(self, obj):
return self._items[obj]
def location(self, obj):
return reverse(obj)
and I'm getting this KeyError on template from this line: template = p.default_args['template']
How can I get template name?
got it working.
Just added template to kwargs of each url