TRiBByX
3/22/2018 - 4:04 PM

Django DB/model

This is the basic setup for views and models to handle the adding of a project to the built in sqlite database. Very basic, but great to build off of.

<!DOCTYPE html>
<html>
    <body>
        <div class='form'>
            <form method='post'>
                {% csrf_token %}
                {{project.as_p}}
                <br>
                <input type="submit" name="submit">
            </form>
        </div>
        <p>------------------------------------------------------------------------------------------------</p>
        {% for p in projects %}
        <div>
            <p>Project id: {{p.id}}</p>
            <p>Project Name: {{p.project_name}}</p>
            <p>Company Name: {{p.company_name}}</p>
        </div>
        <p>------------------------------------------------------------------------------------------------</p>
        {% endfor %}
        
    </body>
</html>
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from django.db import models


from . import models


class Index(View):

    def get(self, request):
        if not models.Project.objects.all():
            print 'no query'
            context = {
                'project': models.ProjectForm()
            }
        else:
            print 'with query'
            context = {
                'project': models.ProjectForm(),
                'projects': list(models.Project.objects.all())
            }
        return render(request, 'index/indextemplate.html', context=context)

    def post(self, request):
        form = models.ProjectForm(request.POST)
        if form.is_valid():
            form.save()
        context = {
                'project': models.ProjectForm(),
                'projects': list(models.Project.objects.all())
            }
        return render(request, 'index/indextemplate.html', context=context)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
from django.forms import ModelForm


class Project(models.Model):
    id = models.AutoField(primary_key=True)
    project_name = models.CharField(max_length=64)
    company_name = models.CharField(max_length=64)


class ProjectForm(ModelForm):
    class Meta:
        model = Project
        fields = ['project_name', 'company_name']