2017-04-21 29 views
2

我最近將Django從1.3升級到了1.8.18,並且在Django admin中對預填充表單的鏈接進行了定製。例如,我有以下鏈接:Django Admin轉義文本

/admin/miscellaneous/whatsnew/add/?title=...%20competition%20results%20uploaded&pub_date=21-04-2017&body=&link= 

執行時預填充數據的形式如下: enter image description here

,它應該是這樣的:

enter image description here

當直接從Safari的URL欄進行測試時,按下回車鍵後會更改爲:

https://flyball.org.au/admin/miscellaneous/whatsnew/add/?title=...%2520competition%2520results%2520uploaded&pub_date=21-04-2017&body=&link= 

models.py

class WhatsNew(models.Model): 
    title = models.CharField(max_length=100,help_text='Title, MAX 100 characters.') 
    body = models.TextField() 
    pub_date = models.DateField() 
    message_expiry = models.DateField(default=datetime.date.today() + relativedelta(years=1)) 
    link = models.URLField(blank=True, null=True) 

    class Meta: 
     ordering = ['-pub_date'] 
     verbose_name_plural = "Whats New?" 

    def __unicode__(self): 
     return self.title 

admin.py

import models 
from django.contrib import admin 

class WhatsNewAdmin(admin.ModelAdmin): 
    list_display = ('title','pub_date','message_expiry','link','body') 

admin.site.register(models.WhatsNew, WhatsNewAdmin) 

我能做些什麼來解決這個問題?

+1

你能不能也顯示負責填寫此表,即讀取來自查詢參數'title'並將其進料形式的代碼? – AKS

+0

@AKS我在這裏沒有做任何特殊的代碼,它是Django的一部分,不知道在哪裏可以找到它 –

+0

它確實對我有效。我嘗試使用'%20',並在管理員表單中顯示空格。 – AKS

回答

1

使用+而不是%20空間和它的作品。

你的鏈接應該是這樣的:

/admin/miscellaneous/whatsnew/add/?title=...+competition+results+uploaded&pub_date=21-04-2017&body=&link= 
2

因此,我不確定如何在ModelAdmin上做到這一點,但是您可以在模型上創建自定義setter來處理這種情況。這是我怎麼會去逃避URL編碼的字符串:

import urllib 


class WhatsNew(models.Model): 
    # Field with custom setter 
    _title = models.CharField(max_length=100, 
          help_text='Title, MAX 100 characters.', 
          db_column='title') 

    body = models.TextField() 
    pub_date = models.DateField() 
    message_expiry = models.DateField(default=datetime.date.today() + relativedelta(years=1)) 
    link = models.URLField(blank=True, null=True) 

    # Custom getter and setter 
    @property 
    def title(self): 
     return self._title 

    @title.setter 
    def title(self, value): 
     self._title = urllib.unquote(value) 

    class Meta: 
     ordering = ['-pub_date'] 
     verbose_name_plural = "Whats New?" 

    def __unicode__(self): 
     return self._title 
+0

這很有趣,以前沒有看過。我只用了'+'符號,它似乎已經解決了它。謝謝 –

+0

我剛剛看到了一些問題,特別是在Chrome中,它會阻止你在URL中插入符號並自動爲你編碼。我認爲這可能是發生了什麼,但我猜不是!很高興一切順利! – wholevinski