w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
best way to add additional fields to django-rest-framework ModelViewSet when create
Update: Since v3 you need to do this: def perform_create(self, serializer): serializer.save(owner=self.request.user) The principle remains the same. You want to make the owner field of your book serializer read-only and then set the association with the user in pre_save(). Something like: def pre_save(self, obj): obj.owner = self.request.user See the tutorial section on "Associating Snippets with Users". I hope that helps.

Categories : Python

django-rest custom url in a ModelViewSet
Pull the list method out as a separate view: post_list = PostViewSet.as_view({'get': 'list'}) Then map this to your date-based lookup URL as you usually would, setting parameters for year, month and day. In get_queryset you can check if these kwargs are set and, if so, filter the queryset.

Categories : Django

Django REST Framework nested relations without related names
I guess you'd need to manually query for the related objects and then construct the serializers by hand. You'd then construct the final representation and pass that as the data parameter to a Response object. It seems like you're making life difficult though. If you just define the related_name on your related models you could use ModelSerializer (or HyperlinkedModelSerializer) and it would all Just Work™. — Is there some reason why you can't do this?

Categories : Django

Return results from multiple models with Django REST Framework
It looks pretty close to me. I haven't used ViewSets in DRF personally, but I think if you change your code to this you should get somewhere (sorry - not tested either of these): class TimelineViewSet(viewsets.ModelViewSet): """ API endpoint that lists all tweet/article objects in rev-chrono. """ def list(self, request): queryset = list(itertools.chain(Tweet.objects.all(), Article.objects.all())) serializer = TimelineSerializer(queryset, many=True) return Response(serializer.data) If you're not wedded to using a ViewSet then a generics.ListAPIView would be a little simpler: class TimeLineList(generics.ListAPIView): serializer_class = TimeLineSerializer def get_queryset(self): return list(itertools.chain(Tweet.objects.all(), Arti

Categories : Python

Django: How are forms related to models?
Conceptually, forms serve as the handler for inputting data in your HTML in order to use that data somewhere in your application (in your views). You'll find two common uses for forms in Django: working with your models (data defined by your database) or for the purposes of accomplishing some kind of task (like sending an e-mail - where you don't necessarily need to have an associated model). Forms do a lot of things for both of these functions. These range from modularity, extensibility and ease of management (as they can be easily defined, interchanged, inherited etc. in Python) to validation (one of the biggies). Validation is crucial - and it's probably what you are referring to in terms of registration. Django Forms will validate against a definition either defined in your Form cl

Categories : Django

Containing information related to two models in Django
A many-to-many relationship with a through table is the right approach here. https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships Behind the scenes, Django will create an intermediary table for a many-to-many field anyway, so worrying about extra overhead on lookups is unnecessary. There's no way around it.

Categories : Django

Plug in django-allauth as endpoint in django-rest-framework
While I'm not quite sure how to use allauth and rest-fremework together, allauth does not offer such an endpoint. Suggestion: make your own that does a variation of the following: Call allauth.socialaccount.providers.facebook.views.fb_complete_login(None, socialtoken) where socialtoken is as created in login_by_token. That performs (a few functions deeper) a django.contrib.auth.login, possibly creating the acct. After that, for use on mobile devices, it might be possible to the the auth (not FB) token: get the user data (from session?), and call rest_framework.authtoken.views.obtain_auth_token Notes: 1. This offers no way to resolve email conflicts or connect social/local accts. 2. I haven't tried it - please post code if you can get it working.

Categories : Python

MVC4 forms that save to entity framework models
When you send in the model to the view, use something like @using(Html.BeginForm("Index")) { @Html.TexboxFor(x => x.Name) // istead of <input type=text> @Html.TextborFor(x => x.Description) <input type="submit" value="Submit button"/> } to bind the model to the view, which in turn will make it post back when you click the submitt button. In the controller you have something like [HttpPost] public ActionResult Index(CourseViewModel model) // because you'd want to use a // view model and not the entity itself { // check if the model is valid // maybe some more logic db.SaveChanges(); return View(model); }

Categories : Forms

Where does related logic go on model creation when working with REST api with Django, Backbone, and Tastypie?
The first thing I would suggest is to switch your mindset to an event-based model, where your code reacts to events. In your example above, you save the model to the server then immediately dd it to the collection. How do you even know that the model was saved correctly? That procedural style of programming works better in a synchronous, server-side style of programming. In the asynchronous world of client-side programming, you make a request and then set up callbacks which determine what will happen next, depending on the events your are listening for. In your case, you want to react a certain way when the message is saved successfully, correct? You can define a success callback for your save operation like so: msg.save({ success: function(model, response, options) { me

Categories : Rest

How to save a related, inline django model when parent is saved in the admin?
First of all, the relationship you're describing is what called a ManyToMany "through" (you can read about it in the documentation here). Secondly, I don't understand why you need the 'hours' to be a field at all. Isn't a function enough for this? why save it in the database in the first place? you can just call it every time you need it. Finally, it seems to me you're doing a lot of extra work that I don't understand - why do you need the volunteer time boolean field? If you link a volunteer with an event isn't that enough to know that he was there? And what's the purpose of "counts_towards_volunteer_time"? I'm probably missing some of the logic here, but a lot of that seems wasteful.

Categories : Django

Django REST Framework API call using IOS.
When you use 'curl' and use the '-u myuser:mypass' you are sending the username and password in the HTTP Authorization header. I'm not sure how to do this in IOS specifically, but I would try doing a POST request with a url like: http://username:password@example.com/

Categories : IOS

django rest Framework authentications
Django rest framerwork supports many auth options. You can use Basic Auth if you want. If you want to use the token you will need to set an http header with the correct token for your user. From the docs you need to set it as (replace 99... with yours) Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

Categories : Python

How to use TokenAuthentication for API in django-rest-framework
"how can I send the token with post request to my api" From the docs... For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b "at api side how can I verify if token is valid and belongs to the correct user?" You don't need to do anything, just access request.user to return the authenticated user - REST framework will deal with returning a '401 Unauthorized' response to any incorrect authentication.

Categories : Python

Incrementing the slug by avoiding Integrity error in django models save method
You will have to use loop instead of just a one condition. Try this: class Publisher(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=150, unique=True) def save(self, *args, **kwargs): if not self.id and not self.slug: slug = slugify(self.name) slug_exists = True counter = 1 self.slug = slug while slug_exists: try: slug_exits = Publisher.objects.get(slug=slug) if slug_exits: slug = self.slug + '_' + str(counter) counter += 1 except Publisher.DoesNotExist: self.slug = slug break super(Publisher, self)

Categories : Django

django-rest-framework and custom routes
The part of the Django Rest Framework docs you're looking for is that on filtering against the URL. The basic idea is that you override get_queryset to return a filtered QuerySet matching parameters you define in your URL conf. The Django ORM field lookups you'll need are year, month and day, which start here in the QuerySet API reference. I hope that helps.

Categories : Django

Django Rest Framework - PUT to (many=True) PrimaryKeyRelatedField()
You need to set traditional to true so jquery will encode the params that contains arrays in a way that django will understand: $.ajax({ url:'<MY MODELVIEWSET>/<ID>', type:'PUT', traditional: true, data:{field1:'xyz', field2:[1,2,3]} }) See here for the difference between default and traditional encoding.

Categories : Django

django-rest-framework different fields for serialization
You could override to_native in your serializer subclass to strip the unwanted fields in your case. Something like: def to_native(self, obj): as_native = super(MySerializer, self).to_native(obj) # Remove image_url and image fields if Text role. if as_native["role"] == "Text": as_native.pop('image_url', None) as_native.pop('image', None) return as_native I hope that helps.

Categories : Django

Django Rest Framework global timestamp
If you add a DateTimeField to your model using the auto_now option you can order by that (decending) and limit to the first result to find the time of the latest update. A RetrieveAPIView in which you override get_object to return the last updated Item together with a serialiser that just exposes the DateTimeField should give you everything you need.

Categories : Django

AttributeError with Django REST Framework and MongoEngine
Finally got the solution. I needed to explicitly set many=False to make it work. So this works fine: from core.models import * from core.serializers import * tiger = Lady(firstname='Tiger', lastname="Lily") serial = LadySerializer(tiger, many=False) serial.data and yields: {'firstname': u'Tiger', 'lastname': u'Lily'} You can find some additional information regarding this problem here. The interesting part for this case is the following post: Version 2.2 starts the deprecation of the implicit iteration behavior. At the moment you'll need to explicitly specify many=False to force the behavior to not iterate over __iter__ style objects. By 2.4 the default value will switch from None to False. Hope this helps....

Categories : Python

django-rest-framework document API in OPTIONS
The generic views already include parameter descriptions in response the OPTIONS requests. For example, after completing the tutorial, you should be able to make OPTIONS requests and inspect the available actions. Make sure to set the --user option to an existing user/password, or you'll only have ready-only access and won't get the actions part of the response. bash: curl -X OPTIONS --user amy:amy -v http://127.0.0.1:8000/snippets/ -H 'Accept: application/json; indent=4'; echo * About to connect() to 127.0.0.1 port 8000 (#0) * Trying 127.0.0.1... connected * Server auth using Basic with user 'amy' > OPTIONS /snippets/ HTTP/1.1 > Authorization: Basic YW15OmFteQ== > User-Agent: curl/7.22.0 (x86_64-apple-darwin11.2.0) libcurl/7.22.0 OpenSSL/1.0.0e zlib/1.2.5 libidn/1.22 >

Categories : Django

Limit items per page in Django REST Framework
You need to set PAGINATE_BY as doc states: PAGINATE_BY: The default page size to use for pagination. If set to None, pagination is disabled by default PAGINATE_BY_PARAM is for users to override the default size. So if you are afraid of its misuse just don't enable it. PAGINATE_BY_PARAM: The name of a query parameter, which can be used by the client to override the default page size to use for pagination. If set to None, clients may not override the default page size.

Categories : Django

How can one customize Django Rest Framework serializers output?
Create a custom serializer field and implement to_native so that it returns the list you want. If you use the source="*" technique then something like this might work: class CustomField(Field): def to_native(self, obj): return obj.macAddresses.all() I hope that helps.

Categories : Python

How can I define a list field in django rest framework?
One way to deal with arrays for a non ORM-based object is to override the to_native and from_native methods. In your case: class TagsField(serializers.WritableField): def from_native(self, data): if isinstance(data, list): return Tags(data) else: msg = self.error_messages['invalid'] raise ValidationError(msg) def to_native(self, obj): return obj.tags If you had an ORM-based object you would like to look at the SlugRelatedField with the many = True attribute. From Django Rest Framework version 3.0 you can also use ListField http://www.django-rest-framework.org/api-guide/fields/#listfield

Categories : Django

Getting mongoengine and django rest framework to play nice
Django REST Framework is intended to work well with Django's models. As MongoEngine is not a replacement for Django's Models, you will need to define a few more functions for it to play nice with Django Rest framework. If you need a framework build for MongoEngine, you might want to take a look at django-tastypie-mongoengine instead. If you prefer to use Django REST Framework it's perfectly feasible though. Your BlogList class is actually a View, not a Serializer. First, define a serializer class: from rest_framework import serializers from .models import Blog class BlogSerializer(serializers.Serializer): post_id = serializers.IntegerField() title = serializers.CharField(max_length=144) date_created = serializers.DateTimeField(required=False) body = serializers.CharFiel

Categories : Django

How to add permissions in Django Rest Framework for specific requests
By default permissions are unrestricted. In your settings.py you can specify a different set of defaults to where users have to be authenticated and have the correct Django model permission. You will need to specify a model attribute on your view class for the DjangoModelPermissions to take effect. # settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.DjangoModelPermissions' ) } # views.py class DocumentList(APIView): model = Document ... The DjangoModelPermissions permission map can be found in the source. GET, OPTIONS and HEAD don't require a permission but since we specified IsAuthenticated we're still requiring that POST maps to add PUT and PATCH map to change DELE

Categories : Django

How I can allow a user to modify only their data in django rest framework?
You want to adapt the example from the tutorial about associating snippets with users. Keep your get_queryset implementation and then set the user field to the request user in pre_save.

Categories : Django

model field named url and django rest framework url
It may be considered poor form (I am by no means a pro programmer or rest_framework expert), but I believe you can add extra context to the serialized output: http://django-rest-framework.org/api-guide/serializers.html#specifying-fields-explicitly class AccountSerializer(serializers.ModelSerializer): url = serializers.CharField(source='get_absolute_url', read_only=True) groups = serializers.PrimaryKeyRelatedField(many=True) class Meta: model = Account Extra fields can correspond to any property or callable on the model. So in the above the field 'get_absolute_url' must be in the 'Account' model. In your case (I think) you could do this: class ModelSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.Field(source='owner.username') ur

Categories : Django

Retrieving a Foreign Key value with django-rest-framework serializers
Just use a related field without setting many=True. Note that also because you want the output named category_name, but the actual field is category, you need to use the source argument on the serializer field. The following should give you the output you need... class ItemSerializer(serializers.ModelSerializer): category_name = serializers.RelatedField(source='category', read_only=True) class Meta: model = Item fields = ('id', 'name', 'category_name')

Categories : Django

How to query by unique attribute with Django-Rest-Framework (Many To Many)
Try this: filter(clients__hostname=clients) Take a look at https://docs.djangoproject.com/en/1.5/topics/db/queries/#spanning-multi-valued-relationships

Categories : Python

Django-rest-framework serializer makes a lot of queries
select_related will work as expected with serializers. Make sure you're setting that in the 'queryset' attribute on the view if you're using the generic views. Using select_related inside 'get_queryset' will work too. Otherwise the only thing I can suggest is trying to narrow the issue down with some more debugging. If you still believe there's an issue and have a minimal example that'll replicate it then raise the issue as a ticket, or take the discussion to the mailing list.

Categories : Django

Django REST framework object level permissions
I have done this in the past using a custom permission and overridden has_object_permission like the following: from rest_framework import permissions class MyUserPermissions(permissions.BasePermission): """ Handles permissions for users. The basic rules are - owner may GET, PUT, POST, DELETE - nobody else can access """ def has_object_permission(self, request, view, obj): # check if user is owner return request.user == obj You can do some more detailed things such as deny specific request types (for instance to allow a GET requests for all users): class MyUserPermissions(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Allow get requests for all if request.method == 'GET':

Categories : Python

Django REST Framework partial updates with depth
This was originally answered in the question, but I feel it deserves a decent explanation. In Django REST Framework 3, the process of saving nested data has been made considerably more clear. Now you can override update on the serializer and manipulate the validated_data, updating your model objects manually. This is specifically documented now, but the implementation is typically very specific to the situation. Original answer (in the question) by user2708386 Short answer is yes, it's possible. The problem was that I still needed to override the .save() method on my model to also save the related User object. class Users(models.Model): user = models.OneToOneField(User) foo = models.CharField() baz = models.CharField() yin = models.CharField() yang = models.

Categories : Python

Return Create Object ID Django Rest Framework
What does your serializer look like? Does it have the 'id' in the fields to be included? http://django-rest-framework.org/api-guide/serializers.html#specifying-which-fields-should-be-included The serializer decides what the object returned looks like in the API

Categories : Python

Make BooleanField required in Django Rest Framework
There was an issue with Boolean fields and the required argument. Should now be fixed in master. See this issue: https://github.com/tomchristie/django-rest-framework/issues/1004

Categories : Django

Django REST Framework HyperlinkedModelSerializer write operations
I think the HyperlinkedModelSerializer is reasonably documented here: http://django-rest-framework.org/api-guide/serializers#hyperlinkedmodelserializer ...may not have been when you last searched. Disclaimer: I am not a programmer or a rest_framework expert I could be on the totally wrong path here, but I feel a bit like the two things you are linking are different URIs - i.e. different resources in the www - and should probably be treated as such (unless you really don't need to separate the two things in the back-end). I don't mean that you should force a crappy experience on the consumer of your to-be-beautifully-RESTful API. I think you may be better off creating a function/method that can receive the data you are after in one call and then it can manage the object manipulation se

Categories : Python

Django REST Framework - Serializing optional fields
The serializers are deliberately designed to use a fixed set of fields so you wouldn't easily be able to optionally drop out one of the keys. You could use a SerializerMethodField to either return the field value or None if the field doesn't exist, or you could not use serializers at all and simply write a view that returns the response directly. Update for REST framework 3.0 serializer.fields can be modified on an instantiated serializer. When dynamic serializer classes are required I'd probably suggest altering the fields in a custom Serializer.__init__() method.

Categories : Python

How to pass django rest framework response to html?
Have you added TemplateHTMLRenderer in your settings? http://www.django-rest-framework.org/api-guide/renderers/#setting-the-renderers

Categories : Python

Serializing ManyToMany in Django Rest Framework (2.3.5) throws ValueError
The problem looks to be that nested representations do not support read–write, and serializing flat structures for write operations is the way to go.

Categories : Python

Django Rest Framework bulk updates inserting instead of updating
The obvious thing that pops out is that you're not passing object instances to your serializer. (Thus it will create new instances rather than update.) See the docs on dealing with multiple objects in serializers where you'll see your QuerySet passed in.

Categories : Django

Django REST Framework: How do I change the color of top strip in Browsable UI
Here's what I added to my api.html: {% block style %} {{ block.super }} <style> .navbar .navbar-inner { -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-right-colors: none; -moz-border-top-colors: none; background: none repeat scroll 0 0 #2C2C2C; border-color: ****MY_COLOR_HERE**** -moz-use-text-color -moz-use-text-color; border-image: none; border-radius: 0 0 0 0; border-right: medium none; border-style: solid none none; border-width: 5px medium medium; color: #FFFFFF; } </style> {% endblock %}

Categories : CSS



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.