I have a basic django form template and it's in english. I would like to change the whole form to finnish. How do i do that?
forms,py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class rekkausform(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
register.html
{%extends "blogi/base.html"%}
{% load crispy_forms_tags %}
{%block content%}
<div class="content-section">
<form method="POST">
{%csrf_token%}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Liity</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Rekkkaa</button>
</div>
</form>
<div class="border-top pt-3">
<a class="text-muted">Joko sinulla on tili? Kirjaudu tästä </small>
</div>
</div>
{%endblock content%}
If you are going to create a register form
It's possible to use django-registration
Install django-registration and add it to INSTALLED_APPS setting.
Setting up the URLs.
Create the templates.
and in registration_form.html add your code, like what you have done in your register.html
Then in settings.py change LANGUAGE_CODE to the proper language
All the form, its labels, errors and helpers will translate to chosen language.
you just have to change the labels you need . for example you need to change the label of the username:
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
username = forms.CharField(
label = 'نام کاربری', #username in persion
required = True,
)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
Related
Hi So I have just set up summernote for the first time, however when I save all the HTML tags are displayed in another page where I am displaying the text. I want it to display the correct way without the HTML, thanks for any help :)
FORMS.PY
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title','content']
widgets = {
'content': SummernoteWidget(),
}
VIEWS.PY
class PostCreateView(CreateView):
model = Post
form_class = PostForm
Form HTML
<div class ='content-section'>
<form method="POST">
{% csrf_token %}
<fieldset class ="form-group">
<legend class ="border-bottom mb-4">Post 1</legend>
{{form|safe}}
</fieldset>
<div class="form-group">
<button class = "btn" type="submit">Post</button>
</div>
</form>
</div>
display Post HTML
{% extends 'guide/base.html' %}
{%block content%}
{% if post.author == user %}
Edit
Delete
{% endif %}
<div class = 'content'>
<h2>{{post.title}}</h2>
<p></p>
<p>{{ post.content }}</p>
</div>
{% endblock content %}
I didn't include the safe in the html so
{{post.content|safe}}
did not include because I thought you only include the safe in the form
I am building a CRUD with Laravel. Each category hasMany attachments and each attachment belongsTo a category.
In the category.edit view I want to give the user the possibility of deleting the attachments (singularly) from the Category. I tried this method but it did not work:
Registering route for the attachment:
Route::group(['middleware' => ['auth']], function () {
Route::delete('attachment/{id}', 'AttachmentController#delete')->name('attachment');
});
Handling the delete building the AttachmentController#delete method:
class AttachmentController extends Controller
{
public function delete($id) {
$toDelete = Attachment::findOrFail($id);
$toDelete->delete();
return redirect()->back();
}
}
In the CategoryController (edit method), I fetch the attachments linked to each category to be rendered inside the view:
public function edit($category)
{
$wildcard = $category;
$category = Category::findOrFail($wildcard);
$attachments = App\Category::findOrFail($wildcard)->attachments()->get()->toArray();
return view('category.edit', [
'category' => $category,
'attachments' => $attachments
]);
}
In the view, I render the attachment and the button to delete. I am fully aware of the error of having a form inside another form, nevertheless I do not know antoher approach to submit this delete request.
// update Category form
#foreach ($attachments as $attachment)
<div class="row">
<div class="col-4">
<img style="width: 100%;" src={{ $attachment['url'] }} alt="">
</div>
<div class="col-4">
<div>
<p class="general_par general_url">{{ $attachment['url'] }}</p>
</div>
</div>
<div class="col-4">
<form action="{{ route('attachment', $attachment['id']) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete Image</button>
</form>
</div>
</div>
<hr>
#endforeach
// end of update Category form
Should I build a deleteAttachment method inside the CategoryController? If so, how can I still submit the Delete request? Also, if any other Model in the future will have attachments, should I build a deleteAttachment method inside each controller? That is cumbersome. Thanks in advance
if you don't like to use form, then use tag:
<a class="btn btn-danger" href="{{ route('attachment', $attachment['id']) }}">Delete Image</a>
And redefine the route to Route::get(...)
(or maybe use ajax for POST method if that is required)
i'm fairly new to django, so couldn't find a way to implement the checkboxes with multiple select in to my custom modelforms and django admin. tried the django docs but still couldnt find solution?the image is my project form wherein the technologies field should have a checkbox with multiple select.
TIA
views.py
class ProjectCreate(CreateView):
model = Project
fields = ['projectid', 'title', 'description', 'startdate', 'enddate', 'cost', 'Project_type',
'employeeid', 'technologies', 'clientid', 'document']
class ProjectUpdate(UpdateView):
model = Project
fields = ['projectid', 'title', 'description', 'startdate', 'enddate', 'cost', 'Project_type',
'employeeid', 'technologies', 'clientid']
form-template.py
{% for fields in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ fields.errors }}</span>
</div>
<label class="control-label col-sm-2">{{ fields.label_tag }}</label>
<div class="col-sm-10">{{ fields }}</div>
</div>
{% endfor %}
We can implement is using django-multiselectfield
First install django-multiselectfield.
pip install django-multiselectfield
In Models.py, we need to import multiselectfield then use MultiSelectField as modal field & pass required arguments.
from django.db import models
from multiselectfield import MultiSelectField
MY_CHOICES = ((1, 'Value1'),
(2, 'Value2'),
(3, 'Value3'),
(4, 'Value4'),
(5, 'Value5'))
#choices can be a list also
class MyModel(models.Model):
#....
my_field = MultiSelectField(choices=MY_CHOICES,
max_choices=3,
max_length=3)
Now in admin panel when you open MyModel form you will see 5 check boxes out of which you can only select a maximum of 3 as defined max_choices=3
If you are rendering modelform using templates then you only need to specify the fields in Forms.py.
If you're getting dropdown data from another table then refer to this question
I've been unable to find a solution to my problem from searching. So I'd like to ask what might be wrong with my code. I'm trying to validate a form from forms.ModelForm but in my views function it won't pass the form.is_valid(). printing form.errors gives me:
<li>title<ul class="errorlist"><li>This field is required.</li></ul>
Model:
class Paper(models.Model):
title = models.CharField(max_length=100, help_text='Hello World!')
forms.FormModel
class eventCreateForm(forms.ModelForm):
class Meta:
Model = Paper
fields = ['title']
widgets = {
'title': forms.TextInput(attrs={'class' :'form-control', 'placeholder' : 'Place title'}),
}
Views
def create_paper(request):
context = {}
if request.method == 'POST':
form = paperCreateForm(request.POST or None, request.FILES or None)
if form.is_valid():
form_data = form.cleaned_data
t1 = form_data['title']
print(t1)
else:
context['create_paper_form'] = form
form_template = "user/paper-event-template.html"
return HttpResponse(render_to_string(form_template, {'context' : context}))
The form dosen't get validated, and in the else clause it'll pass the error when trying to retrieve it from the cleaned_data
I did try and print the form, and it shows:
<tr><th><label for="id_title">Title:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input class="form-control" id="id_title" maxlength="100" name="title" placeholder="Place Title" type="text" required /></td></tr>
But it dosen't contain any value, which I guess it should: I use a jax method for sending the forms data:
ajax
$('#create_paper_form_id').submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "{% url 'Eapp:create_paper' %}",
data: {
csrfmiddlewaretoken : '{{ csrf_token }}',
form_data : $('#create_paper_form_id').serializeArray(),
},
success: function (data) {
console.log(data);
$('.create-paper').html(data);
},
error: function() {
console.log('err');
}
});
});
html
<div class="create-paper">
<div class="container-fluid">
<form class="form" id="create_paper_form_id" novalidate="novalidate" action="{% url 'Eapp:create_event' %}" method="POST">
{% for field in create_paper_form %}
<div class="form-group">
<div class="col-xs-12">
{{ field.label_tag }}
</div>
<div class="col-xs-12">
{{ field }}
</div>
<div class="col-xs-6">
{{ field.help_text }}
</div>
<div class="col-xs-6">
{{ field.errors }}
</div>
</div>
{% endfor %}
<div class="form-group">
<div class="col-xs-6 col-sm-6 col-md-2 col-lg-2">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>
That's expected behaviour, the cleaned_data is only available on a valid form when there's actually cleaned data available.
The form.data is still available though, you can use that.
To quote the manual:
A Form instance has an is_valid() method, which runs validation
routines for all its fields. When this method is called, if all fields
contain valid data, it will:
return True
place the form’s data in its cleaned_data attribute.
[edit] As #fazil-zaid mentioned, you need to include model in your Meta class for it to function as a modelform.
There are quite a few moving parts to this question, but if you have any insight to any piece of it, it would be appreciated.
I want to build a feedback form that acts as one would expect. When the user clicks the feedback button at the bottom right of the page, it launches a bootstrap modal. The modal has a django crispy form that submits or returns the fields that are invalid when the submit button is pressed.
First, I have my feedback button:
{% load crispy_forms_tags %}
.feedback-button {
position: fixed;
bottom: 0;
right: 30px;
}
<div class='feedback-button'>
<a class="btn btn-info" href="#feedbackModal" data-toggle="modal" title="Leave feedback" target="_blank">
<i class="icon-comment icon-white"></i>
Leave feedback
</a>
</div>
<div class="modal hide" id="feedbackModal" tabindex="-1" role="dialog" aria-labelledby="feedbackModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 id="feedbackModalLabel">Contact Form</h3>
</div>
<div class="modal-body">
{% crispy feedback_form feedback_form.helper %}
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Submit</button>
</div>
</div>
Next, I have my form:
class Feedback(models.Model):
creation_date = models.DateTimeField("Creation Date", default=datetime.now)
topic = models.CharField("Topic", choices = TOPIC_CHOICES, max_length=50)
subject = models.CharField("Subject", max_length=100)
message = models.TextField("Message", blank=True)
sender = models.CharField("Sender", max_length=50, blank=True, null=True)
def __unicode__(self):
return "%s - %s" % (self.subject, self.creation_date)
class Meta:
ordering = ["creation_date"]
verbose_name = "Feedback"
verbose_name_plural = "Feedback"
class Crispy_ContactForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
Field('topic', placeholder='Topic', css_class='input-medium'),
Field('subject', placeholder='Subject', css_class='input-xlarge'),
Field('message', placeholder='Message', rows='5', css_class='input-xlarge'),
Field('sender', placeholder='Sender', css_class='input-xlarge'),
),
)
self.helper.form_id = 'id-Crispy_ContactForm'
self.helper.form_method = 'post'
super(Crispy_ContactForm, self).__init__(*args, **kwargs)
class Meta:
model = Feedback
exclude = ['creation_date']
I tried to omit the legend in the crispy form because if I include it, the modal appears to have two form titles. But omitting the legend in the crispy form layout resulted in the fields appearing out of order.
So I'm left with a few questions:
Overall, am I going about this the right way?
If I hook up the modal's submit button to AJAX, how do I go about error checking the
form?
Is there a better way to display the crispy form in the
bootstrap modal?
I found a partial solution on this page. In my base template, I created the button and the form:
<div class='feedback-button'><a class="btn btn-info" href="#feedbackModal" data-toggle="modal" title="Leave feedback" target="_blank"><i class="icon-comment icon-white"></i> Leave feedback</a></div>
{% include "_feedback_form.html" with feedback_form=feedback_form %}
Then I created two feedback forms
<div class="modal hide" id="feedbackModal" tabindex="-1" role="dialog" aria-labelledby="feedbackModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 id="feedbackModalLabel">Contact Form</h3>
</div>
{% include "_feedback_form_two.html" with feedback_form=feedback_form %}
</div>
and
{% load crispy_forms_tags %}
<form action="{% url feedback %}" method="post" id="id-Crispy_ContactForm" class="form ajax" data-replace="#id-Crispy_ContactForm">
<div class="modal-body">
{% crispy feedback_form %}
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<input type="submit" name="submit_feedback" value="Submit" class="btn btn-primary" id="submit-id-submit_feedback" />
</div>
</form>
I broke the feedback forms into two because the bootstrap-ajax.js file that I'm leveraging from the above link replaces the html from the one template. If I use a combined feedback form, it will have class="modal hide". I need it to just have class="modal" so that if the form is refreshing with errors, the modal doesn't disappear.
In my view, I have
#login_required
def feedback_ajax(request):
feedback_form = Crispy_ContactForm(request.POST)
dismiss_modal = False
if feedback_form.is_valid():
message = feedback_form.save()
feedback_form = Crispy_ContactForm()
dismiss_modal = True
data = {
"html": render_to_string("_feedback_form_two.html", {
"feedback_form": feedback_form
}, context_instance=RequestContext(request)),
"dismiss_modal": dismiss_modal
}
return HttpResponse(json.dumps(data), mimetype="application/json")
And then in the bootstrap-ajax.js file (again from the above link), I made a few alterations. In the processData function, I defined:
var $el_parent = $el.parent();
and I added
if (data.dismiss_modal) {
var msg = '<div class="alert alert-success" id="' + $(replace_selector).attr('id') + '">Feedback Submitted</div>'
$(replace_selector).replaceWith(msg);
$el_parent.modal('hide');
$(replace_selector).replaceWith(data.html);
}
This isn't fully functional yet because the Success Message disappears with the modal immediately. I want the modal to display the message and disappear after maybe 3 seconds. haven't figured this out yet, but it works well enough for now.
I'm still tinkering, but this addresses most of my questions:
It submits data with AJAX and returns with error checking if needed.
The form displays fairly well in the modal.
I have a few remaining issues. I need to figure out a way to suppress the legend in the crispy form, and I need to find a way to display the modal crispy form and not interfere with another crispy form that appears elsewhere on the site.
I answered a similar question to this on a related question.
https://stackoverflow.com/a/12905016/1406860
This will get you everything except the return of errors.
I would suggest doing the validation and creating an 'errors': 'List of problems' entry in the dictionary that is fed back and check for this in the AJAX success as per whether to close the modal (because there weren't errors) or displaying errors as appropriate.
JD