我知道这将是一个非常基本的问题.
在Django中,我已经成功创建了一个管理面板.现在我想在我的一个字段即Photo字段中添加一个自定义搜索框.但我不知道如何在django-admin面板中添加自定义搜索框.如果我得到一些适当的提示,我相信我能做到.
Admin.py:
from django.contrib import admin
from photo.models import Photo,
class PhotoAdmin(admin.ModelAdmin):
list_display=('name','approved','approved_time','uploaded_time','user')
Run Code Online (Sandbox Code Playgroud)
models.py:
class Photo(models.Model):
name = models.CharField(max_length = 100)
photo = models.ImageField(upload_to = 'photos', blank=False,null=True)
approved = models.BooleanField(default = False)
approved_time = models.DateTimeField(auto_now=True,null=True,blank=True)
uploaded_time = models.DateTimeField()
description = models.CharField(max_length = 500 , blank = False , null = True)
keyword = models.CharField(max_length = 500 , blank = False , null = True)
image_id = models.CharField(max_length=300, blank=True, null=True)
Certified = models.BooleanField(default …Run Code Online (Sandbox Code Playgroud) 我有一个django模型,
class MyModel(models.Model)
qty = model.IntegerField()
Run Code Online (Sandbox Code Playgroud)
我想为qty这样的东西设置约束,> 0或<0,即qty可以是负数或正数但不能为0.
在Django有没有直接的方法呢?
我是django的新手,并使用django开发Web应用程序.我已经在我的Web应用程序中使用Userena成功设置了注册功能,并且可以注册为具有验证电子邮件的用户.我可以在settings.py文件中显示我的SMTP设置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'raihncse@gmail.com'
DEFAULT_FROM_EMAIL = 'raihncse@gmail.com'
SERVER_EMAIL = 'raihncse@gmail.com'
EMAIL_HOST_PASSWORD = '**************'
Run Code Online (Sandbox Code Playgroud)
在改变我的EMAIL_HOST_PASSWORD之前,一切都很好
事实上,由于某种原因,我必须更改该SERVER_EMAIL的先前密码(raihncse@gmail.com).我已经根据新的SERVER_EMAIL密码编辑了EMAIL_HOST_PASSWORD.
但现在,如果我想注册为新用户,我将面临以下错误
SMTPAuthenticationError at /accounts/signup/
(534, '5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvNq\n5.7.14 S3l1pFXENupDa_SdPphNHrnzeLPUOyf6O0l1s31w7h_UARx11P89AxPeeZ6xBi2KeQRjsw\n5.7.14 nvpxZhPVv771W9ljEDyeWnqpqv3_nakuPo36BEl3IlYj9qVujNB5cm0TYFf9LQAxRjFdda\n5.7.14 xh-y5spA9zIQONDsvRRgN3e0DXoIkgxTO3Mu75IaACi-XlvFtFfPBiQ81gUrBZ_PhZsBmh\n5.7.14 ajsSf-flNEmoSydyOTNdmwdB0__8> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 40sm12125121qgi.47 - gsmtp')
Run Code Online (Sandbox Code Playgroud) 我是Laravel的新手,目前正在与Laravel4合作.我正在尝试在我的项目中添加多列搜索功能.我可以做单列口才搜索查询,但老实说我不知道如何做多列滔滔不绝的搜索查询laravel.我有两个下拉菜单
1.Locatiom 2.blood group.
我要搜索的用户有一定的血型对某些位置.那是,用户将选择一个位置和血型来自这两个在时间下拉菜单,然后点击搜索按钮.
在我的数据库中,我有两列,一列包含位置,另一列包含某个用户的血型.现在,这种搜索的雄辩查询应该是什么?
我在python和django中比较新,
我有以下休息api视图,
class InvoiceDownloadApiView(RetrieveAPIView):
"""
This API view will retrieve and send Terms and Condition file for download
"""
permission_classes = (IsAuthenticated,)
def get(self, invoice_id, *args, **kwargs):
if self.request.user.is_authenticated():
try:
invoice = InvoiceService(user=self.request.user, organization=self.request.organization).invoice_download(
invoice_id=invoice_id)
except ObjectDoesNotExist as e:
return Response(e.message, status=status.HTTP_404_NOT_FOUND)
if invoice:
response = HttpResponse(
invoice, content_type='application/pdf')
response['Content-Disposition'] = 'inline; filename={0}'.format(
invoice.name.split('/')[-1])
response['X-Sendfile'] = smart_str(invoice)
return response
else:
return Response({"data": "Empty File"}, status=status.HTTP_400_BAD_REQUEST)
Run Code Online (Sandbox Code Playgroud)
使用以下网址,
urlpatterns = [
url(r'^invoice/(?P<invoice_id>[0-9]+)/download/$', views.InvoiceDownloadApiView.as_view()),
Run Code Online (Sandbox Code Playgroud)
]
根网址格式如下,
url(r'^api/payments/', include('payments.rest_api.urls', namespace="payments")),
Run Code Online (Sandbox Code Playgroud)
当我呼叫端点时,
localhost:8000/api/payments/invoice/2/download/
Run Code Online (Sandbox Code Playgroud)
它出现以下错误,
TypeError …Run Code Online (Sandbox Code Playgroud) 我想在基于类的视图中使用django formset.这是观点,
class PeriodCreate(RequestPassingFormViewMixin, WammuCreateView):
model = Chain
template_name = 'dashboard/period_form.html'
form_class = ChainForm
def get_object(self):
chain = Chain.objects.get(pk=self.kwargs['chain_pk'])
return chain
def get_success_url(self):
return reverse('dashboard_period_list', kwargs={'chain_pk': self.object.chain.id, })
def get_context_data(self, **kwargs):
context = super(PeriodCreate, self).get_context_data(**kwargs)
return context
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(PeriodCreate, self).get_form_kwargs(*args, **kwargs)
chain = get_object_or_404(Chain, pk=self.kwargs['chain_pk'])
period = Period(chain=chain)
kwargs['instance'] = period
return kwargs
def get(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
PeriodInlineFormSet = inlineformset_factory(Chain, Period,
form=PeriodInlineForm,
can_delete=True,
extra=12)
PeriodInlineFormSet.form …Run Code Online (Sandbox Code Playgroud) 我的一个观点中有一个变量
def ViewName(request):
simple_variable = request.session['value']
Run Code Online (Sandbox Code Playgroud)
在同一个 views.py 文件中,我有另一个视图
def AnotherViewName(request):
--------------------
--------------------
Run Code Online (Sandbox Code Playgroud)
现在我想simple_variable在我的AnotherViewName视图中使用该变量,我已经尝试过
def AnotherViewName(request):
global simple_variable
Run Code Online (Sandbox Code Playgroud)
但是,它不起作用,现在我的问题是,如何在 Django 中使用从一个视图到另一个视图的变量,或者如何全局使用变量?
在提及的simple_variable是存储从值session和最初我不得不把上面给出内称之为ViewName视图。
我正在使用 Django 1.5
我有一个上传表单,每次表单提交后,我想清除发布的数据,实际上表单保存了提交的数据。我知道,如果我将页面重定向到其他页面就可以解决这个问题,但我不这样做不想重定向我的页面,因为提交数据后,该页面中会显示一条成功消息。那么我如何在不重定向我的页面的情况下清除我的表单?
这是我的views.py 文件
def UserImageUpload(request):
if request.method == 'POST':
form = DocumentForm(request.POST,request.FILES)
if form.is_valid():
messages.add_message(request, messages.SUCCESS, 'Your Image upload is waiting for Admin approval')
newdoc = Photo(photo = request.FILES['photo'],watermarked_image=request.FILES['photo'],user = request.user,name = request.POST['name'],description = request.POST['description'],keyword = request.POST['Image_Keyword'],uploaded_time=datetime.datetime.now(),Certified=request.POST['Certification'])
newdoc.save()
else:
messages.add_message(request, messages.ERROR, 'Please Complete All Fields To Submit Your Image')
else:
form = DocumentForm()
uploaded_image = Photo.objects.all()
return render_to_response('myprofile/user_image_upload.html',{'uploaded_image':uploaded_image,'form':form},context_instance = RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
这是我的 forms.py 文件
from django import forms
class DocumentForm(forms.Form):
photo = forms.ImageField(
label='Select A file',)
name = forms.CharField(label='Image Name',max_length=50,widget=forms.TextInput(attrs={'class' : …Run Code Online (Sandbox Code Playgroud) 我正在使用django 1.9.5和rest框架3.x(DRF)。我刚从django rest官方框架学习了教程,可以说它是从DRF开始的,我已经写了以下视图,URL以查看api的工作原理使用DRF,
意见
class DepartMentList(APIView):
"""
List of all departments or create a department
"""
def get(self, request, format=None):
departments = Department.objects.all()
serializer = DepartmentSerializer(departments)
return Response(serializer.data)
def post(self, request, format=None):
serializer = DepartmentSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
return Response(serializer._errors, status=status.HTTP_400_BAD_REQUEST)
Run Code Online (Sandbox Code Playgroud)
网址
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from organizations import views
urlpatterns = [
url(r'^departments/$', views.DepartMentList.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
Run Code Online (Sandbox Code Playgroud)
这是setting.py,我rest framework为DEFAULT_PERMISSION_CLASSES 添加了以下字典
REST_FRAMEWORK = {
# Use Django's …Run Code Online (Sandbox Code Playgroud) 我对 Django 比较陌生。我在过滤数据时遇到问题。我有两个模型,如下所示:
Account(models.Model):
name = models.CharField(max_length=60)
hotel = models.ForeignKey(Hotel)
account_type = models.CharField(choices=ACCOUNT_TYPE, max_length=30)
Transaction(models.Model):
account = models.ForeignKey(Account, related_name='transaction')
transaction_type = models.CharField(choices=TRANSACTION_TYPE, max_length=15)
description = models.CharField(max_length=100, blank=True, null=True)
date_created = models.DateTimeField(default=timezone.now)
Run Code Online (Sandbox Code Playgroud)
ACCOUT_TYPE是:
ACCOUNT_TYPE = (
(0, 'Asset'),
(1, 'Liabilities'),
(2, 'Equity'),
(3, 'Income'),
(4, 'Expense')
)
Run Code Online (Sandbox Code Playgroud)
我想过滤帐户类型所在Income且Expense在给定日期范围内的所有交易。如何在 Django 中组合这些过滤器?
我试过这样:
income_account = Account.objects.filter(account_type=3)
expense_account = Account.objects.filter(account_type=4)
transactions = Transaction.objects.filter(Q(
account=income_account,
date_created__gte=request.data['start_date'],
date_created__lte=request.data['end_date']
) & Q(
account=expense_account,
date_created__gte=request.data['start_date'],
date_created__lte=request.data['end_date'])).order_by('date_created')
Run Code Online (Sandbox Code Playgroud)
但它不起作用。它引发以下错误:
ProgrammingError: more than one row returned …Run Code Online (Sandbox Code Playgroud)