Django - проблема с записью в базу данных

У меня проблема, форма urls работает, но я не могу увидеть записи в url/admin, могу ли я попросить помощи, спасибо :D

SOF хочет, чтобы я добавил больше деталей, иначе он не будет переведен, я не знаю, что еще я могу добавить, в целом temapals и url работают.


class Note(models.Model):
    """..."""
    notes = models.CharField(max_length=100, unique=True)
    description = models.TextField()

    class Meta:
        verbose_name = "Note"
        verbose_name_plural = "Notes"

    def __str__(self):
        return self.notes

class NoteView(View):
    def get(self, request):
        if request.method == 'POST':
            textN = Note.objects.all().order_by('notes')
            form = NoteAddForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect('Files/menu')
        else:
            textN = NoteAddForm()
        return render(request, 'Files/note.html', {'textN': textN})

class NoteAddForm(forms.ModelForm):
    """New note add form"""

    class Meta:
        model = Note
        fields = '__all__'

{% extends 'Files/base.html' %}

{% block title %}Notatnik{% endblock %}
<h2>Notatnik Dietetyka/ Zalecenia ręczne </h2>

{% block content %}

    <form action="/send/" method="post">
        {% csrf_token %}
        {{ textN }}
        <label>
            <input type="text" class="btn btn-second btn-lg">
            <button><a href="{% url 'send' %}">Wyślij formularz</a></button>
        </label>


    </form>

    <button type="button" class="btn btn-primary btn-lg"><a href="{% url 'menu' %}">Powrót</a></button>
{% endblock %}

Внутри вашего NoteView класса в views.py файле находится место, где возникает проблема.

Я вижу, что у вас есть if statement, проверяющий if request.method == 'POST' внутри class-based view get(). get() эквивалентен if request.method == 'GET'. Поэтому, возможно, вы захотите переопределить post() в классе. Например:

class NoteView(View):
     template_name = 'Files/note.html'

     # Use the get method to pass the form to the template
     def get(self, request, *arg, **kwargs):
          textN = NoteAddForm()

          return render(request, self.template_name, {'textN': textN})

     # Use the post method to handle the form submission
     def post(self, request, *arg, **kwargs):
          # textN = Note.objects.all().order_by('notes') -> Not sure why you have this here...
          form = NoteAddForm(request.POST)

          if form.is_valid():
               form.save()

               return redirect('Files/menu') # Redirect upon submission
          else:
               print(form.errors)  # To see the field(s) preventing the form from being submitted

          # Passing back the form to the template in the name 'textN'
          return render(request, self.template_name, {'textN': form})  

Идеально, это должно решить проблему, с которой вы столкнулись.

Обновления

На форме я бы предложил следующее...

# Assuming that this view handles both the get and post request
<form method="POST">  # Therefore, removing the action attribute from the form
    {% csrf_token %}
    {{ textN }}

    # You need to set the type as "submit", this will create a submit button to submit the form
    <input type="submit" class="btn btn-second btn-lg" value="Submit">
</form>

задача решена - спасибо Damoiskii

Вернуться на верх