I have the following urls
url(r'^signup/','social.views.signup'),
url(r'^submit_signup/','social.views.submit_signup'),
url(r'^signup_complete/','social.views.signup_complete'),
Could I make a url that would choose the view based on the url? Like:
url(r'*/', 'social.views.*')
so that a request to /signup would route to 'social.views.signup'
somehow like this
def test(*args,**kwargs):
view_name = kwargs.pop('view')
view = getattr(social.views,view_name)
return view(*args, **kwargs)
urlpatterns = patterns('',
url(r'^test/(?P<view>.*)$', test),
...
)
or like this
VIEWS_LIST = ['signup','submit_signup','signup_complete']
urlpatterns = patterns('social.views',
*[url('%s/' % view,view) for view in VIEWS_LIST]
)
If you want to make signup process of multiple steps than you can user Django form wizard. In this way you don't need to change url for every signup step. The URL will look like this:
url(r'^signup/$', SignupWizard([SignupForm_1, SignupForm_2, SignupFormComplete]) ),
Check the form wizard documentation.
Related
the redirect url is
"liveinterviewList/2"
and, ofcourse, I declare that url in url.py
more over, when I type that url in browser manualy, it works well.
what's the matter?
more question.
at this case, I write the user_id on the url.
I think, it is not good way to make url pattern.
but I don't know how I deliver the user_id variable without url pattern.
please give me a hint.
What HariHaraSudhan left out was how to use parameters. For your case, you would want something like:
path(r'liveinterviewList/<int:userId>', ..., name='live-interview'),
And then when you are ready to reverse, use this:
reverse('app:live-interview', kwargs={ 'userId': userId })
where app is the name of the app in which your view lives. If your url lives in the main urls file , you don't need the app: prefix.
Django reverse function accepts the name of the path not the URL.
lets say i have url patterns like this
urlpatterns = [
path('/users/list', name="users-list")
]
In my view i can use like this
def my_view(request):
return redirect(reverse("users-list"));
You should add a name to your path url and use it to redirect.
As the django doc says :
urls :
urlpatterns = [
path('/name', name="some-view-name")
]
def my_view(request):
...
return redirect('some-view-name')
I am a newbie in django and I was experting different options in Django. I have created a class based view which requires user authentication to view the web page. I am using the inbuilt LoginView.
When the url pattern is specified as follows
url(r'^login/', auth_views.LoginView.as_view(),name='login'),
it is correctly redirected to login page.
But when I give
url(r'^restaurant/login/', auth_views.LoginView.as_view(),name='login'),
I get a 404 when trying to access the page that requires user authentication.
But when I manually go to that url in browser, it works perfectly fine.
Why is that? Shouldn't it both cases work?
It sounds like you need to set LOGIN_URL in your settings:
LOGIN_URL = '/restaurant/login/'
or, it's better to use the URL pattern name, then you don't have to update your settings when you change the login URL
LOGIN_URL = 'login'
Not sure if I'd fully understand your question, just try to give a stupid answer.
Django 2.1.7
use namespace&url name in settings, if you have your own login view just change admin to your url namespace and name your view as 'login'
# settings.py
LOGIN_URL = 'admin:login'
then the login_required decorator will direct you the correct login page.
from django.contrib.auth.decorators import login_required
#login_required()
def month_archive(request, year, month):
production_list = Production.objects.month_archive(year, month)
context = {'production_list': production_list}
return TemplateResponse(request, 'production/production_list.html', context)
If it's a Class Based View, add decorator to urls.py
from django.contrib.auth.decorators import login_required
urlpatterns = [
path('', login_required(views.ProductionList.as_view()), name='production-list'),
path('<int:year>/<int:month>/', views.month_archive, name='production-month'),
]
I am using the Django admin and have just upgraded from 1.8 to 1.9. In 1.8, I added a click button to the change_form that takes me to another html template using the get_urls override. Like this:
def get_urls(self):
urls = super(arunAdmin, self).get_urls()
my_urls = patterns('',
(r'(\d+)/tarrespgraph/$', self.admin_site.admin_view(self.tarrespgraph)),
)
return my_urls + urls
Following some of the recommendations I saw online, I have changed this to:
def get_urls(self):
urls = super(arunAdmin, self).get_urls()
my_urls = [
url(r'^tarrespgraph/$', self.admin_site.admin_view(self.tarrespgraph)),
]
return my_urls + urls
But am receiving this error:
NBI Graph object with primary key '132/change/tarrespgraph' does not exist.
Django finds the customized change_form.html without a problem. My custom template (tarrespgraph.html) is in the same folder as my customized change_form.html. Where is Django looking for my custom template? Should I move the tarrespgraph.html, or change the reference to the url? Thanks in advance for your assistance!
You probably shouldn't have removed the (\d+) group from your url pattern. Try the following:
my_urls = [
url(r'^(\d+)/tarrespgraph/$', self.admin_site.admin_view(self.tarrespgraph), name='tarrespgraph'),
]
Note that I've added a name, which will let us reverse the url later.
Without the (\d+) group, the new url pattern does not match the url, so it is handled by the admin change view which gives the error.
You also need to change the link in your template. In Django 1.9, Django has appended change to the admin change url (e.g it is now /admin/app/model/132/change/ instead of /admin/app/model/132/. That means that your relative link 'tarrespgraph/' now points to /admin/app/model/132/change/tarrespgraph/ instead of /admin/app/model/132/tarrespgraph/. You could change the relative link to ../tarrespgraph/. However, it would be less fragile to use the url tag instead:
<a class="tarrespgraph" href="{% url 'admin:tarrespgraph' object_id %}">
I am reading http://www.django-rest-framework.org/api-guide/routers#usage and can't understand what a base_name is. Also i try to add a custom action and the router won't pick it up
I have this views.py
#authentication_classes((SessionAuthentication, TokenAuthentication))
#permission_classes((IsAuthenticated,))
class utente(CreateModelMixin, RetrieveAPIView, GenericViewSet, ViewSet):
model = MyUser
serializer_class = MyUserSerializer
def retrieve(self, request, *args, **kwargs):
self.object = MyUser.objects.get(
pk = request.user.pk
)
serializer = MyUserSerializerGET(self.object)
return Response(serializer.data)
#action(permission_classes=[IsAuthenticated])#POST action
def customaction(self, request):
return Response( None )
pass
and this urls.py
admin.autodiscover()
router_v1 = routers.DefaultRouter(trailing_slash=True)
router_v1.register(r'register', my_register, 'wtf' )
router_v1.register(r'utente', utente, 'wtf2' )
#router_v1.register(r'utente/customaction', utente.as_view({'post' : 'customaction'}) )
api_urls_v1 = router_v1.urls
api_urls = patterns('',
url(r'^v1/', include(api_urls_v1)),
)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'wecup.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^login/', 'rest_framework.authtoken.views.obtain_auth_token'),
url(r'^logout/', my_logout ),
url(r'^api/', include(api_urls)),
)
when i open http://127.0.0.1:8000/api/v1/
HTTP 200 OK Content-Type: application/json Vary: Accept Allow: GET, HEAD, OPTIONS
{
"register": "http://127.0.0.1:8000/api/v1/register/",
"utente": "http://127.0.0.1:8000/api/v1/utente/"
where is customaction?
}
You've got two different questions here, so I'll address them each separately.
Base Name
First, a base_name is simply the name the ViewSet will use when generating your named urls. By default, this will simply be your model or perhaps your queryset, though you may need to set it automatically if you've played with your ViewSet's get_queryset method.
If you don't implement your own url names, then the base_name will be used to implement them for you. For example, given that your Model is MyUser, your named urls would be something like 'myuser-list' or 'myuser-detail'.
Documentation, if interested, is here.
#action and custom methods
You're using a DefaultRouter, which allows you to access the API root view at http://127.0.0.1:8000/api/v1/, as you've shown. This root view only shows list views. Using #action creates a detail view. In your case, your customaction view can be found at ^utente/{pk}/customaction/$. It will not show up in the API root because it is not a list view.
General information on #action and custom methods can be found here.
Also, if for some reason you do want to make customaction a list-level view, you'll need to make some modifications. You could either string up a custom route yourself, without using the #action decorator (which is specifically for detail views). An example of that can be found here.
Your other option is to use the new-ish drf-extensions package. A discussion of using the package to implement collection level controllers in ViewSets can be found here.
I'm using django-registration app to perform registration. After registration (no matter if successful or not), I'd like to return to whatever page the registation app would redirect, but I want to pass a login form to that template.
Something like this:
def register(request):
registered = reg_views.register(request, backend='registration.backends.default.DefaultBackend', template_name='zzz/index.html')
login_form = AuthenticationForm()
return render_to_response(registered, { 'login_form': login_form })
and then in the template have the ussual:
{{ login_form.as_p }}
Here's what I am trying to achieve:
I want to leverage the functionality of the registration app. However, after a (un)successful registration, I need to be able to display the login form on the page. This login form should be passed from the view (DRY principle).
Thanks,
Matyas
urls.py
urlpatterns = patterns('',
(r'^accounts/', include('external.registration.urls')),
)
new urls.py
urlpatterns = patterns('',
(r'^accounts/register', 'point.to.new.view'),
(r'^accounts/', include('external.registration.urls')),
)
With this set, you can copy the register view somewhere on your code from the registration app, and modify it as you please, without having to modify the app it self. The register view is pretty straight forward so you will have no problem making some changes.
You should not be needed to copy any code from register view of django-registration.
Say, you want to handle authentication functionality in your app named accounts
This goes in accounts/views.py
def registration_complete(request):
login_form = AuthenticationForm()
return render_to_response("registration_complete.html", {"login_form": login_form})
accounts/urls.py
url(r'^registration_complete/', 'accounts.views.registration_complete', name='accounts_registration_complete'),
In your template registration_complete.html
{{login_form.as_p}}
Now you are done with registration_complete setup.
register view of django-registration takes a success_url where it redirects after successful registration.
Provide this success_url as the url we created in accounts.
Your urls.py:
urlpatterns = patterns('',
(r'^registration/register/$', 'registration.register', {'backend': 'registration.backends.default.DefaultBackend', 'success_url': 'accounts_registration_complete'}),
(r'^registration/', include('registration.urls')),
)
Now after registration the user will be redirected to a page which contains the login form.