如何将文件上传到数据库?

时间:2018-01-06 00:15:41

标签: django python-3.x django-models django-forms django-views

这是我的models.py

from django.db import models


# Create your models here.
class Houses(models.Model):
    owner = models.CharField(max_length=250)
    house_name  = models.CharField(max_length=500)
    country = models.CharField(max_length=500)
    genre = models.CharField(max_length=100)
    thumb = models.ImageField(default="default.png")
    body = models.TextField(default=None)
    def __str__(self):
        return self.house_name


class house(models.Model):
    houses = models.ForeignKey(Houses, on_delete=models.CASCADE)
    file_type = models.CharField(max_length=10)
    house_name = models.CharField(max_length=250)

这是我的views.py

from django.shortcuts import render
from . models import Houses
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from . import forms



def houses_list(request):
    house = Houses.objects.all().order_by('owner')
    return render(request,'Houses.html',{'houses':house})


def house_detail(request,house_name):
    #return HttpResponse(house_name)
    house = Houses.objects.get(house_name=house_name)
    return render(request, 'detail2.html',{'house':house})

@login_required(login_url = "/accounts/login/")
def house_create(request):
    if request.method =='POST':
        form = forms.CreateHouses(request.POST,request.FILES)
        if form.is_valid():
            #save house to db
            instance = form.save()
            return render(request, 'Houses.html',{'houses':house})
    else:
        form = forms.CreateHouses()
    return render(request,"house_create.html",{'form':form})

这是我的forms.py

from django import forms
from . import models


class CreateHouses(forms.ModelForm):
    class Meta:
        model = models.Houses
        fields = ['owner','house_name','country','genre','thumb','body']

这是我的house_create.html文件

{% extends 'detail.html' %}

{% block content %}
    <div class="create-house">
        <h2>Create an Awesome New Article</h2>
        <form class="site-form" action="{% url 'accounts:login' %}" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{form}}
        <input type="submit" value="Create">

    </form>
</div>
{% endblock %}

我创建了一个模型,用于保存房屋清单,它有变量,如名称所有者等。我试图上传用户并且已经成功但是当我试图从house_create.html everthings上传新房子时看起来没有错误消息,但没有将数据保存到数据库,我无法从管理页面看到。所以,我做错了,我找不到错误的点。也许可以使用foreingKey参数?

0 个答案:

没有答案