django rest框架在db

时间:2016-07-29 04:39:29

标签: python django django-rest-framework

每一个,我现在在我的项目(django 1.8 +)上使用django rest framework(3.4),我可以创建新用户但我不能使用新用户在db中创建数据(我可以在表单中执行ok)但是,我可以通过admin在db中创建数据。我必须让新用户在db中创建数据,我该怎么做?感谢任何回复者。

  

models.py

class ProductsTbl(models.Model):
    model_number = models.CharField(
        max_length=255,
        blank=True,
        unique=True,
        error_messages={
            'unique': "這 model number 已經被註冊了 ."
        }
    )
    name = models.CharField(max_length=255, blank=True, null=True)
    material = models.CharField(max_length=255, blank=True, null=True)
    color = models.CharField(max_length=255, blank=True, null=True)
    feature = models.TextField(blank=True, null=True)
    created = models.DateTimeField(editable=False)
    modified = models.DateTimeField(auto_now=True)
    release = models.DateTimeField(blank=True, null=True)
    twtime = models.DateTimeField(blank=True, null=True)
    hktime = models.DateTimeField(blank=True, null=True)
    shtime = models.DateTimeField(blank=True, null=True)
    jptime = models.DateTimeField(blank=True, null=True)
    suggest = models.TextField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    cataloggroup = models.ManyToManyField(CatalogGroup)
    place = models.ManyToManyField(Place)
    scale = models.ManyToManyField(Scale)
    slug = models.SlugField(unique=True)
    user = models.ForeignKey(User, blank=True, null=True)
    useredit = models.CharField(max_length=32, blank=True, null=True)

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''

        if not self.id:
            self.created = timezone.now()

        return super(ProductsTbl, self).save(*args, **kwargs)
  

API / serializers.py

from rest_framework import serializers
from ..models import *
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model


UserModel = get_user_model()

class ProductsTblSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductsTbl
        fields = ('model_number',
        'created',
        'name',
        'release',
        'twtime',
        'hktime',
        'shtime',
        'jptime',
        'feature',
        'material',
        'suggest',
        'description',
        'cataloggroup',
        'place',
        'scale',
        'slug',
        'user')



class UserSerializer(serializers.ModelSerializer):

    password = serializers.CharField(write_only=True)

    def create(self, validated_data):

        user = UserModel.objects.create(
            username=validated_data['username']
        )
        user.set_password(validated_data['password'])
        user.save()

        return user

    class Meta:
        model = UserModel
  

API / urls.py

from django.conf.urls import url, include
from . import views


urlpatterns = [
    url(r'^productsTbls/$', views.ProductsTblListView.as_view(), name='productsTbls_list'),
    url(r'^productsTbls/(?P<pk>\d+)/$', views.ProductsTblDetailView.as_view(), name='productsTbls_detail'),
    url(r'^productsTbls/pdelete/(?P<id>[-\w]+)/$',views.api_delete_product,name='api_delete_p'),
    url(r'^productsTbls/register/$', views.CreateUserView.as_view(), name='productsTbls_register'),

]
  

API / views.py

from rest_framework import generics
from ..models import *
from .serializers import ProductsTblSerializer
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse
from django.shortcuts import render, redirect
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt
from django.forms import modelformset_factory
from django.template.defaultfilters import slugify
from rest_framework import permissions
from rest_framework.generics import CreateAPIView
from django.contrib.auth import get_user_model
from .serializers import UserSerializer





class ProductsTblListView(generics.ListCreateAPIView):
    queryset = ProductsTbl.objects.order_by('-created')
    serializer_class = ProductsTblSerializer



class ProductsTblDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = ProductsTbl.objects.all()
    serializer_class = ProductsTblSerializer


class CreateUserView(CreateAPIView):

    model = get_user_model()
    permission_classes = [
        permissions.AllowAny # Or anon users can't register
    ]
    serializer_class = UserSerializer




@csrf_exempt
@login_required
def api_delete_product(request, id):
    # grab the image
    dp = ProductsTbl.objects.get(id=id)
    # security check
    if dp.user != request.user:
        raise Http404
    # delete the image
    dp.delete()
    # refresh the edit page
    return redirect('/api/productsTbls/')
  

settings.py

........

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

2 个答案:

答案 0 :(得分:1)

我更改了settings.py然后它可以正常工作

  

settings.py

......
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
        #'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

答案 1 :(得分:1)

我认为从管理员门户网站,您需要为每个方法PUT,POST,GET或提供AllowAny权限的用户提供权限(这将为任何请求提供对所有已创建用户的访问权限)。有关详细信息,请参阅this