Уведомления

Группа в Telegram: @pythonsu

#1 Июль 16, 2015 12:54:46

skripka696
Зарегистрирован: 2015-04-10
Сообщения: 42
Репутация: +  1  -
Профиль   Отправить e-mail  

django restful api angular

помогите пожалуйста, у меня есть модель

class Color(models.Model):
    code = RGBColorField()
    
    def __unicode__(self):
        return '{0}'.format( self.code)
class Category(models.Model):
    category_name = models.CharField(max_length=255)
    parent = models.ForeignKey('self', blank=True, null=True,
                               verbose_name="Parent", related_name='Child')
    def __unicode__(self):
        return '{0}'.format(self.category_name)
mptt.register(Category,)
class Label(models.Model):
    label_name = models.CharField(max_length=20) 
    def __unicode__(self):
        return '{0}'.format(self.label_name)
class Media_Note(models.Model):
    my_file = models.FileField(upload_to = 'media/', default="media/note.jpg")
    def __unicode__(self):
        return '{0}'.format(self.my_file)
class Note(models.Model):
    title = models.CharField(max_length=30)
    content = models.CharField(max_length=255)
    color = models.ForeignKey(Color, blank=True , null=True, related_name='color')
    note_category = models.ManyToManyField(Category)
    note_label = models.ManyToManyField(Label)
    note_media = models.ManyToManyField(Media_Note)
    user = models.ForeignKey(User)
    list_category = []
 
    def __unicode__(self):
        return '{0} - {1}'.format(self.title, self.content)

есть ангуляр который выводит заметки, котегории и заметки по id
var noteApp = angular.module('noteApp', [
	'ui.router',
	'ngRoute',
	'ngResource',
	'restangular',
//	'pascalprecht.translate',
//	'ngCookies',
//	'ui.bootstrap',
//	'autoActive',
]);
// Get list of notes from rest framework
noteApp.factory('NoteService', function($resource){
	return $resource('http://localhost:8000/api/note/?format=json');
});
// List of notes
noteApp.controller('NoteController',
	function ($scope, NoteService) {
		NoteService.query(function(result) {
			$scope.noteList=result;
			console.log(result);
		});
});
 //Get note detail from rest framework
noteApp.factory('NoteIdService', function($resource){
	return $resource('http://localhost:8000/api/note/:pk/?format=json', {pk:'@pk'});
});
 //Note detail
noteApp.controller('NoteIdController',
	function ($location, $route, $scope, $routeParams, NoteIdService) {
	console.log($location);
			NoteIdService.get({pk: $route.current.params.pk}, function (result) {
				$scope.note = result;
				console.log(result);
		});
});
noteApp.config(function($routeProvider, $locationProvider) {
//console.log($locationProvider);
	$routeProvider.when('/note', {
			templateUrl: '../static/html/note_list.html'
		});
	$routeProvider.otherwise({ redirectTo: '/note' });
	$routeProvider.when('/note/category/', {
			templateUrl: '../static/html/category_list.html'
		});
	$routeProvider.when('/note/new_note/', {
			templateUrl: '../static/html/new_note.html'
		});
	$routeProvider.when('/note/new_category/', {
			templateUrl: '../static/html/new_category.html'
		});
	$routeProvider.when('/note/new_label/', {
			templateUrl: '../static/html/new_label.html'
		});
	$routeProvider.when('/note/:pk/', {
			templateUrl: '../static/html/note_list_id.html'
		});
});
noteApp.config(function($httpProvider) {
	$httpProvider.defaults.xsrfCookieName = 'csrftoken';
	$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});

мне нужно сделать страничку которая будет добавлять новую заметку, через ангуляр
вот моя вьюшка
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from models import Note
from my_rest.serializers import  NoteSerializer,ColorSerializer, LabelSerializer, CategorySerializer
from models import Note, Category, Color, Label
from rest_framework import mixins
from rest_framework import generics
from rest_framework import viewsets 
from rest_framework.decorators import detail_route
from rest_framework import permissions
from django.views.generic import TemplateView
class NoteViewSet(viewsets.ModelViewSet):
    """
    Returns a list of notes.
    Edit, delete and add new ones.
    For more details about all category [see here][ref].
    [ref]: http://127.0.0.1:8000/api/category/
    
    For more details about all color [see here][col].
    [col]: http://127.0.0.1:8000/api/color/
    For more details about all label [see here][lab].
    [lab]: http://127.0.0.1:8000/api/label/
    """
    queryset = Note.objects.all()
    serializer_class = NoteSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
   
class ColorViewSet(viewsets.ModelViewSet):
    """
    Returns a list of color.
    Edit, delete and add new ones.
    For more details about all category [see here][ref].
    [ref]: http://127.0.0.1:8000/api/category/
    
    For more details about all notes [see here][not].
    [not]: http://127.0.0.1:8000/api/note/
    For more details about all label [see here][lab].
    [lab]: http://127.0.0.1:8000/api/label/
    """
    queryset = Color.objects.all()
    serializer_class = ColorSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
class CategoryViewSet(viewsets.ModelViewSet):
    """
    Returns a list of category.
    Edit, delete and add new ones.
    For more details about all note [see here][not].
    [not]: http://127.0.0.1:8000/api/note/
    
    For more details about all color [see here][col].
    [col]: http://127.0.0.1:8000/api/color/
    For more details about all label [see here][lab].
    [lab]: http://127.0.0.1:8000/api/label/
    """
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
class LabelViewSet(viewsets.ModelViewSet):
    """
    Returns a list of label.
    Edit, delete and add new ones.
    For more details about all category [see here][ref].
    [ref]: http://127.0.0.1:8000/api/category/
    
    For more details about all color [see here][col].
    [col]: http://127.0.0.1:8000/api/color/
    For more details about all note [see here][not].
    [not]: http://127.0.0.1:8000/api/note/
    """
    queryset = Label.objects.all()
    serializer_class = LabelSerializer    
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
class NoteList(TemplateView):
    template_name = 'my_rest/note.html'
    def get_context_data(self, **kwargs):
        context = super(NoteList, self).get_context_data(**kwargs)
        return context

и вот мои попытки, уже замучалась с этим , помогите пожалуйста

noteApp.factory("Post", function($resource) {
  return $resource('http://localhost:8000/api/note/?format=json',
  				   'http://localhost:8000/api/category/?format=json',
  				   'http://localhost:8000/api/color/?format=json',
  				   'http://localhost:8000/api/label/?format=json');
});
//new note
noteApp.controller('NoteNewController', function($scope, $http, Post) {
    Post.save(function(data) {
//    console.log(data)
    $scope.posts = data;
//    $http.post('http://localhost:8000/api/note/?format=json');
//	$http.post('http://localhost:8000/api/category/?format=json');
//	$http.post('http://localhost:8000/api/color/?format=json');
//	$http.post('http://localhost:8000/api/label/?format=json');
    });
});
//noteApp.controller('NoteNewController', function($scope, $http) {
//	$scope.method = 'POST';
//
//	$scope.url = 'http://localhost:8000/api/category/?format=json';
//	$http.post('http://localhost:8000/api/note/?format=json');
//	$http.post('http://localhost:8000/api/category/?format=json');
//	$http.post('http://localhost:8000/api/color/?format=json');
//	$http.post('http://localhost:8000/api/label/?format=json');
//});
//noteApp.controller('NoteNewController', function ($scope, $http) {
//  $scope.user = {};
//
////  $scope.user.customField = 'customValue';
//
//  $scope.submitForm = function (form) {
//      $http.post('http://localhost:8000/api/note/?format=json', $scope.user)
//        .success(function (data) {
//          console.log('data:', data);
//        })
//        .error(function (data) {
//          console.log('Error:', data);
//        });
//  };
//});
//noteApp.controller('NoteNewController',
//	function ($location, $route, $scope, $routeParams, NoteIdService) {
//	console.log($location);
//
//			NoteIdService.post({pk: $route.current.params.pk}, function (result) {
//				$scope.note = result;
//				console.log(result);
//
//		});
//});

Офлайн

#2 Июль 16, 2015 14:28:35

inoks
От: Russia
Зарегистрирован: 2012-12-11
Сообщения: 343
Репутация: +  35  -
Профиль   Адрес электронной почты  

django restful api angular

Это нужно в ангулар (в нем же сейчас затык), а не в джангу писать.

Офлайн

#3 Июль 17, 2015 13:37:54

dun
От: Липецк
Зарегистрирован: 2015-01-16
Сообщения: 10
Репутация: +  0  -
Профиль   Отправить e-mail  

django restful api angular

Опишите заметки как фабрику, используя модуль Angular Resource:

(function (A){
    "use strict";
    function Note($resource){
        return $resource('/api/notes/:id/', {id: '@id'}, {
            update: {
                method: 'PATCH'
            }
        });
    }
    Note.$inject = ['$resource'];
    A.module('app').factory('Note', Note);
}(this.angular));

Ниже используйте такой код:

(function (A){
    "use strict";
    var inject= [
        '$scope',
        'Note'
    ];
    function Ctrl($scope, Note){
        $scope.note = new Note();
        $scope.save = function(){
            $scope.note.$save(function(){
                // Закрыть окно или что там
            }, function(response){
                $scope.errors = response.data;
                // Можно ещё и уведомление показать
            });
        };
    }
    Ctrl.$inject = inject;
    A.module('app').controller('NoteAddCtrl', Ctrl);
}(this.angular));

Могу написать статью по теме, кстати. Нужно?

Отредактировано dun (Июль 17, 2015 13:40:13)

Офлайн

#4 Июль 17, 2015 16:03:44

skripka696
Зарегистрирован: 2015-04-10
Сообщения: 42
Репутация: +  1  -
Профиль   Отправить e-mail  

django restful api angular

dun
было бы не плохо,а то сложно как то дается angular.
Спасибо за помощь!!!

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version