小编PK1*_*K10的帖子

添加中间表单后 Django 管理站点操作不起作用

我有一个 django 模型,我想为其添加自定义操作。在此操作中,我需要添加一个带有选择表单(下拉选择)的中间页面。我用下面的代码来得到这个。

模型类:

class VerificationAdmin(admin.ModelAdmin):
      list_display   = ('id','asset_code', 'scan_time','credential','status','operator','location','auth_code','product_details')
      list_filter    = ('status','operator','location')
      ordering       = ('-scan_time',)
      search_fields  = ('asset_code',)
      actions = ['set_interval']

      class AddScanningIntervalForm(forms.Form):
           _selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
           period_choice=["4 hrs","6 hrs","8 hrs","10 hrs","12 hrs"]
           interval = forms.ChoiceField(choices=[(x, x) for x in period_choice])

      @csrf_exempt
      def set_interval(self, request, queryset):
           print "before action"
           form = None
           if 'apply' in request.POST:
               form = self.AddScanningIntervalForm(request.POST)
               print "action taken"
               if form.is_valid():
                   interval = form.cleaned_data['interval']
                   print interval
                   count = 0
                   for vObj in queryset:
                       print vObj.asset_code,vObj.status,interval                
                       at=AlertTable(asset_code=vObj.asset_code,
                       status=vObj.status,interval=interval) …
Run Code Online (Sandbox Code Playgroud)

django django-models django-admin

5
推荐指数
1
解决办法
1327
查看次数

如何解析json数据python django?

我有JSON数据,我想解析它.

我使用了Code bellow:

def json_update(request):
     j = urllib2.urlopen('http://ec2-72-44-51-113.compute-1.amazonaws.com:8001/get_latest_verification')
     j_obj = json.load(j) 
     print j_obj.status
     return HttpResponse(j_obj.status)
Run Code Online (Sandbox Code Playgroud)

但是我收到了错误:

/ json_update中的AttributeError

'list'对象没有属性'status'

我的json数据:

[{"status": "Registered", "credential": "10000323xsds", "scan_time": "Jan.15,2014, 03:30 pm", "asset_code": "cls103", "emp_id": "LS07", "location": "BLR-10", "auth_code": "DSC(Verisign", "operator": "pradeep", "id": 538}]
Run Code Online (Sandbox Code Playgroud)

什么是解析json数据的正确方法.

但是当我将代码更新为:

更新的代码:

def json_update(request):
     j = urllib2.urlopen('http://ec2-72-44-51-113.compute-1.amazonaws.com:8001/get_latest_verification')
     j_obj = json.load(j)
     for jo in j_obj: 
      print j_obj[jo]['status']
     return HttpResponse(j_obj[jo]['status'])
Run Code Online (Sandbox Code Playgroud)

我收到错误:

/ error在/ json_update

list indices必须是整数,而不是dict

python django json

4
推荐指数
1
解决办法
1万
查看次数

为我的站点设置geoip时出错"GeoIP路径必须是有效的文件或目录"

对于我的django应用程序,我试图通过amdin存储登录位置的日志.

我创建了一个中间件并尝试使用"django.contrib.gis.utils import GeoIP"来获取地理位置的纬度和经度值.

但得到的错误如下:

/ admin /的GeoIPException

GeoIP路径必须是有效的文件或目录.

代码:trackware.py

from django.contrib.gis.utils import GeoIP
from core.models import Log # your simple Log model

def get_ip(request):
   xff = request.META.get('HTTP_X_FORWARDED_FOR')
   if xff:
      return xff.split(',')[0]
   return request.META.get('REMOTE_ADDR')

class UserLocationLoggerMiddleware(object):

    def process_request(self, request):
        if request.user and request.user.is_superuser:
            # Only log requests for superusers,
            # you can control this by adding a setting
            # to track other user types
            ip = get_ip(request)
            g = GeoIP()
            lat,long = g.lat_lon(ip)
            Log.objects.create(request.user, ip, lat, long)
Run Code Online (Sandbox Code Playgroud)

我在settings.py中 …

python django

3
推荐指数
2
解决办法
4937
查看次数

如何防止模型中的重复条目来自 django admin

我有一个应用程序有一个名为Verifications. 它具有诸如:asset_code、Status、Location、Emp_id 等字段。我可以使用 django 管理面板中的“添加验证”添加验证。但我想限制添加重复的 asset_code 条目(如果 asset_code 已经存在)。

class Verification(models.Model):
    asset_code = models.CharField(verbose_name="Asset Code",max_length=16, default="")
    scan_time = models.DateTimeField(verbose_name="Time of smartDNA scan",auto_now_add=True,default=datetime.datetime.now)
    credential = models.CharField(verbose_name="smartDNA Credential",max_length=16, default="")
    status = models.IntegerField(verbose_name="Scanning Status",choices=STATUS_CHOICES,default=1)
    operator = models.CharField(verbose_name="Operator",max_length=16, default="")
    location = models.CharField(verbose_name="Branch",max_length=64, default="")
    auth_code = models.CharField(verbose_name="Scanner Authentication",max_length=20, default="DSC(Verisign")
    emp_id = models.CharField(verbose_name="EMP ID",max_length=16, default="")
    image = models.CharField(verbose_name="Image",max_length=24, default="dd")
    created = models.DateTimeField(verbose_name="Created on",blank=True,auto_now_add=True)
    modified = models.DateTimeField(verbose_name="Modified on",blank=True,auto_now=True)
    product_details = models.CharField(verbose_name="Product Details",max_length=64, default="")
Run Code Online (Sandbox Code Playgroud)

状态字段的值可以介于 1 到 10 之间。

如果 asset_code 已经存在并且状态=1,我如何防止在模型中添加条目。

python mysql django django-forms django-validation

2
推荐指数
1
解决办法
7400
查看次数

属性错误对象没有属性cleaned_data

我的 views.py 鳕鱼:

def update_details(request):
   if request.method == "POST":
            form = UpdateDetailsForm(request.POST)
            if form.is_valid:
               asset_code=form.cleaned_data['asset_code1']
               fd=form.cleaned_data['product_details']
               verifications = Verification.objects.filter(asset_code__exact=asset_code)
               verifications.update(product_details=fd)

   return render_to_response('update_details.html',
                {'form':UpdateDetailsForm(),},
                context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

我想在我的模型中更新“product_details”列值,其中资产代码正是用户输入的内容。但是当我提交按钮时出现错误。

错误信息:

AttributeError 对象没有属性“cleaned_data”django

python mysql django

1
推荐指数
1
解决办法
7959
查看次数

使用字典编写数据库时“对象具有关键字参数的多个值”

我有一个字段的Django模型:citycountry_namecountry_code

我有一本字典,其中有超过8个键值对;我只想使用3并写入数据库。

但是我遇到一个错误

ModelBase object got multiple values for keyword argument 'country_code'

我的代码:

dicty = {
    'city': u'Mountain View', 'continent_code': u'NA', 'region': u'CA',
    'charset': 0, 'area_code': 650, 'longitude': -122.05740356445312,
    'country_code3': u'USA', 'latitude': 37.4192008972168, 'postal_code': u'94043',
    'dma_code': 807, 'country_code': u'US', 'country_name': u'United States'
}

m = Logger(city='city',country_name='country_name',country_code='country_code',**dicty)
m.save()
Run Code Online (Sandbox Code Playgroud)

python django django-models

1
推荐指数
1
解决办法
1049
查看次数

用Python解析字符串

我如何解析['FED590498']python中的字符串,因此我可以单独获取所有数值590498和字符FED.

一些样品:

['ICIC889150']
['FED889150']
['MFL541606']
Run Code Online (Sandbox Code Playgroud)

和[]不是字符串的一部分......

python string-parsing

0
推荐指数
1
解决办法
91
查看次数

将图像的色彩空间从RGB转换为HSV

我试图将rgb图像的颜色空间从RGB转换为HSV.我使用过以下代码:

public class Main {
   public static void main( String[] args )
   {
   try{
       System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
       File input = new File("H:/Development/workspace/label.png");
       BufferedImage image = ImageIO.read(input);   
       byte[] data=extractBytes(image);     
       Mat mat = new Mat(image.getHeight(),image.getWidth(),CvType.CV_8UC2);
       mat.put(0, 0, data);

       Mat mat1 = new Mat(image.getHeight(),image.getWidth(),CvType.CV_8UC2);
       Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2HSV);

       byte[] data1 = new byte[mat1.rows()*mat1.cols()*(int)(mat1.elemSize())];
       mat1.get(0, 0, data1);
       BufferedImage image1 = new BufferedImage(mat1.cols(), mat1.rows(), 5);
       image1.getRaster().setDataElements(0,0,mat1.cols(),mat1.rows(),data1);

       File ouptut = new File("H:/Development/workspace/label_hsv.png");
       ImageIO.write(image1, "png", ouptut);
      } catch (Exception e) {
         // System.out.println("Failed");
          System.out.println("Error: " + e.getMessage());
          e.printStackTrace(); …
Run Code Online (Sandbox Code Playgroud)

java opencv image-processing

0
推荐指数
1
解决办法
5255
查看次数