When i change to the page "lostitems" it successfull show up, but when i change to another page "addlostitem" it's still on the same page as before, but the url change the way that i want
Urls.py
url(r'lostitems/$', views.LostItemsView.as_view(), name='lost_items'),
url(r'lostitems/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),
Views.py
class LostItemsView(generic.ListView):
model = Wallet
template_name = 'lostfound/lost_items.html'
class RegisterLostView(View):
model = Wallet
template_name = 'lostfound/register_lost.html'
Its because your URL patterns matches (partially) with the first in order, this should fix that:
url(r'^lostitems/$', views.LostItemsView.as_view(), name='lost_items'),
url(r'^lostitems/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),
Notice I have added the ^ hat sign in beginning to force full match.
Related
So i'm working on an inventory app, a django-app where you can handle inventory in a company. I've been using mostly class-based so far in my views.py, and i can already create and edit all of my models using class-based views.
So when it comes to the generic.DeleteView, i have some problems.
This is my function in views.py:
class DeleteItemView(DeleteView):
model: Item
success_url: reverse_lazy('inventory_app:items')
template_name = 'inventory/detail_pages/item_detail.html'
And this is my URL to the function:
path('items/<int:pk>/delete/', views.DeleteItemView.as_view(), name='delete_item')
When i call this url with a button, this error appears:
DeleteItemView is missing a QuerySet. Define DeleteItemView.model, DeleteItemView.queryset, or override DeleteItemView.get_queryset().
So i heard online that this appears when /<int:pk>/ is missing in the url. But i have it in mine, so whats the problem here?
Thank you already
class DeleteItemView(DeleteView):
model = Item
success_url = reverse_lazy('inventory_app:items')
template_name = 'inventory/detail_pages/item_detail.html'
remove the colon (:) and change to =
I am trying to make urls pattern to catch all urls from root.
my main urls.py is:
path('', (include('myapp.urls', namespace='app1')
I am using two url patterns in app1.urls:
re_path(r'^(?P<url_var1>[-\w./]+)/$', DetailView1.as_view(), name='DetailView1'),
re_path(r'^(?P<url_var2>[-\w./]+)/$', DetailView2.as_view(), name='DetailView2'),
My views.py file is as:
class DetailView1(View):
template_name = 'detail.html'
def get(self, request, url_var1):
obj1 = model1.objects.get(my_url=url_var1)
return render(request, self.template_name, {'obj1':obj1})
class DetailView2(View):
template_name = 'detail.html'
def get(self, request, url_var2):
obj2 = model2.objects.get(my_url=url_var2)
return render(request, self.template_name, {'obj2':obj2})
when i request url "/first-post/my-first-post/", It checks out the url which is in my "model1" under ther header "my_url" and return the page.
But when I request url "/second-post/my-second-post/", It checks out the url in "model1" and throws an error, as the url is in "model2" under header "my_url".
I know that the urlpattern follows a squence check, and stops at the pattern which matches the first urlpattern(DetailView1), thats why It is giving me this error.
I want to know is there a way I can override this behavior of urlpattern.
I have also tried reverse, when url is not found in DetailView1:
try:
obj1 = model1.objects.get(my_url=url_var1)
except:
return reverse('app1:DetailView2')
But Its still giving me an error.
If any of you got any other suggestions for catching urlpattern from root for mare than two type of urlpattern please tell me.
I am making a product cum blog website which has two models "model1" which is a product model, and "model2" which is a blog model. Now the "model1" is for automobile having 2 main categories "car" and "bike" and "model2" is having the same as "latest in cars" & "latest in bikes". For these categories I want to pick up urls from the root which have been given as "/cars/lexus.....", "/bike/ducati....". Also, there can be further additions of subfolder url and all urls have product IDs having "." and numbers. So is there is way i can pick urls frm root for both models using the above url pattern.
Its not possible to have multiple views and single urlpattern in Django.
Take a look at your views. They are almost the same. You should put the logic handling different url parameters in single view.
My advice would be also to carefully review your model design, it looks like you have two models that are essentially the same. I feel that this is the root of your problem.
Additionally I assume that you are trying to create some kind of blog.
Django had its beginning as framework powering news site. And it has some helpful tools. For example take a look at SlugField This may provide you with functionality you are looking for. Without over complicating the urlpatterns.
I am writing one middleware class to handle pagination in django.
I am getting issue when user delete entry in ListView and page number is lost. So, i have to check how many pages for that request and adjust page number to reduce issue 404 error. I can get ClassBase Name, model name but cant get object_list data.
my code is:
url = request.path
resolver_match = resolve(url)
func = resolver_match.func
module = func.__module__
view_name = func.__name__
clss = get_class( '{0}.{1}'.format( module, view_name ) )
I want to count the current page of that request.
Please suggest to get it.
Thanks,
ThanhTruong
It would probably be better to handle pagination in a base view or a mixin. See ListView for an example.
I am new to django. I made a form. I want that if the form is filled successfully then django should redirect to a success page showing the name entered in the form but no parameters should be present in the url itself.
I searched on the internet and the solution I got was to redirect to url with pk as a get parameter which fetches the data and shows in the view. But I don't want to pass any thing in the url itself. and some websites say that http can't redirect with post data.
Here's my views.py
class UserRegistrationView(CreateView):
model = UserForm
template_name = 'userregistration.html'
form_class = UserForm
success_url = 'success'
def get_success_url(self):
return reverse('success',kwargs = {'name' : self.object.firstName})
and here's the template to which I want to redirect:
<h2>Congratualations for registering {{name}} </h2>
Basically what I want is that if the person fill form mentioning his/her firstName as "xyz" then the redirected success page should say that "Congratulations for registering xyz"
You can use django sessions, which I believe installed by default in 1.8
Look here
# Set a session value:
request.session["fav_color"] = "blue"
# Get a session value -- this could be called in a different view,
# or many requests later (or both):
fav_color = request.session["fav_color"]
# Clear an item from the session:
del request.session["fav_color"]
You can pass your pk via session and extract your object in another view without affecting your url.
Make sure you clean up after yourself.
Let me know if more help needed.
One of the possible ways of passing data between views is via sessions. So, in your UserRegistrationView you need to override the form_valid method as shown below.
class UserRegsitrationView(CreateView):
def form_valid(self,form):
self.request.session['name'] = self.object.firstName
return super(UserRegistrationView,self).form_valid(form)
class SuccessView(TemplateView):
template_name = "success_template.html"
def get_context_data(self,**kwargs):
context = super(SuccessView,self).get_context_data(**kwargs)
context['name'] = self.request.session.get('name')
del self.request.session['name']
return context
One more thing that you can modify in your code is that you need not declare success_url if you are overriding get_success_url
So I'm having a bit of trouble. I get a 404 when I try to visit the url for a certain model:
url(r'^rewards/(?P<slug>[-\w]+)/$', RedeemReward.as_view(), name="reward"),
url(r'^rewards/(?P<slug>[-\w]+)/$', CompanyDetail.as_view(), name="company"),
So the top url will be something like rewards/amazon-gift card, while the bottom url would be something like rewards/amazon (to show all of the gift cards that amazon has to offer). The reward url works as expected, but I get a 404 when I try to visit the bottom url. The view:
class CompanyDetail(DetailView):
model = Company
context_object_name = 'company'
slug_field = 'company_slug'
template_name = 'asdx/companies.html'
def get_rewards(self):
rewards = Reward.objects.filter(company=self.object)
return rewards
def get_context_data(self, **kwargs):
context = super(CompanyDetail, self).get_context_data(**kwargs)
context['rewards'] = self.get_rewards()
return context
What's going on here?
Your patterns for the two views are identical, so the CompanyDetail view can never be called. Instead, the pattern for RedeemReward matches all slugs and raises a 404 for slugs that do not match whatever its model class is. (Probably Reward.) Put something in the URLs to differentiate company URLs from reward URLs.