I have a DetailView Based on a model ( A ) and on the same template I have a ModelFormView from a model B which has FK to model (A)
The data from form doesn't get saved to the database.
This is the DetailView:
class LocationView(DetailView):
template_name = "base/stocks/location.html"
model = LocationStock
def get_context_data(self, **kwargs):
context = super(LocationView, self).get_context_data(**kwargs)
context['form'] = OutsModelForm
return context
def get_object(self):
id_ = self.kwargs.get("id")
return get_object_or_404(LocationStock, id=id_)
This is the FormView:
class OutsAdd(FormView):
form_class = OutsModelForm
success_url = reverse_lazy('base:dashboard')
def form_valid(self, form):
return super().form_valid(form)
This is the url.py:
path('locations/<int:id>', LocationView.as_view(), name='location-detail'),
path('locations/outs', require_POST(OutsAdd.as_view()), name='outs-add'),
This is the template:
<form method="POST" action="{% url 'outs-add' %}" >
<div class="modal-content">
{% csrf_token %}
{% render_field form.quantity placeholder="Quantity"%}
{% render_field form.id_year placeholder="Year"%}
{% render_field form.id_location placeholder="ID Location"%}
</div>
<div class="modal-footer">
<input class="modal-close waves-effect waves-green btn-flat" type="submit" value="Save">
</div>
</form>
The data gets POSTED in the /locations/outs but is not saving to the actual database.How can I save it ?
The functionality of Django's FormView is really only meant to display a form on a GET request, show form errors in the case of form_invalid, and redirect to a new URL if the form is valid. In order to persist the data to the database you have two options. First you can simply call form.save() in your FormView:
class OutsAdd(FormView):
form_class = OutsModelForm
success_url = reverse_lazy('base:dashboard')
def form_valid(self, form):
form.save()
return super().form_valid(form)
Or, you can use the generic CreateView. Django's CreateView is similar to a FormView except it assumes it's working with a ModelForm and calls form.save() for you behind the scenes.
Related
I used to send form as content in function-base-view and I could use for loop to simply write down fields and values like:
{% for x in field %}
<p>{{ x.label_tag }} : {{ x.value }} </p>
I don't remember whole the way so maybe I wrote it wrong but is there anyway to do this with class-based-views, because when I have many fields its really hard to write them 1by1
Not entirely sure if this is what you need. But still I will try to answer. I took an example with class AuthorDetail(FormMixin, DetailView) as a basis. In get_context_data saved the form itself. In the template, first I displayed the form, then the value from the bbs model and requested
form.message.label_tag. To get the tag, I looked at this documentation.
In the class, replace the Rubric model with your own. In the template path: bboard/templ.html replace bboard with the name of your application where your templates are located.
views.py
class Dw(FormMixin, DetailView):
model = Rubric
template_name = 'bboard/templ.html'
form_class = TestForm
context_object_name = 'bbs'
def get_context_data(self, **kwargs):
context = super(Dw, self).get_context_data(**kwargs)
context['form'] = self.get_form()
print(77777, context['form']['message'].label_tag())
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
forms.py
class TestForm(forms.Form):
message = forms.CharField()
templates
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="adding">
</form>
<h2>{{ bbs }}</h2>
<h2>{{ form.message.label_tag }}</h2>
urls.py
urlpatterns = [
path('<int:pk>/', Dw.as_view(), name='aaa'),
]
OK so I'm trying to create a page that will have a search form of Well,
I get the contents of the search in the page ex: (http://127.0.0.1:8000/wellsheet/ODN20)
I used this code
urls.py file
path('wellsheet/<slug:Evt_id>', views.wellsets, name='WellSheetg'),
views.py
def wellsets(request, Evt_id):
serchedWl = WellSheets.objects.filter(WellID__WellID__exact=Evt_id)
context ={
'title': 'Eventstopost',
'Wellslist':serchedWl,
'WIDSHT':Evt_id,
}
return render(request, 'Home/WELLINFO/W_TchD/wellshts.html', context)
in addition to this page I want to add another well ,and I have a model form to add in same page using crispy.
urls.py
path('wellsheet/<slug:WeelN>/', views.welshetad2.as_view(), name='AddWellSheet'),
views.py
class welshetad2(LoginRequiredMixin, CreateView):
model = WellSheets
template_name = 'Home/WELLINFO/W_TchD/wellshts.html'
form_class = UploadWSF2
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
but in my page I can't render the crispy form
<div class="border p-3 mb-3 mt-3 w3-round-large w3-light-grey border-dark">
<form method="POST">
{% csrf_token %}
<div class="form-row"><div class="form-group mb-0">
{{ form.as_p }}
</div></div>
this is my page
page
My goal is to see a page like this
My Goal
Hi the problem is solved by using one def as:
views.py
def wellsets(request, pk):
serchedWl = WellSheets.objects.filter(WellID__WellID__exact=pk)
form= UploadWSF2(request.POST or None)
context ={
'title': 'Wellssht',
'Wellslist':serchedWl,
'WIDSHT':pk,
'form':form,
}
return render(request, 'Home/WELLINFO/W_TchD/wellshts.html', context)
and the page will show tow results a Form and results of search
I am inheriting from CreateView to create a form for a model.
class NewBlogView(CreateView):
form_class = BlogForm
template_name = 'blog_settings.html'
def form_valid(self, form):
blog_obj = form.save(commit=False)
blog_obj.owner = self.request.user
blog_obj.slug = slugify(blog_obj.title)
blog_obj.save()
return HttpResponseRedirect(reverse('home'))
Here is my template code:
{% extends 'base.html' %}
{% block content %}
<h1>Create New User</h1>
<form action='' method='post'>{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Create Account' />
</form>
{% endblock %}
At this moment everything is working as expected, but when I am overriding get_context_data() my title field is disappearing.
class NewBlogView(CreateView):
form_class = BlogForm
template_name = 'blog_settings.html'
def form_valid(self, form):
blog_obj = form.save(commit=False)
blog_obj.owner = self.request.user
blog_obj.slug = slugify(blog_obj.title)
blog_obj.save()
return HttpResponseRedirect(reverse('home'))
def get_context_data(self, **kwargs):
ctx = super(NewBlogView, self).get_context_data(**kwargs)
print(ctx)
return ctx
I am thinking although I am running the original get_context_data() form the function that I am inheriting, there is something that is going wrong when it comes to taking the field name from the form_class. Can someone help with that confusion that I have?
How to use context with class in CreateView in django?
Before i have:
#views.py
from django.views.generic import CreateView
from cars.models import *
def CreateCar(CreateView):
info_sended = False
if request.method == 'POST':
form = FormCar(request.POST, request.FILES)
if form.is_valid():
info_sended = True
form.save()
else:
form = FormCar()
ctx = {'form': form, 'info_sended':info_sended}
return render_to_response("create_car.html", ctx,
context_instance=RequestContext(request))
Now, a have, and try:
class CreateCar(CreateView):
info_sended = False
template_name = 'create_car.html'
model = Car
success_url = 'create_car' #urls name
def form_valid(self, form):
info_sended = True
ctx = {'form': form, 'info_sended':info_sended}
return super(CreateCar, self).form_valid(form)
My html page is:
<!-- create_car.html -->
{% extends 'base.html' %}
{% block content %}
{% if info_sended %}
<p>Data saved successfully</p>
<p>Show List</p>
{% else %}
<form class="form-horizontal" action="" method="post">
{% csrf_token %}
{% include "form.html" %}
<div class="col-md-offset-1">
<button class="btn btn-primary" type="submit">Add</button>
</div>
</form>
{% endif %}
{% endblock %}
You should define get_context_data() method in your class view. Update your code as
from django.shortcuts import render
class CreateCar(CreateView):
info_sended = False
template_name = 'create_car.html'
model = Car
success_url = 'create_car' #urls name
def form_valid(self, form):
self.info_sended = True
# Instead of return this HttpResponseRedirect, return an
# new rendered page
super(CreateCar, self).form_valid(form)
return render(self.request, self.template_name,
self.get_context_data(form=form))
def get_context_data(self, **kwargs):
ctx = super(CreateCar, self).get_context_data(**kwargs)
ctx['info_sended'] = self.info_sended
return ctx
You have to use get_context_data
class CreateCar(CreateView):
info_sended = False
template_name = 'create_car.html'
model = Car
success_url = 'create_car' #urls name
def form_valid(self, form):
self.info_sended = True
return super(CreateCar, self).form_valid(form)
def get_context_data(self, **kwargs):
ctx = super(CreateCar, self).get_context_data(**kwargs)
ctx['info_sended'] = self.info_sended
return ctx
If you see the django source CreateView inherits from BaseCreateView this one inherits from ModelFormMixin in turn this one inherits from FormMixin and this one inherits from ContextMixin and the only method this one defines is get_context_data.
Hope this helps you.
PD: This may be a bit confusing for better understanding of inheritance in Python feel free of read this article about MRO.
Since your are creating a new instance of a Car, there is no context for get_context_data because there is no object yet. I didn't test using Mixin to get the context from another class as suggested above, but that seems reasonable. However, if I can assume you want to use the basic CreateView, UpdateView and DeleteView, then I solved this by assuming I will have no context for CreateView. Then in my template I used an if to make the decision, such as:
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value={% if not buttonword %}Save{% else %}{{ buttonword }}{% endif %}>
</form>
In DeleteView I include:
context['buttonword'] = 'Delete'
In UpdateView I include:
context['buttonword'] = 'Update'
As I said, I do not set buttonword in CreateView. Hence, when the template logic is done, if buttonword is assigned, the word in it shows up in the button, otherwise Save shows up on the button.
I built a listview which works fine and gives me exactly what I want.
In the template of this ListView I declared a form that points to a CreateView.
The form is like so,
{% if user.is_authenticated %}
<form action="{% url 'post_wall' %}" method="POST">
{% csrf_token %}
<input type='text' name='body' />
<input type='hidden' name='from_user' value='{{ user.id }}' />
<input type='hidden' name='to_user' value='{{ to_user }}' />
<input type='submit' value='POST'/>
</form>
{% endif %}
the post_wall url corresponds to
url(r'accounts/post_wall', WallCreate.as_view(), name='post_wall'),
The url which contains the form is
url(r'accounts/wall/(?P<slug>\w+)/$', WallList.as_view(), name='wall'),
This calls the CreateView,
class WallCreate(CreateView):
model = WallPost
def get_success_url(self):
url = reverse('wall', kwargs={'slug': request.POST.to_user})
return HttpResponseRedirect(url)
This gives me a
TemplateDoesNotExist at /accounts/post_wall
users/wallpost_form.html
Shouldn't this be working properly as a post is sent to a CreateView? Or have I misunderstood something about CBVs?
Yes, but all the form process will have to be made by the ListView itself. That is simple, considering you can inherit the behaviour from ModelFormMixin. You will only need one url (to the list view). The template will look like:
{% if user.is_authenticated %}
<form action="" method="POST">
{% csrf_token %}
{{ form }}
<input type='submit' value='POST'/>
</form>
{% endif %}
And your view:
from django.views.generic.list import ListView
from django.views.generic.edit import ModelFormMixin
class ListWithForm(ListView, ModelFormMixin):
model = MyModel
form_class = MyModelForm
def get(self, request, *args, **kwargs):
self.object = None
self.form = self.get_form(self.form_class)
# Explicitly states what get to call:
return ListView.get(self, request, *args, **kwargs)
def post(self, request, *args, **kwargs):
# When the form is submitted, it will enter here
self.object = None
self.form = self.get_form(self.form_class)
if self.form.is_valid():
self.object = self.form.save()
# Here ou may consider creating a new instance of form_class(),
# so that the form will come clean.
# Whether the form validates or not, the view will be rendered by get()
return self.get(request, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
# Just include the form
context = super(ListWithForm, self).get_context_data(*args, **kwargs)
context['form'] = self.form
return context