简体   繁体   中英

Understanding Django (from source code): attributes of field via models.CharField and forms.CharField

I would like to understand how django.db.models and django.forms work together on a field .

Consider this example:

# models.py
from django.db import models
class Person(models.Model)
  Telefon1 = models.CharField('Telefon', max_length=30, blank=True, null=True)

displays via generic.edit.FormView in views the form field in HTML correctly with the default value 'Telefon'. In order to turn off autocomplete-functionality I add the following:

# forms.py
from django import forms
class ContactForm(forms.ModelsForm):
  Telefon1 = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}))

The field then is correctly rendered with automplete:off . But the name of the field falls back to the models name: Telefon1

So question 1 : How do I make sure that the default name defined in models is being passed through or do I have to re-define the name with forms.CharField(widget=... ?
Question 2 : How can I find the answer reading the source code? I started by reading site-packages\\django\\forms\\widget.py which either doesn't include the answer or I did not understand.

I would like to learn and understand Django via source code since the tutorial and documentation doesn't always work for me (especially in this case).

Talking about django.db.models.Field and django.forms.Field are exactly two different machines. But still in real life we need forms that supposedly need to map the models. To accomplish that, django has provided us with the concept of django modelforms which we make by passing name of the model.

By default django modelforms shows same name as that of django models but in case you need to override the name, you can by overriding __init() in django modelforms as also specified in here to further clarify your understanding.

The code base of django is already developed and is still being developed to the extent of optimization. The point of learning is deeply admired but falling down into complexities is just waste of effectiveness and beats the purpose of being called as a Rapid Application Development Technology.

Whatever is given in official docs is self sufficient and deep enough to help you gain a great understanding. Ths only best way to learn a framework is to learn its error messages then you will automatically be the master of intricacies of this framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM