django-ckeditor :data not loading in the Form - python

I'm Using Django-ckeditor as a model form widget.I have been able to able to save data using the model-form.
Now that I want to edit any saved data the form does not load the data onto the CKeditor.
Django 1.10 Python 3.5 Windows 7 64bit
forms.py
class templateform(forms.ModelForm):
class Meta:
model = presciptiontemplates
fields = ['template', 'templateid', ]
widgets = {
'template': CKEditorWidget(),
}
labels = {
"templateid": _("Patient ID"),
}
views.py
def get_template(request, tid):
template = presciptiontemplates.objects.get(templateid=tid)
form = templateform(request.POST, instance=template)
if form.is_valid():
form = form.save(commit=False)
form.patientid = tid
form.save()
else:
form = templateform(request.POST, instance=template)
return render(request, 'presapp/viewtemplate.html',{'form': form})
HTML
<div id="preview-content">
<form method="post" style="margin-top:20px;">
{% csrf_token %}
{{ form.media }}
{{ form|safe }}
<div class="" style="margin-top:20px ;">
<button class="btn waves-effect waves-light left" type="submit">Submit
<i class="material-icons right">add_circle</i
</button>
</form>
</div>
</div>

Change {{ form|safe }} to {{ form.as_p }}
<div id="preview-content">
<form method="post" style="margin-top:20px;">
{% csrf_token %}
{{ form.media }}
{{ form.as_p }}
<div class="" style="margin-top:20px ;">
<button class="btn waves-effect waves-light left" type="submit">Submit
<i class="material-icons right">add_circle</i
</button>
</form>
</div>
</div>

Related

Django UpdateView Bootstrap Modal - i've got empty form in modal window

I've got empty Bootstrap modal form with Django UpdateView(CBV)
The most important question without using js , I will not be able to display data in a modal window? (I only use bootstrap.bundle.min.js in base.html)
Modal window show fields of empty form
view.py
class HistoryPamentsByService(ListView):
model=Payments
form_class=PaymentsForm
template_name ='myflat/history_by_service.html'
context_object_name='flats'
slug_url_kwarg = 'slug'
def get_context_data(self, **kwargs):
context=super().get_context_data(**kwargs)
form=PaymentsForm()
payments=Payments.objects.filter(flats_id=self.kwargs['flats_id'])
context['form']=form
return context
def get_form(self,*args,**kwargs):
super().get_form(*args, **kwargs)
form=PaymentsForm()
return form
def get_queryset(self):
return Payments.objects.filter(slug=self.kwargs['slug'],flats_id=self.kwargs['flats_id'])
class UpdatePayments(UpdateView):
model=Payments
pk_url_kwarg='pk'
template_name='myflat/update_modal.html'
context_object_name='name_flat'
fields=['name_service','amount_of_bill',
'amount_of_real',
'date_of_bill',
'date_of_payment',
'status_payment',
'comments',
'bill_save_pdf']
def get_success_url(self):
return reverse('HistoryPamentsByService',
kwargs={'slug':self.object.slug,
'flats_id': self.object.flats_id})
urls.py
urlpatterns = [ path('history_by_service/<slug:slug>/<int:flats_id>/',
HistoryPamentsByService.as_view(),name='HistoryPamentsByService'),
path('UpdatePayments/<int:pk>/',UpdatePayments.as_view(),name='UpdatePayments'),
]
template
history_by_service.html (for ListView)
{%extends "base.html"%}
{%block content%}
{% for flat in flats %}
<tr>
<td scope="row">{{ forloop.counter }} </td>
<td>{{flat.name_service}}</td>
<td>{{flat.amount_of_bill}}</td>
<td>{{flat.amount_of_real}}</td>
<td>{{flat.date_of_bill}}</td>
<td>{{flat.date_of_payment}}</td>
<td>{{flat.get_status_payment_display}}</td>
<td>{{flat.comments}}</td>
<td>{{flat.bill_save_pdf}}</td>
<td>
<form method="post" action="{% url 'UpdatePayments' flat.pk %}" enctype="multipart/form-data">
{% csrf_token %}
<button type='button' class='btn btn-success btn-sm' id="update_modal"
data-bs-toggle="modal" data-bs-target="#update_modal{{flat.pk}}">
<i class="fa-regular fa-pen-to-square fa-fw"></i>Edit</button>
{% include "myflat/update_modal.html" %}
</form>
{% endfor %}
{% endblock content %}
template
update_modal.html
<div class="modal fade" id="update_modal{{flat.pk}}" data-bs-backdrop="static"
data-bs-keyboard="false" tabindex="-1" aria-labelledby="update_modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" style="width:auto">
<div class="modal-header">
<h5 class="modal-title " id="update_modalLabel">{{flat.name_flat}}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form method="post" action="{% url 'UpdatePayments' flat.pk %}" enctype="multipart/form-data">
<div class="modal-body">
{% csrf_token %}
{% for field in form %}
{{field}}
{% endfor %}
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" >
<i class="fa-solid fa-trash fa-fw" ></i>Save</button>
<button type="button" class="btn btn-warning"
data-bs-dismiss="modal">
<i class="fa-regular fa-circle-xmark"></i>Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
I try add in UpdatePayments(UpdateView) next code:
class UpdatePayments(UpdateView):
model=Payments
pk_url_kwarg='pk'
form_class=PaymentsForm
template_name='myflat/update_modal.html'
context_object_name='name_flat'
def get_context_data(self, **kwargs):
context= super().get_context_data(**kwargs)
obj=Payments.objects.get(pk=self.kwargs['pk'])
form=PaymentsForm(self.request.POST or None ,instance=obj)
context['form']=form
return context
but still nothing in Modal is empty fields!!!
What's wrong, any helps,please!!!

Django forms not returning result or errors

I am trying to use a Django form for a login page, but the form is returning False whenever I call form.is_valid(). I tried to print the errors in the console and in the HTML file but there's nothing displaying. I tried to get data from the form with form["email"].value() and it's returning None, even when I input data into the email field.
Here's views.py:
def postlogin(request):
form = BootstrapAuthenticationForm(request.POST)
# This prints out None into the console
print(form["email"].value())
if form.is_valid():
# This code never runs! Even when there are no errors in the form fields!
return render(request, "app/home.html")
# If form is invalid, return to login page
# This always runs, meaning form.is_valid() keeps being false!
return render(request,"app/login.html", {"form":form})
Here's my forms.py:
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
class BootstrapAuthenticationForm(AuthenticationForm):
"""Authentication form which uses boostrap CSS."""
email = forms.CharField(max_length=254,label=('Email'),
widget=forms.TextInput({
'class': 'form-control',
'placeholder': 'Email'}))
password = forms.CharField(label=("Password"),
widget=forms.PasswordInput({
'class': 'form-control',
'placeholder':'Password'}))
Here's my login.html:
{% extends "app/layout.html" %}
{% block content %}
<h2>{{ title }}</h2>
<div class="row">
<div class="col-md-8">
<section id="loginForm">
<form action="/postlogin/" method="post" class="form-horizontal">
{% csrf_token %}
<h4>Use a local account to log in.</h4>
<hr />
<div class="form-group">
<label for="id_username" class="col-md-2 control-label">{{form.email.label}}</label>
<div class="col-md-10">
{{ form.email }}
</div>
</div>
<div class="form-group">
<label for="id_password" class="col-md-2 control-label">{{form.password.label}}</label>
<div class="col-md-10">
{{ form.password }}
</div>
</div>
<div class="form-group">
<label for="id_password" class="col-md-2 control-label">{{form.test.label}}</label>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="hidden" name="next" value="/" />
<input type="submit" value="Log in" class="btn btn-default" />
</div>
</div>
<!-- Nothing below shows even when form.is_valid() is false -->
{% if form.errors %}
<p class="validation-summary-errors">Please enter a correct user name and password.</p>
{% endif %}
{% if form.non_field_errors %}
<p class="validation-summary-errors">Please enter a correct user name and password.</p>
{% endif %}
</form>
</section>
</div>
<div class="col-md-4">
<section id="socialLoginForm"></section>
</div>
</div>
<!-- Again, none of this shows in the HTML file even when form.is_valid() is False -->
{% for error_field, error_message in form.errors.items %}
{{ error_field|striptags }}: {{ error_message|striptags }}
{% endfor %}
{% endblock %}
if form.is_valid():
# after validating form you can print field value using (cleaned_data) method
print(form.cleaned_data['email'])
return render(request, "app/home.html")

Submit django form in a modal popup

I render my form inside a modal:
view:
#login_required
def task_edit(request, pk):
member = get_object_or_404(Tasks, pk=pk)
if request.method == "POST":
form = TasksForm(request.POST or None, instance=member)
if form.is_valid():
reg = form.save(commit=False)
reg.save()
return HttpResponse(
'<script type="text/javascript">window.close();</script>')
else:
form = TasksForm(instance=member)
return render(request, 'TaskProj/task_edit.html', {'form': form})
my html rendered in a modal popup:
{%load staticfiles %}
<div class="row">
<div class="col-lg-12">
<div class="panel">
<div class="content-box">
<h3 class="content-box-header bg-primary">
<span class="icon-separator">
<i class="glyph-icon icon-tasks"></i>
</span>
<span class="header-wrapper">
Eidt Tasks </span>
</span>
</h3>
<div class="panel">
<div class="panel-body">
<form method="POST" id="form" class="form-horizontal bordered-row" autocomplete="off">
{% csrf_token %}
<div class="example-box-wrapper">
<div class="form-group">
{{ form.as_p }}
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Salva</button>
</div>
</div>
</form>
<script type="text/javascript">
$(document).on('click','.submit',function(){
$( "#form" ).submit();
});
</script>
{% endblock %}
This form is rendered inside a modal popup.
I try to save, it close modal but not save form.
I think there is a problem with submit button...
Any idea?
TY
you need to declare an action attribute with the url to your function that handles the specific form in views.py. So that the form knows where to go, and be handled:
<form method="POST" id="form" class="form-horizontal bordered-row" action="{% 'task_edit' your-object.pk %}" autocomplete="off">
{% csrf_token %}
<div class="example-box-wrapper">
<div class="form-group">
{{ form.as_p }}
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Salva</button>
</div>
</div>
</form>

Django - Formset created dynamically not saving

I've created a CreateView form with a Parent (named 'Entrada') model and (multiple) Children models (named 'BalaMateriesPrimeres') as formset. Those formset are created dynamically with a JS I've created so I can add as many children I want (instead of adding one by one with elo80ka dynamic formset plugin). But the problem is that the formset is invalid. When print the formset at the 'def post' method, I get the html tags but the 'value' field of each one is empty. This is the relevant code:
forms.py
class EntradaForm(ModelForm):
class Meta:
model = Entrada
exclude = ()
class BalaMateriesPrimeresForm(ModelForm):
class Meta:
model = BalaMateriesPrimeres
fields = ['quilos', 'material', 'cost_unitari']
BalaMateriesPrimeresFormSet = inlineformset_factory(Entrada, BalaMateriesPrimeres, form=BalaMateriesPrimeresForm, can_delete=True, extra=1)
views.py
class EntradaCreateUpdateView(LoginRequiredMixin, UpdateView):
model = Entrada
form_class = EntradaForm
formset_class = BalaMateriesPrimeresFormSet
def get_context_data(self, **kwargs):
data = super(EntradaCreateUpdateView, self).get_context_data(**kwargs)
if self.request.POST:
data['bales_materies_primeres'] = BalaMateriesPrimeresFormSet(self.request.POST)
data['materials'] = Material.objects.all()
else:
data['bales_materies_primeres'] = BalaMateriesPrimeresFormSet()
data['materials'] = Material.objects.all()
return data
def get_object(self):
self.creating = 'pk' not in self.kwargs
if self.creating:
return None # Sucess
else:
obj = super().get_object()
return obj
def post(self, request, *args, **kwargs):
form = self.get_form()
formset = BalaMateriesPrimeresFormSet(request.POST, prefix='bales_materies_primeres')
if form.is_valid() and formset.is_valid():
return self.form_valid(form, formset)
else:
return self.form_invalid(form, formset)
def form_valid(self, form, formset):
self.object = form.save()
for fmset in formset:
fmset.save()
return super(EntradaCreateView, self).form_valid(form)
form.html
<form class="own-form" action="" method="post">
{% csrf_token %}
{% for hidden_field in form.hidden_fields %}
{{ hidden_field }}
{% endfor %}
<h2 class="text-center text-header"> Crear una nova entrada</h2>
<!-- Formulari d'entrada -->
<div class="form-group">
{% for field in form.visible_fields %}
<div class="form-group row">
<div class="col-4 text-center">{{ field.label_tag }}</div>
<div class="col-8">{{ field }}</div>
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
</div>
{% endfor %}
</div>
<!-- /Formulari d'entrada -->
<hr>
<!-- Formulari de Material -->
<div class="form-group form-material-box row form-0">
<div class="col-3 text-center">
<label>Pes aproximat: </label>
<input type="number" id="kg_0">
</div>
<div class="col-3 text-center">
<label>Bales a crear: </label>
<input type="number" id="num_boxes_0">
</div>
<div class="col-3 text-center">
<label>Material: </label>
<br>
<select name="item_id" id="material_0">
{% for material in materials %}
<option value="{{ forloop.counter }}">{{ material }}</option>
{% endfor %}
</select>
</div>
<div class="col-3 text-center">
<button type="button" id="create_boxes_0" class="btn btn-danger">Crea</button>
</div>
<!-- Nested forms with desired number of boxes -->
<div id="nested_forms_0">
{{ bales_materies_primeres.management_form }}
{% for bala in bales_materies_primeres %}
<div class="row" id="box_0">
<div class="col-3 text-center">
<h5>Bala #1: </h4>
</div>
<div class="col-2 text-center">
{{ bala.quilos }}
</div>
<div class="col-2 text-center" >
{{ bala.material }}
</div>
<div class="col-2 text-center" >
{{ bala.cost_unitari }}
</div>
<div class="col-3 text-center">
<button type="button" id='remove_box_0' class="btn btn-danger">Elimina Bala</button>
</div>
{% endfor %}
</div> <!-- /Bala form -->
</div> <!-- /Nested forms -->
</div> <!-- /Form -->
<!-- /Formulari de Material -->
<p>
<input id="crear" class="btn btn-secondary btn-lg btn-block btn-option btn-form" type="submit" value="Crear" />
</p>
javascript code:
https://pastebin.com/i87mqAaG
What I've tried:
-Yes, I've checked the TOTAL_FORMS value in the dev tools of Chrome. Also all the info is there as Django debug toolbar says
-When I print the formset right after getting it, it returns the HTML structure without values
-If I print the kwargs at the def post method I don't get anything.
I don't know what I'm missing but I had this problem for days.

Django - How to delete an article?

I'm trying to create a button on the framework django that let me delete my own article on my blog. I tried to create a code for this functionality, but it doesn't work.
views.py
if(request.GET.get('delete')): #if the button is clicked
delete_article = get_object_or_404(Article, id=id)
if request.POST:
form = DeleteNewForm(request.POST, request.FILES)
if form.is_valid():
delete_article.delete()
return HttpResponseRedirect("/")
template.html
<form enctype='multipart/form-data' action="." method="post" class="form" autocomplete="off" autocorrect="off">
{% csrf_token %}
<div class="form-group">TITRE
{{ form.title.errors }}
{{ form.title }}
</div>
<div class="form-group">CONTENU
{{ form.media }}
{{ form.contenu.errors }}
{{ form.contenu }}
</div>
<div class="form-group">
{{ form.image.errors }}
{{ form.image }}
</div>
<input type="submit" class="btn btn-default" value="Edit Article"/>
<input type="submit" class="btn btn-default" value="Delete Article" name="delete">
</form>
Here is what happen when I submit the form : I am not redirected on the index as it should redirect me and the article has not been deleted.
Is there a problem which don't let me delete my article in these lines?
I have no idea what you're doing in your views or in your template. But if I want to delete something, I just define a separate view for that.
# views.py
from django.views.generic.base import View
class DeleteView(View):
def post(self, request *args, **kwargs):
article = get_object_or_404(id=request.POST['article_id'])
# perform some validation,
# like can this user delete this article or not, etc.
# if validation is successful, delete the article
article.delete()
return HttpResponseRedirect('/')
Your template should be like this:
<form action="/url/to/delete/view/" method="POST">
{% csrf_token %}
<input type="hidden" value="{{ article.id }}">
<input type="submit" value="Delete">
</form>

Categories