我正在使用django-import-export在迁移文件中加载csv文件,据我了解,这是Django 1.7加载初始数据的当前最佳做法。这对于第一个文件效果很好:
class Country(models.Model):
ISO2 = models.CharField(max_length=2, primary_key=True)
name = models.CharField(max_length=50, unique=True)
Run Code Online (Sandbox Code Playgroud)
以及整个迁移文件的内容。请注意,ISO2是主键,因此需要添加行import_id_fields = ['ISO2']。针对以下问题的答案改编了代码:使用Django 1.7加载初始数据和数据迁移:
from django.conf import settings
import tablib
from import_export import resources
from web.models import Country
import os
import csv
# load initial data - assume it is all in web/fixtures directory
class CountryResource(resources.ModelResource):
class Meta:
model = Country
import_id_fields = ['ISO2']
fixture_dir = os.path.abspath(os.path.join(settings.PROJECT_ROOT, 'web/fixtures'))
fixture_filename = 'web_country.csv'
def load_fixture(apps, schema_editor):
fixture_file = os.path.join(fixture_dir, fixture_filename)
with open(fixture_file, 'r') as content_file:
content …Run Code Online (Sandbox Code Playgroud) 该应用程序具有可在会话中设置的类别字段,但可能不是.如果是,我不希望看到表单上的字段只是将其作为隐藏字段,其值等于请求中的值.如果没有设置,那么我想显示一个下拉列表.
我已经设置了表单以包含下拉列表,这是此字段的默认值,我的问题是,将窗口小部件更改为隐藏的最佳位置在哪里,请记住我需要请求所以我无法在表单init,这是显而易见的地方.
试过这种方法,但这个领域仍然可见:
class DocForm(forms.ModelForm):
class Meta:
model = Document
fields = __all__
widgets = {"creator": forms.HiddenInput(),}
def __init__(self, *args, **kwargs):
#cant do it here because don't have request
class DocAddView(CreateView):
form_class = DocForm
def get_form_class(self):
form_class = super(DocAddView, self).get_form_class()
form_class.Meta.widgets['category'] = forms.HiddenInput()
return form_class
Run Code Online (Sandbox Code Playgroud) 几乎有这个工作,但......
javascript调用django像这样:
.sortable({
connectWith: '.object',
update: function() {
var order = $(this).sortable('serialize');
$.ajax({
type: "POST",
data: order,
url: "/focus_upd/"
});
....
Run Code Online (Sandbox Code Playgroud)
并且在focus_upd函数中,数据到达正常
POST:<QueryDict: {u'task[]': [u'29', u'20', u'29', u'28']}>,
Run Code Online (Sandbox Code Playgroud)
但如果我参考request.POST ['task []']我得到28
为什么会发生这种情况?如何获得整个列表?
我想在查询集中包含一个月份数字,其中日期在相关模型中。这是我尝试过的:
OrderItem.objects.all().annotate(order_month=Sum('order__payment_date__month'))[0].__dict__
Join on field 'payment_date' not permitted. Did you misspell 'month' for the lookup type?
Run Code Online (Sandbox Code Playgroud)
然后我试过了
OrderItem.objects.all().extra(select={'order_month': "order__payment_date__month"})
(1054, "Unknown column 'order__payment_date__month' in 'field list'")
OrderItem.objects.all().extra(select={'order_month': "order.payment_date"}).select_related('Order')
(1054, "Unknown column 'order.payment_date' in 'field list'")
Run Code Online (Sandbox Code Playgroud)
但这有效,因此 order.payment_date 没有问题
OrderItem.objects.all().values('id','order__payment_date').select_related('Order')
Run Code Online (Sandbox Code Playgroud)
我在查询集结果中需要它,因为我在 Geraldo 中使用查询集。有谁知道我怎么能得到这个?
答案是在额外的部分中,您需要指定您想要的内容,以便 MySQL 理解它。就我而言,在模型名称前添加应用程序。在这种情况下,web_order.payment_date。这有效:
OrderItem.objects.all().extra(select={'order_month': "MONTH(web_order.payment_date)"}).select_related('order')[0].__dict__
{'product_id': None, 'order_id': 1L, 'price': Decimal("1.00"), 'order_month': 7L, 'id': 1L}
Run Code Online (Sandbox Code Playgroud) I have a simple model::
class HasUUID(models.Model):
name = models.CharField(max_length=10)
batchid = models.UUIDField(default=uuid.uuid4(), unique=True)
Run Code Online (Sandbox Code Playgroud)
running makemigrations gives me the migration::
operations = [
migrations.CreateModel(
name='HasUUID',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=10)),
('batchid', models.UUIDField(default=uuid.UUID('79a2d9fe-e1d0-4d4b-884f-fad0bfb14f0f'), unique=True)),
],
),
]
Run Code Online (Sandbox Code Playgroud)
Running migrate gives me the new table no problem. But I can run makemigrations again and I get::
operations = [
migrations.AlterField(
model_name='hasuuid',
name='batchid',
field=models.UUIDField(default=uuid.UUID('3b96231c-5848-430b-aa90-b6e41b11fd0a'), unique=True),
),
]
Run Code Online (Sandbox Code Playgroud)
and while I have lived with this for a while, manually removing the …
我想添加一个href链接到前缀为#或!的所有单词.或者@如果这是文本
检查#bamboo并联系@Fred re #bamboo #garden
应转换为:
Check the <a href="/what/bamboo">#bamboo</a> and contact <a href="/who/fred">@Fred</a> re <a href="/what/bamboo">#bamboo</a> <a href="/what/garden">#garden</a>
Run Code Online (Sandbox Code Playgroud)
请注意#和@去不同的地方.
这是我所拥有的,只是做哈希...
matched = re.sub("[#](?P<keyword>\w+)", \
'<a href="/what/(?P=keyword)">(?P=keyword)</a>', \
text)
Run Code Online (Sandbox Code Playgroud)
任何一位专家都能指出我正确的方向.我是否需要为每个符号分别进行匹配?
整个晚上都看不到我错过的东西:
JS:
$(document).ready(function() {
$("#form").submit(function () {
var txt = $('textarea[name=text]').val();
$.ajax({
type: "POST",
url: "/parse_text/",
data: {"text": txt},
dataType: "text",
success: function(h) {
alert('ok');
},
error: function() {
alert('failed');
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
和django代码:
def parse_text(request):
return HttpResponse("hello", mimetype="text'/plain")
Run Code Online (Sandbox Code Playgroud)
我无法让它触发成功方法.使用萤火虫我可以看到django返回"你好"并且状态为200.
我也尝试过改为json(虽然我真正想要的是返回一个html表).
在js中:
dataType: "json",
Run Code Online (Sandbox Code Playgroud)
在视图中:
return HttpResponse('[{"hello": "hello"}]', mimetype="application'/json")
Run Code Online (Sandbox Code Playgroud)
现在返回[{"hello":"hello"}]和200状态.
我究竟做错了什么!?
最终工作代码:
$(document).ready(function() {
$("#form").submit(function () {
var txt = $('textarea[name=text]').val();
$.ajax({
type: "POST",
url: "/parse_text/",
data: {text : txt},
success: function(html) {
$("#actions").html(html);
},
error: function() {
alert("fail"); …Run Code Online (Sandbox Code Playgroud)