我知道根据文档,以下字段不采取allow_blank=True和allow_null=True
BooleanField()
IntegerField()
Run Code Online (Sandbox Code Playgroud)
我需要允许客户端不指定g或d(如下所示)并将值存储在DB中None.
g = serializers.BooleanField()
d = serializers.IntegerField()
Run Code Online (Sandbox Code Playgroud)
有任何想法吗 ?
当我尝试运行此测试时:
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.test import Client
class StatisticTest(TestCase):
def setUp(self):
self.client = Client()
def test_schedule_view(self):
url = reverse('schedule')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'schedule.html')
Run Code Online (Sandbox Code Playgroud)
我得到AssertionError:没有用于呈现响应的模板。
我的看法是:
class Schedule(View):
def get(self, request):
games = add_team_info(query.get_current_schedule())
if games is not []:
available_schedules = generate_schedule_list(games[0]["season_type"], games[0]["week"])
is_available = True
else:
available_schedules = []
is_available = False
return render_to_response("schedule.html",
{"games": games, "available_schedules": available_schedules, "is_available": is_available})
Run Code Online (Sandbox Code Playgroud)
和urls.py:
url(r'^schedule/$', views.Schedule.as_view(), name='schedule'),
Run Code Online (Sandbox Code Playgroud) 在模型形式中,我可以覆盖表单字段
class waypointForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ModelChoiceField(queryset=Waypoint.objects.filter(user=user))
Run Code Online (Sandbox Code Playgroud)
如何在基于类的视图中使用相同的功能CreateView,以便我可以覆盖表单字段?
我试过get_form_kwargs和get_form,但一切都是徒劳.我需要创建一个模型表单吗?
我想在我的系统中实现用户.我知道Django已经有了一个身份验证系统,我一直在阅读文档.但我不知道它们之间的区别
from django.contrib.auth.models import User
class Profile(User):
# others fields
Run Code Online (Sandbox Code Playgroud)
和
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User)
# others fields
Run Code Online (Sandbox Code Playgroud)
我不想知道为什么要使用这一个或另一个,但是在引擎盖下会发生什么.有什么不同?
我正在尝试设置Django API(POST API端点).我希望有相同的URL路径指向同一个处理不同的函数,因为它是POST或GET.因此,我使用了这样的方法
def handle_post(request):
dict = {}
dict['email'] = "test"
if request.method == "POST":
return HttpResponse(json.dumps(dict), content_type="application/json")
Run Code Online (Sandbox Code Playgroud)
在url.py中,我有以下代码
router = routers.DefaultRouter()
router.register(r'notes', UsernotesViewSet)
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^admin/', include(admin_site.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^docs/', include('rest_framework_swagger.urls')),
url(r'^example/postrequest', handle_post),
)
Run Code Online (Sandbox Code Playgroud)
但是当我在URL http://127.0.0.1:8000/example/postrequest?requestid=abc&starthour=10上执行POST时,我无法完成这项工作 .我没有发布任何内容,只是在httpclient上将方法从GET更改为POST以尝试此API.如果我没有将任何内容发布到URL,这样可以吗?
我收到403错误,如下所示:
禁止(403)
CSRF验证失败.请求中止.
您看到此消息是因为此站点在提交表单时需要CSRF cookie.出于安全原因,需要此cookie,以确保您的浏览器不会被第三方劫持.如果您已将浏览器配置为禁用cookie,请重新启用它们,至少对于此站点或"同源"请求.
感谢任何帮助.
我正在尝试向我的base.html添加一个haystack搜索,以便在我的网站上全局包含它.当我提交搜索时,它会出错
我正进入(状态:
Django-Haystack:'NoneType'对象没有属性'_default_manager'
我已将其添加到INSTALLED_APPS和我的urls.py. ./manage.py rebuild_index运行正常.
models.py:
class Site(models.Model):
site_name = models.CharField(max_length=100, blank=False, null=False)
site_manager = models.CharField(max_length=100, blank=False, null=False)
address_1 = models.CharField(max_length=100, blank=False, null=False)
address_2 = models.CharField(max_length=100, blank=True, null=True)
address_3 = models.CharField(max_length=100, blank=True, null=True)
town_city = models.CharField(max_length=100, verbose_name='Town/City')
county = models.CharField(max_length=100, blank=False, null=False)
postcode = models.CharField(max_length=100, blank=False, null=False)
region = models.CharField(max_length=100, blank=True, null=True)
tel = models.CharField(max_length=100, blank=False, null=False)
email = models.EmailField(max_length=100, blank=False, null=False)
creation = models.DateField(auto_now_add=True)
last_modified = models.DateField(auto_now=True)
def __unicode__(self):
return self.site_name
Run Code Online (Sandbox Code Playgroud)
SiteIndex.py:
class SiteIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用__init__参数将变量传递给 ModelForm clean 方法,但到目前为止还没有成功 - 我查看了 StackOverflow 上的各种帖子,但似乎没有一个有帮助。
我的代码如下:
forms.py
class property_booking_form(forms.ModelForm):
check_in_date = forms.DateField(widget=SelectDateWidget)
check_out_date = forms.DateField(widget=SelectDateWidget)
class Meta:
model = Properties_bookings
fields = ['check_in_date', 'check_out_date']
def __init__(self, property_id):
self.property_id = property_id
super(property_booking_form, self).__init__(self, property_id)
def clean(self):
check_in_date = self.cleaned_data.get('check_in_date')
check_out_date = self.cleaned_data.get('check_out_date')
property_min_nights = Properties.objects.get(id=self.property_id).property_minimum_nights
...
views.py
def view(request):
...
if request.method == 'POST':
booking_form = property_booking_form(request.POST, property_id=property_id)
if booking_form.is_valid():
...
else:
booking_form = property_booking_form(property_id=property_id)
return render(...)
Run Code Online (Sandbox Code Playgroud)
这会引发以下错误:“property_booking_form”对象没有属性“get”
根据错误描述,这似乎与小部件有关:
异常位置:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py in value_from_datadict, line 1058
Run Code Online (Sandbox Code Playgroud)
该表单在没有覆盖的情况下工作正常 …
我已经阅读了每一篇文章,并在过去的 4 个小时里用谷歌搜索,试图找到解决这个错误的方法。
我没有运行虚拟环境,该服务器仅用于 django。
服务器:Ubuntu 16.04
蟒蛇:3.5.2
我收到此错误
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?
Run Code Online (Sandbox Code Playgroud)
尝试安装 mysqlclient
sudo -H pip3 install mysqlclient
Requirement already satisfied: mysqlclient in /usr/local/lib/python3.5/dist-packages (1.3.12)
Run Code Online (Sandbox Code Playgroud)
使用 ubuntu
sudo apt-get install -y python3-mysqldb
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-mysqldb is already the newest version (1.3.7-1build2).
0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded.
Run Code Online (Sandbox Code Playgroud)
任何帮助是极大的赞赏
我收到这些错误
不支持在 include() 中指定命名空间而不提供 app_name。在包含的模块中设置 app_name 属性,或者传递包含模式列表和 app_name 的 2 元组。
我的代码如下所示
项目名称.urls
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('learning.urls',namespace='learning')),
]
Run Code Online (Sandbox Code Playgroud)
应用程序名称.url
from django.urls import path
from learning.views import SendEmail
urlpatterns = [
path('',SendEmail.as_view(),name='home')
]
Run Code Online (Sandbox Code Playgroud) 我正在尝试访问我的项目(本地),并且收到此回溯:
追溯
Page not found (404)
Request Method:
GET
Request URL:
http://127.0.0.1:8000/account/login/
Using the URLconf defined in tutorial.urls, Django tried these URL patterns, in this order:
[name='login_redirect']
admin/
account/ ^$
account/ ^login$
account/ ^logout$
account/ ^register$ [name='register']
account/ ^profile$ [name='view_profile']
account/ ^profile/edit$ [name='edit_profile']
account/ ^change-password$ [name='change_password']
account/ ^reset-password$ [name='reset_password']
account/ ^reset-password/done$ [name='password_reset_done']
account/ ^reset-password/confirm(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A- Za-z]{1,13}-[0-9A-Za-z]{1,23})/$ [name='password_reset_confirm']
account/ ^reset-password/complete$ [name='password_reset_complete']
The current path, account/login/, didn't match any of these.
Run Code Online (Sandbox Code Playgroud)
主/urls.py
from django.contrib import admin
from django.urls import path, re_path, include
from …Run Code Online (Sandbox Code Playgroud) django ×10
python ×7
assert ×1
django-1.9 ×1
django-forms ×1
django-urls ×1
http-post ×1
jinja2 ×1
mysql-python ×1
testing ×1