django 如何将dictionary转换为JavaScript并使用它来更改复选框值?

bvjxkvbb  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(158)

我想cahnge我的复选框正在检查使用dicitonary。我无法得到的字典JavaScript太这是我的models.py

# Create your models here.
class Logs(models.Model):
    id=models.AutoField(primary_key=True)
    name=models.CharField(max_length=200)
    email=models.EmailField(max_length=200,unique=True)
    password=models.CharField(max_length=200)
    checkbox_dict = models.JSONField(null=True, blank=True, default=dict)
    created=models.DateTimeField(auto_now_add=True)
    updated=models.DateTimeField(auto_now=True)
    def get_special_combination_value(self):
        return '{}{}'.format(self.name,self.password)

字符串
这是我的views.py

from django.shortcuts import render,redirect
from django.contrib.auth.forms import AuthenticationForm
from .models import Logs
from .forms import Login
from django.contrib import messages
from django.contrib.auth import authenticate, login ,logout
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
import json
from django.http import JsonResponse
# Create your views here.
def loger(request):
    formy = AuthenticationForm()
    c=[]
    a=Logs.objects.all()
    if request.method == 'POST':
        formy = AuthenticationForm(data=request.POST)
        name=request.POST.get('username')
        password = request.POST.get('password')
        obj=Logs()
        obj.get_special_combination_value
        for b in a:
            if name == b.name and password == b.password:
                return redirect('ticket',pk=b.id)
    return render(request,'project/loger.html',{'formy':formy,'a':a})
def homepage(request):
    form=Login()
    if request.method=='POST':
        form=Login(request.POST)
        if form.is_valid():
            user=form.save()
            return redirect('ticket',pk=user.pk)
    return render(request,'project/homepage.html',{'form':form})

def ticket(request,pk):
    tic=Logs.objects.get(id=pk)
    return render(request,'project/ticket.html',{'tic':tic})
def forgor(request):
    a=Logs.objects.all()
    if request.method=='POST':
        username=request.POST.get('name')
        password=request.POST.get('password')
        obj=Logs()
        obj.get_special_combination_value
        Logs.objects.filter(name=username).update(password=password)
        return redirect('homepage')
    return render(request,'project/forgor.html',{'a':a})
def plane(request,pk):
    log_instance = Logs.objects.get(pk=pk)

    if request.method == 'POST':
        checkbox_dict_json = request.POST.get('checkboxDict')
        if checkbox_dict_json:
            # Parse the JSON data from the request
            checkbox_dict = json.loads(checkbox_dict_json)
            
            # Update the 'json_data' field of the instance with the new JSON data
            log_instance.json_data = checkbox_dict
            Logs.objects.update(checkbox_dict=checkbox_dict)
    
    # Retrieve the JSON data from the instance
    checkbox = log_instance.checkbox_dict
    print(checkbox)

    return render(request, 'project/plane.html', {'checkbox':checkbox})


这是我的飞机.html(缩短版本)

<!DOCTYPE html>
    <html>
    <head>
        <style>
            .container {
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
            }

            .a, .b {
                transform: scale(2.5);
            }

            .b {
                margin-left: 200px; /* Add margin between the two divs */
            }

            /* Additional CSS to adjust the layout */
            .a, .b {
                display: inline-block;
            }
            #sub
            {
                margin-bottom: -200px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <form method="POST" action="">
                {% csrf_token %}
                <div class="a">
                    <table>
                <tr>
                    <td>
                    <input type="checkbox" name="seat">
                    </td>
                    <td>
                    <input type="checkbox" name="seat">
                    </td>
                    <td>
                    <input type="checkbox" name="seat">
                    </td>
                </tr>
                <tr>
                    <td>
                    <input type="checkbox" name="seat">
                    </td>
                    <td>
                    <input type="checkbox" name="seat">
                    </td>
                    <td>
                    <input type="checkbox" name="seat">
                    </td>
                </tr>
                <tr>
                    <td>
                    <input type="checkbox" name="seat">
                    </td>
                    <td>
                    <input type="checkbox" name="seat">
                    </td>
                    <td>
                    <input type="checkbox" name="seat">
                    </td>
                </tr>
                <tr>
                    <td>
                    <input type="checkbox" name="seat">
                    </td>
                    <td>
                    <input type="checkbox" name="seat">
                    </td>
                    <td>
                    <input type="checkbox" name="seat">
                    </td>
                </tr>
                <tr>


这是我的JavaScript

<script>
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#myForm').addEventListener('submit', function(event) {
    event.preventDefault();
    var checkboxDict = {};
    var checkboxes = document.querySelectorAll('input[type="checkbox"]');
    checkboxes.forEach(function(checkbox) {
        checkboxDict[checkbox.id] = checkbox.checked;
    });

    // Set the value of the hidden input to the JSON representation of checkboxDict
    document.querySelector('#checkboxDict').value = JSON.stringify(checkboxDict);

    // Now submit the form
    this.submit();
});
});
let dic= {% autoescape off %}{{checkbox}}{% endautoescape %};
for(const[i,j] of Object.entries(dic))
{
console.log(i,j)
}
</script>


我面临的问题,在得到字典,我的JavaScript和改变复选框被勾选

fkaflof6

fkaflof61#

复选框只是一个布尔字段:
https://docs.djangoproject.com/en/4.2/ref/models/fields/#booleanfield
当你为此构建视图和表单时,只需从模型中引用布尔字段。这将默认显示为复选框。如果你想要复选框以外的任何东西(例如开/关滑块),你可以覆盖小部件。
在你的例子中,我猜你不想在你的模型上有一个布尔型字段,你想要一个座位号。
然后,您的视图获取座位号并决定模板上的哪个复选框应该被选中,当表单被POST时,视图执行相反的操作-检查哪个座位被选中并将其转换为座位号以存储在数据库中。
评论后编辑:
每个复选框都需要在您提交的表单中,这样您就可以在视图中查询数据。然后您可以在各个复选框字段中进行搜索,当您找到选中的复选框时,您可以设置座位号。
为此,您需要为每个座位复选框分配一个唯一的ID,以便您知道每个座位实际上指的是哪个座位。

相关问题