Skip to content

Commit 915dc44

Browse files
authored
Merge pull request Fechin#616 from SaeidJavadi/main
Update Forms
2 parents 0bda9fb + 543a293 commit 915dc44

File tree

1 file changed

+119
-97
lines changed

1 file changed

+119
-97
lines changed

source/_posts/django.md

Lines changed: 119 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ CSRF_COOKIE_SECURE = True
204204

205205
```python
206206
# models.py
207-
# The id fields is automatically created by Django
207+
# The id fields is automaticly created by Django
208208
# for each model that why it's not show below
209209
from django.db import models
210210

@@ -220,25 +220,53 @@ class Customer(models.Model)
220220
img = models.ImageField(upload_to ='uploads/')
221221
# Select Field (return value, display value)
222222
TYPE_CHOICES = (
223-
('Customer', 'Customer'),
224-
('Supplier', 'Supplier'),
225-
('Student', 'Student'),
223+
('Customer', _('Customer')),
224+
('Supplier', _('Supplier')),
225+
('Student', _('Student')),
226226
)
227227
type = models.CharField(choices=TYPE_CHOICES)
228228

229229
class Meta:
230230
verbose_name = "Customer"
231231
verbose_name_plural = "Customers"
232232

233-
def __str__(self): # Model string representation
233+
# Model string representation
234+
def __str__(self):
234235
return self.name
235236

236237
# the URL that points to a resource or page on your website
237238
def get_absolute_url(self):
238239
return reverse("customer_detail", kwargs={"pk": self.pk})
239240
```
240241

241-
### Relationship between models
242+
#### We can also use this method to define the ChoiceField value.
243+
244+
```python
245+
class Customer(models.Model)
246+
class TypeList(models.IntegerChoices):
247+
customer = 1, _('Customer'))
248+
supplier = 2, _('Supplier'))
249+
student = 3, _('Student'))
250+
.
251+
.
252+
.
253+
type = models.CharField(choices=TypeList.choices, default=1)
254+
```
255+
256+
#### To access the ChoiceField value in the template, we need to do the following in the template:
257+
258+
- In Django templates you can use the "`get_FOO_display()`" method, that will return the readable alias for the field, where `'FOO'` is the name of the field.
259+
- If the choices are stored in the variable `CHOICES` and the model field storing the selected choice is `'type'` then you can directly use
260+
261+
```html
262+
<!-- Here, X is the model instance -->
263+
{{ X.get_type_display }}
264+
265+
<!-- You can even use this method to display its translation. -->
266+
{% trans X.get_type_display %}
267+
```
268+
269+
#### Relationship between models
242270

243271
```python
244272
# One-to-Many: (use double quotes if the entity is not yet declare) ex. "Supplier"
@@ -423,7 +451,8 @@ def show(request, id):
423451
return render(request, 'appfolder/show.html', {'post': post})
424452

425453
def create(request):
426-
form = PostForm(request.POST or None)
454+
form = PostForm(request.POST or None, request.FILES or None)
455+
# When the form contains an image or file field, we should use request.FILES
427456
if form.is_valid():
428457
# optionally we can access form data with form.cleaned_data['first_name']
429458
post = form.save(commit=False)
@@ -435,7 +464,7 @@ def create(request):
435464

436465
def edit(request, id):
437466
post = Post.objects.get(id=id)
438-
form = PostForm(request.POST or None, instance=post)
467+
form = PostForm(request.POST or None, request.FILES or None, instance=post)
439468
if form.is_valid():
440469
form.save()
441470
return redirect('/posts')
@@ -531,8 +560,7 @@ Templates are store in `project_folder/templates` or in your <code>app_folder/te
531560
{% extends 'base.html' %}
532561

533562
<!-- A part of the parent template that is defined and is replaced by a part in the child template -->
534-
{% block contents %}
535-
{% endblock contents %}
563+
{% block contents %} {% endblock contents %}
536564

537565
<!-- include template-->
538566
{% include 'partials/header.html' %}
@@ -541,101 +569,92 @@ Templates are store in `project_folder/templates` or in your <code>app_folder/te
541569

542570
<!-- If statement in template -->
543571
{% if user.username = 'Mike' %}
544-
<p>Hello Admin</p>
572+
<p>Hello Admin</p>
545573
{% elif user.username = 'john' %}
546-
<p>Hello John Doe</p>
574+
<p>Hello John Doe</p>
547575
{% else %}
548-
<p>Hello User</p>
576+
<p>Hello User</p>
549577
{% endif %}
550578

551579
<!-- for loop in template -->
552580
{% for product in products %}
553-
<p> row:
554-
{{ forloop.counter }} # starting index 1
555-
{{ forloop.counter0 }} # starting index 0
556-
</p>
557-
<p>The product name is {{ product.name }}<p>
558-
<p>The product name is {{ product.price }}<p>
559-
{% endfor %}
560-
561-
<!-- Access to the variable in the template -->
562-
{{ var_name }}
563-
564-
<!-- Template variables formating -->
565-
{{ title | lower }}
566-
{{ blog.post | truncatwords:50 }}
567-
{{ order.date | date:"D M Y" }}
568-
{{ list_items | slice:":3" }}
569-
{{ total | default:"nil" }}
570-
571-
<!-- Current path (ex. posts/1/show) -->
572-
{{ request.path }}
573-
574-
<!-- URL by name with param -->
575-
{% url 'posts.delete' id=post.id %}
576-
577-
<!-- Use static in template: -->
578-
{% load static %}
579-
{% static 'css/main.css' %}
580-
581-
<!-- Define the variable in the template -->
582-
{% with name="World" %}
583-
<html>
584-
<div>Hello {{ name }}!</div>
585-
</html>
586-
{% endwith %}
587-
588-
<!-- Template translate text -->
589-
{% load i18n %}
590-
<title>{% trans "This is the title." %}</title>
591-
<!-- Use variable translate in the template -->
592-
<title>{% trans object.title %}</title>
593-
594-
<!-- Define the list in the template -->
595-
<input type="number"
596-
{% if product.unit in 'kg,milligram,milliliter' %}
597-
step="0.01"
598-
{% else %}
599-
step="1"
600-
{% endif %}>
601-
602-
<!-- Safely Pass Data to JavaScript in a Django Template: -->
603-
<!--+ Use data attributes for simple values -->
604-
<script data-username="{{ username }}">
581+
<p>row: {{ forloop.counter }} # starting index 1 {{ forloop.counter0 }} # starting index 0</p>
582+
<p>The product name is {{ product.name }}</p>
583+
<p></p>
584+
<p>The product name is {{ product.price }}</p>
585+
<p>
586+
{% endfor %}
587+
588+
<!-- Access to the variable in the template -->
589+
{{ var_name }}
590+
591+
<!-- Template variables formating -->
592+
{{ title | lower }} {{ blog.post | truncatwords:50 }} {{ order.date | date:"D M Y" }} {{ list_items | slice:":3" }} {{
593+
total | default:"nil" }}
594+
595+
<!-- Current path (ex. posts/1/show) -->
596+
{{ request.path }}
597+
598+
<!-- URL by name with param -->
599+
{% url 'posts.delete' id=post.id %}
600+
601+
<!-- Use static in template: -->
602+
{% load static %} {% static 'css/main.css' %}
603+
604+
<!-- Define the variable in the template -->
605+
{% with name="World" %}
606+
<html>
607+
<div>Hello {{ name }}!</div>
608+
</html>
609+
{% endwith %}
610+
611+
<!-- Template translate text -->
612+
{% load i18n %}
613+
<title>{% trans "This is the title." %}</title>
614+
<!-- Use variable translate in the template -->
615+
<title>{% trans object.title %}</title>
616+
617+
<!-- Define the list in the template -->
618+
<input type="number" {% if product.unit in 'kg,milligram,milliliter' %} step="0.01" {% else %} step="1" {% endif %}>
619+
620+
<!-- Safely Pass Data to JavaScript in a Django Template: -->
621+
<!--+ Use data attributes for simple values -->
622+
<script data-username="{{ username }}">
605623
const data = document.currentScript.dataset;
606624
const username = data.username;
607-
</script>
625+
</script>
608626

609-
<!-- + Separate script files: can use document.currentScript for separate script files -->
610-
<script src="{% static 'index.js' %}" data-username="{{ username }}"></script>
627+
<!-- + Separate script files: can use document.currentScript for separate script files -->
628+
<script src="{% static 'index.js' %}" data-username="{{ username }}"></script>
611629

612-
<!-- + Case conversion -->
613-
<script src="{% static 'index.js' %}" data-full-name="{{ full_name }}"></script>
614-
<!-- Read it in JavaScript as fullName: -->
615-
<script>
630+
<!-- + Case conversion -->
631+
<script src="{% static 'index.js' %}" data-full-name="{{ full_name }}"></script>
632+
<!-- Read it in JavaScript as fullName: -->
633+
<script>
616634
const data = document.currentScript.dataset;
617635
const fullName = data.fullName;
618-
</script>
636+
</script>
619637

620-
<!-- + Non-string types -->
621-
<script src="{% static 'index.js' %}" data-follower-count="{{ follower_count }}"></script>
638+
<!-- + Non-string types -->
639+
<script src="{% static 'index.js' %}" data-follower-count="{{ follower_count }}"></script>
622640

623-
<!-- parseInt() to convert this value from a string: -->
624-
<script>
641+
<!-- parseInt() to convert this value from a string: -->
642+
<script>
625643
const data = document.currentScript.dataset;
626644
const followerCount = parseInt(data.followerCount, 10);
627-
</script>
645+
</script>
628646

629-
<!-- + There’s no limit: A <script> can have as many data attributes as you like: -->
630-
<script src="{% static 'index.js' %}"
631-
defer
632-
data-settings-url="{% url 'settings' %}"
633-
data-configuration-url="{% url 'configuration' %}"
634-
data-options-url="{% url 'options' %}"
635-
data-preferences-url="{% url 'preferences' %}"
636-
data-setup-url="{% url 'setup' %}"
637-
>
638-
</script>
647+
<!-- + There’s no limit: A <script> can have as many data attributes as you like: -->
648+
<script
649+
src="{% static 'index.js' %}"
650+
defer
651+
data-settings-url="{% url 'settings' %}"
652+
data-configuration-url="{% url 'configuration' %}"
653+
data-options-url="{% url 'options' %}"
654+
data-preferences-url="{% url 'preferences' %}"
655+
data-setup-url="{% url 'setup' %}"
656+
></script>
657+
</p>
639658
```
640659

641660
### Custom Template Tags and Filters
@@ -653,7 +672,7 @@ app_name/
653672

654673
- And in your template you would use the following:
655674

656-
```python
675+
```html
657676
{% load basetags %}
658677
```
659678

@@ -732,7 +751,7 @@ def site_email(request):
732751
'OPTIONS': {
733752
'context_processors': [
734753
735-
'app_name.context_processors.site_email',
754+
'app_name.context_processors.site_email',
736755
# New context processor here
737756
738757
],
@@ -866,8 +885,16 @@ class ArticleForm(ModelForm):
866885
{% csrf_token %} {{ form }}
867886
<button type="submit">Submit</button>
868887
</form>
888+
```
869889

870-
{% load crispy_forms_tags %} {{ form|crispy }} {{ form.email|as_crispy_field }}
890+
- NOTE: If the form contains a file field, your form MUST contain `enctype="multipart/form-data"`, eg:
891+
892+
```html
893+
<form action="" method="post" enctype="multipart/form-data">
894+
{% csrf_token %}
895+
{{ form.as_p }}
896+
<button type="submit">{% trans 'Submit' %}</button>
897+
</form>
871898
```
872899

873900
##### A Tailwind CSS template pack for the wonderful django-crispy-forms.
@@ -918,7 +945,6 @@ def clean(self):
918945

919946
### Displaying messages
920947

921-
922948
```python
923949
# Message tags
924950
# debug, info, success, warning and error
@@ -929,11 +955,7 @@ messages.error(request, 'Login error')
929955

930956
```html
931957
<!-- Display flash messages in template -->
932-
{% if messages %}
933-
{% for message in messages %}
934-
{% message %} {% message.tags %}
935-
{% endfor %}
936-
{% endif %}
958+
{% if messages %} {% for message in messages %} {% message %} {% message.tags %} {% endfor %} {% endif %}
937959
```
938960

939961
## User Model

0 commit comments

Comments
 (0)