This is the view which was written for my django project.
if user is not None:
if user.is_active:
auth_login(request, user)
return HttpResponseRedirect('/home/')
else:
messages.error(self.request,
_("User is not Active"))
return HttpResponseRedirect('/')
else:
messages.error(self.request,_("User Does not Exist"))
return HttpResponseRedirect(settings.LOGIN_URL)
Suppose there is 3 groups of users customer,admin and super admin. How can I redirect the views to different html for each of the user groups? Thank You
if user.groups.all()[0].name == "groupname":
return redirect('some view')
you can do it like this
or if the user has many groups
l = request.user.groups.values_list('name',flat=True)
if "groupname" in l:
return redirect('some view')
Related
I have a form with counterparty, object and sections i connected them to each other with django-forms-dynamic package but object not connected to sections
Counterparty connected to object form but sections are not connected to object how can i fix that?
I guess that im wrong with 2 functions in forms.py: section_choices and initial_sections and they`re not connected to objects but dont know how to fix that
forms.py
class WorkLogForm(DynamicFormMixin, forms.ModelForm):
def object_choices(form):
contractor_counter = form['contractor_counter'].value()
object_query = ObjectList.objects.filter(contractor_guid__in=[contractor_counter])
return object_query
def initial_object(form):
contractor_counter = form['contractor_counter'].value()
object_query = ObjectList.objects.filter(contractor_guid__in=[contractor_counter])
return object_query.first()
def section_choices(form):
contractor_object = form['contractor_object'].value()
section_query = SectionList.objects.filter(object=contractor_object)
return section_query
def initial_sections(form):
contractor_object = form['contractor_object'].value()
section_query = SectionList.objects.filter(object=contractor_object)
return section_query.first()
contractor_counter = forms.ModelChoiceField(
label='Контрагент',
queryset=CounterParty.objects.none(),
initial=CounterParty.objects.first(),
empty_label='',
)
contractor_object = DynamicField(
forms.ModelChoiceField,
label='Объект',
queryset=object_choices,
initial=initial_object,
)
contractor_section = DynamicField(
forms.ModelMultipleChoiceField,
label='Раздел',
queryset=section_choices,
initial=initial_sections,
)
views.py
#login_required
def create_work_log(request):
if request.method == 'POST':
form = WorkLogForm(request.POST, user=request.user)
if form.is_valid():
work_log = form.save(commit=False)
work_log.author = request.user
work_log = form.save()
messages.success(request, 'Данные занесены успешно', {'work_log': work_log})
return redirect('create_worklog')
else:
messages.error(request, 'Ошибка валидации')
return redirect('create_worklog')
form = WorkLogForm(user=request.user, initial=initial)
return render(request, 'contractor/create_work_log.html', {'form': form})
def contractor_object(request):
form = WorkLogForm(request.GET, user=request.user)
return HttpResponse(form['contractor_object'])
def contractor_section(request):
form = WorkLogForm(request.GET, user=request.user)
return HttpResponse(form['contractor_section'])
This may not be an answer you want but I use HTMX for these things. Here is a link to their example for this.
https://htmx.org/examples/value-select/
There is also a package plugin called Django-htmx.
You may need to learn HTMX but it is a mature technology, rather simple and reliable. I am unfamiliar with Django-forms-dynamic
i have a django website that runs a chatbot app to simulate a customer service by getting the question and retrieving the best match reply in the DB using queries.
view.py:
#csrf_exempt
def home(request):
context= locals()
template= 'home.html'
return render(request,template,context)
#csrf_exempt
def male_chatbot(request):
if not request.session.session_key:
request.session.create()
context= locals()
template= 'male_chatbot.html'
return render(request,template,context)
#csrf_exempt
def run_python_male(request):
if request.method == "POST":
session_key = request.session.session_key
param11 = request.POST.get('param1')
msg = chatbot.run_conversation_male(param11)
return JsonResponse({ 'msg': msg})
chatbot.py:
raw_chatting_log =[]
chatting_log =[]
def chatting_log_data(raw_Input,Input,check):
if check== "check":
if raw_Input in raw_chatting_log:
return True
else:
return False
else:
if check== "app":
raw_chatting_log.append(raw_Input)
chatting_log.append(Input)
def check_lastB():
new='جديد'
if len(raw_chatting_log) == 0:
return new
else:
return raw_chatting_log[-1]
def delandsave_chat_log():
name= str(uuid.uuid4())
thefile = open('/home/mansard/webapps/gadgetron/src/chatting_logs/'+name+'.txt', 'w')
for item in chatting_log:
thefile.write("%s\n" % item)
thefile.close()
raw_chatting_log.clear()
chatting_log.clear()
def run_conversation_male(user_in):
last_B = check_lastB()
H = user_in
NN1= "H:"+str(user_in)
New_H= ' '.join(PreProcess_text(H))
if last_B== 'تقييمك للمحادثة و الخدمة؟':
#do_somthing
else:
if chatting_log_data(H,NN1,"check") == True:
#do_somthing
else:
#find_replay
So, the idea is saving the input/output conversation in two list :
raw_chatting_log ==> hold the data with out the addition 'H:' or 'B:' just a the input and output.to help the chatbot remembering the asked questions and using it in chatting_log_data(H,NN1,"check").
chatting_log=> will hold the the conversation to the chat log in form of 'H:' and 'B:' to save the whole list when the user ends the conversation or close the page in def delandsave_chat_log()
and for last_B helps me know what is the chatbot's last responce
So far it is working for one user, now what i'm thinking is switching to make it handle or chat with many users at the same time where each user has it own chatbot.run_conversation_male and each chat/conversation is separate each with it own chatting log list so that i can use it for checking and saving the data.
I have a Django template that has data from a few different model types combining to make it. A dashboard if you will. And each of those has an edit form.
Is it best to process all those forms in one view as they are posted back to the same place and differentiating between them by a unique field like below?
Or if having lots of different dedicated avenues is the way forward? Thanks for any guidance
class ProjectDetail(DetailView):
template_name = 'project/view.html'
def get_object(self):
try:
return Project.objects.filter(brief__slug=self.kwargs['slug']).filter(team=get_user_team(self.request)).first()
# add loop to allow multiple teams to work on the same brief (project)
except Exception as e:
project_error = '%s (%s)' % (e.message, type(e))
messages.error(self.request, 'OH NO! %s' % project_error)
return redirect('home')
def get_context_data(self, **kwargs):
project = self.get_object()
context = dict()
context['project'] = project
context['milestone_form'] = MilestoneForm(initial={'project': project})
context['view'] = self
return context
def post(self, request, *args, **kwargs):
# get the context for the page
context = self.get_context_data()
try:
# switch for each of the form types on the team profile page (shown if member)
if 'milestone_form_submit' in request.POST:
project=self.get_object()
# set date arbitrarily to half way to brief deadline
brief = Brief.objects.get(project=project)
last_milestone = self.milestones().last()
milestone_del_date = last_milestone.del_date + timedelta(days=7)
new_milestone = Milestone(
project=project,
title_text=request.POST.get('title_text'),
del_date=milestone_del_date,
)
try:
new_milestone.save()
messages.success(self.request, "Excellent! New delivery popped on the bottom of the list")
except Exception as e:
# pass the erroring form back in the context if not
form = MilestoneForm(request.POST)
context['milestone_form'] = form
messages.error(self.request, "OH NO! Deadline didn't save. Be a sport and check what you entered")
elif 'milestone-edit-date-form-submit' in request.POST:
# get object from db
milestone = Milestone.objects.get(pk=request.POST['id'])
# update del_date field sent
milestone.del_date = request.POST['del_date']
# save back to db
milestone.save()
messages.success(self.request, "Updated that delivery right there!")
elif ...
except Exception as e:
messages.error(self.request, "OH NO! Deadline didn't save. Be a sport and check what you entered")
return render(request, self.template_name, context)
You can use mixins in order to solve your problem.
Example from the gist https://gist.github.com/michelts/1029336
class MultipleFormsMixin(FormMixin):
"""
A mixin that provides a way to show and handle several forms in a
request.
"""
form_classes = {} # set the form classes as a mapping
def get_form_classes(self):
return self.form_classes
def get_forms(self, form_classes):
return dict([(key, klass(**self.get_form_kwargs())) \
for key, klass in form_classes.items()])
def forms_valid(self, forms):
return super(MultipleFormsMixin, self).form_valid(forms)
def forms_invalid(self, forms):
return self.render_to_response(self.get_context_data(forms=forms))
As you can see, when you inherit from this class, you can handle multiple forms simultaneously. Look at the gist's code and adapt it to your problem.
Look at this answer
I currently have a model form that submits an entered domain to the db.
The problem I'm encountering is, I need to save the currently logged in user's ID (PK from the django.auth table) when a domain is submitted to satisfy a PK-FK relationship on the db end.
I currently have:
class SubmitDomain(ModelForm):
domainNm = forms.CharField(initial=u'Enter your domain', label='')
FKtoClient = User.<something>
class Meta:
model = Tld #Create form based off Model for Tld
fields = ['domainNm']
def clean_domainNm(self):
cleanedDomainName = self.cleaned_data.get('domainNm')
if Tld.objects.filter(domainNm=cleanedDomainName).exists():
errorMsg = u"Sorry that domain is not available."
raise ValidationError(errorMsg)
else:
return cleanedDomainName
and views.py
def AccountHome(request):
if request.user.is_anonymous():
return HttpResponseRedirect('/Login/')
form = SubmitDomain(request.POST or None) # A form bound to the POST data
if request.method == 'POST': # If the form has been submitted...
if form.is_valid(): # If form input passes initial validation...
domainNmCleaned = form.cleaned_data['domainNm'] ## clean data in dictionary
clientFKId = request.user.id
form.save() #save cleaned data to the db from dictionary`
try:
return HttpResponseRedirect('/Processscan/?domainNm=' + domainNmCleaned)
except:
raise ValidationError(('Invalid request'), code='300') ## [ TODO ]: add a custom error page here.
else:
form = SubmitDomain()
tld_set = request.user.tld_set.all()
return render(request, 'VA/account/accounthome.html', {
'tld_set':tld_set, 'form' : form
})
The problem is it gives me an error of: (1048, "Column 'FKtoClient_id' cannot be null"), very odd thing happening, for the column FKtoClient, its trying to submit: 7L instead of 7(the PK of this user's record). Any ideas?
If someone can please help, I would really appreciate it
Firstly, remove FKtoClient from your form. You need to set the user in your view where you can yes the request object. It's not possible to set an attribute on the form that automatically sets the current user.
When instantiating your form, you can pass a tld instance which already has the user set.
def AccountHome(request):
# I recommend using the login required decorator instead but this is ok
if request.user.is_anonymous():
return HttpResponseRedirect('/Login/')
# create a tld instance for the form, with the user set
tld = Tld(FKtoClient=request.user)
form = SubmitDomain(data=request.POST or None, instance=tld) # A form bound to the POST data, using the tld instance
if request.method == 'POST': # If the form has been submitted...
if form.is_valid(): # If form input passes initial validation...
domainNm = form.cleaned_data['domainNm']
form.save() #save cleaned data to the db from dictionary
# don't use a try..except block here, it shouldn't raise an exception
return HttpResponseRedirect('/Processscan/?domainNm=%s' % domainNm)
# No need to create another form here, because you are using the request.POST or None trick
# else:
# form = SubmitDomain()
tld_set = request.user.tld_set.all()
return render(request, 'VA/account/accounthome.html', {
'tld_set':tld_set, 'form' : form
})
This has an advantage over #dm03514's answer, which is that you can access the user within form methods as self.instance.user if required.
If you want to Require that a user be logged in to submit a form, you could do something like:
#login_required # if a user iS REQUIRED to be logged in to save a form
def your_view(request):
form = SubmitDomain(request.POST)
if form.is_valid():
new_submit = form.save(commit=False)
new_submit.your_user_field = request.user
new_submit.save()
You can get the logged in user from the request object:
current_user = request.user
In the Django app I am building I would like to have the user creation process go as follows: As user signs up, if valid is then redirected to create a LIST object, and if valid is then redirected to what will be a dashboard for the LIST object just created. My views.py are as follows:
def user_signup(request):
if request.method == 'POST':
form = forms.UserSignupForm(data=request.POST)
if form.is_valid():
user = form.save()
g = Group.objects.get(name='test_group')
g.user_set.add(user)
# log user in
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, u'Welcome to Social FollowUp')
return redirect('user_create')
else:
form = forms.UserSignupForm()
return TemplateResponse(request, 'user_signup.html', {
'form': form,
})
#login_required
#permission_required('')
def user_create(request):
if request.method == 'POST':
list_form = forms.ListForm(request.POST)
if list_form.is_valid():
list_create = list_form.save()
messages.success(request, 'List {0} created'.format(list_create.list_id))
return redirect('user_dashboard')
else:
list_form = forms.ListForm()
return TemplateResponse(request, 'dashboard/create.html', {'list_form': list_form, })
def user_dashboard(request, list_id):
try:
list_id = models.List.objects.get(pk=list_id)
except models.List.DoesNotExist:
raise Http404
return TemplateResponse(request, 'dashboard/view.html', {'list_id': list_id})
My urls.py for these views is as follows:
url(r'user/signup/$', views.user_signup, name='user_signup'),
url(r'u/dashboard/(?P<list_id>\d+)/$', views.user_dashboard, name='user_dashboard'),
url(r'u/list/create/$', views.user_create, name='user_create'),
When I try to run through the process, the first two views work correctly. However when I redirect to the user_dashboard I get the following error:
Reverse for 'user_dashboard' with arguments '' and keyword arguments '{}' not found.
which sites this:
return redirect('user_dashboard')
I'm assuming this has something to do with me not passing in a list_id, however, even when I tried to pass in a hardcoded value it did not work (like this):
return redirect('user_dashboard', {'list_id': 2})
What am I doing wrong here?
Try:
return redirect(reverse('user_dashboard', args=(2,)))
Your code
return redirect('user_dashboard')
would not work because in your url pattern, you have
url(r'u/dashboard/(?P<list_id>\d+)/$', views.user_dashboard, name='user_dashboard'),
which requires list_id as a parameter.