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.
Related
I'm building a Django server for my company and I'm still unfamiliar with some processes. I'm sure this is super simple, I'm just completely unaware of how this works.
How do I differentiate between user's data so it doesn't get mixed up?
If Jill is a user and she requests a page of her profile data, how do I not send her Jack's profile data, especially if there are multiple models invovled?
For example, the code in the view would look like this:
def display_profile(request)
profile = Profile.objects.get(???) # What do I put in here?
I understand that I can do:
def display_profile(request, user)
profile = Profile.objects.get(user_id=user)
But that's not my design intention.
Thank you in advance.
As documented
Django uses sessions and middleware to hook the authentication system into request objects.
These provide a request.user attribute on every request which
represents the current user. If the current user has not logged in,
this attribute will be set to an instance of AnonymousUser, otherwise
it will be an instance of User.
So in your case (notice field not being called user_id )
profile = Profile.objects.get(user=user)
In your Django view, you can access the current user with request.user.
So if you want to get a Profile instance matching your current logged in user, just do a query as follow:
profile = Profile.objects.get(user=request.user)
This assumes you have a user foreign key field (or OneToOne) in your Profile model.
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
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.
I have a custom admin page:
class StripeAdminSite(admin.AdminSite):
...
pass
I have registered django.contrib.auth.models to this admin site:
stripe_admin_site = StripeAdminSite(name='Stripe')
stripe_admin_site.register(User)
Now User show up in the admin page, it also let me create users (as stuff), but after creation when I try to log in using them to dashboard it does not allow me to do that.
After switching back to default admin site, I got this written in my old users password fields:
Invalid password format or unknown hashing algorithm.
Now what can be done?
More/Extra information: How to bring default add user page at django custom admin page?
The problem is that you did not register the User model with Django's UserAdmin. This means that the password was not hashed properly when the user was created, so they can't log in.
To use Django's UserAdmin, change your code as follows.
stripe_admin_site = StripeAdminSite(name='Stripe')
from django.contrib.auth.admin import UserAdmin
stripe_admin_site.register(User, UserAdmin)
Once you have done this, you will not get this problem for new users that you add in future.
Use the change password link to reset the password for any existing users, and then they should be able to log in.
Django has a built in admin page where it comes with a feature to add/edit/remove user (and its authentication).
However, i need to create a custom form involving the following models
employee/models.py
# Stores profile details such as DoB, Martial Status, TFN and so on
class Profile(models.Model):
user = models.OneToOneField(User)
MARTIAL_STATUS = (
('s', 'Single'),
('m', 'Married'),
('d', 'Divorced'),
('w', 'Widowed')
)
martial = models.CharField(max_length=1, choices=MARTIAL_STATUS, null=True)
tfn = models.CharField(max_length=200, blank=False)
What i want to do is to have one form where user can enter information about the username, first_name, and so on along with all fields required in my models.
So far this is what i have done
Notice how an account needs to be created first, before additional information (from different model) can be inserted
ps: i am using Django ver 1.6
If I understand correctly, you need to create custom users for adding it to your profile form in admin site. Why don't you use django shell? For example:
where manage.py resides, open terminal/command prompt and type:
>>python manage.py shell
In [1]: from django.contrib.auth.models import User
In [2]: i=User(username="test")
In [3]: i.save()
In [4]: i.set_password('test')
In [5]: i.save()
You can use this username/password to login into site.
EDIT:
Assuming your admin url is like www.mysite.com/admin, you can access user directly using this like: www.mysite.com/admin/auth/user/add/. Also admin interface looks like this: .
And if you want to add email address and other data, you can press save and continue editing like below:
This will lead you to updating user contents.
If you want to create user not from admin site, then less painful way to implement user registration is using UserCreationForm.
from django.views.generic.edit import CreateView
from django.contrib.auth.forms import UserCreationForm
urlpatterns = patterns('',
url('^register/', CreateView.as_view(
template_name='register.html',
form_class=UserCreationForm,
success_url='/'
)),
url('^accounts/', include('django.contrib.auth.urls')),
# rest of your URLs as normal
)
you have to create a register.html here though like:
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create" />
</form>
details: http://www.obeythetestinggoat.com/using-the-built-in-views-and-forms-for-new-user-registration-in-django.html
I usually start from the documentation full example then I adapt it for my needs. You keep the Django permissions but you also add some custom permissions.
I don't know how far are you in your project but if you're just starting I recommend you to use twoscoops templates or cookiecutter-django of Daniel Greenfield. It also implements django all auth library which is very useful for social authentifcations.
There should be + symbol near by user model dropdown box which eases the user to quick add, like the below one.
If the user model in registered with admin i think you could get access to create it on the fly.
OR
As Ruddra's above answer, you have create all user profiles, then you can fillup the form in straight manner.