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
Related
I have an update form to update information. Here problem is, product_title is updating but product_image is not working. Where is the problem that's for why the photo is not updating?
views.py:
def update_product(request,id):
product = Products.objects.get(pk=id)
form = update_product_info(request.POST or None, instance=product)
if request.method == 'POST' and form.is_valid():
form.save()
print(form.errors)
messages.success(request,"Successfully product information updated.")
return redirect("my_products")
context = {
'product':product,
"form":form
}
return render(request, "update_product.html", context)
update form:
class update_product_info(forms.ModelForm):
class Meta:
model = Products
fields = ('product_title','product_image')
widgets = {
'product_title':forms.TextInput(attrs={'class':'form-control', 'style':'font-size:13px;'}),
'product_image':forms.FileInput(attrs={'class':'form-control', 'style':'font-size:13px;'})
}
template:
<form action="" method="POST" class="needs-validation" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<div class="d-flex align-items-center">
<button type="submit" class="btn btn-outline-dark ms-auto" value="Update" style="font-size: 13px;">Add</button>
</div>
You should pass both request.POST and request.FILES to the form:
from django.shortcuts import get_object_or_404
def update_product(request, id):
product = get_object_or_404(Products, pk=id)
if request.method == 'POST':
form = update_product_info(request.POST, request.FILES, instance=product)
if form.is_valid():
form.save()
messages.success(request, 'Successfully product information updated.')
return redirect('my_products')
else:
form = update_product_info(instance=product)
context = {'product': product, 'form': form}
return render(request, 'update_product.html', context)
Note: It is often better to use get_object_or_404(…) [Django-doc],
then to use .get(…) [Django-doc] directly. In case the object does not exists,
for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using
.get(…) will result in a HTTP 500 Server Error.
Note: normally a Django model is given a singular name, so Product instead of Products.
Note: Usually a Form or a ModelForm ends with a …Form suffix,
to avoid collisions with the name of the model, and to make it clear that we are
working with a form. Therefore it might be better to use ProductInfoForm instead of
update_product_info.
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.
I have a index.html file which has the submit button. I want the functionality that when I click submit button, python function should get called in background but the rendering view of index.html should stay same. Right now every time I click on submit button a new copy of index.html is getting loaded. Here are my codes
index.html
<form action = "submit" method = "post">
<p>latitude <input type = "text" id = "Latbox" name = "Latbox" /></p>
<p>Longitdue <input type = "text" id = "Lonbox" name = "Lonbox" /b></p>
<p><input type = "submit" value = "submit" /></p>
</form>
My views.py file is as follow :
from django.shortcuts import render
from django.views.generic import TemplateView
class HomePageView(TemplateView):
def get(self, request, **kwargs):
return render(request, 'index.html', context=None)
def submit(request):
LAT=request.POST['Latbox']
LON= request.POST['Lonbox']
print (LAT, LON)
return render(request,'index.html',context=None)
I am new to django. Can I get some pointer or answer as to how to solve this.
Use the same view to perform both actions.
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<p><input type = "submit" value = "submit" /></p>
</form>
At forms.py:
class LocationForm(forms.Form):
latitude = form.CharField()
longitude = form.CharField()
Then at views.py you do something like this:
class HomePageView(TemplateView):
template_name = "index.html"
def get(self, request, **kwargs):
form = LocationForm()
return render(request, self.template_name, {"form": form})
def post(self, request, **kwargs):
form = LocationForm(request.POST)
if form.is_valid():
pass # do something with form.cleaned_data
return render(request, self.template_name, {"form": form})
It is not fully covered in the tutorial but take a look at forms and generic views.
My problem is not to show django form fields on template.It's silly but I just haven't found any solution.
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['name', 'email', 'text']
def __init__(self, content_type, id, *args, **kwargs):
super(CommentForm, self).__init__(*args, **kwargs)
self.content_type = content_type
self.id = id
def save(self, commit=True):
post_type = ContentType.objects.get_for_model(Post)
comment_type = ContentType.objects.get_for_model(Comment)
comment = super(CommentForm, self).save(commit=False)
if self.content_type == 'post':
comment.content_type = post_type
comment.post = self.id
else:
parent = Comment.objects.get(id=self.id)
comment.content_type = comment_type
comment.post = parent.post
comment.object_id = self.id
if commit:
comment.save()
return comment
my view:
def add_comment(request, content_type, id):
if request.method == 'POST':
data = request.POST.copy()
form = CommentForm(content_type, id, data)
if form.is_valid():
form.save()
return redirect(reverse('index'))
my add_comment template:
<form method="post" action="{% url 'add_comment' 'post' post.id %}">
{% csrf_token %}
{% if not user.is_authenticated %}
{{ form.name.label_tag }}
{{ form.name }}
{{ form.email.label_tag }}
{{ form.email }}
{% endif %}
{{ form.text.label_tag }}
{{ form.text }}<br>
<input type="submit" value="Comment" />
</form>
and I included like:
<button id="button" type="button">Add Comment</button>
<div id="post_comment_form">{% include 'articles/add_comment.html' %}</div>
</article> <!-- .post.hentry -->
why not django rendered form fields,despite of showing buttons?
EDIT:
I'm rendering form in post view.
def post(request, slug):
post = get_object_or_404(Post, slug=slug)
comments = Comment.objects.filter(post=post.id)
return render(request,
'articles/post.html',
{'post': post,
'form': CommentForm,
'comments': comments,
# 'child_comments': child_comments
}
)
You forgot to instantiate the form, change this line:
'form': CommentForm,
to this
'form': CommentForm(),
In your view, you're not sending any context variables to the template, so your 'form' object isn't available for your template to process.
For example, the following return statement will render your .html and pass along all local variables, this isn't necessarily the best option (how much do you want your template to have access to), but is simple:
from django.shortcuts import render
...
return render(request, "template.html", locals())
you can also pass a dictionary instead of all local variables. Here's the documentation for render
I have register function, it is displayed on every pages in my project using context_processors.
How to display errors if my form is not valid in my modal box in base.html?
Now errors is displayed in: /register/ subpage.
views.py
def UserRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/showcase/')
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username=form.cleaned_data['username'], email= form.cleaned_data['email'], password = form.cleaned_data['password'])
user.save()
klient = ClientProfile(user=user, name= form.cleaned_data['name'], address= form.cleaned_data['address'], zip_code=form.cleaned_data['zip_code'], city=form.cleaned_data['city'], tel= form.cleaned_data['tel'] )
klient.save()
return HttpResponseRedirect('/')
return render_to_response('registration.html', {'form':form}, context_instance=RequestContext(request))
else:
form = RegistrationForm()
context= {'form':form}
return render_to_response('registration.html', context, context_instance=RequestContext(request))
context_processors.py
from content.forms import *
def include_register_form(request):
form = RegistrationForm()
return {'register_form':form}
base.html
<div class="modalBox" id="modalRegister">
<div class="modalBox_iks"></div>
<div class="titleShowcase">Register</div>
<form method="POST" action="/register/">{%csrf_token%}
{{register_form}}
<input type="submit" value="Register">
</form>
</div>
It is possible?
You need to post your data with Ajax call, Showing errors in modal need Ajax call.
Or you can use third party app to enable Ajax form validation
what version of django are you using? If you are in django 1.5, use FormView.
view.py
class UserRegistration(FormView):
template_name = 'form_registration.html'
def render_to_response(self, context):
if self.request.user.is_authenticated():
return redirect('other_page')
return super(UserRegistration, self).render_to_response(context)
def form_valid(self, form):
# Here you know that you form is valid
user = User.objects.create_user(username=form.cleaned_data['username'], email=form.cleaned_data['email'], password = form.cleaned_data['password'])
user.save()
klient = ClientProfile(user=user, name= form.cleaned_data['name'], address= form.cleaned_data['address'], zip_code=form.cleaned_data['zip_code'], city=form.cleaned_data['city'], tel= form.cleaned_data['tel'] )
klient.save()
return redirect('home') #I'm not sure that this really redirect you
Now write a 'form_registration.html' template where you show the errors. see here
And in your 'base.html'
<div class="modalBox" id="modalRegister">
<div class="modalBox_iks"></div>
<div class="titleShowcase">Register</div>
<form method="POST" id="ajax_form"action="/register/">{%csrf_token%}
{% include "form_registration.html" with form=form %}
<input type="submit" id="ajax_form_submit"value="Register">
</form>
</div>
Now, for your ajax, you can use this jquery plug-in.
You can set the 'target' option to override with the server response
Maybe that javascript help you:
<script>
$('#modalRegister').click("#ajax_form_submit", function(event){
event.preventDefault();
$('#ajax_form').ajax_form(target:'#ajax_form').submit();
})
</script>
I've used that plugin, it works fine.
hope that help!