在django中单击按钮时如何更改模型字段的值? [英] How to change the value of model field when button is clicked in django?

查看:150
本文介绍了在django中单击按钮时如何更改模型字段的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个django应用程序,其主页上显示了不同公司提供的实习机会列表。usertype= Student的用户可以查看这些实习机会。单击申请时,每个实习列表视图都有一个名为申请的按钮。我希望将我的Django模型(StudentApplying)中名为 applied 的布尔字段设置为true。这样,创建此帖子的公司可以查看申请的学生列表,然后可以接受/拒绝他们。我不想使用ajax,javascript等,除非无法用django本身做不到。

I'm making a django app in which the homepage shows list of internships available of different companies.A user of usertype=Student can view those internships. Each internship list view has a button named 'Apply' when apply is clicked I want the booleanfield in my django model(StudentApplying) named applied to be set to true. So that the company who created this post can view the list of students who applied and then can accept/reject them. I don't want to use ajax,javascript etc unless there is no way I can't do it with django itself.

models.py >

from django.db import models
from InternsOnboardMain.models import internshipPost
from django.contrib.auth.models import User

class StudentApplying(models.Model):
    companyName = 
models.ForeignKey(internshipPost,on_delete=models.CASCADE)
    studentName = models.ForeignKey(User,on_delete=models.CASCADE)
    applied = models.BooleanField(default=False)

view.py 我已经尝试过了,但是没有用

from django.shortcuts import render, redirect,get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import StudentApplying
from django.contrib.auth.models import User
from django.db.models import F

def applyStatus(request):
    if request.GET.get('applybtn'):
        profil = get_object_or_404(StudentApplying, 
        created_by=request.user)
        profil.applied = True
        profil.save(update_fields=["applied"])
        return redirect('InternsOnboard-Home')
    return HttpResponse('Not done')

我没有使用任何表格。py

html文件

<form method="POST" action="{% url 'Student-Apply' %}">
{% csrf_token %}
<button class="btn btn-info" name="applybtn">Apply</button>
</form>

没有必要添加标签

推荐答案

再检查一点,问题似乎是您尝试提交一个空表格。因此,您应该尝试执行以下操作:

Checking this a little more, the problem looks like that you try to submit an empty form. So you should try to do the following:

在视图中:

if "applybtn" in request.POST:
    # do this and that

按钮的名称将出现在请求中,因此应该可以使用。

The name of the button will be in the request thus it should work.

这篇关于在django中单击按钮时如何更改模型字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆