Creating two separate registration forms in Web2py? - python

So I want to create two registration forms side by side. One for users and other for employees. So basically the index page will have something like "Click here if you are a user" and "Click here if you are an employee". It will redirect to the appropriate registration page. I want the user registration to be just like how the built in web2py registration is. For the employee registration I want the following fields:
Name 2. Store Name 3. Store Type 4. Zip Code
I am really new to web2py so not sure how to implement this. Could someone please tell me how I should go about creating a registration.py model for this? Also I want the index to redirect to these two links as appropriate:
[app]/user/register
[app]/employee/register
Also what would my controller file look like? Would I need a separate controller for user and the employee?

Your question is not quite clear. Do you want to show two forms side by side OR do you want to redirect to the appropriate registration page?
Let's assume you opt for the second option as you described in your question. I'm also assuming that for whatever reason, employees and users are not the same as i understood from your question.
First create the employee table in models:
STORE_TYPE = ['Department store', 'Discount store', 'Warehouse store', 'Mom-And-Pop', 'Boutique']
db.define_table('employee',
Field('first_name'),
Field('last_name'),
Field('store_name'),
Field('store_type', requires=IS_IN_SET(STORE_TYPE)),
Field('zip_code'),
auth.signature)
Then in the controller just ask the user if she is an employee or user:
def index():
form = SQLFORM.factory(Field('user_or_employee', requires = IS_IN_SET(['user', 'employee']))).process()
if form.accepted:
if form.vars.user_or_employee == 'user':
redirect(URL('user/register'))
elif form.vars.user_or_employee == 'employee':
redirect(URL('employee_register'))
return locals()
If the user is a 'user' then you'll redirect them to the user/register as wished. if they are an 'employee' then redirect them to index/employee_register
def employee_register():
form = SQLFORM(db.employee)
if form.process().accepted:
redirect(URL('welcome')) # or whatever function you wish...
return locals()
From there you can take it by yourself.
Don't forget to create the views. For index and for default/employee-register.html. In both views you should include the forms you've created, something like that:
{{extend 'layout.html'}}
<h2>Please Register to Continue</h2>
{{=form}}

Related

Userena group based categorization on signup/registration

I would like to separate users into two different groups, sellers or buyers, at signup. I'm using django-userena and for the authentication and registration of users. I'm thinking of using a clone of the same signup view except with a different url tied to it.
So whoever signs up at url(r'^account/signup/seller/$) linked to a seller signup button will be added to the seller group
and whoever signs up at url(r'^account/signup/$) linked to a buyer signup button will be added to the buyer group.
Note: I will be using this grouping to grant access to view functions in another django app in my project via signals/decorators.
in my accounts/form.py file, I have:
class SellerSignupFormExtra(SignupForm):
def save(self):
new_user = super(SignupFormExtra, self).save()
new_user.groups.add(Group.objects.get(name=‌​'seller'))
return new_user
and I added this to accounts/urls.py file
url(r'^accounts/signup/seller$', 'userena_views.signup', {'signup_form': SellerSignupFormExtra}),
So my question is that can I add the other users that click the buyer signup button by doing the same thing I did for sellers above or is their a better way to achieve this so that I remain DRY.

How to populate choice form from db in Django?

I can't figure out how to populate choice form from db. I know about ModelChoiceForm but the problem seems to be slightly different.
I want user to choose which sector does he work in. For example: 'Finance','Electronics' etc. which I would do simple:
SECTOR_CHOICES = (('finance',_('Finance'),
'electronics',_('Electronics')...
))
But the problem is that I want admin of the web to be able to add new choices, remove choice etc.
What came to my mind is to create a simple Model called Sector:
class Sector(models.Model):
name = models.CharField(max_length=40)
and User would have new attribute sector = models.ModelChoice(Sector).
But I'm scared what would happend when admin changes or removes a sector which is already used, and more, what if he removes it and the sector attribute is required?
How to solve this problem?
I would just override the delete_model as custom action and there check if the selected sector object is in use.
def delete_model(modeladmin, request, queryset):
for obj in queryset:
if UserModel.objects.filter(sector=obj).exists():
# do not delete, just add some message warning the admin about it
else:
obj.delete()
class UserModelAdmin(admin.ModelAdmin):
actions = [delete_model]
# ...

Two types of user accounts with django user accounts

I'm creating a web application and I'd like to split the sign-up/registration process between
A. Individuals
and
B. Employers
where each sign-up form contains similar elements but are also different.
What's the best approach to doing this? Inheritance?
Concentrating only on forms + views section ( assuming you are done with the models).
Since all the fields are same for both the entities. You can differentiate when you create the object of the signup form in views method.
def employer_signup(request):
form = CommonSignupForm(request.Post or None)
# do something with it
def individual_signup(request):
form = CommonSignupForm(request.Post or None)
# do something else with it
Now, i assume, max you have to do in this is to set user_type of the user signing up. Following code should be in each method.
user = form.save(commit=false)
user.user_type = 'E' # depends what tags you are using
user.save()

django: keep each users data separate

I am trying to workout how / the best, most secure way to keep a user's data separate within a django site that I need to write.
Here is an example of what I need to do...
example app ToDoList
Using django contrib.auth to manage users / passwords etc, I will have the following users
tom
jim
lee
There will be a ToDo model (in my real app there will be additional models)
class ToDo(models.Model):
user = models.ForeignKey(User)
description = models.CharField(max_length=20)
details = models.CharField(max_length=50)
created = models.DateTimeField('created on')
The issue that I am having - and may be over thinking this: How would this be locked down so tom can only see Tom's todo list, lee can only see his todo list and so on...
I have seen a few posts stating that you could use filter in every query, or use urls, so the url could look like www.domain.com/username/todo
But either way I am not sure if this is the right way / best way, or bonkers in terms of stopping users seeing each others data
cheers
Richard
One approach is to filter the ToDo items by the currently logged in user:
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from your_app.models import ToDo
#login_required
def todos_for_user(request):
todos = ToDo.objects.filter(user=request.user)
return render(request, 'todos/index.html', {'todos' : todos})
This locks down the view for authenticated users only, and filtering by the logged in user from the request, another user, even if logged in, can't access another user's ToDo records. Hope that helps you out.
Make url like www.domain.com/username/todo is one way to implement it, but it doesn't guarantee you achieve security.
What you should do keep your user's login information in a session data after user login, and every time you check certain view,
check whether that particular user has right to see this view.
using user's login info (ID, or username) when querying user's Todo list.
And I guess this link will help you to do your job.
Sessions, Users, and Registration.

Converting separate functions into class-based

I have several function that need to have a 'redirect' filter. The redirect filter goes something like this --
1) if a user is not logged in and has no session data, redirect to login page.
2) if a user is logged in and has already filled out the page, redirect to user home.
3) if a user is logged in and has not already filled out the page, stay on the page.
4) if a user is not logged in and has session data, stay on the page
I've started to convert the functions into a class-based approach to make it more efficient and less code (previously my view functions were pretty massive). This is my first stab at trying make something class-based, and this is what I have so far --
def redirect_filter(request):
if request.user.is_authenticated():
user = User.objects.get(email=request.user.username)
if user.get_profile().getting_started_boolean:
return redirect('/home/') ## redirect to home if a logged-in user with profile filled out
else:
pass ## otherwise, stay on the current page
else
username = request.session.get('username')
if not username: ## if not logged in, no session info, redirect to user login
return redirect('/account/login')
else:
pass ## otherwise, stay on the current page
def getting_started_info(request, positions=[]):
location = request.session.get('location')
redirect_filter(request)
if request.method == 'POST':
form = GettingStartedForm(request.POST)
...(run the function)...
else:
form = GettingStartedForm() # inital = {'location': location}
return render_to_response('registration/getting_started_info1.html', {'form':form, 'positions': positions,}, context_instance=RequestContext(request))
Obviously, this view is not fully working yet. How would I convert this into something that's functional?
Also, I have three variables that will need to be reused in several of the getting_started functions:
user = User.objects.get(email=request.user.username)
profile = UserProfile.objects.get(user=user)
location = profile.location
Where would I put these variable definitions so I can reuse them in all the functions, and how would I call them?
Thank you.
Django actually already includes a login_required decorator that makes handling user authentication trivial. Just include the following at the top of your view.py page:
from django.contrib.auth.decorators import login_required
and then add
#login_required
before any views that require a login. It even handles redirecting the user to the appropriate page once they log in.
More info here:
https://docs.djangoproject.com/en/dev/topics/auth/#the-login-required-decorator
This should greatly simplify your views, and may result in not having to write a separate class, since all that's left is a simple re-direct.
As for the variables, each request already contains a request.user object with information on the user. You can do a search in the docs for Request and response objects to learn more.
You can use that user object to get the profile variable by extending the user module. Set AUTH_PROFILE_MODULE = 'myapp.UserProfile' in your Settings, which will allow you to access a users profile as follows:
user.get_profile().location.
More about that here:
http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/

Categories

Resources