NoReverseMatch at django - python

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

Related

Django: Reverse for '<WSGIRequest: GET '/index/'>' not found. '<WSGIRequest: GET '/index/'>' is not a valid view function or pattern name

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')

DisallowedRedirect Django

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

Django web app error. Login_check() takes exactly 1 argument

So this is the view :
def login_check(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request,user)
return render(request,'authen/match.html')
else:
return render(request,'authen/notmatch_2.html')
else:
return render(request,'authen/notmatch.html')
This is what should happen when I press the login button but it says that login_check() takes exactly 1 argument.
urls.py :
urlpatterns = [
url(r'^login/', views.login, name='login'),
url(r'^register/', views.register, name='register'),
url(r'^registered/', views.registered, name='registered'),
url(r'^check/', views.login_check(), name='login_check'),
]
and the template is something really basic it has just one tag with the text "You are registered"
i believe you should not call login_check() in the urls.py
try this
url(r'^check/', views.login_check, name='login_check')

Couldn't load admin interface due the error below

I've got following code and got two issues.
1. I couldn't get joins added up and not showing up on the page.
2. Admin interface is not loading.
I've re-created the DB checked the code thoroughly and really need help.
Views.py.
from django.conf import settings
from django.shortcuts import render, HttpResponseRedirect, Http404
from.models import Join
from .forms import EmailForm, JoinForm
def get_ip(request):
try:
x_forwarded = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded:
ip = x_forwarded.split(",")[0]
else:
ip = request.META.get("REMOTE_ADDR")
except:
ip = ""
return ip
import uuid
def get_ref_id():
ref_id = str(uuid.uuid4())[:11].replace('-', '').lower()
try:
id_exists = Join.objects.get(ref_id=ref_id)
get_ref_id()
except:
return ref_id
def home(request):
try:
join_id = request.session['join_id_ref']
obj = Join.objects.get(id=join_id)
except:
obj = None
form = JoinForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit=False)
email = form.cleaned_data['email']
new_join_old, created = Join.objects.get_or_create(email=email)
if created:
new_join_old.ref_id = get_ref_id()
if not obj == None:
new_join_old.friend = obj
new_join_old.ip_address = get_ip(request)
new_join_old.save()
return HttpResponseRedirect("/%s" %(new_join_old.ref_id))
context = {"form": form}
template = 'home.html'
return render(request, template, context)
def share(request, ref_id):
#try:
join_obj = Join.objects.get(ref_id=ref_id)
friends_referred = Join.objects.filter(friend=join_obj)
count = join_obj.referral.all().count()
ref_url = settings.SHARE_URL + str(join_obj.ref_id)
context = {"ref_id": join_obj.ref_id, "count": count, "ref_url": ref_url}
template = "share.html"
return render(request, template, context)
#except:
#raise Http404
Error message I am getting after commenting out exception is:
DoesNotExist at /admin
Join matching query does not exist. Lookup parameters were {'ref_id': u'admin'}
Urls.py includes following.
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'joins.views.home', name='home'),
url(r'^(?P<ref_id>.*)$', 'joins.views.share', name='share'),
)
Your regular expression in line
url(r'^(?P<ref_id>.*)$', 'joins.views.share', name='share'),
matches admin/ as well you should use something less "greedy".

Django - No Reverse Match at /

I'm trying to get the absolute url for particular items in my model.
models.py
class BannerAds(models.Model):
name = models.CharField(max_length=256)
phone = models.CharField(max_length=20)
def __unicode__(self):
return self.name
#permalink
def get_absolute_url(self):
from django.core.urlresolvers import reverse
return reverse('index', args=[str(self.name)])
views.py
def banners(request):
context = RequestContext(request)
all_banners = BannerAds.objects.all()
content_dict = {'banners': all_banners,}
return render_to_response('templates/banner.html', content_dict, context)
def index(request):
context = RequestContext(request)
banner_list = BannerAds.objects.all()
city_list = Cities.objects.order_by('name')
offer_list = NewOffers.objects.order_by('offer_add_date')[:5]
context_dic = {'banner_list': banner_list,
'cities': city_list,
'offers': offer_list,
}
return render_to_response('templates/index.html', context_dic, context)
urls.py
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.index, name='index'),
url(r'^advertise/', views.advertise, name='advertise'),
url(r'^about/', views.about, name='about'),
url(r'^listing/', views.listing, name='listing'),
url(r'^search/', views.search, name='search'),
url(r'^add/', views.add_listing, name='add'),
url(r'^offers/', views.offers, name='offer'),
url(r'^add_listing/$', views.add_listing, name='add_listing'),
url(r'^listing/(?P<listing_url>\w+)/$', views.listing, name='category'),
url(r'^testimonial/', views.testimonials, name='testimonial'),
url(r'^add_testimonial', views.add_testimonial, name='add_testimonial'),
url(r'^banner', views.banners, name='banners'),
)
I've entered test data as name=test, phone = testing.
When I try to open the page, it gives me a No Reverse Match at / error along with a
Reverse for '' with arguments '('Testing',)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Any idea what I'm missing? I'm pretty new to Django development so solutions with code examples would help me a lot.
Change the view banners to as you are passing args.
def banners(request, name):
context = RequestContext(request)
all_banners = BannerAds.objects.all()
content_dict = {'banners': all_banners,}
return render_to_response('templates/banner.html', content_dict, context)
Also, make sure you have made an entry in urls.py with name="banners"
Don't use both #permalink and reverse(). They do the same thing. Either drop the decorator, or just return the tuple of (view_name, args).
In fact, the documentation says that permalink is deprecated, so the best thing is just to remove it.
The url url(r'^$', views.index, name='index') does not accept any parameter so why are you passing args here reverse('index', args=[str(self.name)])?
If you want a detail view and wants the name to be optional parameter for index then you can do:
url(r'^(?:(?P<name>.+?)/)?$', views.index, name='index')
Also change the index view to this:
def index(request, name=None):
context = RequestContext(request)
banner_list = BannerAds.objects.all()
# now if name parameter is not None you may want to just pick single object
banner_obj = None
if name:
banner_obj = BannerAds.objects.get(name__exact=name)
city_list = Cities.objects.order_by('name')
offer_list = NewOffers.objects.order_by('offer_add_date')[:5]
context_dic = {'banner_list': banner_list,
'cities': city_list,
'offers': offer_list,
'banner_obj': banner_obj,
}
return render_to_response('templates/index.html', context_dic, context)
Or have a separate view which will serve for the detail of BannerAds.

Categories