The problem is I can't type http://localhost:8000/1 to see spesific ViedoLibrary in my database. Can anyone help me to find the solution?
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('main/', views.main, name='main'),
path('create_view/', views.create_view, name='create_view'),
path('list_view/', views.list_view, name='list_view'),
path('<id>', views.detail_view),
]
views.py
def detail_view(request, id):
context = {}
context['data'] = VideoLibrary.objects.get(shop_id=id)
return render(request, 'app/detail_view.html', context)
models.py
class VideoLibrary(models.Model):
shop_id = models.AutoField(primary_key=True, unique=True)
shop_name = models.CharField(max_length=264)
adress = models.TextField(max_length=264, default='')
Also if I type id=id in views.py the next error pops up : Cannot resolve keyword 'id' into field. Choices are: adress, attendance, equipment, films, genre, income, shop_id, shop_name, staff.
This are all my classes in models.py but there are also adress, shop_id and shop_name that are from specific model
Updated.
You have overriden the id field of your model that is why it won't work with id=id since the latter is actually shop_id. Change it accordingly and it should work.
The id error is telling you that you cannot use id as a field and giving you the list of available model fields you can use for filtering. See this answer for more details. Error: Cannot resolve keyword 'id' into field
Update 2
Your views:
from . models import VideoLibrary
def videoLibrary(request):
context = {}
context['data'] = VideoLibrary.objects.all()
return render(request, 'appname/list_view.html', context)
def detail_view(request, id):
context = {}
context['data'] = VideoLibrary.objects.get(shop_id=id)
return render(request, 'appname/detail_view.html', context)
Your urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('videos/', views.videoLibrary, name='list_view'),
path('videos/<int:id>', views.detail_view),
]
Now, if you enter http://127.0.0.1:8000/videos this gives you the list view. And http://127.0.0.1:8000/videos/1 gives you VideoLibrary with id 1.
Related
I have 2 models (one is a custom user model) with a relation ManyToMany through a third model. I have the pks of the two first models in the client side and i need to retrive the relationship model object with a RetriveAPIView. How can i do it? Here is the code i got:
models.py
class Patient(models.Model):
rut = models.CharField(max_length=50)
userAccount = models.ManyToManyField('accounts.UserAccount', through='therapy.Therapy')
class Therapy(models.Model):
patient= models.ForeignKey(Patient, on_delete=models.CASCADE)
userAccount = models.ForeignKey(UserAccount, on_delete=models.CASCADE)
isActive = models.BooleanField(default=True)
views.py
class UpdateRetriveTherapyView(RetrieveUpdateAPIView):
queryset = Therapy.objects.all()
serializer_class = TherapySerializer
urls.py (project urls)
urlpatterns = [
path('api/patient/', include('apps.patient.urls')),
path('api/therapy/', include('apps.therapy.urls')),
path('admin/', admin.site.urls),
path('auth/', include('djoser.urls')),
path('auth/', include('djoser.urls.jwt')),
]
urlpatterns += [
re_path(r'^.*', TemplateView.as_view(template_name='index.html'))
]
urlpatterns += [
path('api-auth/', include('rest_framework.urls'))
]
therapy.urls.py (the relationship model urls)
urlpatterns = [
path('<int:pk>', UpdateTerapiaView.as_view()),
]
may be there is a way to pass fk as a parameter in the url but idk.
If I have another field like ISBN in book so how do I filter with this field in from django.views.generic import DetailField
here is my book/urls.py file code
urlpatterns = [
path('',BookListView.as_view(), name="book_list"),
path('<isbn>/',BookDetailView.as_view(), name="book_detail")
]
book/views.py
class BookDetailView(DetailView):
template_name = "book/detail.html"
def get_queryset(self,*args, **kwargs):
print(self.kwargs['isbn'])
return BookModel.objects.filter(isbn=self.kwargs['isbn'])
and the Error is
Generic detail view BookDetailView must be called with either an object pk or a slug in the URLconf.
you can use isbn as slug
book/urls.py
urlpatterns = [
path('',BookListView.as_view(), name="book_list"),
path('<slug:isbn>/',BookDetailView.as_view(), name="book_detail")
]
book/views.py
class BookDetailView(DetailView):
model = BookModel
template_name = "book/detail.html"
slug_field = 'isbn'
slug_url_kwarg = 'isbn'
I am really having hard time to understand ways to dispatch arguments and keword arguments to Django urls. Following is the case study:
I've a view using generic base view:
class CartView(View):
def get(self, request, *args, **kwargs):
item = request.GET.get('item')
qty = request.GET.get('qty')
print item, qty
return HttpResponseRedirect('/')
With above view I was able to work with aurguments in url like "localhost:8000/cart/?item=4&qty=200" and it prints the item with quantity in terminal.
As soon I've made changes in code like:
from carts.models import Cart, CartItem
from products.models import Variation
class CartView(View):
def get(self, request, *args, **kwargs):
item_id = request.GET.get('item')
if item_id:
item_instance = get_object_or_404(Variation, id=item_id)
qty = request.GET.get('qty')
cart = Cart.objects.all()[0]
cart_item = CartItem.objects.get_or_create(cart=cart, item=item_instance)[0]
cart_item.quantity = qty
cart_item.save()
print cart_item
return HttpResponseRedirect('/')
With same way passing arguments like "localhost:8000/cart/?item=4&qty=200" it shows me the error:
404 Page Not Found No Variation matches the given query.
urls.py
urlpatterns = [
url(r'^home/$', 'newsletter.views.home', name='home'),
url(r'^contact/$', 'newsletter.views.contact', name='contact'),
url(r'^about/$', 'project.views.about', name='about'),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^cart/$', CartView.as_view(), name='cart'),
url(r'^', include('products.urls')),
url(r'^categories/', include('products.urls_categories')),
404 Page Not Found
No Variation matches the given query.
This message comes from your line:
item_instance = get_object_or_404(Variation, id=item_id)
And means that you have no Variation object matching the given id.
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.
I have a model with some fields and I want to add a LinkColumn to a detail page. I have a working version, but I want to move to django-tables2
The problem is that the link column doesnt show any link, just a "-"
The model
class Events(models.Model):
id = models.IntegerField(primary_key=True)
date = models.DateField(null=True, blank=True)
time = models.TimeField(null=True, blank=True)
The Table. Here I tried with args=[A('id')] and args=[A('pk')]
class EventsTable(tables.Table):
time = tables.TemplateColumn("{{value|time:'H:i'}}", verbose_name='Time UTC')
detail_link = tables.LinkColumn('detail', args=[A('id')], verbose_name='Detail')
class Meta:
model = Events
attrs = {"class": "paleblue"}
fields = ("date", "time", "detail_link")
mi url pattern is
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<event_id>\d+)/$', views.detail, name='detail'),
)
and the view
def index(request):
table = EventsTable(Events.objects.all(), order_by=('-date', '-time'))
RequestConfig(request, paginate={"per_page": PAGE_LIMIT}).configure(table)
return render(request, "db_interface/events.html", {"table": table})
EDIT:
Changing the detail_link to
detail_link = tables.LinkColumn('detail', args=[A('id')], verbose_name='Detail', empty_values=())
now I got a NoReverseMatch Exception
Reverse for 'detail' with arguments '(5075,)' and keyword arguments '{}' not found
the number 5075 is the id of the first event. I dont know if for any reason is not passing the argument as an int ?
Try:
detail_link = tables.LinkColumn('detail', args=[A('id')], verbose_name='Detail', empty_values=())
According to the docs, render methods are only called if the value for a cell is determined to be not an empty value. Since the Event model does not have a detail_link field, there's no value given to it.