David J Nevin+= Code

Last updated: Sep 15, 2022

Django Dynamic Content

Day 2: Dynamic Content

A few useful django db queries:

100
variable_name = model_name.objects.all()

Returns all objects from the database for the specified model_name

100
variable_name = model_name.objects.first()

Returns the first object from the database for the specified model_name

100
variable_name = model_name.objects.last()

Returns the last object from the database for the specified model_name

100
variable_name = model_name.objects.get(name='Sam')

Returns an object or objects from the database that match name=‘Sam’ for the specified model_name

100
variable_name = model_name.objects.order_by('list_date')

Returns an object or objects from the database ordered by list_date for the specified model_name

django docs: making queries

SQL Queries

From my C# projects, it feels already like a layer between the actual SQL queries and the process. Looking forward to seeing how actual SQL queries and SQL stored procedures are used.

For now it’s django ORM tricks.

Template tags

Similar to Razor pages, django has template tags.

100
101
102
103
104
105
106
{% ... %}

{% for items in list %}

{% empty %} # if empty

{% endfor %}

Forms

Pulling form the model in models.py the forms.py imports forms and the class inherits from forms.ModelForm

100
101
102
103
104
105
106
107
108
109
110
111
from django import forms
from .models import Listings

class ListingForm(forms.ModelForm):
    class Meta:
        model = Listings
        fields = [
                    'title',
                    'condition',
                    ...
                ]

The template used to display the form, new_listing.py

100
101
102
103
104
105
106
<form action="{% url 'listing_app:new_listing' %}" method='post' enctype="multipart/form-data">
    <div class="form-group">
        {% csrf_token %}
        {{ form.as_p }}
    </div>
    <button type="submit" class="btn">Create Listing</button>
</form>

{% csrf_token %} - Cross Site Request Forgery Token {{ form.as_p }} – Render Django Forms as paragraph

So far

The site has a working form, which when first called is blank and once confirmed as valid submits the content, using a csrf_token and returns a redirect address. Good.


Next: Django Individual Item Page
Previous: Django Next Steps