1👍
If you are not using the generic django class based views, you will have to implement the request’s POST and GET functionality yourself. The easiest is to create a form from your user model and handle the request based on whether it’s a POST request type or not.
Try this:
forms.py (https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/)
from django.forms import ModelForm
from .models import User
class UserForm(ModelForm):
class Meta:
model = Users
fields = ['username', 'organization_id']
views.py
from .models import User
from .forms import UserForm
def UsersCreate(request):
# This function can hadle both the retrieval of the view, as well as the submission of the form on the view.
if request.method == 'POST':
form = UserForm(request.POST, request.FILES)
if form.is_valid():
form.save() # This will save the user.
# Add the user's role in the User Role table below?
#
else:
# The form should be passed through. This will be processed when the form is submitted on client side via this functions "if request.method == 'POST'" branch.
form = UserForm()
var = user_group_validation(request)
userInc = Users.objects.get(id=request.user.id).organization_id.pk
request.session['userInc'] = userInc
if var['group'] == 'superuser':
object_list = Users.objects.all()
organization = Organizations.objects.all()
roles_choice = DefaultLandingPage.objects.all()
if var['group'] == 'admin' or var['group'] == 'user':
object_list = Users.objects.filter(organization_id=request.session['userInc'])
organization = Organizations.objects.filter(id=request.session['userInc'])
# The line below will ensure that the the dropdown values generated from the template will be filtered by the 'request.session['userInc']'
form.organisation_id.queryset = organization
roles_choice = DefaultLandingPage.objects.exclude(role=1)
url = request.session['url']
tpl = var['tpl']
role = var['group']
organization_inc = Organizations.objects.filter(id=request.session['userInc'])
template = get_template(app+u'/users_form.html')
return HttpResponse(template.render(locals()))
In your app+u’/users_form.html’ file, you can access the UserForm fields as follows:
<!-- inside your <form> tag add: -->>
{{ form.username }}
{{ form.organisation_id }}
I haven’t tested this code but this should get you on the right track.
Source:stackexchange.com