私信  •  关注

ruddra

ruddra 最近创建的主题
ruddra 最近回复了
5 年前
回复了 ruddra 创建的主题 » django只将参数从视图传递到窗体一次

我认为你不应该通过 otp GET 相反,请求应该由 POST 请求:

form = OTPAuthenticationForm(request.POST, request=request, otp=otp)

class OTPAuthenticationForm(AuthenticationForm):
    otp = forms.CharField(required=True, widget=forms.TextInput)

    def __init__(self, otp, *args, **kwargs):
       self.otp_value = kwargs.pop("otp", None)
       super(OTPAuthenticationForm, self).__init__(*args, **kwargs)

    def clean(self):
       otp = self.cleaned_data['otp']
       if self.otp_value != otp:
          raise forms.ValidationError("Invalid OTP")
       return super(OTPAuthenticationForm, self).clean()

现在,问题是当您收到POST请求时如何存储这个OTP。你可以使用会话。这样地:

if request.method == 'GET':
   otp = 'abcd'
   form = OTPAuthenticationForm(request=request)
   request.session['otp'] = otp  # storing data in session
   return ....
elif request.method == 'POST':
    form = OTPAuthenticationForm(request.POST, request=request, otp=request.session.get('otp'))
    if form.is_valid():
        del request.session['otp'] # deleting data in session
        ...
5 年前
回复了 ruddra 创建的主题 » 如何在django URL中使用可选参数

在django urls.py中不能这样做。但是可以向视图传递URL查询字符串。例如,如果您点击此url:

http://localhost:8000/Category1-comparison/Brand1-vs-Brand2/?vs=Brand3

Brand3 价值来源 request.GET . 这样地:

def compare_brand(request, category_slug, brand_slug1, brand_slug2):
     brand_slug3 = request.GET.get('vs')

更好的解决方案:

也许更好的方法是将URL查询字符串一起使用。因为那样的话,url会更干净。例如:

# url

path('/comparison/<slug:category_slug>/', compare_brand)

# view
def compare_brand(request, category_slug):
    brands = request.GET.getlist('brands')
    if len(brands) < 2:
        raise Exception('Need 2 brands atleast')

# browser url
http://localhost:8000/comparison/Cat1/?brands=Brand1,Brand2

您可以创建指向同一视图的另一个url

# url
path('<slug:category_slug>-comparison/<slug:brand_slug1>-vs-<slug:brand_slug2>-vs-<slug:brand_slug3>/',views.compare_brand),
path('<slug:category_slug>-comparison/<slug:brand_slug1>-vs-<slug:brand_slug2>/',views.compare_brand)

# view

def compare_brand(request, category_slug, brand_slug1, brand_slug2, brand_slug3=None):
    if brand_slug3:
       # do something

只要把 url 具有 path :

# main urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.url'))
]

# app urls.py
from django.urls import path
from .view import hello

urlpatterns = [
    path('hello/', hello, name='hello'),
]

如你所见 documetation , 路径 已经引入(来自Django>=2.0),因此不必使用 网址 在这里。下面的教程是针对旧版本的,因此它使用 网址 使用regex生成url。

6 年前
回复了 ruddra 创建的主题 » 如果DEBUG=False,为什么Django不加载静态文件?

DEBUG=False 使用( docs )(在生产服务器中不建议这样做):

python manage.py runserver --insecure

另外,你可以使用 whitenoise 提供静态内容。为此,您需要通过 pip install whitenoise ,然后在设置中添加新的中间件,如下所示:

MIDDLEWARE = [
  # 'django.middleware.security.SecurityMiddleware',
  'whitenoise.middleware.WhiteNoiseMiddleware',
  # ...
]

6 年前
回复了 ruddra 创建的主题 » Django DB Model,创建两个相同的表,一个继承另一个

你可以用 Proxy Model . 例如:

class BaseModel(models.Model):
    # your common fields


class Current(BaseModel):
     class Meta:
         proxy=True

     def some_current_model_method(self):
         # specific method for this class

class Archive(BaseModel):
     class Meta:
         proxy=True

     def some_archive_model_method(self):
         # specific method for this class

更新

用法:

archive1 = Archive.objects.create(title="Archive 1")
archive2 = Archive.objects.create(title="Archive 2")
current1 = Current.objects.create(title="Current 1")
current2 = Current.objects.create(title="Current 2")


archives = Archive.objects.all().count()  # will print 4
currents = Current.objects.all().count()  # will print 4
base = BaseModel.objects.all().count()  # print 4


Archive.objects.get(title="Archive 1")  # will work
Archive.objects.get(title="Current 1")  # will work

Current.objects.get(title="Archive 1")  # will work
Current.objects.get(title="Current 1")  # will work

BaseModel.objects.get(title="Archive 1")  # will work
BaseModel.objects.get(title="Current 1")  # will work

BaseModel.objects.create(title="BaseModel")
Archive.objects.get(title="BaseModel")  # will work
Current.objects.get(title="BaseModel")  # will work
6 年前
回复了 ruddra 创建的主题 » Django 2.1无法在makemigration期间检测到我的新模型

确保有一个 migrations 应用程序中的文件夹中有一个 __init__.py 在里面。“模型”文件夹也是如此,您应该确保 __初始年 在那里归档。否则python将无法将其识别为模块。 同样在init文件(对于model)中,需要导入如下模型类:

from .project import ProjectModel

或者你可以跑 python manage.py makemigrations <app_name> 创建迁移文件夹。

6 年前
回复了 ruddra 创建的主题 » 如何防止Django Admin重写自定义字段的自定义小部件?

在模型管理中,需要将这些小部件添加到 formfield_overrides . 例如:

class BaseModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.CharField: {'widget': forms.Textarea},
    }

现在,您可以从这个类中对所有模型管理员进行子类划分,而不必为重写编写多余的代码。

5 年前
回复了 ruddra 创建的主题 » 如何在django view.py中调用远程api?

最好使用外部库 requests . 例如:

import requests
def categorydashboard(request):
     r = requests.get('xxx.xxx.xx.xxx:xxxx/Category/getSubCategoryNamev2', params=request.GET)
     return render (request,'categoryDashboard.html', context={'subcategory':r.json()})
5 年前
回复了 ruddra 创建的主题 » Django正确显示ImageField上传的图像

原因也在 documentation :

这种方法效率很低,可能不安全,因此不适合生产。

在生产中部署媒体文件的正确方法是使用反向代理服务器(如nginx或apache),或者也可以使用与s3兼容的存储(如amazons3)来提供这些媒体文件。我可以在nginx中为您提供一个用于提供媒体文件的示例配置:

location /media {
    alias /path/to/media/direcoty; # Change to your own media directory here.
    access_log off;
}
6 年前
回复了 ruddra 创建的主题 » 在django视图中创建嵌入表单

我认为您可以像这样将这些字段添加到ruleform中,并重写 save 保存它们的方法:

class RuleForm(forms.ModelForm):
    question = forms.CharField(required=True)
    answer = forms.CharField(required=True)

    class Meta:
       model = Rule
       fields=['name', 'question', 'answer']

    def save(self, commit=False):
       question = self.cleaned_data.pop('question')
       answer = self.cleaned_data.pop('answer') 
       rule = super(RuleForm, self).save(commit=True)
       Question.objects.create(rule=rule, name=question)
       Answer.objects.create(rule=rule, name=answer)
       return rule

现在,您只需在视图中传递规则表单:

def create_rule_view(request,id, sc_id):
    rule = RuleForm(request.POST or None)
    if rule.is_valid():
        rule.save()
        return redirect('../')
    context = {
        'rule': rule,
    }
    return render(request, "rule/create_rule.html", context)
6 年前
回复了 ruddra 创建的主题 » 如何使用django批量添加到数据库功能

如下更新代码:

def populate_backup_db(dumpfile):
    datalist =[]
    start_time = time.time()
    file= open(dumpfile)
    filedata = file.readlines()
    endcount=len(filedata)
    i=0
    imagecount=0
    while i<endcount:
        lineitem = split_entry(filedata[i])
        if (lineitem[0]== "HEADER"):
            imagecount=imagecount+1
            sensordata = sensorrecords()  # initiating object here
            sensordata.Sensor          = lineitem[1]
            sensordata.Date1           = lineitem[2]
            sensordata.Date2           = lineitem[3]
            sensordata.Version         = lineitem[4]  
            sensordata.Proxyclient     = lineitem[8]
            sensordata.Triggerdate     = ctodatetime(lineitem[13])
            sensordata.Compression     = lineitem[16]
            sensordata.Encryption      = lineitem[17]
            sensordata.Fragments       = lineitem[21]
            sensordata.Pbit            = lineitem[37]
            sensordata.BlockIntFT      = lineitem[38]
            sensordata.OriginServer   =  lineitem[56]
            datalist.append(sensordata)
        i=i+1
    elapsed_time = time.time() - start_time
    print(imagecount ,'entries saved to database from ',dumpfile,'. Time Taken is ',elapsed_time,' seconds.')
    sensorrecords.objects.bulk_create(datalilist) # you need to access objects method via model class name   
    file.close()
6 年前
回复了 ruddra 创建的主题 » 需要在django管理界面上显示用户计数其他数据计数

一个想法是 习俗 context-processor . 可以添加新的上下文处理器,如下所示:

# in context_processor.py

def user_count(request):
   return { 'total_user' : User.objects.all().count() }

在中注册 settings.py 里面 TEMPLATE 配置:

   'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
            'your_app.context_processor.user_count'
        ],
    },

在模板内使用:

<div>
    {{ user_count }}
</div>

供参考

上下文处理器 当您希望在每个模板中显示相同的数据时非常有用。但是如果这些数据只用于一个页面,并且可能需要通过modeladmin发送额外的上下文数据,那么 change_view 更适合这个。例如(从文档粘贴的副本):

class MyModelAdmin(admin.ModelAdmin):
    change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'

    def get_osm_info(self):
        pass

    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = extra_context or {}
        extra_context['osm_data'] = self.get_osm_info()
        return super().change_view(
            request, object_id, form_url, extra_context=extra_context,
        )
6 年前
回复了 ruddra 创建的主题 » 验证django中电子邮件数组字段的每个值

如果使用表单,请使用 Form Serializer ,您可以使用 clean_<attribute_name> 方法验证数据。例如:

from django.core.validators import email_re
from django.core.exceptions import ValidationError

class YourForm(forms.ModelForm):  # serializers.ModelSerializer

    def clean_billing_emails(self): 
         data = self.cleaned_data['billing_emails']
         for email in data:
             if not email_re.match(email):
                 raise ValidationError('Invalid email {}'.format(email)  # or raise serializers.ValidationError
         return data

你也可以用 model's clean method .

class YourModel(models.Model):
    ...
    def clean(self):
         try:
              for email in self.billing_emails:
                  if not email_re.match(email):
                       raise ValidationError('Invalid email {}'.format(email) 
         except (TypeError, Exception)  as e:
              # log error
              # handle error

    def save(self, *args, **kwargs):
        self.full_clean()
        return super(YourModel, self).save(*args, **kwargs)
6 年前
回复了 ruddra 创建的主题 » 如何比较django 2.1中的两个字段?

你可以试试 SerializerMethodField . 这样试试:

class AndroidSerializers(serializers.ModelSerializer):
    return_label =  serializers.SerializerMethodField()

    class Meta:
        model = Android
        fields = ('label', 'imagestring', 'return_label')

    def get_return_label(self, obj):
        queryset = Server.objects.filter(
            label=obj.label)
        queryset_serializer = FoodSerializers(
            queryset, many=True, read_only=True)
        return queryset_serializer.data
6 年前
回复了 ruddra 创建的主题 » NoreversMatch at/blog/in Django 2.0网站

正如错误所说,这里缺少参数。也许你需要改变 {% url 'category_detail' slug=post.Category.slug %} 具有 {% url 'category_detail' slug=obj.category.slug %} 因为我没有看到任何 post 中的变量引用 blog.html 模板。

更新

您没有共享您的型号代码,但我假设您的 Post 模型具有外键 Category 模型和它看起来像 Category=models.ForeignKey(Category) . 所以你需要像这样更新视图:

def category_detail(request,slug=None):
    category=get_object_or_404(Category,slug=slug)
    post=Post.objects.filter(Category=category,status='Published')
5 年前
回复了 ruddra 创建的主题 » 如果语句在Django项目的for循环中工作不正常

你不需要发送 teacher_available 通过上下文,您可以访问 post 变量:

<div class="available">
    {% if post.is_available %}                    
            <a href="#">Teacher Available</a>
    {% endif %}                
</div>

也, {% if teacher_available %} 无法工作,因为您正在通过该变量发送queryset。如果要检查查询集中是否存在任何值,请使用 .exists . 例如:

# in template 
{% if teacher_selected.exists %}

# in python
if teacher_selected.exists():

最后,您不需要发送 有教师 , assigned_private_teacher , assigned_group_teacher 通过上下文,因为您可以从 posts ,就像这样:

{% for post in posts %}

    {% if post.is_avalilable %}
       // do something
    {% endif %}

    {% if post.is_private %}
       // do something
    {% endif %}

    {% if post.is_group %}
       // do something
    {% endif %}

    {% if post.is_selected %}
       // do something
    {% endif %}

{% endfor %}
5 年前
回复了 ruddra 创建的主题 » M2M Django在遵循教程后的实现

它应该引起问题,因为 request 没有任何名为container的属性。在您的教程示例中,它得到了 登录用户 使用 request.user ,因为Django将登录的用户实例分配给 请求 (通过中间件)。

你已经有了 sample container 您的 change_container 查看方法,您可以这样尝试:

if operation == 'add':
    ContainerContents.add_to_container(container, sample)
elif operation == 'remove':
    ContainerContents.remove_from_container(container, sample)

更新

错过了一件事,你需要在里面换车 add_to_container remove_from_container 方法也一样:

    @classmethod
    def add_to_container(cls, current_container, new_sample):
        container, created = cls.objects.get_or_create(
            current_container=current_container
        )
        container.sample.add(new_sample)

    @classmethod
    def remove_from_container(cls, current_container, new_sample):
        container, created = cls.objects.get_or_create(
            current_container=current_container
        )
        container.sample.remove(new_sample)

因为sample是一个许多字段,在 CurrentContainer Sample 模型。

更新2

@classmethod
def remove_from_container(cls, current_container, new_sample):
     from app_name.models import ContainerSample

     c_sample = ContainerSample.objects.get(container=current_container, sample=new_sample)
     c_sample.delete()
5 年前
回复了 ruddra 创建的主题 » 将值从视图传递到窗体-Django

首先,删除 sim 字段,因为它在模型表单中不是必需的:

class AddPaymentForm(models.Model):
    class Meta:
       model = Payment
       fields = ('deposit_date', 'file')

然后更新视图以保存 模拟 值如下:

def updatePayment(request, id):
    sim  = get_object_or_404(Sim, pk=id)
    if request.method == "POST":
        payment_form = AddPaymentForm(request.POST, request.FILES)
        sim_form = UpdatePayment(request.POST, instance=sim)
        try:
            if  payment_form.is_valid() and sim_form.is_valid():
                sim_form.save()
                payment = payment_form.save(commit=False)
                payment.sim_id = id
                payment.save()
                messages.success(request, ("Payment has been updated"))
            else:
                messages.warning(request, ("Data in fields is incorrect, please try again"))
        except Exception as e:
            messages.warning(request, ("Error: {}".format(e)))
    else:
        sim_form = UpdatePayment(instance=sim)
        payment_form = AddPaymentForm()
    context = {'sim_form': sim_form,'payment_form': payment_form,}
    return render(request, 'payment/updatePayment.html', context)

这是我用的 payment_form.save(commit=False) 生成 Payment 尚未保存到数据库的对象。然后我分配 sim_id 并使用 .save() 方法。

6 年前
回复了 ruddra 创建的主题 » 带有外键的Django序列化程序不工作

我不知道你为什么要用 PrimaryKeyRelatedField 在这里,您只需执行以下操作:

class AdvertiserConfigSerializer(serializers.ModelSerializer):
    class Meta:
        model = AdvertiserConfig
        fields = ('advertiser_id', 'config_id', 'value')

如果只需要一个带有配置名称的字段,则可以使用 SerializerMethodField :

class AdvertiserConfigSerializer(serializers.ModelSerializer):
    config_name = serializers.SerializerMethodField()
    class Meta:
        model = AdvertiserConfig
        fields = ('advertiser_id', 'config_name', 'value')

    def get_config_name(self, obj):
         return obj.config_id.name  # will return config_id's name

另外,请考虑重命名您的模型的FK。因为当你用forignkey的时候 config ,django在db中创建一个名为的列 config_id 指向配置模型。