project() missing 1 required positional argument: 'pk' - django

am confuse right now...i want to pass in a key value but i kept on getting error
my code urls
from django.urls import URLPattern, path
from . import views
urlpatterns = [
path('', views.projects, name="projects"),
path('project/', views.project, name="project"),
]
and the function i created
def project(request, pk):
projectObj = None
for i in projectslist:
if i['id'] == pk:
projectObj = i
return render(request, 'projects/single-project.html', {'project': projectObj})

You need to set the pk argument in your url.
path('project/<int:pk>/', views.project, name="project"),
Related docs. URLS, Views

Related

How can i use csrf token in customised django model admin?

I am working in a simple Django project, and i want to add a button for every model object in admin and i am able to create it by using this:
in admin.py
class RegistrationAdmin(admin.ModelAdmin):
def button(self, obj):
isreg = obj.username
return format_html('<form action="/validate/" method="post">{% csrf_token %}<script>x={{isreg}};</script><button class="btn btn--pill btn--green"'
' type="submit">Validate</button></form>', {'isreg': isreg})
button.short_description = 'Action'
button.allow_tags = True
list_display = ['username', 'button']
But when i excute it it gives key error:
KeyError at /admin/myapp/registration/
'% csrf_token %'
so how can resolve this error?
or
is there any other way to add functionality to my validate button?
If you are talking about creating a new action for every instance, you can do something like this:
from django.conf.urls import url
from django.contrib import admin
from django.http import HttpResponseRedirect
from django.utils.html import format_html
class RegistrationAdmin(admin.ModelAdmin):
list_display = ['username', 'button']
def button(self, obj):
return format_html('{}', obj.id, obj.username)
def get_urls(self):
urls = super().get_urls()
my_urls = [
url(r'^new-action/(?P<id>[0-9]+)$', self.new_action)
]
return my_urls + urls
def new_action(self, request, id):
if request.user.is_authenticated:
# your stuff
self.message_user(request, 'ID {} successfully processed'.format(id))
return HttpResponseRedirect('/admin')
solution provided by #Danilo Akamine has worked comletely fine for me.
but those who have same problem may require there:
url method in:
my_urls = [
url(r'^new-action/(?P<id>[0-9]+)$', self.new_action)
]
belongs to
django.conf.urls
so add this line to admin.py:
from django.conf.urls import url
or you can also use path method from django.urls as:
my_urls = [
path('new-action/<int:id>', self.new_action)
]
for more info:
visit https://docs.djangoproject.com/en/2.2/topics/http/urls/

Django CreateView redirect to UpdateView if already have an object created

I have tried how to check(using get() function) inside CreateView. so when we try to access CreateView URL, this view will check is there an object has been created. if yes, it will redirect to that object UpdateView URL. but the problem is I don't know how to reverse it.
urls.py
app_name = 'product'
urlpatterns = [
url(r'^$', pglist, name='list'),
url(r'^create/$', pcreate, name='create'),
url(r'^(?P<slug>[\w-]+)/$', pdetail, name='detail'),
url(r'^(?P<slug>[\w-]+)/update/$', pupdate, name='update'),
url(r'^redire/$', ered, name='redire'),
views.py
CreateView class
def get(self, *args, **kwargs):
if self.model.objects.get(user=self.request.user):
return redirect("product:update", kwargs={'slug': ??? I HAVE NO IDEA HOW TO DOING THIS PART ???slug})
else:
return redirect("product:create")
if I change the line into ==> return redirect("pages:update"), CreateView URL show
NoReverseMatch at /create/
Reverse for 'update' with no arguments not found. 1 pattern(s) tried: ['(?P<slug>[\\w-]+)/update/$']
so, what it should be?
return redirect("product:update", kwargs={'slug': ??? I HAVE NO IDEA HOW TO DOING THIS PART ???slug})
Well I would hazard a guess you have a slug field on your model, and you could provide the slug to the reverse method's kwargs like so:
return redirect(
"product:update",
kwargs={'slug': self.model.objects.get(user=self.request.user).slug}
)

missing 1 required positional argument: 'request' django restframework

I was using routers for creating urls now i want to make urls for my api, but problem is, i am getting error
createuser() missing 1 required positional argument: 'request'missing 1 required positional argument: 'request'
iam getting same error for all my methods inside UserAuthAPIView class, i have already read solutions on stackoverflow but they are not working i my case.
I have many methods in UserAuthAPIView class and i want to create urls for all of those.
for eg
127.0.0.1:8000/api
127.0.0.1:8000/api/createuser
127.0.0.1:8000/api/login
127.0.0.1:8000/api/<pk>/viewuser
urls.py
from django.conf.urls import url
from UserAPI.api import views
from UserAPI.api.views import UserAuthAPIView
urlpatterns = [
url(r'^$', UserAuthAPIView.as_view({'get': 'list'}), name='user-list'),
url(r'createuser/$', views.UserAuthAPIView.createuser, name='user-create'),
#url(r'userlogin/$', views.UserAuthAPIView.userlogin, name='user-login'),
]
views.py
class UserAuthAPIView(ModelViewSet):
queryset = UserModel.objects.all()
serializer_class = ListViewSerializer
def get_object(self, queryset=None):
return self.request.user
#action(methods=['post'], detail=False, permission_classes=[AllowAny], serializer_class=UserSerializer)
def createuser(self, request, *args, **kwargs):
data = request.data
serializer = UserSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response({ "status" : "user created successfully"}, status=HTTP_201_CREATED)
Routers preform a couple of operations on the viewset and in particular add a mapping from the http verbs to the associated functions.
You need to do something similar for your action:
urlpatterns = [
url(r'^$', UserAuthAPIView.as_view({'get': 'list'}), name='user-list'),
url(r'createuser/$', views.UserAuthAPIView.as_view({'post': 'createuser'}), name='user-create'),
]
You are call the Viewset in urls in wrong way. You need do it like this:
router = routers.DefaultRouter()
router.register(r'auth', UserAuthAPIView)
urlpatterns = [
url(r'^', include(router.urls)),
]
Or
urlpatterns = [
url(r'createuser/$', UserAuthAPIView.as_view({'post':'createuser'}),
]

Django DetailView occurs an error?

I Implemented very simple DetailView in Django 1.9.5:
class PostDetailView(DetailView):
Model = Post
template_name = "post/detail.html"
urls.py
from django.conf.urls import url
from chacha_dabang.views import *
urlpatterns = [
url(r'^$', PostListView.as_view(), name="post_list"),
url(r'^new/$', post_new, name="post_new"),
url(r'^(?P<pk>\d+)/$', PostDetailView.as_view(), name="post_detail"),
url(r'^(?P<pk>\d+)/edit$', post_edit, name="post_edit"),
url(r'^(?P<pk>\d+)/delete$', post_delete, name="post_delete"),
url(r'^(?P<pk>\d+)/comment/new/$', comment_new, name="comment_new"),
url(r'^(?P<pk>\d+)/comment/(?P<comment_pk>\d+)/edit$', comment_edit, name="comment_edit"),
]
Errors :
I don't know why it says I have to override query_set(). (As I Know, DetailView automatically set query according to pk)
If I used Function Based View like below,
def post_detail(request, pk):
post = Post.objects.get(pk=pk)
return render(
request,
'post/detail.html',
{
'post': post,
}
)
It totally works fine. Need your helps.
You capitalized model. It is not Model, it should be model.

IndexError: tuple index out of range

I was referring to this page of django documentation to write views. Can someone explain what I did wrong ? And what could be the solution
self.object_list = self.get_queryset()
File "/vagrant/projects/kodeworms/course/views.py", line 23, in get_queryset
self.Course = get_object_or_404(Course, name=self.args[0])
IndexError: tuple index out of range
My views.py file
# Create your views here.
from django.views.generic import ListView, DetailView
from django.shortcuts import get_object_or_404
from .models import Course, Content
class PublishedCourseMixin(object):
def get_queryset(self):
queryset = super(PublishedCourseMixin, self).get_queryset()
return queryset.filter(published_course=True)
class CourseListView(PublishedCourseMixin, ListView):
model = Course
template_name = 'course/course_list.html'
class CourseContentListView(ListView):
model = Content
template_name = 'course/content_list.html'
def get_queryset(self):
self.Course = get_object_or_404(Course, name=self.args[0])
return Content.objects.filter(course=self.course, published=True)
My urls.py file
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(r"^$", views.CourseListView.as_view(), name="list" ),
url(r"^(?P<slug_topic_name>[\w-]+)/$", views.CourseContentListView.as_view(), name="list"),
)
You are using self.args[0] which is for positional arguments, but you are passing in a keyword argument to your view.
As you have no positional arguments self.args is a zero-length tuple which is why you get that exception.
You should be using self.kwargs['slug_topic_name'] since you have a keyword argument in your url.
if you are going to this url
url(r"^$", views.CourseListView.as_view(), name="list" ),
there is no self.args, you should check it
I suppose, it will work if you will go to this url
url(r"^(?P<slug_topic_name>[\w-]+)/$", views.CourseContentListView.as_view(), name="list"),