GVKun编程网logo

Django 自定义视图“您没有权限错误”(django 自定义权限管理)

7

在本文中,您将会了解到关于Django自定义视图“您没有权限错误”的新资讯,同时我们还将为您解释django自定义权限管理的相关在本文中,我们将带你探索Django自定义视图“您没有权限错误”的奥秘,

在本文中,您将会了解到关于Django 自定义视图“您没有权限错误”的新资讯,同时我们还将为您解释django 自定义权限管理的相关在本文中,我们将带你探索Django 自定义视图“您没有权限错误”的奥秘,分析django 自定义权限管理的特点,并给出一些关于$ Django 调API的几种方式,django自定义错误响应、android – 使用单选按钮向自定义组添加自定义视图、android – 将xml中相邻视图的id传递给自定义视图,并在自定义视图的构造函数中检索它、android – 手动膨胀自定义视图会为ActionBar自定义视图生成不同的布局的实用技巧。

本文目录一览:

Django 自定义视图“您没有权限错误”(django 自定义权限管理)

Django 自定义视图“您没有权限错误”(django 自定义权限管理)

如何解决Django 自定义视图“您没有权限错误”?

我为 Django 管理员创建了自己的视图。在这里,我想添加一个订单链接以查看订单,而不会像这样打扰change_form。

enter image description here

我在 admin.py 中添加了以下代码。

 def get_urls(self):
    urls = super(OrderAdmin,self).get_urls()
    custom_urls = [
        path(''order/<int:order_id>/view'',self.view_order,name="view_order")
    ]
    print(urls)
    return urls + custom_urls

def view_order(self,request,order_id):
    order = Order.objects.get(pk=order_id)
    return render(request,''shop/order.html'',{''order'':order})

现在,当我单击链接时,会出现以下屏幕。

enter image description here

有什么问题吗?如何让原始仪表板保留我所做的事情?

解决方法

您可以拥有需要权限的自定义装饰器。

例如,如果您的视图应该可供登录用户使用:

from rest_framework.permissions import IsAuthenticated

@permission_classes((IsAuthenticated,))
def view_order(self,request,order_id):
    order = Order.objects.get(pk=order_id)
    return render(request,''shop/order.html'',{''order'':order})

如果任何人都可以使用,您可以使用 AllowAny

from rest_framework.permissions import AllowAny

@permission_classes((AllowAny,{''order'':order})

此外,您可以将视图编写为类并重新加载 def has_change_permission(self,obj=None): 方法

$ Django 调API的几种方式,django自定义错误响应

$ Django 调API的几种方式,django自定义错误响应

django自定义错误响应

  前提:settings.py

   #debug为true时要配置网站的allowed_hosts域名
# 简单就为"*"
DEBUG = False
ALLOWED_HOSTS = [''127.0.0.1'']
直接templates下书写404.htm,400.html,403.html,500.html
方式1
#第一步:总的urls.py 重写handler函数,(注意要加项目app名  要写在上面)
from django.conf.urls import url
from django.contrib import admin
from app01 import views
# handler404="app01.views.erro"
# handler400="app01.views.erro"
# handler403="app01.views.erro"
# handler500="app01.views.erro"

urlpatterns = [
    url(r''^admin/'', admin.site.urls),
    url(r''^download/'', views.Download),#下载
    url(r''^file/'', views.File.as_view()),#播放
    url(r''^tes/'', views.tes),#test
    url(r''^data/'', views.date),#test
]
#第二步:views.py写错误调的视图
from django.http import HttpResponseNotFound
def erro(request):
    return HttpResponseNotFound("NOT FOUND!")
方式2

API调用方式

下面是python中会用到的库。
urllib2
httplib2
pycurl
requests
urllib2

#request
import requests, json 
github_url = ” 
data = json.dumps({‘name’:’test’, ‘description’:’some test repo’}) 
r = requests.post(github_url, data, auth=(‘user’, ‘*‘)) 
print r.json 
#以上几种方式都可以调用API来执行动作,但requests这种方式代码最简洁,最清晰,建议采用。
#urllib2, urllib 
import urllib2, urllib 
github_url = ‘https://api.github.com/user/repos’ 
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() 
password_manager.add_password(None, github_url, ‘user’, ‘*‘) 
auth = urllib2.HTTPBasicAuthHandler(password_manager) # create an authentication handler 
opener = urllib2.build_opener(auth) # create an opener with the authentication handler 
urllib2.install_opener(opener) # install the opener… 
request = urllib2.Request(github_url, urllib.urlencode({‘name’:’Test repo’, ‘description’: ‘Some test repository’})) # Manual encoding required 
handler = urllib2.urlopen(request) 
print handler.read()
#httplib2
import urllib, httplib2 
github_url = ’ 
h = httplib2.Http(“.cache”) 
h.add_credentials(“user”, “**“, ” 
data = urllib.urlencode({“name”:”test”}) 
resp, content = h.request(github_url, “POST”, data) 
print content
#pycurl
import pycurl, json 
github_url = ” 
user_pwd = “user:*” 
data = json.dumps({“name”: “test_repo”, “description”: “Some test repo”}) 
c = pycurl.Curl() 
c.setopt(pycurl.URL, github_url) 
c.setopt(pycurl.USERPWD, user_pwd) 
c.setopt(pycurl.POST, 1) 
c.setopt(pycurl.POSTFIELDS, data) 
c.perform() 

 

android – 使用单选按钮向自定义组添加自定义视图

android – 使用单选按钮向自定义组添加自定义视图

我有一个自定义视图,其中包含一个RadioButton.

SingleRadioItem:

public class SingleRadioItem extends LinearLayout {
    private TextView mTextKey;
    private RadioButton mRadioButton;
    private ImageView mImageSeparator;

    public SingleRadioItem(Context context,AttributeSet attrs) {
        super(context,attrs);
        View view = LayoutInflater.from(context).inflate(R.layout.rtl_single_radio_item,this,true);

        mTextKey = (TextView)view.findViewById(R.id.single_radio_item_text_key);
        mRadioButton = (RadioButton)view.findViewById(R.id.single_radio_item_button);
        mImageSeparator = (ImageView)view.findViewById(R.id.single_image_separator);
    }

    public void setKey(String key) {
        mTextKey.setText(key);
    }

    public boolean getSelectedState() {
        return mRadioButton.isSelected();
    }

    public void setSelectedState(boolean selected) {
        mRadioButton.setSelected(selected);
    }
}

我想创建此视图的实例,将它们添加到RadioGroup并将RadioGroup添加到LinearLayout.
当我这样做时,它允许我将所有单选按钮设置为选中,这意味着,RadioGroup运行不正常(可能是因为我这样做…)

RadioGroup radioGroup = new RadioGroup(this);
        radioGroup.setorientation(RadioGroup.VERTICAL);

        SingleRadioItem radio1 = new SingleRadioItem(this,null);
        SingleRadioItem radio2 = new SingleRadioItem(this,null);

        radioGroup.addView(radio1);
        radioGroup.addView(radio2);

        updateDetailsView.addView(radioGroup);

显然,当我添加RadioButton radio1 = new RadioButton(this); RadioGroup效果很好.

是否甚至可以添加一个视图,将一个单选按钮添加到一个放射组,我只是遗漏了一些东西或根本不可能?

谢谢!

解:
扩展@cosmincalistru回答并帮助他人:

对于我添加到LinearLayout的每个SingleRadioItem我附加了一个这样的监听器:

radio1.setonClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (lasTradioChecked != null) {
                    lasTradioChecked.setCheckedState(false);
                }

                lasTradioChecked = (SingleRadioItem)v;
                lasTradioChecked.setCheckedState(true);
            }
        });

您还需要将SingleRadioItem XML中的RadioButton视图设置为可单击:false.

解决方法

RadioButton必须直接从属于RadioGroup,否则您的按钮将被视为来自不同的组.
最好的想法是在你的情况下在每个RadioButton上使用监听器.

编辑:
每当我想将一组RadioButtons作为一个组的一部分而不能使用RadioGroup时,我会做这样的事情:

RadioButton r1,r2,....;
// Instantiate all your buttons;
...
// Set listener on each
for(each RadioButton) {
    rx.setonCheckedchangelistener(OnCheckedchangelistener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
            if (isChecked) {
                //set all buttons to false;
                for(each RadioButton) {
                    rx.setChecked(false);
                }
                //set new selected button to true;
                buttonView.setChecked(true);
            }
        }
    });
}

android – 将xml中相邻视图的id传递给自定义视图,并在自定义视图的构造函数中检索它

android – 将xml中相邻视图的id传递给自定义视图,并在自定义视图的构造函数中检索它

下面是我的xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp" xmlns:app="http://schemas.android.com/apk/res/com.infibeam.allthingsd.apps.spinr">

   <com.asyncimagewidget.AsyncImageView
        android:id="@+id/discover_list_icon"
        android:layout_width="130dp"
        android:layout_height="130dp"
        android:layout_alignParentLeft="true"
        android:layout_centerHorizontal="true"
        app:progressId="@+id/asyncLoadingProgress"
         />
    <ProgressBar
        android:id="@+id/asyncLoadingProgress"
        android:layout_width="130dp"
        android:layout_height="130dp"
        android:layout_alignParentLeft="true"
        android:layout_centerHorizontal="true"
     />
</RelativeLayout>

你可以看到

app:progressId=”@+id/asyncLoadingProgress”

这是我在attrs.xml中定义的自定义属性,如下所示.

<resources>
    <declare-styleable name="AsyncImageView">
        <attr name="defaultSrc" format="reference" />
        <attr name="parentId" format="reference" />
        <attr name="progressId" format="reference" />
        <attr name="url" format="string" />
        <attr name="inDensity">
            <enum name="ldpi" value="120" />
            <enum name="mdpi" value="160" />
            <enum name="hdpi" value="240" />
            <enum name="xhdpi" value="320" />
        </attr>
    </declare-styleable>
</resources>

现在我的问题是我想在AsyncImageView的构造函数中获取Progressbar的资源标识符,如下所示.

public AsyncImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        initializeDefaultValues();

        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.AsyncImageView, defStyle, 0);

        Drawable d = a.getDrawable(R.styleable.AsyncImageView_defaultSrc);
        if (d != null) {
            setDefaultimageDrawable(d);
        }

        final int inDensity = a
                .getInt(R.styleable.AsyncImageView_inDensity, -1);
        if (inDensity != -1) {
            setInDensity(inDensity);
        }

        setUrl(a.getString(R.styleable.AsyncImageView_url));

        a.recycle();

    }

解决方法:

Now My question is I want to obtain the resource identifier of
Progressbar in constructor of AsyncImageView which is as follows.

如果我没弄错,你可以在构造函数中使用getResourceId()方法:

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AsyncImageView, defStyle, 0);
int progressId = a.getResourceId(R.styleable.AsyncImageView_progressId, 0);

另外,如果在AsyncImageView属性中声明ProgressBar的id,那么我认为你需要为ProgressBar设置这样的id:

android:id="@id/asyncLoadingProgress"

android – 手动膨胀自定义视图会为ActionBar自定义视图生成不同的布局

android – 手动膨胀自定义视图会为ActionBar自定义视图生成不同的布局

资源的自定义视图:
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setCustomView(R.layout.custom_action_bar);
actionBar.setdisplayOptions(ActionBar.disPLAY_SHOW_CUSTOM);

结果是:

自定义视图手动膨胀:

// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
LayoutInflater inflater = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_action_bar,null);
actionBar.setCustomView(view);
actionBar.setdisplayOptions(ActionBar.disPLAY_SHOW_CUSTOM);

结果是:

custom_action_bar.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" 
    android:weightSum="3">

    <TextView 
        android:id="@+id/bar_title1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textColor="@color/White"
        android:text="title1"/>
    <TextView 
        android:id="@+id/bar_title2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textColor="@color/White"
        android:text="title2"/>
    <TextView 
        android:id="@+id/bar_title3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textColor="@color/White"
        android:text="title3"/>

</LinearLayout>

这里显示的第一个布局是正确的,因为它的小部件有权重.第二次尝试应该产生相同的结果,但事实并非如此.

解决方法

实际上,这里的问题是在第二种情况下,ActionBar需要额外的布局参数:
final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.custom_action_bar,null);
    actionBar.setCustomView(view,new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
    actionBar.setdisplayOptions(ActionBar.disPLAY_SHOW_CUSTOM);

因此,它涵盖了所有ActionBar区域.默认情况下看起来WRAP_CONTENT llayout参数应用于自定义视图.

关于Django 自定义视图“您没有权限错误”django 自定义权限管理的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于$ Django 调API的几种方式,django自定义错误响应、android – 使用单选按钮向自定义组添加自定义视图、android – 将xml中相邻视图的id传递给自定义视图,并在自定义视图的构造函数中检索它、android – 手动膨胀自定义视图会为ActionBar自定义视图生成不同的布局等相关知识的信息别忘了在本站进行查找喔。

本文标签: