我正试图从index.html的下拉菜单中将数据发送到数据库,这就是为什么我创建了models.py作为名为Program的初始类,然后使用它来使用ForeignKey联系类。在admin.py注册联系人,后来我在index.html中使用类名程序,它正在呈现程序的名称,这是我在django的管理面板输入的。但问题是{{ program2 }确实在索引页显示,但是当用户转到表单并选择并提交此program2数据时,不会将其发送到数据库。如何使用下拉列表将值发送到数据库。帮助欣赏,接受从我的方式解决它。
models.py
class Program(models.Model):
program1 = models.CharField(max_length=50, default='')
class Contact(models.Model):
name = models.CharField(max_length=50, primary_key=True)
contact = models.CharField(max_length=50, default='')
address = models.TextField(max_length=1000, default='')
program2 = models.ForeignKey(Program, on_delete=models.CASCADE, null=True, blank=True)
# program = models.CharField(max_length=50, default='')
# bba = models.CharField(max_length=50, default="")
# bhm = models.CharField(max_length=50, default="")
email = models.CharField(max_length=50, default="")
w3review = models.TextField(max_length=1000, default="")
def __str__(self):
return self.nameviews.py
def index(request):
if request.method == 'POST':
name = request.POST.get('name', '')
contact = request.POST.get('contact', '')
address = request.POST.get('address', '')
program2 = request.POST.get('mba', '')
# bba = request.POST.get('bba', '')
# bhm = request.POST.get('bhm', '')
email = request.POST.get('email', '')
w3review = request.POST.get('w3review', '')
if name and contact and address and email and w3review and program2:
contact = Contact(name=name, contact=contact, address=address, email=email, w3review=w3review, program2=program2)
contact.save()
else:
return HttpResponse("Enter all details")
return render(request, 'index.html')index.html
<label for="cars">Choose Program:</label>
<select name="cars" id="cars">
<option id="mba" name="mba">{{program2}}</option>
<option id="bba" name="bba">BBA</option>
<option id="bhm" name="bhm">BHM</option>
</select>发布于 2021-05-24 18:39:33
首先,您需要将program2添加到contect dict中,以使其在html中可用,如
return render(request, 'index.html', {'program2': program2})对于提交问题,您需要在index.html中发布完整的表单
https://stackoverflow.com/questions/67677120
复制相似问题