I am doing a tutorial regarding django and I have two errors:
When I try to create a plant that plant is saved in the data but I get this error:
Exception Type: DisallowedRedirect
Exception Value: Unsafe redirect to URL with protocol 'data'
when I try to edit then I get this error
Exception Type: NoReverseMatch
Exception Value: Reverse for 'plants' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Looking forward to find my mistake.
views.py:
def create_plant(request):
if not request.user.is_authenticated():
return render(request, 'data/login.html')
elif request.method == "POST":
form = PlantForm(request.POST)
if form.is_valid():
plant = form.save(commit=False)
plant.save()
return redirect('data:plants.html', slug = plant.slug)
else:
form=PlantForm()
template = 'data/create_plant.html'
context = {'form': form, }
return render(request, template, context)
def edit_plant(request, slug):
plant = get_object_or_404(Plant, slug=slug)
if request.method=="POST":
form = PlantForm(request.POST, instance=plant)
if form.is_valid():
plant = form.save(commit=False)
plant.save()
return redirect('data:plants')
else:
form = PlantForm(instance=plant)
template = 'data/create_plant.html'
context = {'form': form}
return render(request, template, context)
urls.py:
from django.conf.urls import url
from . import views
app_name = 'data'
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^plants/$', views.index, name='index'),
url(r'^create_plant/$', views.create_plant, name='create_plant'),
url(r'^logout_user/$', views.logout_user, name='logout_user'),
url(r'^login_user/$', views.login_user, name='login_user'),
url(r'^register/$', views.register, name='register'),
url(r'^plants/(?P<slug>[-\w]+)/$',views.detail, name='detail'),
url(r'^plants/(?P<slug>[-\w]+)/edit/$', views.edit_plant, name='edit_plant'),
url(r'^(?P<plant_id>[0-9]+)/delete_plant/$', views.delete_plant, name='delete_plant'),]
The problem was at return redirect('data:plants.html', slug = plant.slug) it should be return redirect('data:index') – George 3 hours ago
Related
Every time I attempt to write a comment on a post, I get an AttirbuteError at the post number. e.g- 'AttributeError at /post/54/', and below this it says 'type object 'Post' has no attribute 'filter''. It then directs me to my views.py line 58, which reads: post = self.get_object(Post). It is a part of my PostDetailClass:
class PostDetailView(DetailView):
model = Post
form = CommentForm
def post(self, request, *args, **kwargs):
form = CommentForm(request.POST)
if form.is_valid():
post = self.get_object(Post)
form.instance. user = request.user
form.instance.post = post
reply_id = request.POST.get('comment_id')
comment_qs = None
if reply_id:
comment_qs = Comment.objects.get(id=reply_id)
reply = comment_qs, reply=None
form.save()
form.save_m2m()
return redirect(reverse("post", kwargs={
'content': Post.content
}))
urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from django.urls.conf import re_path
from django.views.generic.base import RedirectView
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostDeleteView,
UserPostListView,
TagIndexView,
about,
)
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-
detail'),
path('user/<str:username>', UserPostListView.as_view(),
name='user-posts'),
path('post/new', PostCreateView.as_view(), name='post-create'),
path('about/', views.about, name='blog-about'),
path('map/', views.map, name='blog-map'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(),
name='post-delete'),
path('latest-posts/', views.latest_posts, name='latest-posts'),
path('focused/', views.focused, name='focused'),
path('snakegame/',views.snake_game, name='snake-game'),
re_path(r'^tag/(?P<slug>[-\w]*)/$',TagIndexView.as_view(),
name='tagged')
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Can anyone point out what is wrong with my code? Thank you.
The issue comes from passing Post to self.get_object(). get_object accepts a queryset as its argument. A queryset object would have .filter() but not Post.
In this case you actually don't need to pass anything to self.get_object. When you don't pass anything to it, the queryset defaults to self.get_queryset().
In short, change that line to:
post = self.get_object()
you should try to get the post object first like below :-
object_id = self.kwargs[self.pk_url_kwarg]
post = self.model.objects.get(id=object_id)
in your post method :-
def post(self, request, *args, **kwargs):
form = CommentForm(request.POST)
if form.is_valid():
object_id = self.kwargs[self.pk_url_kwarg]
post = self.model.objects.get(id=object_id)
form.instance.user = request.user
form.instance.post = post
reply_id = request.POST.get('comment_id')
comment_qs = None
if reply_id:
comment_qs = Comment.objects.get(id=reply_id)
reply = comment_qs, reply=None
form.save()
form.save_m2m()
return redirect(reverse("post", kwargs={
'content': post.content
}))
I am getting the above error when i tried to redirect from my UserAuth app to UserArea app.
It says 'NoReverseMatch at /index/'.
UserAuth/views.py
def loginUser(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# return render(request, 'home.html')
return redirect('nsUserArea:urlUserHome')
else:
messages.info(request, 'User name or password is incorrect')
return render(request, "Login.html")
USerAuth/urls.py
urlpatterns = [
path('', views.loginUser, name="urllogin"),
path('logout/', views.logoutUser, name="urllogout"),
path('register/', views.register, name="urlregister"),
path('home/', views.home, name="urlhome"),
]
UserArea/urls.py
urlpatterns = [
path('', views.IndexPage, name="urlUserHome"),
]
My main project urls.py file is this:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('UserAuth.urls', namespace="nsUserAuth")),
path('index/', include('UserArea.urls', namespace="nsUserArea")),
]
UserArea/views.py
def IndexPage(request):
return redirect(request, 'home.html')
home.html
<h1>Home</h1>
I was also getting the same problem that you are getting:
I modified my redirect to render.
Change
return redirect()
to
return render()
def IndexPage(request):
return redirect(request, 'home.html')
Try without request
def IndexPage(request):
return redirect('home.html')
I am unable to show purchasing template by writing URL "localhost:8000/purchasing" on browser. I am beginner here.
projectforms
urls.py
bookingform
urls.py
views.py
projectforms.urls
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import include, url
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('bookingform.urls')),
path('purchasing/', include('bookingform.urls')),
]
bookingform.urls
from django.urls import path
from . import views
urlpatterns = [
path('',views.add_model),
path(r'^purchasing/',views.purchasing_view,name="purchasing"),
]
This is the view. I have defined two functions in it.
bookingform.views
def add_model(request):
if request.method == "POST":
form = Form(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Booking Saved')
# return redirect('/')
return render(request, "template.html", {'form': form})
else:
form = Form()
# purchaing = purchasing.objects.all()
return render(request,"template.html",{'form': form})
def purchasing_view(request):
if request.method == "POST":
purchasing_form = purchasingform(request.POST)
if purchasing_form.is_valid():
purchasing_form.save()
messages.success(request, 'Purchaing Record Saved')
# return redirect('/')
return render(request, "purchasing.html", {'purchasing_form':
purchasing_form})
else:
purchasing_form = purchasing()
# purchaing = purchasing.objects.all()
return render(request, "purchaing.html", {'purchasing_form':
purchasing_form})
Let's assume that you want to have the following URL's
localhost:8000 -> which maps to the add_model
localhost:8000/purchasing -> which maps to the purchasing_view
For this in projectforms.urls you need:
from bookingform.views import add_model, purchasing_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', add_model),
path('purchasing', purchasing_view),
]
Either I'm getting a weird URL error in my project or I'm missing something.
I want to get the profile ID and show the informations in a template called "profile.html". Quite simple isn't it?
But I'm getting a NoReverseMatch error every time I call this "profile url".
My urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from sugar import views
urlpatterns = [
url(r'^area51/', admin.site.urls),
url(r'^search/', views.search, name="search"),
url(r'^terms/', views.terms, name="terms"),
url(r'^thanks/', views.thanks, name="thanks"),
url(r'^create_user/', views.create_user, name="create_user"),
url(r'^profile_edit/', views.profile_edit, name="profile_edit"),
url(r'^upload_photos/', views.photo_upload, name="photo_upload"),
url(r'^recover/', views.recover_account, name="recover"),
url(r'^login/', views.log_user_in, name="login"),
url(r'^logout/', views.log_user_out, name="logout"),
url(r'^register/', views.register, name="register"),
url(r'^profile/(?P<sugarid>\d+)/$', views.profile, name="profile"),
url(r'^payment/', views.payment, name="payment"),
url(r'^home', views.home, name="home"),
url(r'^paypal/', include('paypal.standard.ipn.urls')),
url(r'^$', views.home, name="home"),
]
My profile view:
def profile(request, sugarid):
if not request.user.is_authenticated():
return redirect("home")
variables = {}
exists = SugarUser.objects.filter(user_id=sugarid)
if exists:
user = SugarUser.objects.get(user_id=sugarid)
if not check_payment(user):
return redirect("payment")
midList = []
lastList = []
queryPhotos = UserPhoto.objects.filter(user_id=sugarid).order_by("-id")[:8]
featuredPhoto = queryPhotos.values().first()
midPhotos = queryPhotos[4:]
for mid in midPhotos:
midList.append(mid)
if len(midList) < 4:
result = 4 - len(midPhotos)
for r in range(result):
midList.append(None)
lastPhotos = queryPhotos[1:4]
for last in lastPhotos:
lastList.append(last)
if len(lastList) < 3:
result = 3 - len(lastPhotos)
for r in range(result):
lastList.append(None)
variables['name'] = user.name
variables['status'] = user.status
variables['description'] = user.description
variables['whatyouwant'] = user.whatyouwant
variables['state'] = user.state
variables['city'] = user.city
if featuredPhoto:
variables['featuredPhoto'] = featuredPhoto['photo']
else:
variables['featuredPhoto'] = None
variables['midPhotos'] = midList
variables['lastPhotos'] = lastList
variables['user'] = sugarid
return render(request, "profile.html", variables)
My login user redirection view:
def log_user_in(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return redirect("profile", kwargs={'sugarid': request.user.id})
I am getting this error ALWAYS:
django.core.urlresolvers.NoReverseMatch: Reverse for 'profile' with arguments '()' and keyword arguments '{'kwargs': {'sugarid': 24}}' not found. 1 pattern(s) tried: ['profile/(?P<sugarid>\\d+)/$']
I don't know what to do anymore, help :)
You should pass sugarid as a kwarg itself. This should work:
return redirect("profile", sugarid=request.user.id)
You can pass positional or keyword arguments as it is:
redirect("profile", sugarid=request.user.id)
Check the docs:
redirect in Django
I get the following error on a redirect call when using my admin site to process an image:
NoReverseMatch at /admin/restapi/checkuserimage/1
Reverse for 'pendinguserimages' with arguments '()' and keyword arguments '{}'
not found. 0 pattern(s) tried: []
In urls.py I have:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
...
]
And in admin.py:
class UserImageListPendingView(ListView):
model = UserImage
queryset = UserImage.objects.filter(status=ImageBase.PENDING)
template_name = 'userimage_list_pending.html'
context_object_name = 'userimage_list'
paginate_by = 5
#method_decorator(staff_member_required)
def dispatch(self, *args, **kwargs):
return super(UserImageListPendingView, self).dispatch(*args, **kwargs)
#staff_member_required
def userimage_check(request, pk):
context = RequestContext(request)
user_image = get_object_or_404(UserImage, pk=pk)
if request.method == 'POST':
proc_image(request, user_image, user_image.user, Count.USER_IMAGES)
return HttpResponseRedirect(reverse_lazy('pendinguserimages'))
else:
context_dict = {
'pk': pk,
'username': user_image.user.username,
'image_url': user_image.image.url
}
return render_to_response('userimage_check.html', context_dict, context)
def get_admin_urls(urls):
def get_urls():
return patterns('',
url(r'^restapi/pendinguserimages/?$',
UserImageListPendingView.as_view(), name='pendinguserimages'),
url(r'^restapi/checkuserimage/(?P<pk>[0-9]+)/?$',
userimage_check, name='checkuserimage'),
) + urls
return get_urls
admin.site.get_urls = get_admin_urls(admin.site.get_urls())
The error occurs on the reverse_lazy function. Something's not right!
Try including the admin namespace when you reverse the URL.
return HttpResponseRedirect(reverse('admin:pendinguserimages'))
You shouldn't have to use reverse_lazy inside a view function, reverse should work.