I've come a cross a lot of tutorials regarding how to setup a class based view for ajax. Example:
class JoinFormView(FormView):
form_class = JoinForm
template_name = 'forms/ajax.html'
success_url = '/form-success/'
def form_valid(self, form):
response = super(JoinFormView, self).form_valid(form)
if self.request.is_ajax():
print(form.cleaned_data)
data = {
'message': "Successfully submitted form data."
}
return JsonResponse(data)
else:
return response
I'm wondering how would insert the required code for ajax into this function based view. Does the code required depend on whether or not I want to pull from or write to the db asynchronously?
def my_func_view(request):
template = 'accounts/profile.html'
form = Form123(request.POST or None)
if request.method == 'POST':
if form.is_valid():
instance = form.save(commit=True)
return redirect('/accounts/profile/')
else:
messages.error(request, 'There was an error.')
context = {'form': form,}
return render(request, template, context)
else:
context = {'form': form,}
return render(request, template, context)
Thanks for your help!
you do the same thing for the function based view too..
from django.http import JsonResponse
def my_func_view(request):
template = 'accounts/profile.html'
form = Form123(request.POST or None)
if request.is_ajax():
if form.is_valid():
instance = form.save(commit=True)
return JsonResponse({'status':'data'})
else:
messages.error(request, 'There was an error.')
return JsonResponse({'status':'data'})
else:
context = {'form': form,}
return render(request, template, context)
Related
I am trying to convert a function based view to a class based view. I've done it with the CreateView but the UpdateView is giving me grief. It won't take my update. I can get the view to take my update, but it doesn't save it.
Here's my function based view:
def update_task_update_view(request, pk):
task = Task.objects.get(id=pk)
form = TaskForm(request.POST or None, instance=task)
if request.method == "POST":
if form.is_valid():
form.save()
return redirect("MyTasks:task_detail", pk=task.id)
context = {
"form": form,
"task": task
}
return render(request, "partials/task_form.html", context)
And here was my attempt at a Class Based View.
class UpdateTaskUpdateView(LoginRequiredMixin,UpdateView):
model = Task
form_class = TaskForm
template_name = 'partials/task_form.html'
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
task = form.save()
task.save()
return redirect("MyTasks:task_detail", pk=task.id)
else:
return render(request, "partials/task_form.html", {
"form":form
})
This function based view is working fine, no issues with it.
Thanks to an assist from FB...Travis Tucker....
I did this instead and it seems to be working fine...
class UpdateTaskUpdateView(LoginRequiredMixin,UpdateView):
model = Task
form_class = TaskForm
template_name = 'partials/task_form.html'
def form_valid(self, form):
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
task = form.save()
task.save()
return redirect("MyTasks:task_detail", pk=task.id)
else:
return render(request, "partials/task_form.html", {
"form":form
})
I am trying to convert my Form which is laid out in a function to be in a class based view:
Here is what I have reach out.
Function:
def add_business_plan(request):
info = Info.objects.all()
if request.method == 'POST':
form = infoForm(request.POST)
if form.is_valid():
form.save()
business_name = form.cleaned_data.get('businessName')
info_id = form.instance.id
messages.success(request, f'PDF created for {business_name}!, No.({info_id})')
return render(request, 'businessplan/businessplan.html', {'form': form, 'successful_submit': True})
else:
form = infoForm()
print(form.errors)
return render(request, 'businessplan/businessplan.html',
{
'form': form,
'successful_submit': False,
"Info": info
}
)
here is form
class infoForm(forms.ModelForm):
class Meta:
model = Info
fields = [
'businessName',
]
widgets = {
'problem_summary': RichTextFormField(),
}
You may try the following:
class AddBusinessPlan(View):
template_name = 'businessplan/businessplan.html'
form_class = infoForm
def get(self, request, *args, **kwargs):
form = self.form_class
print(form.errors)
return render(request, template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
form.save()
business_name = form.cleaned_data.get('businessName')
info_id = form.instance.id
messages.success(request, f'PDF created for {business_name}!, No.({info_id})')
return render(request, self.template_name, {'form': form, 'successful_submit': True})
else:
return render(request, self.template_name, {'form': form})
Help needed. I have no idea what is error-ed in the line of code. The traceback points to the form.save() line.
#views.py
class TestimonyFormFunction(View):
form = TestimonyForm
template = 'variablized_form.html'
#method_decorator(login_required)
def get(self, request):
form = self.form_class(None)
return render(request, self.template, {'form':form})
def post(self, request):
if request.method == 'POST':
form = TestimonyForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return render(request, 'testimony_post.html', {'Testimony':Testimony})
else:
form = TestimonyForm()
return render(request, 'variablized_form.html', {'form': form})
#forms.py
class TestimonyForm(forms.Form):
body = forms.CharField(label='Details', widget=forms.Textarea)
I'd like to redirect to a detail view after I successfully submitted a form and created the object.
My view.py
class ObjectCreateView(CreateView):
model = Object
form_class = ObjectCreateForm
template_name = 'frontend/base/object_create.html'
def get(self, request, *args, **kwargs):
form = ForecastConfigurationCreateForm()
form.fields['status'] = ModelChoiceField(queryset=ObjectStatus.get_object_status_list(self))
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
self.fcc_form = form.save(commit=True)
messages.add_message(self.request, messages.INFO, 'Good job!')
return render_to_response(reverse(viewname='object_detail', kwargs={'uuid': self.fcc_form.uuid}))
else:
messages.add_message(self.request, messages.ERROR, 'Error!')
return render(request, self.template_name, {'form': form})
The error message is:
TemplateDoesNotExist at /object_create/
/object_detail/3a3d6279-1531-45d4-9ba9-b691886facf4/
And the URL that's calling is:
http://test.com:8000/object_create/?next=/object_detail/a5b2a693-6f90-4b98-b9a2-fc2fe6a90995/
what I want it to be is
http://test.com:8000/object_detail/a5b2a693-6f90-4b98-b9a2-fc2fe6a90995/
Thanks!
Instead of trying to render the page, use HttpResponseRedirect instead:
class ObjectCreateView(CreateView):
...
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
self.fcc_form = form.save(commit=True)
messages.add_message(self.request, messages.INFO, 'Good job!')
return HttpResponseRedirect(reverse('object_detail', kwargs={'uuid': self.fcc_form.uuid}))
else:
messages.add_message(self.request, messages.ERROR, 'Error!')
return render(request, self.template_name, {'form': form})
just stumbled across the answer. The return should be:
return redirect(reverse('object_detail', kwargs={'uuid': self.fcc_form.uuid}))
Why doesn't this work and it returns ValueError instead? I'm trying to get an input from the user and then, depending on the choice the user makes, render a specific view. If i move return redirect() back inside post function it does work.
class Choice(View):
form_class = SomeForm
template_name = 'app/object_form.html'
def get(self,request,*args, **kwargs):
form = self.form_class()
return render (request, self.template_name, {'form':form})
def post(self,request,*args,**kwargs):
form = self.form_class(request.POST)
if form.is_valid():
self.redirect_to_createform(request,form.cleaned_data['choice'])
else:
print('form not valid')
print(form.errors)
return render (request, self.template_name, {'form':form})
def redirect_to_createform(self, request, option):
print(option)
## Here i should have some logic to redirect to different views depending on the `option`
return redirect('to_somewhere')
Edit - I understand what the error means but how can i achieve the above mentioned goal.
You are missing return statement as below
if form.is_valid():
return self.redirect_to_createform(request,form.cleaned_data['choice'])