美文网首页
Django学习总结 2

Django学习总结 2

作者: 公民w先生 | 来源:发表于2018-01-04 22:29 被阅读0次

    1. Model - defines the data (database)

    In this section, it is really about implementation. However, the database design also requires a whole new chapter to talk about. I have learnt basic relational database design (1-3 normalisation rules) from Udemy.

    a) Define the table and field.

    Simple example:

    class Topic(models.Model):
        top_name = models.CharField(max_length=264, unique=True)
    
    class Webpage(models.Model):
        category = models.ForeignKey(Topic)
        name = models.CharField(max_length=264)
        url = models.URLField()
        def __str__(self):
            return self.name
    
    

    In the above example, topic is a table and top_name is a field (column) of the table. __str__ is a string representation of the model, for example in the result of a print function.

    b) Creates the table in the database

    Django will do the heavy-lift job and you just need a piece of code:
    python manage.py migrate

    In normal procedure, for any change made to the models, it is to run in the following sequence:
    python manage.py makemigrations
    python manage.py migrate

    Using console to interact with the database:
    python manage.py shell
    Exit the shell:
    exit() or quit()

    c) Register the models in the admin.py (so that you can interact in the admin interface)

    Import models first:
    from app_name.models import model_name
    admin.site.register(model_name)

    Create a superuser to access the admin

    python manage.py createsuperuser
    Using the 'username' and 'password' to login the admin interface.

    2 Model - View - Template (MTV) methodology of Django

    • Model: defines the database
    • View: Takes in the request from the client side, query the database if necessary (take or save data), and then send the response (with data) with templates. This is where the main logic is written.
    • Template: The skeleton of the content is defined in static HTML with dynamic content represented by template tag. The dynamic content(variables) is basically the 'end' connected to the back-end.

    a) Import models (or forms) into views.py

    from app_name.models import model_name

    b) Query the database

    Create a model instance
    • Inherit the whole table:
      instance = model_name.objects.all()
    • Sort the table by a specified column:
      instance = model_name.objects.order_by('field_name')
    Group the data in a dictionary if necessary.

    c) Edit the template file

    {% for record in Record %}
    <tr>
      <td>{{ record.name }}</td>
      <td>{{ record.date }} </td>
    </tr>
    {% endfor %}
    

    .name and .date are model fields defined in the models.py. 'Record' must be the same as the key of the dictionary defined in the views.py file (end-to-end aligned).

    d) Edit the urls.py to connect the view function.

    Import the corresponding view module:
    from app_name import views
    Match url pattern (e.g. home/) with the view function (home):
    url(r'^home/', views.home, name='home')

    3. Django Forms

    Advantages of using django forms:

    • Quickly generate HTML form widgets
    • Validate data and process it into a Python data structure.
    • Create form versions of Models, quickly update models from Forms.

    My understandings of django forms:

    It is a 'staging' interface (borrow from git) to bridge the client side (front-end HTML) and the server side (Models -
    database) . Users provide data and want to write it into the database. The data needs to be validated before actually writing into the database. Therefore, Django forms serve as the 'buffer' layer between the client and the server. In practice, I found by using Django forms, saving data into the database is straightforward and error-free, which makes the implementation very easy for the beginners.

    The implementation is very similar to Django models.

    a) Create a forms.py file under app folder.

    Import forms:

    from django import forms

    Create a form class:
    Class FormName(forms.Form):
      name = forms.CharField()
      text = forms.CharField(widget=forms.Textarea)
    
    Create a Model form class (inherit from the model)

    Import models: from app.models import Selection
    Create model forms:

    class SelectionForm(forms.ModelForm):
        text_content = forms.CharField(widget = forms.Textarea, label='Your content')
        class Meta():
            model = Selection
            fields = ('text_content',)
    

    class Meta() provides metadata to the model; Model metadata is 'anything that is not a table field'.

    Inside the above class Meta(): it tells text_content you created to receive data from the client is actually a field of the table named 'Selection'. Therefore, ModelForm connects the client input with the server's database.

    b) Create a view for the form

    Import forms:

    form . import forms - '.' represents the current directory.

    Define a view function:
    def SelectionFormView(request):
        form = forms.SelectionForm()
        return render(request, 'appname/forms.html', {'form', form})
    

    c) Connect the view function and URL pattern in urls.py

    d) Template tags for django forms

    A code snippet for form template tag

    In above HTML template, it defines a form with method 'post'. In the server side, form validation needs to be added in.

    e) Form validation in views.py

    if request.method == "POST":
            selection_form = SelectionForm(data=request.POST)
    
            if selection_form.is_valid() :
                user_selection = selection_form.save()
                user_selection.save()
            else:
                print(selection_form.errors)
            #Empty the form after saving the content into the databaes
            selection_form = SelectionForm()
    else:
       selection_form = SelectionForm()
    
    - Adding a check for empty fields/ for a bot

    The idea is to define a hidden field, which is not seen by the client user but seen by bot in HTML element. A normal human user will not fill in that 'unseen' field but not the bot. Therefore, by checking whether the field is empty or not, one can distinguish between a human user and a bot.

    You can set one field of the form as:

    • Can be empty: required = False
    • Not shown to client users: widget = forms.HiddenInput
    Django provides built-in validators:
    1. Import the model:
      from django.core import validators
    2. Add validation into the field arguments:
      validators = [validators.MaxLengthValidator(0)]
      This will check if the maxlength of the field exceeds 0. If so, raise errors.
    Self-defined validator:

    Firstly, define the validation function:
    e.g.

    def check_for_z(value):
        if value[0].lower() != 'z':
            raise forms.ValidationError("Name needs to start with Z")
    

    Then, pass the function name into the field's validators:
    validators = [function_name]

    Double check one field has been inputed correctly (e.g. email address)
    def clean(self):
        all_clean_data = super().clean()
        email = all_clean_data['email']
        vmail = all_clean_data[‘verify_email’]
    
        if email != vmail:
            raise forms.ValidationError("Make sure emails match!")
    
    

    For more information on this: https://docs.djangoproject.com/en/2.0/ref/forms/validation/#validating-fields-with-clean

    相关文章

      网友评论

          本文标题:Django学习总结 2

          本文链接:https://www.haomeiwen.com/subject/epyrnxtx.html