【问题标题】:Django views database value remains '\'\Django 视图数据库值仍然是 '\'\
【发布时间】:2018-01-10 10:57:08
【问题描述】:

我是 web-dev 的新手,并被要求使用 Django 和 Ajax 编写调查。我在数据库中更新值时遇到了一些麻烦。如图所示

即使打印了值,我的 SQL 值也始终为空(RxCx 是它从 request.POST.get 获得的值)

模型.py

class Office(models.Model):
    Office_Space = (
        ('R1B1', 'R1B1'),
        ('R2B1', 'R2B1'),
        ('R3B1', 'R3B1'),
        ('R1B2', 'R1B2'),
        ('R2B2', 'R2B2'),
        ('R3B2', 'R3B2'),
        ('R1B3', 'R1B3'),
        ('R2B3', 'R2B3'),
        ('R3B3', 'R3B3')
    )
    space = models.CharField(max_length=4, choices=Office_Space) 

Forms.py

 from django import forms
 from Survey.models import Office 

 class officeForm(forms.ModelForm):
     class Meta:
         model = Office
         fields = ['space',]

视图中的功能(视图写得不好,但如果我这样做,表单最终会无效......)

def get_Office(request):
    form_class = officeForm

    if request.method == 'POST':
        space = request.POST.get('result')  
        response_data = {}      
        print(space) # here is the RxCx printed for debugging
        response_data['space'] = space
        form = Office()
        form.save()
        print (connection.queries) #the SQL log          
        return JsonResponse(response_data)
    else:
        form = officeForm()
    return render(request, 'Front.html', {'officeform': form})

提前致谢。

【问题讨论】:

  • 如果以下任何一个答案帮助您解决了您的问题,请将其中一个标记为正确,谢谢。这是 StackOverflow 中的一个好习惯 :)

标签: jquery sql ajax django forms


【解决方案1】:

您没有传递form 任何数据(!),这就是它为空的原因。为了工作,将response_data dict 传递给form。像这样:

form = Office(response_data)

更正:上述行仍然不起作用,因为Office 是模型,您需要声明为form_class 的表单。所以,

form = form_class(response_data)

或者更好的是,删除 form_class = officeForm 行,然后写:

form = officeForm(response_data)

【讨论】:

    【解决方案2】:

    view.py

    def get_Office(request):
        form_class = officeForm(request.POST or None)
    
        if request.method == 'POST':
            if form_class.is_valid():
                space = request.POST.get('result')  
                response_data = {}      
                print(space) # here is the RxCx printed for debugging
                response_data['space'] = space
                form_class.save()
                print (connection.queries) #the SQL log          
                return JsonResponse(response_data)
    
        return render(request, 'Front.html', {'officeform': form_class})
    

    【讨论】:

    • 谢谢!所以我尝试了这个功能;但是,每次我单击一个单选按钮时 form_class 都无效(因为其余部分未填写)。但是每次用户单击单选按钮时,我都需要某种更新。如何避免 is_valid 为假?
    猜你喜欢
    • 2011-04-15
    • 2020-03-08
    • 2017-03-21
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多