Django: Show View after password entry - django

How can I return a View only after letting the user enter a password which is checked against the link?
class Foo(models.Model):
url = models.CharField(max_length=10) #a randomly created ASCII-string
name = models.CharField(max_length=10)
password = models.CharField(max_length=10)
url_patterns = [path('foo/<url>/admin', views.foo, name='foo_admin'),]
So a user goes to url:
localhost/foo/bar
now he should enter the correct password to see the content of model Foo with url='bar'.

If you are using class based views you will want the UserPassesTestMixin.
If you are using function based views you will want the user_passes_test decorator.
Both are described here. Both will essentially divert to the process flow to anything you define. In your case you will want to divert to whatever your using for password checking.
In case you haven't implemented a password scheme you can also read about the default django authentication at the same link.

Related

Django - Filtering user information related to the URL

I have 4 models: Blogger, User, Post and Comment.
Here is the blogger model.
class Blogger(models.Model):
username = models.OneToOneField(User, related_name='bloggers')
blogger_bio = models.CharField(max_length=1000)
Now, I want to display username and blogger_bio depending to the URL.
For example, is someone is using: /testuser, the template will filter username and blogger_bio of only user named testuser.
How to filter this Dynamically?
Use URL dispatcher in django to pass the username to your views. You can render the response template as you wish through views. Try it and post if there are any issues.
https://docs.djangoproject.com/en/1.8/topics/http/urls/

The relation between a model and it's form in Django, and user authentication

I'm migrating something from an old PHP/apache server to Django. I'm a bit stumped with the 'ModelForm'.
As far as I understand, a "Model" is the abstraction for persistent elements in my website/server - specifically this is something stored physically, say in a database, and defines the fields (read columns) in the DB.
I started moving the authentication part of the site, and discovered models, and specifically the User model (I made an empty User inheriting AbstractUser just in case I will ever need to extend things). Now I want to create a simple two field form, to authenticate login.
The form:
Username (which is a field of User, by default)
Password (Which is not).
Even the 'Username' needs a redefinition in the model form. So my questions:
What is the advantage of the model form (over just a form)? - seems like you're redefining fields anyway, and obviously sometimes adding fields on top of the model.
Specifically for authentication, I probably need to store my salted hash associated with the user somehow, compare my password using that and retrieve the user object. This is something I find very hard to find in the Django docs - they just have too much written on authentication, and not one full code example. Do I put this in the "validate" method of form, retrieving there an object and storing it in a session or something?
If there is a deeper relation between a model form and the associated model, I would like to know as well.
Simple django forms and modelforms have quite differences.
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['pub_date', 'headline', 'content', 'reporter']
The above example illustrates that you don't have to write any form field in here. The model form will itself create a form which is based on the attributes provided in the model ('Article' in this example).
If you create a simple django form then it would be something like:
class ArticleForm(forms.Form):
some_field = forms.CharField(some_attrs)
...
The django User model provides you everything you need for authentication. When you want to create users just import django.contrib.auth.models.User and use create method to create objects. Then when you want to authenticate a user use authenticate method.
from django.contrib.auth import authenticate, login
def user_login(request):
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
# after authentication login the user or set cookies or modify the session or some other action can be taken
return HttpResponse("Some response or use render for html page")
username and password will be coming from your post request.
If you want to extend default Django user model you can use django user model as onetoonefield in your extended model.
class AppUser(models.Model):
user = models.OneToOneField(User)
... # other custom fields

Secure URL/page for AnonUser to update a model field - Django Rest framework

I have a model called Lead which represents my possible future_customer.
In order to update a boolean field called is_approved in this model, I'm sending an email to the Lead's email ID along with a URL and this URL will take you to a page in my website where it asks for Approval.
How do I deal with permissions in Django Rest framework views? There is no django user associated with Lead model and I cannot use any authentication related classes.
Obscured url along with AllowAny permission is good enough?
What generally happens in a normal scenario for validation of emails is that they generate a unique token for the corresponding email. Then they when the user clicks on the email. He is taken to a page where there could be form submit which takes to a POST page or just validates directly.
The only security is that the unique id is just unique and there is a very rare chance for someone generate those id's via brute-force. That's the only security. You can add a expire also that makes the link valid only for few days.
You find the corresponding email associated with the same and update is_approved field accordingly.
Your model and view should look something like this.
class Lead(models.Model):
email = models.EmailField()
unique_id = models.CharField(default=uuid.uuid4)
is_approved = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse('lead_verification', kwargs={'unique_id': self.unique_id})
class LeadVerificationView(APIView):
def post(self, unique_id):
lead = Lead.objects.get(unique_id=unique_id)
lead.is_approved = True
lead.save()

Django: model.ForeignKey referring to field type

I try to build a model, e.g. Userprofile, in which fields will be chosen in the admin panel.
class UserProfile(models.Model):
user = models.OneToOneField(User)
regfield = models.ForeignKey(Regfields)
This model refers to a second model Regfields:
class Regfields(models.Model):
field_name = models.CharField(max_length = 256, unique=True, blank=False)
field_type = models.ForeignKey(FOREIGNKEY_TO_DATATYPES)
I want to choose the Fieldname and the Fieldtype (e.g. Char_field ...) to use this in a second model Userprofile, to refer to the field names and field types in the Regfields model. What is the best approach to realize this?
Edit:
I don't seek to have a kind of dynamic database for the user profile. I think I could achive something like this by using a "static" choice list, e.g.:
FIELD_TYPE_CHOICES = (
(BigIntegerField,'Long Int'),
(BooleanField,'Boolean'),
(CharField,'Char'),
...
)
field_type = models.CharField(max_length=20, choices=FIELD_TYPE_CHOICES, default=CharField)
However, this way I can have the required registration fields to be choosen from a given set, but I only get the fieldtypes as strings, which in turn might lead to complicated data validation.
Example of what i try to achive:
In the admin panel I want the admin to have they choice what kind of data is required (additionally to username and password) at the registration page. The admin might like to ask for (username, password and email) but might also ask for (username, password, email, first_name, last_name, company, department)
Allowing users to customize forms via forms is not that simple, and will probably drag you into more non standard problems... How about trying out a ready made django package that helps building forms?
https://www.djangopackages.com/grids/g/form-builder/

Mongoengine User Authentication

Does anyone have specific examples of using the authentication from Mongoengine?
A couple questions I have are:
extending the User class
from mongoengine.django.auth import User
from mongoengine import *
class User(User):
location = GeoPointField()
When I create a user with no documents are saved
User.create_user('bob','bobpass','bobsaget#fullhouse.gov')
User.objects
>>>[]
explicitly call the .save() method has the same affect
Can the User class not be inherited?
Also
Is there a login() method like in the standard authentication backend?
I am starting to feel like I am trying to put a square peg in a round hole with MongoDB and Django...
I haven't used MongoEngine, but I've been looking at it documentation.
First, don't use the User name for your extension, there could be name clashes. Call it for example Profile:
from mongoengine.django.auth import User
from mongoengine import *
class Profile(User):
location = GeoPointField()
If that is not working, try:
class Profile(Document):
user = ReferenceField(User)
location = GeoPointField()
For your login question, look at this.
create instance.
user = User.create_user('bob','bobpass','bobsaget#fullhouse.gov')
user.save()
or
user = User(username='bob', password='bobpass', email='bobsaget#fullhouse.gov')
user.save()
or
user = User()
user.username = 'bob'
user.password = 'bobpass'
user.email = 'bobsaget#fullhouse.gov'
user.save()