How to get all user in django template without using views.py? - python

I have an existing project that has no views.py and models.py.It has a user login system.I want to get the list of all user in the template.I have searched more but found no solution.

If you for some reason don't want views.py, you can create custom template tag:
#register.simple_tag
def user_list():
return '<br>'.join([str(u) for u in get_user_model().objects.all()])

Related

How to get current app when user is in Django admin?

I need to get from which admin page(app) current request is from in django admin.
Currently request.resolver_match.app_name only returns "admin" which is not what I want.
I have noticed that my app name is in 'view_name' and 'url_name' but is it reliable to parse these variables to access current app name?
Django 1.11 LTS
EDIT: For example, when a user enters admin page for my course app with the above method I still only get 'admin' in my request which should be 'course' not 'admin'. My ultimate goal is to hide some of my app model fields in admin page based on user group.
Thanks
From a ModelAdmin you have access to the model via self.model. In a ModelAdmin method you can thus get the app name using self.model._meta.app_label.
I you need to access it from the template rather than the ModelAdmin, self.model._meta is passed to the context as opts. You can thus access it via {% if opts.app_label == "some_app" %}.
you can simply do this by tracking requested.user i.e who is logged in currently.
something like this
if(requested.user=='admin'):
(show all fields)
else:
(show mentioned fields)
here you are restricting access of your's models fields based on currently logged in user

Why is my django urlpattern not resolving?

So I'm creating a small ecommerce website for a friend and cannot work out why the url won't resolve itself.
For the sake of simplicity whilst making the website I'm using a product called "number 1". It has a slug field of "number-1" and on the product page clicking on the product takes a user to "/shop/number-1"
My url pattern for this is:
url(r'^<slug:url>', views.item, name='products')
with the view:
def item(request, url=""):
products = product.objects.get(url=url)
return render(request, 'shop\product.html', {'products', products})
As far as I can tell this should render my product.html template but instead it returns a 404 and I'm not sure why?
If it helps I have other views, such as product types set within the same views and they work fine so as far as I can tell its that the slug:url isn't being used in the views.item, or the view isn't getting the context properly.
Also I'm on django 1.11.7 for this project.
The url pattern you are trying to use (slug:url) is only valid in Django 2.
If you are on Django 1.11 then you need to use a regular expression - something like this:
url(r'^?P<url>[\w-]+', views.item, name='products')
Always make sure you're looking at the documentation for your version of Django ;-).
Please change url pattern to:
url(r'^?P<url>[\w-]+', views.item, name='products')

How do I separate user accounts in Django ?

I am using Django to create an app that allows recording of medical information however I am having problems with seperating the user accounts so currently all users see the same information entered. Anyone familiar with django knows how to set the proper permissions and roles and is willing to help a newby out?
I want the user to only access to the account the user creates and the records that the user create.
This is my github link
If you are able to to help I would really appreciate it.
If you want to list only the user's records in your /home . You only need to change the query in your home/views.py, from Identity_unique.objects.all() to Identity_unique.objects.filter(user=request.user)
class Identity_view(TemplateView):
def get(self, request):
form = Identity_form()
Identities = Identity_unique.objects.filter(user=request.user)
var = {'form': form, 'Identities': Identities}
return render(request, self.template_name, var)
Or if you want to filter objects in your Django Admin panel you should read this:
Django Documentation: ModelAdmin.get_queryset(request)
Create a custom user model with an extra field user_type.
https://github.com/samimsk/debatehub/blob/master/devdebatehub/UserApp/models.py
Implemented here.

Django - Redirect at login based on group

I am currently working on a Django project that has a number of user groups. After login, I am looking to redirect each user to a unique page created for that group.
I have already created the login functionality but for the life of me cannot figure out how to redirect based on group. If there is more efficient way of doing this, I am also open to other suggestions.
The reason for having a separate page for each group is due to a wide range of permissions. I don't want to show a user an option that they would be unable to access.
Thanks in advance.
----Edit----
To expand on the above statement, I have extended the user model to include some needed parameters and set AUTH_USER_MODEL to 'User_Profile.User' (the application created for the extended user model) in settings.py.
In views.py, I am attempting to redirect based on user group based on the below code; however, when redirecting I receive an AttributeError stating that "type object User has no attribute 'groups'. In an html template I am able to access {{user.groups.all.0}} correctly.
From views.py
from django.shortcuts import render, render_to_response, RequestContext
from django.contrib.auth.decorators import login_required
from User_Profile.models import User
#login_required
def home(request):
if User.groups.filter(name='group1') == True:
return render_to_response("home.html", locals(),
context_instance=RequestContext(request))
else:
return render_to_response("login.html", locals(),
context_instance=RequestContext(request))
Have you considered, rather than having many separate different templates, you could have one template, and in django's template language you can do
{% if user.permission %}
<!-- whatever needs to be put here based on the user's permission -->
{% endif %}

Django registration-profile - next step to a user profile

I have installed the django-registration app to my project. After a successful log in step, I am redirecting the user to localhost:8000/ - this is my default testing host and port. And I am displaying somewhere on the page, the username of the logged in user.
What I want to do now is that when I click the username some options like edit profile or change password will appear. My questions are the following:
Should I create another model (inside another new app) containing fields like profile photo, gender, birthday etc and add a foreign key to the User model from django.contrib.auth.models ? Or should I modify the model from django-registration to add some additional fields but which I do not ask for at registration phase and only update them later?
if I want my profile edit feature to be at /accounts/edit, which would be the best practice to do it? to edit the URLconf of my project and add a line like (r'^accounts/edit$',.....) just before (r'^accounts/', include('registration.backends.default.urls')), ?
I hope I made myself clear. I'm trying to figure out which would be the best approach before coding, as I am new to Django... Thanks
I find it's easier to decouple the profile table from the auth table. Just like you mentioned you can use a foreign key relationship to link that profile to the user. You can also apply a lambda inside of your profile table to automatically create a profile when a new user object is created.
Inside your template you can link to the profile page dynamically based on the current authenticated party by using
{% if request.user.is_authenticated %}
Update Profile
{% endif %}
user_profile being the name of your app which holds your user_profile table. That way when the request is made you use the regular expression for the current user id (similar to the polls example provided by django) to get the id number of the currently logged in user than inside the views you just query the database for that particular user.
views.py
def myView(request, user_id):
userProfile = UserProfile.objects.get(user.pk=user_id)
This is a high level example to give an idea of one way to accomplish it.

Categories