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.
Related
i have a form for update view like this:
class editpost(forms.ModelForm):
class Meta:
model = Posts
fields = ['body']
and a view like this:
#login_required
def post_edit(request, user_id, post_id):
if request.user.id == user_id:
post = get_object_or_404(Post, pk=post_id)
if request.method == 'POST':
form = editpost(request.POST, instance=post)
if form.is_valid():
ep = form.save(commit=False)
ep.slug = slugify(form.cleaned_data['body'][:30])
ep.save()
messages.success(request, 'your post edited successfully', 'success')
return redirect('account:dashboard', user_id)
else:
form = EditPostForm(instance=post)
return render(request, 'editpost.html', {'form':form})
else:
return redirect('Posts:index')
and url.py like this:
from django.urls import path
from . import views
app_name = 'Posts'
urlpatterns = [
path('', views.index.as_view(),name='index'),
path('<int:year>/<int:month>/<int:day>/<slug:slug>', views.detailPost,name='detail'),
path('addpost/<int:user_id>', views.addpost,name='addpost'),
path('delpost/<int:user_id>/<int:post_id>', views.delpost,name='delpost'),
path('editpost/<int:user_id>/<int:post_id>', views.editpost,name='editpost'),
]
when i open editpost url i got this error,what should i do to fix it?
The path for editpost should point to your view method: views.post_edit not views.editpost
path('editpost/<int:user_id>/<int:post_id>', views.post_edit, name='editpost'),
My question is when I use an UpdateView, it doesn't update the record. Besides this it also doesn't give any error.
When I debug code, the form_valid() function is not called after the HTTP POST request. But my form class (AdvertisementDetailForm) is correctly working. I couldn't find what I'm doing wrong.
Console outputs like that:
GET
/advertisement/publish/adv1_3ad5f56a-d99d-4ed4-b878-1327b9fa1bf8/1/
HTTP/1.1
POST
/advertisement/publish/adv1_3ad5f56a-d99d-4ed4-b878-1327b9fa1bf8/1/
HTTP/1.1
1st App views.py:
class PublishAdvertisement(LoginRequiredMixin, generic.UpdateView):
login_url = '/'
redirect_field_name = '/'
model = AdvSummary
form_class = AdvertisementDetailForm
template_name = 'advertisement/publish_advertisement.html'
success_url = reverse_lazy('brand:brand_home')
def form_valid(self, form):
pk = self.kwargs.get('pk')
obj = get_object_or_404(AdvSummary, pk=pk)
obj.advertisement_image = form.cleaned_data['advertisement_image']
obj.adv_max_follower = self.request.POST['adv_max_follower']
obj.adv_min_follower = self.request.POST['adv_min_follower']
obj.adv_desc = self.request.POST['adv_desc']
selected_categories = Category.objects.filter(pk__in=self.request.POST.getlist('categories'))
obj.categories.add(*[cat for cat in selected_categories])
obj.publish_date = timezone.now()
obj.save()
return super().form_valid(form)
urls.py:
urlpatterns = [
path('publish/<slug:slug_name>/<int:pk>/',
views.PublishAdvertisement.as_view(), name='publish'),
path('delete/<slug:slug_name>/<int:pk>/',
views.DeleteAdvertisement.as_view(), name='delete'),
]
2nd app views.py:
class BrandHomePage(LoginRequiredMixin, generic.View):
login_url = '/'
redirect_field_name = '/'
def post(self, request, *args, **kwargs):
view = CreateAdvertisement.as_view()
return view(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
view = PublishedAdvertisementList.as_view()
return view(request, *args, **kwargs)
urls.py:
urlpatterns = [
path('', views.BrandHomePage.as_view(), name='brand_home'),
]
Solution:
I've figured it out problem's reason when I added form_invalid() function just like that:
def form_invalid(self, form):
print("form is invalid")
return HttpResponse("form is invalid.. this is just an HttpResponse object")
And I've find out error in forms.py
Thank you
def form_valid(self, form):
pk = self.kwargs.get('pk')
obj = get_object_or_404(AdvSummary, pk=pk)
Check here that you are getting object or not.
I would redirect the user to "admin" page if he is superuser, else to normal "profile" but it didn't work
urls.py
url(r'^user/login/', LoginUserView.as_view(), name='login'),
url(r'^user/profile/', UpdateUserView.as_view(), name='profile'),
url(r'^user/admin/$', UpdateAdminView.as_view(), name='admin'),
views.py
class LoginUserView(auth_views.LoginView):
template_name = "Login/login.html"
#TODO
def dispatch(self, request, *args, **kwargs):
if self.request.user.is_superuser:
self.redirect_field_name = reverse_lazy("admin")
else:
self.redirect_field_name = reverse_lazy("profile")
return super(LoginUserView, self).dispatch(request, *args, **kwargs)
Setting redirect_field_name isn't going to work - it is the name of a parameter, by default 'next', not the url to redirect to.
If you want to the success url, you should override get_success_url.
class LoginUserView(auth_views.LoginView):
template_name = "Login/login.html"
def get_success_url(self):
url = self.get_redirect_url()
if url:
return url
elif self.request.user.is_superuser:
return reverse("admin")
else:
return reverse("profile")
The get_redirect_url() call at the beginning of the method means that the default behaviour that tries to use the redirect field will still work.
"e" is missing in:
self.redirect_field_name = reverse_lazy("profile")
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
I have this function in views.py:
def detel_kar(request, id):
detel = {}
detel['detels'] = DipPegawai.objects.filter(PegID=id)
detel['kels']=DipKeluargaPeg.objects.filter(PegID_id=id)
return render(request, 'karyawan/detel_kar.html', detel)
I then have a function to insert data with parameter id by getting a primary key from elsewhere.
def tambah_kel(request, id):
kar = DipPegawai.objects.get(PegID=id)
if request.method == "POST":
kel=DipKeluargaPeg(PegID=kar)
form = datakeluarga(request.POST,instance=kel)
if form.is_valid():
form.save(commit=True)
return redirect('detel_kar')
else:
form = datakeluarga()
return render(request, 'karyawan/tambah_kel.html', {'form': form, 'kars': kar})
How to redirect to detel_kar view? if i use this code in tambah_kel function
return redirect('detel_kar')
it will return anerror
Reverse for 'detel_kar' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
urls.py
from django.conf.urls import url
from . import views
urlpatterns=[
url(r'^$', views.index, name='index'),
url(r'^tambah/$', views.tambah, name='tambah_kar'),
url(r'^karyawan/detel_kar/(?P<id>\d+)/$',views.detel_kar, name='detel_karyawan'),
url(r'^karyawan/edit_kar/(?P<id>\d+)/$',views.edit_kar, name='edit_karyawan'),
url(r'^karyawan/del_kar/(?P<id>\d+)/$',views.del_kar, name='del_karyawan'),
url(r'^karyawan/tambah_kel/(?P<id>\d+)/$',views.tambah_kel, name='tambah_keluarga'),
]
In your urls.py, you have defined:
url(r'^karyawan/detel_kar/(?P<id>\d+)/$',views.detel_kar, name='detel_karyawan'),
i.e., the view that calls the function detel_kar() is named 'detel_karyawan'. This is the name you need to use in your redirect:
return redirect('detel_karyawan')
However the view expects an ID, so you must supply an ID when calling it:
return redirect('detel_karyawan', id=id)
(Where id is determined based on the logic in your view).