变量在get_context_view()
内定义,因为它需要id
来访问正确的数据库对象:
class FooView(TemplateView):
def get_context_data(self, id, **kwargs):
---
bar = Bar.objects.get(id=id)
---
def post(self, request, id, *args, **kwargs):
# how to access bar?
# should one call Bar.objects.get(id=id) again?
将bar
变量传递给post()
的方式是什么?
尝试将其保存为FooView的字段并通过self.bar
访问它,但这不起作用。 self.bar
post()
答案 0 :(得分:4)
你应该扭转它。如果bar
中需要post()
,则需要在那里创建:
class FooView(TemplateView):
def get_context_data(self, **kwargs):
bar = self.bar
def post(self, request, id, *args, **kwargs):
self.bar = Bar.objects.get(id=id)
...
在post()
之前调用 get_context_data
,这就是post
如果您在get_context_data
中定义它就看不到它的原因。
答案 1 :(得分:0)
正如knbk所说,我的解决方案是调度方法,在那里我定义了将在get_context_data和post方法中使用的变量,这些变量对我来说是共享数据的一种方式 这是我的例子
class _AddWalkinServiceScheduleScreenState
extends State<AddWalkinServiceScheduleScreen>
with TickerProviderStateMixin {
final GlobalKey<FormState> _formkey = GlobalKey<FormState>();
AddWalkinModel model;
bool autovalidate = false;
final TextEditingController _bspBusinessLegalAddress =
TextEditingController();
LocationResult _pickedLocation;
Map<String, dynamic> _typeValue;
AnimationController controller;
Animation<double> animation;
final TextEditingController _serviceDate = TextEditingController();
TextEditingController _serviceTime = new TextEditingController();
String _isoDate;
String addresschoice;
List<String> _imageFilesList2 = [];
List<File> _licenseImages2 = [];
bool _isFlexible = false;
String _serviceType;
List<dynamic> _type = <dynamic>[];
@override
void initState() {
super.initState();
}
Widget _builddate() {
return Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5.0),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 11),
child: Text(
"Date",
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
),
_buildservicedate(),
],
),
);
}
Widget _buildselectAddress() {
return Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5.0),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 11),
child: Text(
"Select Address",
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
),
_buildaddresschoice(),
addresschoice == "Current Location"
? _addressTextfield()
: (addresschoice == "Select from address book" ||
model.address != null)
? _addressTextfield()
: SizedBox(),
_buildServicetype()
],
),
);
}
Widget _addressTextfield() {
return TudoTextWidget(
prefixIcon: Icon(FontAwesomeIcons.mapMarkedAlt),
labelText: "Address",
hintText: "Address",
controller: _bspBusinessLegalAddress,
validator: (val) =>
Validators.validateRequired(val, "Address"),
);
}
Widget _buildServicetype() {
return FormBuilder(
autovalidate: autovalidate,
child: FormBuilderCustomField(
attribute: "Select Address",
validators: [FormBuilderValidators.required()],
formField: FormField(
builder: (FormFieldState<dynamic> field) {
return InputDecorator(
decoration: InputDecoration(
prefixIcon: Icon(Icons.business_center),
errorText: field.errorText,
),
isEmpty: _typeValue == [],
child: new DropdownButtonHideUnderline(
child: DropdownButton(
hint: Text("Service Type"),
isExpanded: true,
items: [
"Normal",
"Urgent",
"Emergency",
].map((option) {
return DropdownMenuItem(
child: Text("$option"),
value: option,
);
}).toList(),
value: field.value,
onChanged: (value) {
field.didChange(value);
_serviceType = value;
},
),
),
);
},
)),
);
}
Widget content(BuildContext context, AddWalkinServiceDetailViewModel awsdVm) {
var colorStyles = Theming.colorstyle(context);
Orientation orientation = MediaQuery.of(context).orientation;
return Scaffold(
backgroundColor: colorStyles['primary'],
appBar: AppBar(
elevation: 0,
title: Text("Service Details"),
centerTitle: true,
),
bottomNavigationBar: Container(
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new FlatButton.icon(
icon: Icon(FontAwesomeIcons.arrowCircleRight),
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 30),
label: Text('Search'),
color: colorStyles["primary"],
textColor: Colors.black,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(7),
),
onPressed: () {
setState(() {
autovalidate = true;
});
if (_formkey.currentState.validate()) {
List<ServicePicture> id1Images = [];
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ServiceProviderMapScreen(
addWalkinModel: model,
),
),
);
}
}
),
],
),
),
body: FadeTransition(
opacity: animation,
child: Container(
child: Form(
autovalidate: autovalidate,
key: _formkey,
child: Stack(
children: <Widget>[
SingleChildScrollView(
padding: EdgeInsets.all(16.0),
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
_builddate(),
_buildflexible(),
],
),
),
)
],
),
),
),
),
);
}
@override
Widget build(BuildContext context) {
return new StoreConnector<AppState, AddWalkinServiceDetailViewModel>(
converter: (Store<AppState> store) =>
AddWalkinServiceDetailViewModel.fromStore(store),
builder: (BuildContext context, AddWalkinServiceDetailViewModel awsdVm) =>
content(context, awsdVm),
);
}
}
Classy CBV 希望对您有帮助
答案 2 :(得分:0)
如果在您的 CBV(基于类的视图)中定义了该变量,则可以直接在您的模板中调用它。
视图.py
class SomeRandomView(FormView):
username = 'SomeValue'
模板.html
<p>Username is {{view.username}}<p>
旁注:如果我没记错的话,您甚至可以直接在 Django 1.5 版之后的模板文件中调用视图类中的方法。