使用FBV

时间:2018-04-25 10:45:08

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

大家好,我是Django的新手,我正在秃顶拉我的头发。有人可以帮我这个。

我正在尝试在我的帖子中添加多个图片,但我遇到了问题。我有2个型号。一个岗位模型和一个图像模型。我的帖子模型已经有1个图像域。然后我有另一个允许多个图像的相关模型。以下是我的模型的样子

class Post(models.Model):
    user = models.ForeignKey(User, related_name='posts')
    title = models.CharField(max_length=250, unique=True)  
    slug = models.SlugField(allow_unicode=True, unique=True)  
    message = models.TextField()  
    post_image = models.ImageField()

class Image (models.Model): #(Images)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='images/', blank=True, null=True)
    image_title = models.CharField(max_length=100)
    image_description = models.CharField(max_length=250)

    def __str__(self):
        return self.post.title + " Image"

以下是我的观点的样子。当表单加载时。它有多个图像字段。它只是在我的帖子创建时没有保存这些图像。我得到一个完全忽略formset和多个图像的帖子。它仅显示Post模型方面和Post模型的1个图像。即使在管理员中也没有多个图像。

有人能指出我代码中的错误是什么吗?

VIEWS.py首次尝试

@login_required
def post_create(request):
    ImageFormset = modelformset_factory(Image, fields=('image', 'image_title', 'image_description'), extra=7)
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        formset = ImageFormset(request.POST or None, request.FILES or None)
        if form.is_valid() and formset.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save() ## It seems as if my code just plays till here and then disconnects
            for f in formset:
                try:
                    photo = Image(post=post, image=f.cleaned_data['image', 'image_title', 'image_description'])
                    photo.save()
                    return redirect('posts:single', username=request.user.username, slug=post.slug)
                except Exception as e:
                    break
    else: ## This part works too as it shows the correct empty form
        form = PostForm()
        formset = ImageFormset(queryset=Image.objects.none())
    context = {'form': form, 'formset': formset}
    return render(request, 'posts/post_form.html', context)
下面的

是我的forms.py

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'message', 'post_image' )

更改了像user3054319建议的视图,如下所示。它工作正常,但只保存图像文件夹中的1个图像。一切都正确我的缩进

VIEWS.py第二次尝试

@login_required
def post_create(request):
    ImageFormset = modelformset_factory(Prep, fields=('image', 'image_title', 'image_description'), extra=7)
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        formset = ImageFormset(request.POST or None, request.FILES or None)
        if form.is_valid() and formset.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()
            for f in formset:
                try:
                    photo = Prep(post=post, image=f.cleaned_data['image'], image_title=f.cleaned_data['image_title'],
                                 image_description=f.cleaned_data'image_description'])
                    photo.save()
                    return redirect('posts:single', username=request.user.username, slug=post.slug)
                except Exception as e:
                    break 

然后我尝试删除try和except语句并在循环外部获取重定向它保存所有7个图像但最终会出错(请参阅下面附带的错误图像)

VIEWS.py第三次尝试

@login_required
def post_create(request):
    ImageFormset = modelformset_factory(Prep, fields=('image', 'image_title', 'image_description'), extra=7)
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        formset = ImageFormset(request.POST or None, request.FILES or None)
        if form.is_valid() and formset.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()
            for f in formset:
                    photo = Prep(post=post, image=f.cleaned_data['image'], image_title=f.cleaned_data['image_title'], image_description=f.cleaned_data['image_description'])                                 
                    photo.save()
                return redirect('posts:single', username=request.user.username, slug=post.slug)

下面的错误图片 如果这可以通过CBV实现,我可以添加一个像我赢得彩票一样跳舞的视频。但是我不会太贪心,即使解决这个问题也可以节省一些头发 Error I get on 3rd try

2 个答案:

答案 0 :(得分:1)

我浏览了你的帖子创建视图,发现你试图通过一次调用来访问字典的多个键,这是f.cleaned_data ['image','image_title'],这在语法上是错误的

如果你打印(f.cleaned_data)它会给出字典,你应该知道如何访问字典。

您必须使用

photo =图片(post = post,image = f.cleaned_data [' image'],image_title = f.cleaned_data [' image_title'])

答案 1 :(得分:0)

以下是正确的 Views.py ,感谢user3054319

{{1}}