I want to use the default PasswordChangeView to change passwords for users in a project. The problem is that by default it works for the current user. Is it possible to use the view with a custom user, i.e. provided in the URL?
# this doesn't work by default
url(r'users/(?P<user_id>\d+)/change_password/$',
PasswordChangeView.as_view()
name="password-change")
I think that PasswordChangeView is designed to change the password of a user that is already logged in. Then you have to create a view that inheritance from PasswordChangeView and override the method get_form_kwargs like this:
class _PasswordChangeView(PasswordChangeView):
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['user'] = User.objects.get(id=1) # or any, or get id from url
return kwargs
Be sure of add some permissions to this view, for security reasons. By the way the django admin have this option already.
I am building a simple app using User Authentication.
My app has 3 models:
Users : The standard Django user model
Locations: A model for an office (address, site name, etc)
Employees: A model for an employee (name, email, etc)
I also have a series of views that allow a user to login, create, and edit locations/sites, etc.
What I want to know, is what is the best practice to restrict editing of model instances to those which the user has created? E.g. with no amendment, two users could create data and both could edit the others. How do I restrict this to editing their own?
I know the long form way is to put a ForeignKey(User) on each model to restrict the view with a queryset, but this seems lengthy and cumbersome. Is there a Django trick I am missing? Perhaps a decorator?
What's the best practice?
The easiest way would be to edit your models so that they have an owner or user field that is a ForeignKey to the creator.
class Locations(models.Model):
owner = ForeignKey(User)
...
And in your views:
def edit_location(request, location_id):
location = Locations.objects.get(pk=location_id)
if request.user is not location.owner:
# return a 401 or redirect to somewhere
else:
# do stuff
You can use Django's ManyToManyField option if each Location and User can have multiple relationships. For example:
class Locations(models.Model):
owners = models.ManyToManyField(User)
user = User.objects.create(username='Ian')
location = Locations.objects.create(...)
location.owners.add(user)
And then the User/Locations are available on both:
>>> location.owners.all()
[<User: Ian>]
>>> user.locations_set.all()
[<Locations: ...>]
The set on User will be automatically created and it will be named <Model Name>_set.
You can then use the in operator to check ownership:
def edit_location(request, location_id):
location = Locations.objects.get(pk=location_id)
if request.user in location.owners.all():
# return a 401 or redirect to somewhere
else:
# do stuff
In my application I have created a Consumer class which keeps data in Django User class and adds other characteristics in the fields create by me. The Consumer class is connected to User in one to one relationship. I am able to post the data.
But now I need to search and retrieve information based on the username received in a request. I am not able to search the Consumer class based on the username. Please advise how I achieve this.
My code is given below
class Consumer(models.Model):
user= models.OneToOneField(User)
company=models.CharField(max_length=64)
street1=models.CharField(max_length=64)
street2=models.CharField(max_length=64)
city=models.CharField(max_length=64)
state=models.CharField(max_length=64)
country=models.CharField(max_length=64)
I am trying to get a record as below
def user_page(request, username):
consumer=get_object_or_404(Consumer, username=username) # locate record
I get the following error
Cannot resolve keyword 'username' into field
I tried User.username=username as well.
You probably mean something like this: consumer = get_object_or_404(Consumer, user__username=username)
avoid using User.username. Replace . with double underscores __
try this instead.
def user_page(request, username):
consumer=get_object_or_404(Consumer, user__username=username)
I'm new to the web development world, to Django, and to applications that require securing the URL from users that change the foo/bar/pk to access other user data.
Is there a way to prevent this? Or is there a built-in way to prevent this from happening in Django?
E.g.:
foo/bar/22 can be changed to foo/bar/14 and exposes past users data.
I have read the answers to several questions about this topic and I have had little luck in an answer that can clearly and coherently explain this and the approach to prevent this. I don't know a ton about this so I don't know how to word this question to investigate it properly. Please explain this to me like I'm 5.
There are a few ways you can achieve this:
If you have the concept of login, just restrict the URL to:
/foo/bar/
and in the code, user=request.user and display data only for the logged in user.
Another way would be:
/foo/bar/{{request.user.id}}/
and in the view:
def myview(request, id):
if id != request.user.id:
HttpResponseForbidden('You cannot view what is not yours') #Or however you want to handle this
You could even write a middleware that would redirect the user to their page /foo/bar/userid - or to the login page if not logged in.
I'd recommend using django-guardian if you'd like to control per-object access. Here's how it would look after configuring the settings and installing it (this is from django-guardian's docs):
>>> from django.contrib.auth.models import User
>>> boss = User.objects.create(username='Big Boss')
>>> joe = User.objects.create(username='joe')
>>> task = Task.objects.create(summary='Some job', content='', reported_by=boss)
>>> joe.has_perm('view_task', task)
False
If you'd prefer not to use an external library, there's also ways to do it in Django's views.
Here's how that might look:
from django.http import HttpResponseForbidden
from .models import Bar
def view_bar(request, pk):
bar = Bar.objects.get(pk=pk)
if not bar.user == request.user:
return HttpResponseForbidden("You can't view this Bar.")
# The rest of the view goes here...
Just check that the object retrieved by the primary key belongs to the requesting user. In the view this would be
if some_object.user == request.user:
...
This requires that the model representing the object has a reference to the User model.
In my project, for several models/tables, a user should only be able to see data that he/she entered, and not data that other users entered. For these models/tables, there is a user column.
In the list view, that is easy enough to implement, just filter the query set passed to the list view for model.user = loggged_id.user.
But for the detail/update/delete views, seeing the PK up there in the URL, it is conceivable that user could edit the PK in the URL and access another user's row/data.
I'm using Django's built in class based views.
The views with PK in the URL already have the LoginRequiredMixin, but that does not stop a user from changing the PK in the URL.
My solution: "Does Logged In User Own This Row Mixin"
(DoesLoggedInUserOwnThisRowMixin) -- override the get_object method and test there.
from django.core.exceptions import PermissionDenied
class DoesLoggedInUserOwnThisRowMixin(object):
def get_object(self):
'''only allow owner (or superuser) to access the table row'''
obj = super(DoesLoggedInUserOwnThisRowMixin, self).get_object()
if self.request.user.is_superuser:
pass
elif obj.iUser != self.request.user:
raise PermissionDenied(
"Permission Denied -- that's not your record!")
return obj
Voila!
Just put the mixin on the view class definition line after LoginRequiredMixin, and with a 403.html template that outputs the message, you are good to go.
In django, the currently logged in user is available in your views as the property user of the request object.
The idea is to filter your models by the logged in user first, and then if there are any results only show those results.
If the user is trying to access an object that doesn't belong to them, don't show the object.
One way to take care of all of that is to use the get_object_or_404 shortcut function, which will raise a 404 error if an object that matches the given parameters is not found.
Using this, we can just pass the primary key and the current logged in user to this method, if it returns an object, that means the primary key belongs to this user, otherwise it will return a 404 as if the page doesn't exist.
Its quite simple to plug it into your view:
from django.shortcuts import get_object_or_404, render
from .models import YourModel
def some_view(request, pk=None):
obj = get_object_or_404(YourModel, pk=pk, user=request.user)
return render(request, 'details.html', {'object': obj})
Now, if the user tries to access a link with a pk that doesn't belong to them, a 404 is raised.
You're going to want to look into user authentication and authorization, which are both supplied by [Django's Auth package] (https://docs.djangoproject.com/en/4.0/topics/auth/) . There's a big difference between the two things, as well.
Authentication is making sure someone is who they say they are. Think, logging in. You get someone to entire their user name and password to prove they are the owner of the account.
Authorization is making sure that someone is able to access what they are trying to access. So, a normal user for instance, won't be able to just switch PK's.
Authorization is well documented in the link I provided above. I'd start there and run through some of the sample code. Hopefully that answers your question. If not, hopefully it provides you with enough information to come back and ask a more specific question.
This is a recurring question and also implies a serious security flaw. My contribution is this:
There are 2 basic aspects to take care of.
The first is the view:
a) Take care to add a decorator to the function-based view (such as #login_required) or a mixin to the class-based function (such as LoginRequiredMixin). I find the official Django documentation quite helpful on this (https://docs.djangoproject.com/en/4.0/topics/auth/default/).
b) When, in your view, you define the data to be retrieved or inserted (GET or POST methods), the data of the user must be filtered by the ID of that user. Something like this:
def get(self, request, *args, **kwargs):
self.object = self.get_object(queryset=User.objects.filter(pk=self.request.user.id))
return super().get(request, *args, **kwargs)
The second aspect is the URL:
In the URL you should also limit the URL to the pk that was defined in the view. Something like this:
path('int:pk/blog-add/', AddBlogView.as_view(), name='blog-add'),
In my experience, this prevents that an user sees the data of another user, simply by changing a number in the URL.
Hope it helps.
In django CBV (class based views) you can prevent this by comparing the
user entered pk and the current logged in user:
Note: I tested it in django 4 and python 3.9.
from django.http import HttpResponseForbidden
class UserDetailView(LoginRequiredMixin, DetailView):
model = your_model
def dispatch(self, request, *args, **kwargs):
if kwargs.get('pk') != self.request.user.pk:
return HttpResponseForbidden(_('You do not have permission to view this page'))
return super().dispatch(request, *args, **kwargs)
I'm trying to make a form that handles the checking of a domain: the form should fail based on a variable that was set earlier in another form.
Basically, when a user wants to create a new domain, this form should fail if the entered domain exists.
When a user wants to move a domain, this form should fail if the entered domain doesn't exist.
I've tried making it dynamic overload the initbut couldn't see a way to get my passed variabele to the clean function.
I've read that this dynamic validation can be accomplished using a factory method, but maybe someone can help me on my way with this?
Here's a simplified version of the form so far:
#OrderFormStep1 presents the user with a choice: create or move domain
class OrderFormStep2(forms.Form):
domain = forms.CharField()
extension = forms.CharField()
def clean(self):
cleaned_data = self.cleaned_data
domain = cleaned_data.get("domain")
extension = cleaned_data.get("extension")
if domain and extension:
code = whoislookup(domain+extension);
#Raise error based on result from OrderFormStep1
#raise forms.ValidationError('error, domain already exists')
#raise forms.ValidationError('error, domain does not exist')
return cleaned_data
Overriding the __init__ is the way to go. In that method, you can simply set your value to an instance variable.
def __init__(self, *args, **kwargs):
self.myvalue = kwargs.pop('myvalue')
super(MyForm, self).__init__(*args, **kwargs)
Now self.myvalue is available in any form method.
Do you have a model that stores the domains? If so, you want to use a ModelForm and set unique=True on whichever field stores the actual domain in the model. As of Django 1.2, you can even do any additional validation inside the model, rather than the form.