Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

python - Django - form.save() is not creating ModelForm

In my Django application users send feedback about task. I'm creating this form with ModelForm, and after form.save() my object is not creating and is not uploading to database. Here are my codes:

views.py:

@login_required(login_url='sign_in')
def task_details(request, slug):
    if slug:
        task = get_object_or_404(Task, slug=slug)
        today = datetime.now().date()
        deadline = task.task_deadline.date()
        time_left = deadline - today
        form = CreateFeedbackForm()

    if request.method == 'POST':
        form = CreateFeedbackForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = CreateFeedbackForm()
    messages.info(request, 'Feedback sent.')

    context = {
        'task': task,
        'form': form,
        'days_left': time_left.days
    }
    return render(request, 'task-details.html', context)

models.py:

class TaskFeedback(models.Model):
    task = models.ForeignKey(Task, on_delete=models.CASCADE, null=True, blank=True)
    sender = CurrentUserField()
    is_solved = models.BooleanField(default=False)
    feedback_content = models.TextField(max_length=1000, null=True, blank=True)
    date_added = models.DateTimeField(auto_now_add = True)

    def __str__(self):
        return self.feedback_content

forms.py:

class CreateFeedbackForm(forms.ModelForm):
    class Meta:
        model = TaskFeedback
        fields = ['feedback_content', 'is_solved']

    def __init__(self, *args, **kwargs):
        super(CreateFeedbackForm, self).__init__(*args, **kwargs)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem was in action of form in my html page:

<form action="{% url 'task_details' task.slug %}" method="POST">
            {% csrf_token %}
            {{ form.feedback_content }}
            <div class="panel-buttons">
                <div class="checkbox">
                    {{ form.is_solved }}
                </div>
                <div class="save-btn-container">
                    <button class="btn btn--pill btn--green" type="submit">Send</button>
                </div>
            </div>
        </form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...