Задать вопрос
@David5

Ошибка KeyError?

Делал выборку по пользователям в форме, но выдает ошибку, не знаю с чем связано
5de78164da45f812344232.png
Forms.py
from django import forms
from django.core.exceptions import ValidationError
from .models import Cat, Link
from .views import *

class CatForm(forms.ModelForm):
    class Meta:
        model = Cat
        fields = ['title', 'slug']


    def clean_slug(self):
        new_slug = self.cleaned_data['slug'].lower()


        if new_slug == 'create':
            raise ValidationError('Slug may not be "creare" ')
        if Cat.objects.filter(slug__iexact=new_slug).count():
            raise ValidationError('Slug must be unique')
        return new_slug

class LinkForm(forms.ModelForm):
    class Meta:
        model = Link
        fields = ['title','slug', 'content', 'cats', 'user']
        exclude = ['user']

    def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['cats'].queryset = Cat.objects.filter(user=self.initial['user'])
        
    
           

    def clean_slug(request, self, quaryset):
        new_slug = self.cleaned_data['slug'].lower()

        if new_slug == 'create':
            raise ValidationError('Slug may not be "creare"')
        return new_slug

views.py
from django.shortcuts import render
from django.views.generic import View
from .models import Link, Cat
from django.shortcuts import  get_object_or_404
from .forms import *
from django.shortcuts import redirect
from django.http import HttpResponseRedirect
from django.views.generic import View
from .utils import *
from django.urls import reverse




def contact(request):
    return HttpResponseRedirect("/accounts/login")

def vihod(request):
    return HttpResponseRedirect("/accounts/logout")

def CreateCategory(request):
    return HttpResponseRedirect("/cat/create")

def CreateLink(request):
    return HttpResponseRedirect("/link/create")




def index(request, *args, **kwargs):
    user = request.user.id
    context = {'links': Link.objects.filter(user=user)}
    return render(request,'zakladki/index.html', context)
    


class LinkDetail(ObjectDetailMixin, View):
    model = Link
    template = 'zakladki/link_detail.html'

class LinkCreate(ObjectCreateMixin, View):
    model_form = LinkForm
    template = 'zakladki/link_create_form.html'

class LinkUpdate(ObjectUpdateMixin, View):
    model = Link
    model_form = LinkForm
    template = 'zakladki/link_update_form.html'





class CatUpdate(ObjectUpdateMixin, View):
    model = Cat
    model_form = CatForm
    template = 'zakladki/cat_update_form.html'


class LinkDelete(ObjectDeleteMixin, View):
    model = Link
    template = 'zakladki/link_delete_form.html'
    redirect_url = 'main'

class CatDelete(ObjectDeleteMixin, View):
    model = Cat
    template = 'zakladki/cat_delete_form.html'
    redirect_url = 'cats_list_url'






class CatDetail(ObjectDetailMixin, View):
    model = Cat
    template = 'zakladki/cat_detail.html'



def cats_list(request, *args, **kwargs):
    user = request.user.id
    context = {'cats': Cat.objects.filter(user=user)}
    return render(request,'zakladki/cats_list.html', context)


class CatCreate(ObjectCreateMixin, View):
    model_form = CatForm
    template = 'zakladki/cat_create.html'

  • Вопрос задан
  • 287 просмотров
Подписаться 1 Средний Комментировать
Пригласить эксперта
Ответы на вопрос 1
Hivemaster
@Hivemaster
Админ, который хочет программировать
У формы нет начальных значений, поэтому и ключа user в self.initial нет.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы