iT邦幫忙

0

Django 動態下拉式選單連接資料庫

想要詢問一下
django 網頁下拉式選單
但下拉式選單內容的資料是要抓models某個資料表的欄位

models.py

class Category(models.Model):
c_name = models.CharField(db_column='C_name', primary_key=True, max_length=10)

class Article(models.Model):
a_id = models.AutoField(db_column='A_id', primary_key=True)
a_title = models.CharField(db_column='A_subject', max_length=20)
c_name = models.ForeignKey('Category', models.DO_NOTHING, db_column='C_name')
a_content = models.TextField(db_column='A_content')

c_name在html要呈現下拉式選單該如何撰寫viwe和html

1 個回答

1
froce
iT邦大師 2 級 ‧ 2019-04-02 08:10:01
最佳解答

views.py

def dropdownMenu(request):
    allCategory = Category.objects.all()
    return render(request, "dropdownMenu.html", {'allCategory': allCategory})

dropdownMenu.html

<select>
    {% for c in allCategory %}
    <option>{{ c.c_name }}</option>
    {% endfor %}
</select>
看更多先前的回應...收起先前的回應...
zxc990398 iT邦新手 5 級 ‧ 2019-04-02 17:47:09 檢舉

allCategory = Category.objects.all()
if request.method == "POST": #如果是以POST方式才處理
nnn = bbb(request.POST) #建立forms物件
if nnn.is_valid(): #通過forms驗證
nickname = nnn.cleaned_data['nickname']
n_subject = nnn.cleaned_data['n_subject']
n_content = nnn.cleaned_data['n_content']
n_date = nnn.cleaned_data['n_date']
display = nnn.cleaned_data['display']
c_name = nnn.cleaned_data['c_name']
unit = Subscription.objects.create(nickname=nickname, n_subject=n_subject, n_content=n_content,n_date=n_date,display=display,c_name=c_name)
unit.save() #寫入資料庫
message = '已儲存...'
return redirect('/Newall/')
else:
message = '驗證碼錯誤!'
else:
message = '姓名、性別、生日必須輸入!'
nnn = bbb()
return render(request, "New_N.html", locals(), {'allCategory': allCategory})
我用了你的寫法之後,網頁可以正常顯示 但我要讓我的表單送出,回傳給資料庫時 會寫出驗證碼錯誤 請問是我if判斷寫得不好嗎?

froce iT邦大師 2 級 ‧ 2019-04-03 08:31:13 檢舉

1.python的程式碼是需要縮排的,請利用站方編輯器的「新增程式碼(</>這個按鈕)」把你的code依照縮排來呈現。
2.對那個變數有問題,在迴圈前先把變數print出來。
也就是我會這樣做:

print(nnn.is_valid())
if nnn.is_valid():
    ...

3.進階debug技巧:善用type()、dir()來檢查變數類型和變數的屬性、方法

zxc990398 iT邦新手 5 級 ‧ 2019-04-03 15:33:28 檢舉

views

def New_N(request):
	allCategory = Category.objects.all()
	now =  datetime.now()
	if request.method == "POST":
		nnn = bbb(request.POST)
		if nnn.is_valid():
			nickname =  nnn.cleaned_data['nickname']
			n_subject =  nnn.cleaned_data['n_subject']
			n_content = nnn.cleaned_data['n_content']
			display =  nnn.cleaned_data['display']
			c_name =  nnn.cleaned_data['c_name']
			unit = Subscription.objects.create(nickname=nickname, n_subject=n_subject, n_content=n_content,n_date=now,display=display,c_name=c_name)
			unit.save()
			message = '已儲存...'
			return redirect('/Newall/')	
		else:
			message = '驗證碼錯誤!'	
	else:
		message = '暱稱、標題、內容必須輸入!'
		nnn = bbb()
	return render(request, "New_N.html", locals(), {'allCategory': allCategory})

forms

from django import forms
from django.forms import widgets

class bbb(forms.Form): #最新消息
	nickname = forms.CharField(max_length=20,initial='')  # Field name made lowercase.
	n_subject = forms.CharField(max_length=20,initial='')
	n_content = forms.CharField(widget=forms.Textarea)
	display = forms.BooleanField(required=False)
	c_name = forms.CharField(widget=widgets.Select())

models

class Category(models.Model):
    c_name = models.CharField(db_column='C_name', primary_key=True, max_length=10)  # Field name made lowercase.

    class Meta:
        managed = False
        db_table = 'category'


class New(models.Model):
    new_id = models.AutoField(primary_key=True)
    nickname = models.CharField(max_length=20)
    n_subject = models.CharField(db_column='N_subject', max_length=20)  # Field name made lowercase.
    n_content = models.TextField(db_column='N_content')  # Field name made lowercase.
    n_date = models.DateTimeField(db_column='N_date')  # Field name made lowercase.
    display = models.IntegerField()
    clicks = models.IntegerField()
    c_name = models.ForeignKey(Category, models.DO_NOTHING, db_column='C_name')  # Field name made lowercase.

    class Meta:
        managed = False
        db_table = 'new'

html

{% extends "base.html" %}
{% block title %}<title>資料新增</title>{% endblock %}
{% block content %}
	<h2>最新消息資料新增</h2>
	<form action="." method="POST" name="form1">
	{% csrf_token %}
	<table border="1" cellspacing="1" cellpadding="5">
		<tr><th>暱稱</th><td>{{nnn.nickname}}</td></tr>
		<tr><th>標題</th><td>{{nnn.n_subject}}</td></tr>
		<tr><th>內容</th><td>{{nnn.n_content}}</td></tr>
		<tr><th>時間</th><td>{{now}}</td></tr>
		<tr><th>顯示</th><td>{{nnn.display}}是</td></tr>
		<!-- <tr><th>點擊數</th><td>{{nnn.clicks}}</td></tr> -->
		<tr><th>類別</th><td><select>{% for c in allCategory %}<option>{{ c.c_name }}</option>{% endfor %}
</select></td></tr>
		<tr>
		<th align="center" >
		  <input type="submit" name="button" id="button" value="送出">
		  <input type="reset" name="button2" id="button2" value="重設">
  		 
		  <td> <a href="/Newall">最新消息</a> </td>
		</th>
		</tr>

		</table>
		<span style="color:red">{{message}}</span>
		</form>
{% endblock %}

麻煩您了

views

println(nnn.errors)

試試看

我要發表回答

立即登入回答