Проблемы с сохранением форм django в sqlite

В настоящее время я работаю над программой, которая находится в стадии разработки. До этого я никогда не работал с Django, и у меня возникли некоторые проблемы.

Я пытаюсь сохранить несколько полей формы в базе данных sqlite, но получаю ошибки.

Вот ошибка, которую я получаю

NameError at /recipes
name 'form' is not defined
Request Method: POST
Request URL:    http://localhost:8000/recipes
Django Version: 4.0.2
Exception Type: NameError
Exception Value:    
name 'form' is not defined
Exception Location: C:\Users\Admin\Desktop\praktika\brew\brewery\views.py, line 24, in recipes
Python Executable:  C:\Program Files\Python310\python.exe
Python Version: 3.10.2
Python Path:    
['C:\\Users\\Admin\\Desktop\\praktika\\brew',
 'C:\\Program Files\\Python310\\python310.zip',
 'C:\\Program Files\\Python310\\DLLs',
 'C:\\Program Files\\Python310\\lib',
 'C:\\Program Files\\Python310',
 'C:\\Users\\Admin\\AppData\\Roaming\\Python\\Python310\\site-packages',
 'C:\\Program Files\\Python310\\lib\\site-packages',
 '/home/ponasniekas/wwwpi/brew',
 '/home/ponasniekas/wwwpi/brew/brew',
 '/home/ponasniekas/wwwpi/brew/brew/brewery',
 '/home/ponasniekas/.local/lib/python3.8/site-packages']

Вот мой файл представлений:

from django.http import HttpResponse
import json
from django.http import StreamingHttpResponse
from django.shortcuts import render
from django.core.serializers import serialize
from django.http import JsonResponse
from django.template import RequestContext


from .models import StockYeast, queryset_to_indexlist,queryset_to_array, Brew, Fermentable, Miscs, RecipeYeast, Recipes, Yeast,StockFermentables
from .models import Hop,StockHop,StockMiscs

from .forms import RecipeForm, RecipeFermentableForm, RecipeHopForm, RecipeMiscForm,RecipeWaterForm, RecipeYeastForm,RecipeMashForm, StockMiscForm
from .forms import StockFermentableForm,StockHopForm,StockYeastForm, StockMiscForm
from django.forms import formset_factory

def index(request):
    return render(request, 'index.html')

def recipes(request):
    if request.method == 'POST':
        recipes = RecipeForm(request.POST)
        
        if form.is_valid():
            n = form.cleaned_data["name"]
            t = Recipes(name=n)
            t.save()
        
    else:
        recipes = Recipes.objects.all()
        recipeFermentableFormset = formset_factory(RecipeFermentableForm, extra=1)
        recipeHopFormset = formset_factory(RecipeHopForm, extra=1)
        RecipeMiscFormSet= formset_factory(RecipeMiscForm, extra=1)
        RecipeYeastFormSet = formset_factory(RecipeYeastForm,extra=1)
        RecipeMashFormSet = formset_factory(RecipeMashForm,extra=1)
        return render(request, 'recipes.html', {'recipes':recipes,"recipe_form" :RecipeForm(auto_id="recipe_%s"), 
        "recipe_fermentableformset":recipeFermentableFormset(prefix='fermentable'),
        "recipe_hopformset":recipeHopFormset(prefix='hop'),
        "recipe_miscformset":RecipeMiscFormSet(prefix='misc'),
        "recipe_yeastformset":RecipeYeastFormSet(prefix='yeast'),
        "recipe_mashformset" :RecipeMashFormSet(prefix='mash'),
        "recipeWaterForm":RecipeWaterForm()})

А вот мой файл recipes.html :

{% block content %}
<!-- Modal -->

                

                <div class="card shadow-sm">
                  <div class="card-header" id="headingOne">
                    <h5 class="mb-0"> Receptas</h5>
                    
                  </div>
              
                  <div id="card-base" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
                    <div class="card-body">
                      <div class="row">
                        <div class="col">
                        <form method="post" action="/recipes">
                        {% csrf_token %}
                        {{recipe_form.ibu}}
                        {{recipe_form.abv}}
                        <div class="row">
                          <div class="col">{{recipe_form.name|as_crispy_field}}</div> 
                          <div class="col">{{recipe_form.style|as_crispy_field}}</div>
                        </div>
                        
                        <div class="row">
                          <div class="col">{{recipe_form.batch_size|as_crispy_field}}</div>
                          <div class="col">{{recipe_form.boile_time|as_crispy_field}}</div>
                          <div class="col">{{recipe_form.efficiency|as_crispy_field}}</div>
                        </div>
                        <div class="row">
                          <div class="col">{{recipe_form.primary_age|as_crispy_field}}</div>
                          <div class="col">{{recipe_form.secondary_age|as_crispy_field}}</div>
                          <div class="col">{{recipe_form.age|as_crispy_field}}</div>
                        </div>
                        <div class="row">
                          <div class="col">{{recipe_form.pub_date|as_crispy_field}}</div>
                        </div>
                        <div class="row">
                          <div class="col">{{recipe_form.notes|as_crispy_field}}</div>
                        </div>
                      </div>
                    
                    <span class="d-flex flex-row-reverse"><button class="btn btn-secondary" id="save_recipe_btn" type="submit"><i class="bi bi-save"></i></br> Saugoti</button></span>
                    </form>

Я сделал все, пока смотрел учебник, и мне кажется, что я все сделал правильно, однако, похоже, что это не работает.

Может ли кто-нибудь сказать мне, что я сделал не так? Пожалуйста, имейте в виду, что это будут отношения "многие к одному" с рецептами и рецептами-ферментами, магазинами рецептов и так далее. Однако для начала я пытаюсь сохранить только основную часть рецепта.

У вас опечатка в views.py

def recipes(request):
    if request.method == 'POST':
        form = RecipeForm(request.POST) <------ change recipes to form or use recipes in below form valid and cleaned_data
    
        if form.is_valid():
            n = form.cleaned_data["name"]
            t = Recipes(name=n)
            t.save()

Теперь я получаю другую ошибку ValueError в /recipes

Это означает, что вы ничего не вернули HttpResponse после сохранения рецепта. Поэтому либо верните HttpResponse, либо redirect в любое место, которое вы хотите после успешного создания данных рецепта.

from django.http import HttpResponse

def recipes(request):
    if request.method == 'POST':
        form = RecipeForm(request.POST)
    
        if form.is_valid():
            n = form.cleaned_data["name"]
            t = Recipes(name=n)
            t.save()
            # Return a "created" (201) response code.
            return HttpResponse('Recipe Saved Sucessfully', status=201)

Если вы не хотите ничего добавлять после валидации формы, вы можете напрямую сохранить данные как

if form.is_valid():
    form.save()
    # Return a "created" (201) response code.
    return HttpResponse('Recipe Saved Sucessfully', status=201)
Вернуться на верх