Re: Nested fields error: Write an explicit update() method, but there is already one?

2023-10-31 Thread Carl Nobile
First of all, you need to get the formatting correct. It's not easy to read
the way it is now, plus how would anyone know if the error you are getting
is because the formatting on your end was a problem that caused your error?

The other thing which is even more important, you need to provide the
Python error or traceback.

On Tue, Oct 31, 2023 at 11:09 AM Michael Shamoon 
wrote:

> Hiya, friend of mine and I are pretty stumped about a nested fields error,
> we're getting the following:
> ```AssertionError: The `.update()` method does not support writable nested
> fields by default. Write an explicit `.update()` method for serializer
> `documents.serialisers.DocumentSerializer`, or set `read_only=True` on
> nested serializer fields.``` but what is confusing is that *there already
> is an update method*. See the code below, really appreciate any thoughts.
>
> ```
> class DocumentSerializer(OwnedObjectSerializer,
> DynamicFieldsModelSerializer):
> ...
>
> custom_fields = CustomFieldInstanceSerializer(many=True, allow_null=True)
>
> ...
>
> def update(self, instance, validated_data):
> ...
> super().update(instance, validated_data)
> return instance
>
> def __init__(self, *args, **kwargs):
> self.truncate_content = kwargs.pop("truncate_content", False)
>
> super().__init__(*args, **kwargs)
>
> class Meta:
> model = Document
> depth = 1
> fields = (
> "id",
> "correspondent",
> "document_type",
> "storage_path",
> "title",
> "content",
> "tags",
> "created",
> "created_date",
> "modified",
> "added",
> "archive_serial_number",
> "original_file_name",
> "archived_file_name",
> "owner",
> "permissions",
> "user_can_change",
> "set_permissions",
> "notes",
> "custom_fields",
> )
> ```
>
> ```
> class CustomFieldSerializer(serializers.ModelSerializer):
> class Meta:
> model = CustomField
> fields = [
> "id",
> "name",
> "data_type",
> ]
> ```
> ```
> class CustomFieldInstanceSerializer(serializers.ModelSerializer):
> parent = CustomFieldSerializer()
> value = SerializerMethodField()
>
> def get_value(self, obj: CustomFieldInstance):
> return obj.value
>
> def create(self, validated_data):
> parent_data = validated_data.pop("parent")
> parent = CustomField.objects.get(id=parent_data["id"])
> instance = CustomFieldInstance.objects.create(parent=parent)
> return instance
>
> def update(self, instance: CustomFieldInstance):
> return instance
>
> class Meta:
> model = CustomFieldInstance
> fields = [
> "parent",
> "value",
> ]
> ```
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/32ac3ee1-292d-4a82-9243-3790f1fb0538n%40googlegroups.com
> 
> .
>


-- 
--
Carl J. Nobile (Software Engineer/API Design)
carl.nob...@gmail.com
--

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2BKdiA_eazEkPw_Wk9%2BsYDdCiD%2BVEFiwUT52b52Vni0Rw%40mail.gmail.com.


Re: Which Python file renders textarea.html and forms.html ?

2022-12-29 Thread Carl Nobile
If you need to change what is in a standard Django HTML form you'll need to
override the form itself. The docs will explain how to do this.
Here's a StackOverflow page that may help.

https://stackoverflow.com/questions/10040442/override-a-form-in-django-admin

On Thu, Dec 29, 2022 at 12:13 PM Pallav Rai  wrote:

> I want to add certain things in Django's existing html form but cannot
> understand how can i set textarea initial values in this project.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/56a0d294-548a-4e9d-bfc6-02d7ba26a9a8n%40googlegroups.com
> 
> .
>


-- 
--
Carl J. Nobile (Software Engineer/API Design)
carl.nob...@gmail.com
--

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2BMF-4Kjt%3Dj0qLX%3D3gLae%2BD%3Debo2AMbepxxkiY%2BQDh0hg%40mail.gmail.com.


Re: Invoking views directly

2022-11-17 Thread Carl Nobile
I have relatives with the name D'Ambra, they live in New York.

Relating to your question. It is generally the rule under REStFul web
services is to not put everything under one endpoint.
If you need to change versions and have both still active, at least for a
while, the best thing to use is minetypes to differentiate them.
In general, you should expose only one root endpoint for your API. The root
endpoint should be an index into all the other endpoints
essentially mappings using keywords to find the one you need.
Then you can change endpoints and add versions without breaking anybody's
code. If this interests you I can go into more detail if you want.

~Carl

On Tue, Nov 15, 2022 at 9:42 AM 'Paul D'Ambra' via Django REST framework <
django-rest-framework@googlegroups.com> wrote:

> I'm relatively new to Django/DRF so apologies if this question exposes
> that too much 😊
>
> I have a set of API endpoints that have grown organically. Together they
> cover one set of functionality and I'd like to combine them under one new
> API endpoint
>
> So
>
> myapi.com/thing?info=I-need
> myapi.com/stuff?how=to-return-this
> myapi.com/and-this?even=more-params
>
> would unify under
>
> myapi.com/q?type=thing&info=I-need
> myapi.com/q?type=stuff&how=to-return-this
> myapi.com/q?type=and-this&even=more-params
>
> There's a few reasons to do this but most importantly
>
> 1) The responses are complex and I'd like to run both the old and new code
> paths and compare the results
> 2) there are external users of the API and I'd like to be able to redirect
> their old uses to the new endpoint rather than break their integrations
>
> In an ideal world I would have a handler that looked like this:
>
> @action(url_path="q", methods=["GET"], detail=False)
> def query(self, request, *args, **kwargs) -> Response:
> query_type = request.query_params.get("type")
> if query_type == "legacy_trends":
> insight_trend_view = InsightViewSet.as_view({"get": "trend"})
> return insight_trend_view(request._request, *args, **kwargs)
> else:
>  raise ValidationError(detail=f"{query_type} is not a valid query
> type")
>
> But I'm wondering if there's a better/safer way of achieving this
>
> Thanks in advance
>
> Paul
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/235a48c7-a612-4b7e-a02f-8ecae69639ean%40googlegroups.com
> 
> .
>


-- 
--
Carl J. Nobile (Software Engineer/API Design)
carl.nob...@gmail.com
--

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLEUv%3Db9Ag7_jqFt3XnEJ_nTK_VMu76yncOVHOKD18wag%40mail.gmail.com.


Re: ModelSerializers & schema generation

2021-08-21 Thread Carl Nobile
In this part do this:

class JobState(IntEnum):
RECEIVED = 0
PROCESSING = 1
DONE = 2
FAILED = 3
INT_ENUM = {'RECEIVE': RECEIVE, 'PROCESSING': PROCESSING,
'DONE': DONE, 'FAILED': FAILED}

Then use the INT_ENUM in your serializer. This may not work exactly in your
case, however, it could be useful.
I do this all the time, but I don't make another embedded class, I don't
see any real need for it. Just use the standard Django way to create an
iterator for a model field.
https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.Field.choices

~Carl

On Sat, Aug 21, 2021 at 2:44 PM Adam Fletcher  wrote:

> Hi DRFers,
>
> I have a model like this:
>
> class Job(Model):
>
> class JobState(IntEnum):
> RECEIVED = 0
> PROCESSING = 1
> DONE = 2
> FAILED = 3
>
> @classmethod
> def choices(cls: Any) -> List[Tuple[int, str]]:
> return [(key.value, key.name) for key in cls]
>
> state = IntegerField(
> choices=JobState.choices(),
> default=JobState.RECEIVED,
> )
>
> I have a ModelSerializer:
> class JobSerializer(serializers.ModelSerializer):
> class Meta:
> model = Job
> fields = [
> "state",
> ]
> How do I get the OpenAPI schema to show the _names_ of the fields, not the
> enum values?
>
> My schema generates to:
>
> "state": {
> "enum": [
> 0,
> 1,
> 2,
> 3
> ],
> "type": "integer",
> "minimum": -2147483648,
> "maximum": 2147483647
> },
>
> Any ideas on how to make the enum use the name, not the value?
>
> Thanks!
> -Adam
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/CAEP43uOWYYhQ8hH7xt0qqOk9E4D9rW0Z0OzDyYqKvnE0pg2jSQ%40mail.gmail.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQKr78hh1u2EofSJSRUPuJ-4Yr0W3jBHfS3cJ3SeWgbFFg%40mail.gmail.com.


Re: Field to_representation function seems to have inconsistent arguments

2021-07-07 Thread Carl Nobile
If I'm not mistaken there are two types of incoming data an object or a
dict, but the output type should always be a dictionary.
The `field.get_attribute` method is used to get values from embedded fields
on the serializer.
I override the `to_representation` method all the time because I write
custom serializers often.
So it's not only fields that have the `to_representation`, but as I
mentioned above serializers have them also, but both cases should always
return an ordered dict.
I agree that this can be confusing but the problem is that it's not always
known which one will be called and how deep the calls will go.
~Carl

On Wed, Jul 7, 2021 at 1:54 PM russ...@vida.com  wrote:

> Hi all,
>
> I'm troubleshooting a bug in the drf-spectacular library that we're trying
> to use to generate Open Api 3.0 schemas from our DRF codebase (link:
> https://github.com/tfranzel/drf-spectacular/issues/422), and I stumbled
> across what looks like a bit of an inconsistency in what arguments are
> expected to be passed to the to_representation function on different field
> types.
>
> Inside of Serializer.to_representation, I see the following code, where it
> first calls field.get_attribute, and then calls the to_representation
> function on each field individually (link
> https://github.com/encode/django-rest-framework/blob/98e56e0327596db352b35fa3b3dc8355dc9bd030/rest_framework/serializers.py#L493
> ).
>
> for field in fields:
> try:
> attribute = field.get_attribute(instance)
> except SkipField:
> continue
>
> # We skip `to_representation` for `None` values so that fields do
> # not have to explicitly deal with that case.
> #
> # For related fields with `use_pk_only_optimization` we need to
> # resolve the pk value.
> check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else
> attribute
> if check_for_none is None:
> ret[field.field_name] = None
> else:
> ret[field.field_name] = field.to_representation(attribute)
>
> What is interesting, is that different fields return different types from
> the call to field.get_attribute.  Most fields seem to fetch the attribute
> from the instance that is passed in and return the attribute.  Some fields
> however, like ModelField and SerializerMethodField, just return the
> instance, without fetching an attribute.
>
> This means that the to_representation functions for ModelField and
> SerializerMethodField expect the entire instance to be passed in as the
> argument, whereas most fields expect just the attribute.
>
> Is this different signature for Field.to_representation expected?  And are
> there any suggestions for how to handle it, perhaps there is a way to know
> which fields have different signatures?
>
> We're trying to use to_representation to make sure that we're using
> primitive types when generating the Open API schemas.
>
> Thanks for the help,
> Russell
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/02af1ce6-3269-46d2-82b9-272a3c81cadcn%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2BdpBGWj772UVLmNQr%2BOgbw6iSGgbpTS%2B_z%2B6sMt5%2B5vQ%40mail.gmail.com.


Re: Requiring format extension on all URLs

2021-06-22 Thread Carl Nobile
Phil,

The correct, normal, and common ways are not always the same as many people
don't understand that RFCs define the correct way to do things, not a
specific framework like DRF. The quick a dirty way will ALWAYS lead to
issues down the road.
I use format queries also but only when maneuvering around the browsable
API the DRF gives you, never for machine to machine access.

These are some of the standard documents:
https://datatracker.ietf.org/doc/html/rfc7231
https://datatracker.ietf.org/doc/html/rfc6839
https://datatracker.ietf.org/doc/html/rfc4288

Roy Fielding is the editor of many RFCs he's also the one that pretty much
invented REST he's the editor of RFC7231 above.

Building a RESTful web service that is done properly is not easy. It takes
planning and understanding best practices. This includes security concerns.

You should also read Roy Fielding dissertation on REST which can be
found here: https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

~Carl

On Tue, Jun 22, 2021 at 11:51 AM Phil Gyford  wrote:

> Thanks Carl. I'll think about your suggestion.
>
> I'm a little hesitant as I usually try to do things the most conventional
> way, especially with a tool like DRF that I'm using for the first time. I
> want to go with the flow and do things the expected, "normal" way. The DRF
> docs are a little confusing about this topic, although, to my reading, they
> seem to go more for format extensions rather than Accept headers and mime
> types. (
> https://www.django-rest-framework.org/api-guide/format-suffixes/#accept-headers-vs-format-suffixes
> ).
>
> But, as I said, having tried to enforce the use of format extensions –
> thinking this is more explicit (which I like) than having them be optional,
> or having optional ?format= query parameters  – I've ended up
> going down a path that feels wrong and excessive. Hence me trying to find
> out what's "normal", or most common.
>
> Thanks again,
> Phil
>
> On Monday, 21 June 2021 at 18:18:08 UTC+1 carl@gmail.com wrote:
>
>> Hi Phil,
>>
>> The best way to solve all these issues is to use mime types to
>> determine the type of return data.
>> For example application/vnd.{company name}.{endpoint name}+json;ver=1.
>> In the above you would replace {company name} with your company or
>> organization name, and {endpoint name} with something like account,
>> customer, or whatever the specific endpoint would be.
>> The +json could also be +api in your case.
>> The ;ver=1 would indicate the version number.
>>
>> So why is this better?
>>
>>1. You no longer need /v1/ or /v2/ in the URI.
>>2. Each endpoint can have different versions independently of any
>>other endpoint.
>>3. The type of data is defined by the mime type not by changing the
>>URI.
>>4. You can send one type of data and receive another type. For
>>example using different Accept and Content-Type headers.
>>
>> This is the best way to do this and solves a lot of issues down the road,
>> but it does require a bit more code written upfront.
>>
>> ~Carl
>>
>> On Mon, Jun 21, 2021 at 10:28 AM Phil Gyford  wrote:
>>
>>> Hi,
>>>
>>> I'm trying to set up DRF as a read-only API, and want to require that
>>> all URLs have either a .api or .json format extension.
>>>
>>> I've sort of managed this so far by copying the DefaultRouter class and
>>> in its get_urls() method changing this call:
>>>
>>> urls = format_suffix_patterns(urls)
>>>
>>> to this:
>>>
>>> urls = format_suffix_patterns(
>>> urls, suffix_required=True, allowed=["api", "json"]
>>> )
>>>
>>> This gets me what I need but leaves me with two remaining/resulting
>>> issues:
>>>
>>> 1. Tbe API Root URL looks like /api/v1/.api or /api/v1/.json. I feel it
>>> shouldn't have that final slash but, given all non-API URLs on the site
>>> have an ending slash, and I include my API URL conf with path("api/v1/",
>>> include("myproject.api.urls", namespace="v1")), I can't see how to fix
>>> it.
>>>
>>> 2. When I view the Browsable API, using the .api extension URLs, the
>>> links in the Breadcrumbs do not have the extension, and so clicking them
>>> 404s. I can't see any way to fix this other than subclassing
>>> BrowsableAPIRenderer and using a modified
>>> utils.breadcrumbs.get_breadcrumbs function.
>>>
>>> I didn't think this was an unreasonable thing to want – explicit URLs
>>> for each format – but given the amount of fiddling required to get it
>>> functioning, maybe this is a dumb idea? Have I missed something? How do you
>>> set up your URLs and formats?
>>>
>>> Many thanks,
>>> Phil Gyford
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django REST framework" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-rest-fram...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-rest-framework/87e4d9e4-bde5-4285-ae66-dfdc32c3384bn%40googlegroups

Re: Requiring format extension on all URLs

2021-06-21 Thread Carl Nobile
Hi Phil,

The best way to solve all these issues is to use mime types to
determine the type of return data.
For example application/vnd.{company name}.{endpoint name}+json;ver=1.
In the above you would replace {company name} with your company or
organization name, and {endpoint name} with something like account,
customer, or whatever the specific endpoint would be.
The +json could also be +api in your case.
The ;ver=1 would indicate the version number.

So why is this better?

   1. You no longer need /v1/ or /v2/ in the URI.
   2. Each endpoint can have different versions independently of any other
   endpoint.
   3. The type of data is defined by the mime type not by changing the URI.
   4. You can send one type of data and receive another type. For example
   using different Accept and Content-Type headers.

This is the best way to do this and solves a lot of issues down the road,
but it does require a bit more code written upfront.

~Carl

On Mon, Jun 21, 2021 at 10:28 AM Phil Gyford  wrote:

> Hi,
>
> I'm trying to set up DRF as a read-only API, and want to require that all
> URLs have either a .api or .json format extension.
>
> I've sort of managed this so far by copying the DefaultRouter class and
> in its get_urls() method changing this call:
>
> urls = format_suffix_patterns(urls)
>
> to this:
>
> urls = format_suffix_patterns(
> urls, suffix_required=True, allowed=["api", "json"]
> )
>
> This gets me what I need but leaves me with two remaining/resulting issues:
>
> 1. Tbe API Root URL looks like /api/v1/.api or /api/v1/.json. I feel it
> shouldn't have that final slash but, given all non-API URLs on the site
> have an ending slash, and I include my API URL conf with path("api/v1/",
> include("myproject.api.urls", namespace="v1")), I can't see how to fix it.
>
> 2. When I view the Browsable API, using the .api extension URLs, the
> links in the Breadcrumbs do not have the extension, and so clicking them
> 404s. I can't see any way to fix this other than subclassing
> BrowsableAPIRenderer and using a modified
> utils.breadcrumbs.get_breadcrumbs function.
>
> I didn't think this was an unreasonable thing to want – explicit URLs for
> each format – but given the amount of fiddling required to get it
> functioning, maybe this is a dumb idea? Have I missed something? How do you
> set up your URLs and formats?
>
> Many thanks,
> Phil Gyford
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/87e4d9e4-bde5-4285-ae66-dfdc32c3384bn%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQJN-S_NMAX%3D6e75ax%3DwrswXjY%2B9e0b_KumsiLVP835z-A%40mail.gmail.com.


Re: Question about combining the results of two serializers

2021-05-26 Thread Carl Nobile
You will have to write your own code to do this.
You can convert an OrderedDict to a standard dict like this value =
dict(OrderedDict(...))

~Carl

On Wed, May 26, 2021 at 5:01 PM Dana Adams  wrote:

> This may be more of a Django than Django Rest question - I am new to both
> - but I thought I'd start here
>
> I've got two objects of type * 'rest_framework.utils.serializer_helpers.ReturnDict'>* that I'd like to
> combine and then feed back into Response()
>
> *Object **1*
>
> {'data':
> OrderedDict([('agent_info', [
> OrderedDict([('agent', OrderedDict([('id', 10001), ('name', 'Jimmy
> McBride')])),
> ('silence', OrderedDict([('averagePercent', 0.15), ('averageSeconds', 21.3
> ),('percentAgent', 0.71), ('percentCustomer', 0.29)])),
> ('calls', 14)]),
> OrderedDict([('agent', OrderedDict([('id', 10002), ('name', 'Sally Walker'
> )])),
> ('silence', OrderedDict([('averagePercent', 0.24), ('averageSeconds', 26.5
> ),('percentAgent', 0.65), ('percentCustomer', 0.35)])),
> ('calls', 20)])
> ])])
> }
>
> Object *2*
>
> {'data':
> OrderedDict([('team_info', [
> OrderedDict([('silence', OrderedDict([('averagePercent', 0.21), (
> 'averageSeconds', 24.8), ('percentAgent', 0.68), ('percentCustomer', 0.32)
> ])),
> ('calls', 34)])
> ])])
> }
>
> How can I combine these such that the resulting json response, produced
> by Response(), looks like:
>
> {
> "data": {
> "agent_info": [
> {
> "agent": {
> "id": 10001,
> "name": "Jimmy McBride"
> },
> "silence": {
> "averagePercent": 0.15,
> "averageSeconds": 21.3,
> "percentAgent": 0.71,
> "percentCustomer": 0.29
> },
> "calls": 14,
> },
> {
> "agent": {
> "id": 10002,
> "name": "Sally Walker"
> },
> "silence": {
> "averagePercent": 0.24,
> "averageSeconds": 26.5,
> "percentAgent": 0.65,
> "percentCustomer": 0.35
> },
> "calls": 20,
> },
> ],
> "team_info": [
> {
> "silence": {
> "averagePercent": 0.21,
> "averageSeconds": 24.8,
> "percentAgent": 0.68,
> "percentCustomer": 0.32
> },
> "calls": 34
> }
> ]
> }
> }
>
>
> Thanks!
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/dfe936af-3abd-40e1-85c8-cddf61caa5fbn%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQKqb%2BRgZ0vGUW7%3DTuX4HSrbxWktyUUO9B%3DnwwHhW7uejg%40mail.gmail.com.


Re: Updating foreign key

2021-01-03 Thread Carl Nobile
First, never use the PK that Django generates as a way to access a record
through an API. These types of PKs are a numeric sequence and can leave
your site open to sequence attacks where an attacker tries a long series of
numbers to access all or many of your records. Use a public ID of some
sort, you can use a UUID or generate your own complex ID.
There should be no reason you should not be able to access a record with a
company name. There is nothing in Django or DRF that would prevent that.
You must have something in your code that is preventing it.

~Carl

On Sun, Jan 3, 2021 at 2:35 AM Stats Student 
wrote:

> Hi, I have a basic one-to-many foreign key relationship (each product
> has a company associated with it, one company can have multiple
> products). I do not specify an explicit serializer relation for this
> field (e.g. PrimaryKeyRelatedField) so it's using the FK definition
> from the models ( company = models.ForeignKey(Company, models.CASCADE,
> blank=True, null=True) )
>
> I have overridden the .create() method in the Product serializer
> (inherits from ModelSerializer) to use the company name that's passed
> in, to look up the relevant ID (or create a new record) and assign it
> to " validated_data['company'] = company_obj " and it works fine.
>
> However, on the update (PATCH) where I also pass in the company name,
> I get a validation error saying that it expects a primary key instead
> of the name ("Incorrect type. Expected pk value, received str"). I
> have added breakpoints in .update() and .partial_update() of the
> Product serializer but the error seems to come from an earlier
> validation routine. Could someone suggest where I can intercept the
> validation process to translate the company name into an object and
> put in validated_data['company'] , the same way I am doing in
> .create() ?
>
> I tried adding a field level validation, but that doesn't seem to make
> a difference.
>
> def validate_company(self, value):
> c, created = Company.objects.get_or_create(name = value)
> return c
>
>
> TIA
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/CAMZO7wJT7-OyjxRdubPKOAzZk15iGOdSw_stLaDra%3DyHipqPLg%40mail.gmail.com
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQL2LSgTFsOcWVmvAytwuJNRogtdRh%2B5ZrrMu%2BqgNbA8jg%40mail.gmail.com.


Re: How to convert Stored procedure logic to Django rest framework

2020-11-15 Thread Carl Nobile
I've converted many systems in my life and I have always found it best to
use the old system as a guide and not try to use anything from the old
system at all. Know what it is that you are trying to do, understand what
the inputs and outputs are, and write new code. The old system would
therefore be a guide as to what these inputs and outputs are, in other
words, it defines your use cases.
With that said you haven't mentioned what DB your old .NET system is using.
The only DB I ever use anymore with Django is PostgreSQL, it is also
supported better than any other DB.
I do consult work specifically for these types of cases.
~Carl

On Sun, Nov 15, 2020 at 1:41 PM brijesh dutta  wrote:

> Hi All,
>
> i am new to DRF
>
> We have an existing application in .NET which uses complex  stored
> procedures
> (mainly  taking dataset as a paramter and inserting the data into multiple
> tables)
> we have an initiative to move the backend to Django rest framework
>
> hence just wanted suggestions what is the best practice in DRF for such
> use cases and if any one could direct me o some useful content to get
> started
>
> Thank You
> Regards
> -Brijesh
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/214d12ab-ac5c-4ee4-871f-9c4e2648d09an%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQL0nBO%2BrKO5ndX3oAH_exxzoVD58JeMQF_U%3DJ-5GZK9Rw%40mail.gmail.com.


Re: How to deal with nested serializers and form data

2020-10-27 Thread Carl Nobile
Look at the DRF documentation.
https://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations


On Tue, Oct 27, 2020 at 7:50 PM C G  wrote:

> Hello, i have a question regarding writable nested serializers, i have two
> models that are related through a OneToOne relationship, when i try to
> serialize the data from the request (which is in 'form-data' format because
> it contains an Image file) it fails, i overrided the 'create' method as the
> official docs says but i am still not able to accomplish the creation of
> the objects in the DB.
>
> I've found this thread in Stackoverflow
> 
> that says that handling writable nested serializers using form-data format
> is not supported.
>
> Thanks a lot in advance.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/649a1a7f-a4e0-472d-b238-e5b5e364aa4cn%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQJ4FP6RBm%2Bt6rDE6uauuSqwpp7hFYHab_h7scUB_oWt-w%40mail.gmail.com.


Re: Limit content-types in request body?

2020-10-11 Thread Carl Nobile
You might want to look at the docs for different methods of versioning. The
way you do versioning is directly related to how you will use mime types in
your code.
I personally use the mine type to determine the versions, this allows you
to change the version on any endpoint just by changing the version on the
mime type.
https://www.django-rest-framework.org/api-guide/versioning/

~Carl

On Sun, Oct 11, 2020 at 2:36 PM Adam Fletcher  wrote:

> Hi folks,
>
> I'd like to limit the request body types I accept to just JSON (this is
> oddly to work around an `openapi-generator` bug). I see that I can add a
> `accepted_media_type` to requests - but is there a way to do this for all
> DRF requests?
>
> Thanks!
>
> -Adam
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/CAEP43uPn7UR4gDECrHHk6eZj%3Dnd9y3ETs2irSRJgrq-gFJWSHA%40mail.gmail.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQJq-%3DUuOkxSm_9njcPyvH9h2G7ub0rNSs_W%2BUfvNx3Tag%40mail.gmail.com.


Re: How to make my own model authentication and authorizations in Django Rest Framework

2020-09-30 Thread Carl Nobile
It's always best to read the docs before asking questions here because in
many instances there are many answers to your questions.

Here's a link to the DRF docs for authentication:
https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/

~Carl

On Wed, Sep 30, 2020 at 2:45 PM Osama Imran  wrote:

> Hello All,
> I am new to Django rest frame work and my questions is how I can apply
> Authentication and  Authorizations to any model for API view which  I have
> developed from scratch and what is the best way to implement these
> concepts. please help.
> Thank you
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/6c08b363-6326-45aa-a748-ffae253c66d3n%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQJGae1U-RGQCaGnShr0zj5159MJck3s6kJ6__mR4Hn9AQ%40mail.gmail.com.


Re: action methods is not allowed to have more methods rather than their viewsets

2020-09-30 Thread Carl Nobile
As I said I don't use ViewSets, but if you add in mixins that cause the
signature of the ViewSet to change it cannot easily and automatically
generate schemas--at least this is my understanding.
The mixins are used in generic views and are not generally needed when
defining your own views except under very few situations when you need to
override a lot of functionality in the given generic views.
You might want to just use the generic view I mentioned previously.

ViewSets are there to make things easy and give you some additional perks,
but they take away a lot of flexibility.

~Carl


On Tue, Sep 29, 2020 at 4:10 PM Ali Yazdi  wrote:

> I've got a new problem with this new viewset that when I generate schema
> with `generateschema --file schema.yml` it says:
> ```
>  UserWarning:  is
> not compatible with schema generation
>   warnings.warn(
> ```
> But, it creates the schema of that viewset!
>
> On Tuesday, September 29, 2020 at 11:04:35 PM UTC+3:30 Ali Yazdi wrote:
>
>> Thanks for your answer. I try using
>> `(mixins.RetrieveModelMixin,mixins.ListModelMixin, GenericViewSet)` without
>> setting `http_method_names = ['get']` and my action works fine for `post`
>> method.
>> Thank you Carl.
>>
>> On Tuesday, September 29, 2020 at 9:47:59 PM UTC+3:30 carl@gmail.com
>> wrote:
>>
>>> If you set `http_method_names = ['get']` and the POST is on the same
>>> endpoint it won't allow a POST. You might want to add 'post' to that
>>> variable.
>>> I, myself don't use ViewSets. I tend to use generic Views. In your case
>>> the ListCreateAPIView generic view in this case. You can find it at
>>> https://www.django-rest-framework.org/api-guide/generic-views/#listcreateapiview
>>>
>>> ~Carl
>>>
>>> On Tue, Sep 29, 2020 at 11:16 AM Ali Yazdi  wrote:
>>>
 1. I have a `viewsets.ModelViewSet` that has `http_method_names =
 ['get']`
 2. and its action method needs to have `methods=['get', 'post']`
 3. But `post` method is not allowed for its action
 4. I don't is it normal behavior to have this scenario or not?

 --
 You received this message because you are subscribed to the Google
 Groups "Django REST framework" group.
 To unsubscribe from this group and stop receiving emails from it, send
 an email to django-rest-fram...@googlegroups.com.
 To view this discussion on the web visit
 https://groups.google.com/d/msgid/django-rest-framework/abec1376-0619-4557-a7ea-1bab1f6473aan%40googlegroups.com
 
 .

>>>
>>>
>>> --
>>>
>>> ---
>>> Carl J. Nobile (Software Engineer)
>>> carl@gmail.com
>>>
>>> ---
>>>
>> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/411bdc9a-6f7d-40e2-8b16-d6e4298af2dfn%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQJML4z1KCsuS8sOXhMnZusjqe0buiJVsa4R8yDfrhu56Q%40mail.gmail.com.


Re: action methods is not allowed to have more methods rather than their viewsets

2020-09-29 Thread Carl Nobile
If you set `http_method_names = ['get']` and the POST is on the same
endpoint it won't allow a POST. You might want to add 'post' to that
variable.
I, myself don't use ViewSets. I tend to use generic Views. In your case
the ListCreateAPIView generic view in this case. You can find it at
https://www.django-rest-framework.org/api-guide/generic-views/#listcreateapiview

~Carl

On Tue, Sep 29, 2020 at 11:16 AM Ali Yazdi  wrote:

> 1. I have a `viewsets.ModelViewSet` that has `http_method_names = ['get']`
> 2. and its action method needs to have `methods=['get', 'post']`
> 3. But `post` method is not allowed for its action
> 4. I don't is it normal behavior to have this scenario or not?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/abec1376-0619-4557-a7ea-1bab1f6473aan%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQJVB8UxbHEnnYAM4M%2BSkXxGQLBzPsy_NPHr9TNri5yAYg%40mail.gmail.com.


Re: Problem with unique_together and field override in ModelSerializer

2020-09-11 Thread Carl Nobile
You may have to override the UniqueTogetherValidator to use the correct
field.

https://www.django-rest-framework.org/api-guide/validators/#uniquetogethervalidator

~Carl


On Fri, Sep 11, 2020 at 3:25 PM Michael Goffioul 
wrote:

> I have the following model:
>
> class UnitData(models.Model):
> unit = models.ForeignKey(Unit, on_delete=models.CASCADE)
> key = models.CharField(max_length=64)
> data = models.TextField(blank=True)
>
> class Meta:
> unique_together = ["unit", "key"]
>
> I would like to rename the field 'unit' to 'device' in my serializer, so
> I've used the following:
>
> class UnitDataBatchSerializer(serializers.HyperlinkedModelSerializer):
> device = serializers.HyperlinkedRelatedField(
> source='unit',
> view_name='unit-detail',
> queryset=Unit.objects.all())
>
> class Meta:
> model = UnitData
> fields = [ 'device', 'key', 'data' ]
>
> However, I'm getting an exception when validating posted data. It appears
> the UniqueTogetherValidator will try to access the 'unit' field in the
> serializer, but it doesn't exist:
>
> https://github.com/encode/django-rest-framework/blob/master/rest_framework/validators.py#L109
>
> Is that expected? Or a bug? Is there a better way to rename the field in
> the serializer?
>
> Thanks,
> Michael.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/049037ba-0104-404e-a921-570992b91d45n%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLgOVW3MwOsYd4JUTbjA-qv74YTmgasfkdOVTwQX53A4g%40mail.gmail.com.


Re: message": "Cannot query \"\": Must be \"User\" instance.",

2020-09-10 Thread Carl Nobile
Please try to format code properly. It is very difficult to read when not
and you will get more responses if the code is readable.
Thanks

On Thu, Sep 10, 2020 at 4:16 AM Ashuosh Mishra 
wrote:

> Trying to generate token of custom user but getting above error,
>
> models.py
> class MyUserManager(BaseUserManager):
> def create_user(self, email, password=None, **extra_fields):
> if not email:
> raise ValueError('Users must have an email address')
>
> account = self.model(
> email=self.normalize_email(email),
>
> )
> account.account_type = extra_fields.get('account_type')
> account.set_password(password)
> account.save(using=self._db)
> return account
>
> def create_superuser(self, email, password, **extra_fields):
> account = self.create_user(
> email,
> password=password,
> )
> account.account_type = 'A'
> account.is_admin = True
> account.save(using=self._db)
> return account
>
>
> class Account(AbstractBaseUser):
> name=models.CharField(blank=True,null=True,max_length=255)
> Address=models.CharField(blank=True,null=True,max_length=255)
> type_choice = (
> ('A', 'Admin'),
> ('S','Student'),
> ('T','Teacher'),
> )
> email = models.EmailField(
> verbose_name='email address',
> max_length=255,
> unique=False,
> )
> account_type = models.CharField(choices=type_choice, max_length=1,
> null=True)
> is_active = models.BooleanField(default=True)
> is_admin = models.BooleanField(default=False)
> objects = MyUserManager()
>
> USERNAME_FIELD = 'email'
>
> def __str__(self):
> return self.email
>
> def has_perm(self, perm, obj=None):
> return True
>
> def has_module_perms(self, app_label):
> return True
>
> @property
> def is_staff(self):
> return self.is_admin
>
> VIEWS.PY
> class AccountViewSet(viewsets.ViewSet):
> def create(self,request):
> permission_classes = [TokenHasReadWriteScope]
> try:
> name=request.data.get('name')
> Address=request.data.get('Address')
> account_type=request.data.get('account_type')
> if not all([name,Address,account_type]):
> raise Exception('All Fields are mandatory')
>
> obj=Account()
> obj.name=name
> obj.Address=Address
> obj.account_type=account_type
> obj.save()
> print('hello')
> app = Application.objects.get(user=obj)
> token = generate_token()
> print('token',token)
> refresh_token = generate_token()
> expires = now() +
> timedelta(seconds=oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS)
> scope = "read write"
> access_token = AccessToken.objects.create(user=obj,
> application=app,
> expires=expires,
> token=token,
> scope=scope,
> )
> print("access token --->", access_token)
> RefreshToken.objects.create(user=obj,
> application=app,
> token=refresh_token,
> access_token=access_token
> )
> return Response({"response":'delivered'})
> except Exception as error:
> traceback.print_exc()
> return Response({"message": str(error), "success": False},
> status=status.HTTP_200_OK)
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/47c552e0-2ed0-4085-9866-a921dffb2eb9n%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLhLhj5niMuFRj9CJx3QrdDciGqV4s%2BJ%2Bw81F%2B%2BW33ruw%40mail.gmail.com.


Re: Custom user model

2020-09-08 Thread Carl Nobile
The best way to learn is to look at what other people have done, that's why
I gave you the link to a Django/DRF project I've been working on.

On Tue, Sep 8, 2020 at 12:44 PM Ashutosh Mishra 
wrote:

> Thanks for your priceless information
> But my task is to by custom code,i M not looking for shortcut,ready to
> learn and and implement.
>
> On Tue 8 Sep, 2020, 22:11 Carl Nobile,  wrote:
>
>> The serializers are what I customize the most. You will need to write
>> field validation methods along with custom create and update methods. If
>> you have embedded serializer there is no way around this. DRF provides you
>> a framework, not a finished product.
>> Depending on the size of the web service you are building any project
>> like this is between three and ten months. I just left one at Cisco that
>> was three years and it's still being worked on. Building for the web is
>> time-consuming there are NO short cuts. An make sure you write tests on
>> your code WILL be broken.
>>
>> ~Carl
>>
>> On Tue, Sep 8, 2020 at 12:33 PM Ashutosh Mishra <
>> ashutoshmishra...@gmail.com> wrote:
>>
>>> My bad,means using custom code,,not by serializer
>>>
>>> On Tue 8 Sep, 2020, 21:56 Carl Nobile,  wrote:
>>>
>>>> If you don't want to write ANY custom code then you probably cannot do
>>>> it. I've never written any site without at least some custom code.
>>>> At a minimum, you will probably need some custom permission classes
>>>> that you would set on the views--this keeps people with different roles out
>>>> of stuff they shouldn't be in.
>>>> You need to use some sort of token system either OAuth2 (better--more
>>>> flexible) or the one built into DRF for communication between the frontend
>>>> and backend. This is usually non-trivial.
>>>>
>>>> Think about what you are asking and you will see it takes work and
>>>> customization is always part of it.
>>>>
>>>> ~Carl
>>>>
>>>> On Tue, Sep 8, 2020 at 3:21 AM Ashutosh Mishra <
>>>> ashutoshmishra...@gmail.com> wrote:
>>>>
>>>>> i want to create authentication of student,admin and superadmin using
>>>>> viewset and routers without serializers(custom code) how can i do 
>>>>> this,some
>>>>> please guide me
>>>>>
>>>>> --
>>>>> You received this message because you are subscribed to the Google
>>>>> Groups "Django REST framework" group.
>>>>> To unsubscribe from this group and stop receiving emails from it, send
>>>>> an email to django-rest-framework+unsubscr...@googlegroups.com.
>>>>> To view this discussion on the web visit
>>>>> https://groups.google.com/d/msgid/django-rest-framework/a9c47573-7ae1-4a3e-b1a2-181fb3cee08dn%40googlegroups.com
>>>>> <https://groups.google.com/d/msgid/django-rest-framework/a9c47573-7ae1-4a3e-b1a2-181fb3cee08dn%40googlegroups.com?utm_medium=email&utm_source=footer>
>>>>> .
>>>>>
>>>>
>>>>
>>>> --
>>>>
>>>> ---
>>>> Carl J. Nobile (Software Engineer)
>>>> carl.nob...@gmail.com
>>>>
>>>> ---
>>>>
>>>> --
>>>> You received this message because you are subscribed to a topic in the
>>>> Google Groups "Django REST framework" group.
>>>> To unsubscribe from this topic, visit
>>>> https://groups.google.com/d/topic/django-rest-framework/RAsaI4kquNc/unsubscribe
>>>> .
>>>> To unsubscribe from this group and all its topics, send an email to
>>>> django-rest-framework+unsubscr...@googlegroups.com.
>>>> To view this discussion on the web visit
>>>> https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLTFyyvB6LK3OyY1OnTuTvhoe64sLL2eRwoeyTPfuaExg%40mail.gmail.com
>>>> <https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLTFyyvB6LK3OyY1OnTuTvhoe64sLL2eRwoeyTPfuaExg%40mail.gmail.com?utm_medium=email&utm_source=footer>
>>>> .
>>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django REST framework" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>

Re: Custom user model

2020-09-08 Thread Carl Nobile
Here's an open-source project I've been working on so you can see what I'm
talking about. BTW--I don't use viewsets nor routers in my code.
https://github.com/cnobile2012/inventory
Be sure you are looking in the develop branch, master is very old.

~Carl

On Tue, Sep 8, 2020 at 12:41 PM Carl Nobile  wrote:

> The serializers are what I customize the most. You will need to write
> field validation methods along with custom create and update methods. If
> you have embedded serializer there is no way around this. DRF provides you
> a framework, not a finished product.
> Depending on the size of the web service you are building any project like
> this is between three and ten months. I just left one at Cisco that was
> three years and it's still being worked on. Building for the web is
> time-consuming there are NO short cuts. An make sure you write tests on
> your code WILL be broken.
>
> ~Carl
>
> On Tue, Sep 8, 2020 at 12:33 PM Ashutosh Mishra <
> ashutoshmishra...@gmail.com> wrote:
>
>> My bad,means using custom code,,not by serializer
>>
>> On Tue 8 Sep, 2020, 21:56 Carl Nobile,  wrote:
>>
>>> If you don't want to write ANY custom code then you probably cannot do
>>> it. I've never written any site without at least some custom code.
>>> At a minimum, you will probably need some custom permission classes that
>>> you would set on the views--this keeps people with different roles out of
>>> stuff they shouldn't be in.
>>> You need to use some sort of token system either OAuth2 (better--more
>>> flexible) or the one built into DRF for communication between the frontend
>>> and backend. This is usually non-trivial.
>>>
>>> Think about what you are asking and you will see it takes work and
>>> customization is always part of it.
>>>
>>> ~Carl
>>>
>>> On Tue, Sep 8, 2020 at 3:21 AM Ashutosh Mishra <
>>> ashutoshmishra...@gmail.com> wrote:
>>>
>>>> i want to create authentication of student,admin and superadmin using
>>>> viewset and routers without serializers(custom code) how can i do this,some
>>>> please guide me
>>>>
>>>> --
>>>> You received this message because you are subscribed to the Google
>>>> Groups "Django REST framework" group.
>>>> To unsubscribe from this group and stop receiving emails from it, send
>>>> an email to django-rest-framework+unsubscr...@googlegroups.com.
>>>> To view this discussion on the web visit
>>>> https://groups.google.com/d/msgid/django-rest-framework/a9c47573-7ae1-4a3e-b1a2-181fb3cee08dn%40googlegroups.com
>>>> <https://groups.google.com/d/msgid/django-rest-framework/a9c47573-7ae1-4a3e-b1a2-181fb3cee08dn%40googlegroups.com?utm_medium=email&utm_source=footer>
>>>> .
>>>>
>>>
>>>
>>> --
>>>
>>> ---
>>> Carl J. Nobile (Software Engineer)
>>> carl.nob...@gmail.com
>>>
>>> ---
>>>
>>> --
>>> You received this message because you are subscribed to a topic in the
>>> Google Groups "Django REST framework" group.
>>> To unsubscribe from this topic, visit
>>> https://groups.google.com/d/topic/django-rest-framework/RAsaI4kquNc/unsubscribe
>>> .
>>> To unsubscribe from this group and all its topics, send an email to
>>> django-rest-framework+unsubscr...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLTFyyvB6LK3OyY1OnTuTvhoe64sLL2eRwoeyTPfuaExg%40mail.gmail.com
>>> <https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLTFyyvB6LK3OyY1OnTuTvhoe64sLL2eRwoeyTPfuaExg%40mail.gmail.com?utm_medium=email&utm_source=footer>
>>> .
>>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django REST framework" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-rest-framework+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-rest-framework/CAGDmY64n%2B7532DaV6mS7fSTB6z1UoSxcubFzZeDRmV%3D2VpCcug%40mail.gmail.com
>> <https://groups.google.com/d/msgid/django-rest-framework/CAGDmY64n%2B7532DaV6mS7fSTB6z1UoSxcubFzZeDRmV%3D2VpCcug%40mail.gmail.com?utm_medium=email&utm_so

Re: Custom user model

2020-09-08 Thread Carl Nobile
The serializers are what I customize the most. You will need to write field
validation methods along with custom create and update methods. If you have
embedded serializer there is no way around this. DRF provides you a
framework, not a finished product.
Depending on the size of the web service you are building any project like
this is between three and ten months. I just left one at Cisco that was
three years and it's still being worked on. Building for the web is
time-consuming there are NO short cuts. An make sure you write tests on
your code WILL be broken.

~Carl

On Tue, Sep 8, 2020 at 12:33 PM Ashutosh Mishra 
wrote:

> My bad,means using custom code,,not by serializer
>
> On Tue 8 Sep, 2020, 21:56 Carl Nobile,  wrote:
>
>> If you don't want to write ANY custom code then you probably cannot do
>> it. I've never written any site without at least some custom code.
>> At a minimum, you will probably need some custom permission classes that
>> you would set on the views--this keeps people with different roles out of
>> stuff they shouldn't be in.
>> You need to use some sort of token system either OAuth2 (better--more
>> flexible) or the one built into DRF for communication between the frontend
>> and backend. This is usually non-trivial.
>>
>> Think about what you are asking and you will see it takes work and
>> customization is always part of it.
>>
>> ~Carl
>>
>> On Tue, Sep 8, 2020 at 3:21 AM Ashutosh Mishra <
>> ashutoshmishra...@gmail.com> wrote:
>>
>>> i want to create authentication of student,admin and superadmin using
>>> viewset and routers without serializers(custom code) how can i do this,some
>>> please guide me
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django REST framework" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-rest-framework+unsubscr...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-rest-framework/a9c47573-7ae1-4a3e-b1a2-181fb3cee08dn%40googlegroups.com
>>> <https://groups.google.com/d/msgid/django-rest-framework/a9c47573-7ae1-4a3e-b1a2-181fb3cee08dn%40googlegroups.com?utm_medium=email&utm_source=footer>
>>> .
>>>
>>
>>
>> --
>>
>> ---
>> Carl J. Nobile (Software Engineer)
>> carl.nob...@gmail.com
>>
>> ---
>>
>> --
>> You received this message because you are subscribed to a topic in the
>> Google Groups "Django REST framework" group.
>> To unsubscribe from this topic, visit
>> https://groups.google.com/d/topic/django-rest-framework/RAsaI4kquNc/unsubscribe
>> .
>> To unsubscribe from this group and all its topics, send an email to
>> django-rest-framework+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLTFyyvB6LK3OyY1OnTuTvhoe64sLL2eRwoeyTPfuaExg%40mail.gmail.com
>> <https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLTFyyvB6LK3OyY1OnTuTvhoe64sLL2eRwoeyTPfuaExg%40mail.gmail.com?utm_medium=email&utm_source=footer>
>> .
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/CAGDmY64n%2B7532DaV6mS7fSTB6z1UoSxcubFzZeDRmV%3D2VpCcug%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-rest-framework/CAGDmY64n%2B7532DaV6mS7fSTB6z1UoSxcubFzZeDRmV%3D2VpCcug%40mail.gmail.com?utm_medium=email&utm_source=footer>
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2B9MBEB3%3DrFhyhtU_usXyfLE%3DWa0u9yoTmCt5fmiG14vQ%40mail.gmail.com.


Re: Custom user model

2020-09-08 Thread Carl Nobile
If you don't want to write ANY custom code then you probably cannot do it.
I've never written any site without at least some custom code.
At a minimum, you will probably need some custom permission classes that
you would set on the views--this keeps people with different roles out of
stuff they shouldn't be in.
You need to use some sort of token system either OAuth2 (better--more
flexible) or the one built into DRF for communication between the frontend
and backend. This is usually non-trivial.

Think about what you are asking and you will see it takes work and
customization is always part of it.

~Carl

On Tue, Sep 8, 2020 at 3:21 AM Ashutosh Mishra 
wrote:

> i want to create authentication of student,admin and superadmin using
> viewset and routers without serializers(custom code) how can i do this,some
> please guide me
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/a9c47573-7ae1-4a3e-b1a2-181fb3cee08dn%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLTFyyvB6LK3OyY1OnTuTvhoe64sLL2eRwoeyTPfuaExg%40mail.gmail.com.


Re: I am facing issues in django with images can any one help me... to sort it out

2020-08-30 Thread Carl Nobile
You need to at least describe the issues you are having. The mimetype you
are using etc.

On Sat, Aug 29, 2020 at 1:00 AM yashwanth balanagu <
balanaguyashwa...@gmail.com> wrote:

> I got it atlast i am storting the images in server side instead of storing
> in cloud storage so i got mistake there that i was solved by using firebase
> and amazon s3 bucket for images
>
> On Friday, August 21, 2020 at 5:25:11 AM UTC+5:30 Ryoma Han wrote:
>
>> show me your code
>>
>> 在2020年8月20日星期四 UTC+8 下午4:46:31 写道:
>>
>>> Hey hi ,
>>> I am facing some issues in django rest api's when sending the images
>>> through ajax javascript. Can you help me ,
>>>
>>> *If anyone intrested i willl connect with them to clarify my doubts in
>>> django rest api's in images *
>>>
>>> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/4c4c74f1-b07c-4230-8341-0722d65e0952n%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2BTGC4m7VVK3pcoOE8JeH6w7n3BBZE2Vs8A6pj-5yOEPg%40mail.gmail.com.


Re: How can i get user login details from auth token is it possible

2020-08-30 Thread Carl Nobile
It depends on the type of token you user JWT (JSON Web Token) are the most
comment types to use when needed additional user details, however, you must
be using OAuth2 to use these. DRF \'s internal token system cannot use JWT
tokens.


On Sat, Aug 29, 2020 at 12:58 AM yashwanth balanagu <
balanaguyashwa...@gmail.com> wrote:

> To show in the user details in home page
>
> On Saturday, August 29, 2020 at 12:58:36 AM UTC+5:30 yezile...@gmail.com
> wrote:
>
>> Why don't you return user info along with the token when logging in or
>> singing up.
>>
>> On Fri, Aug 28, 2020, 22:09 yashwanth balanagu 
>> wrote:
>>
>>> After Registration and login i was created the auth token for login
>>> authentication through api
>>>
>>> user auth token  :- e3b026312e366c5005cc90a36bfb430a2aa2,
>>> generated by backend after login from frontend using django rest login
>>> api's
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django REST framework" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-rest-fram...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-rest-framework/51908865-3a8a-4e68-bc76-1ee6fd6e3a55n%40googlegroups.com
>>> 
>>> .
>>>
>> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/4548e6d6-6573-45b7-8643-1f866def5fcan%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2BQV5ymG%2BVbUZVZRWCMDv_xH42ueT8g1VVVgwQyyFVGDQ%40mail.gmail.com.


Re: Reality Check for (problematic?) DRF Installation Instructions

2020-08-08 Thread Carl Nobile
So the url() function is deprecated you should use re_path() if you need to
use regex.

from django.urls import path, re_path

~Carl


On Sat, Aug 8, 2020 at 12:32 PM Wanderley S  wrote:

> Hi again Daniel.
> You made your point, I don't agree with you though.
> Seems to me that the documentation is fine
> In the "installation" link you were following you have just small pieces
> of code, so don't follow this as a tutorial, if you just want "copy and
> paste" go the the "Tuorial" part from the DRF (Django Rest Framework).
> The "Installation" provides only some examples, but you should not just
> copy and paste from there.
>
> In your code for example you're trying to use the url function without
> importing it, for this code to work properly, you should first import the
> url function.
>
> from django.contrib import admin
> from django.urls import path, include
> from django.conf.urls import url #IMPORT THIS LINE IT WILL WORK.
>
> urlpatterns = [
> path('admin/', admin.site.urls),
> url(r'^api-auth/', include('rest_framework.urls'))   # Per:
> https://www.django-rest-framework.org/#installation:
>  # ...add REST
> framework's login and logout views.
> ]
> as I said, follow the tutorial session and you will find a really working
> project.
>
> That would be advises.
>
> Em sáb., 8 de ago. de 2020 às 02:57, Daniel Cunningham <
> daniel.phillip.cunning...@gmail.com> escreveu:
>
>> Appreciate the response.
>>
>> I was working directly off a brand-new generated Django project, which I
>> had named
>> restservice
>>
>> ...and following the installation instructions on:
>> https://www.django-rest-framework.org/#installation
>>
>> So I (trivially) modified the skeleton to the state (below), and when I
>> ran it, encountered (completely unexpected) exceptions.
>>
>> """
>> restservice URL Configuration
>>
>> The `urlpatterns` list routes URLs to views. For more information please
>> see:
>> https://docs.djangoproject.com/en/3.1/topics/http/urls/
>> Examples:
>> Function views
>> 1. Add an import:  from my_app import views
>> 2. Add a URL to urlpatterns:  path('', views.home, name='home')
>> Class-based views
>> 1. Add an import:  from other_app.views import Home
>> 2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
>> Including another URLconf
>> 1. Import the include() function: from django.urls import include,
>> path
>> 2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
>> """
>>
>>
>> #
>> # Original (default) now disabled per DRF Installation Guide:
>> https://www.django-rest-framework.org/#example
>> # We intend to create a read-write API for accessing information on the
>> users of our project.
>> #
>> from django.contrib import admin
>> from django.urls import path, include
>>
>> urlpatterns = [
>> path('admin/', admin.site.urls),
>> url(r'^api-auth/', include('rest_framework.urls'))   # Per:
>> https://www.django-rest-framework.org/#installation:
>>  # ...add REST
>> framework's login and logout views.
>> ]
>>
>>
>> It hasn't stopped me -- I went on to adopt the Quickstart examples and
>> moved on.  And, by the way, DRF looks *nice*!  As in  *REALLY* nice!
>>
>> But I was thinking it wasn't good for the project to have errors from the
>> very first example.
>>
>> Is there someone responsible for the DRF documentation examples that I
>> should notify of this issue?
>>
>> Best regards,
>>
>> -- Daniel
>>
>>
>> On Friday, August 7, 2020 at 8:44:55 PM UTC-7, Wandss wrote:
>>>
>>> Hi Daniel.
>>>
>>> Since you didn't posted any code, I can only make some assumptions here.
>>> Since Django 2, the url function has been sort of replaced by path
>>> function, so instead writing your urls like:
>>>
>>> urlpatterns = [ url(some_regexp, your_views)]
>>>
>>> You will probably use:
>>>
>>> urlpattern = [path("some-path/", your views]
>>>
>>> Above examples are not actually code. I'm just giving you an idea.
>>> The url function had been moved to another package in Django 2, and I'm
>>> not sure if it even exists in DJango3
>>> https://docs.djangoproject.com/en/2.0/releases/2.0/#whats-new-2-0
>>> https://docs.djangoproject.com/en/3.0/ref/urls/
>>>
>>> I'd suggest taking a look at the Django Documentation as well, since
>>> Django itself had some important changes since version 1.11
>>> About the admin not working, I can only guess that since you're having
>>> issues with your urls mapping, it's probably getting lost and not been able
>>> to reach the admin page.
>>>
>>> Hope I could help.
>>> If not, please post some part of your code, and I might help you better
>>> on this.
>>>
>>> Cheers, and happy coding!
>>>
>>>
>>>
>>>
>>> Em sex., 7 de ago. de 2020 às 23:43, Daniel Cunningham <
>>> daniel.phil...@gmail.com> escreveu:
>>>
 Hi All:

 I need a reality check on a misunderstanding I'm having with the
 installation inst

Re: How to rename field?

2020-07-26 Thread Carl Nobile
You can use the source argument in a serializer field.
https://www.django-rest-framework.org/api-guide/fields/#source

inventory_type_public_id = serializers.CharField(
source='inventory_type.public_id', required=False)

In the above example `inventory_type_public_id` becomes the new field name,
but it's source is `inventory_type.public_id`. Notice that the source name
is a dotted path from the object.

~Carl

On Sat, Jul 25, 2020 at 2:21 PM hec...@yandex.ru  wrote:

> I have a SomeModelSerializer wich have foreign key. How to change name of
> field wich represented this foreign key from `some_object` to
> `some_object_id`?
>
> Thanks!
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/4468f426-3ee1-4f5d-9d51-67ebcb455f90n%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLGGauetco3bWykCULgiseK7JTdURwRazb-LEzmdZ3MHw%40mail.gmail.com.


Re: Unusual default serialization for DateRangeField (django.contrib.postgres.fields.DateRangeField)

2020-07-17 Thread Carl Nobile
Humm, interesting, I never used that functionality.

OK, so then it looks like the to_representation() method in the serializer
may not be converting the type coming from the DB correctly into a JSON
object, so it just gives you the raw data. You may need to override that
method and convert it to JSON yourself.
So the DB field needs to match the serializer field if they don't you can
get garbage. Another thing you can look at is are you using the right field
type in the serializer? As I said it needs to match what is in the model.
You may have to write your own serializer field type.
Some links below.
https://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior
https://www.django-rest-framework.org/api-guide/fields/#a-basic-custom-field

~Carl


On Fri, Jul 17, 2020 at 2:29 PM Eric Theise  wrote:

> Hi Carl,
>
> This is a PostgreSQL range type (
> https://www.postgresql.org/docs/12/rangetypes.html) and the "[)" is its
> standard interval; it means lower bound inclusive and upper bound
> exclusive. Django offers PostgreSQL-specific model fields (
> https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#range-fields)
> and IntegerRangeField and DateRangeField, which prompted this thread, are
> both examples. You'll note Baze's dates also exhibit the "[)".
>
> I'm using django-filters and it knows to display the field correctly, as
> two inputs, but I don't understand why DRF outputs it as a string.
>
> Eric
>
> On Fri, Jul 17, 2020 at 9:34 AM Carl Nobile  wrote:
>
>> So I see one issue, but first, is this supposed to be a JSON object?
>> If so it will not parse correctly. Consider the line below.
>>
>> "{\"bounds\": \"[)\", \"lower\": \"1935\", \"upper\": \"1946\"}"
>>^
>>You have a [) which will never parse correctly,
>> you probably want [], right?
>>
>> Also single quotes (') and double quotes (") have the same meaning in
>> Python. So '{"bounds": "[)", "lower": "1935", "upper": "1946"}'is
>> probably better.
>>
>> ~Carl
>>
>>
>> On Fri, Jul 17, 2020 at 12:32 AM Eric Theise 
>> wrote:
>>
>>> I'm working on an application that uses integers to represent years (the
>>> client assures me months and dates will never be known or used) and am
>>> having this same problem using an IntegerRangeField.
>>>
>>> "years_produced": "{\"bounds\": \"[)\", \"lower\": \"1935\", \"upper\":
>>> \"1946\"}",
>>>
>>> Baze, did you ever get to the bottom of your issues or, Carl, do you
>>> have any insights as to what I'm missing?
>>>
>>> Thanks, Eric
>>>
>>> On Thursday, August 15, 2019 at 10:13:05 AM UTC-7, Carl Nobile wrote:
>>>
>>>> Are you talking about incoming data? If so you should be sending ISO
>>>> aware date-time objects as such: 2019-05-12T16:27:34.503919-04:00
>>>> If you are talking about outgoing data then you should be saving in the
>>>> DB aware UTC date-times as python datetime objects.
>>>> DRF will always do the right thing if you always do the above.
>>>>
>>>> Aware means with the time zone.
>>>> Naive means without the time zone.
>>>>
>>>> Always always always save UTC time, but not all databases let you store
>>>> the time zone.
>>>>
>>>> On Thu, Aug 15, 2019 at 12:35 PM Baze Blackwood 
>>>> wrote:
>>>>
>>>>> It seems that DRF's default behavior is to stringify the object
>>>>> returned by DateRangeField. For example, this is how an entry appears in a
>>>>> "dates" field which uses this field.
>>>>>
>>>>> "dates": "{\"bounds\": \"[)\", \"lower\": \"2019-07-19\", \"upper\":
>>>>> \"2019-09-14\"}",
>>>>> Has anyone else experienced this behavior and/or know how to get it to
>>>>> preserve the object?
>>>>>
>>>>> --
>>>>> You received this message because you are subscribed to the Google
>>>>> Groups "Django REST framework" group.
>>>>> To unsubscribe from this group and stop receiving emails from it, send
>>>>> an email to django-rest-framework+u

Re: Unusual default serialization for DateRangeField (django.contrib.postgres.fields.DateRangeField)

2020-07-17 Thread Carl Nobile
So I see one issue, but first, is this supposed to be a JSON object?
If so it will not parse correctly. Consider the line below.

"{\"bounds\": \"[)\", \"lower\": \"1935\", \"upper\": \"1946\"}"
   ^
   You have a [) which will never parse correctly, you
probably want [], right?

Also single quotes (') and double quotes (") have the same meaning in
Python. So '{"bounds": "[)", "lower": "1935", "upper": "1946"}'is probably
better.

~Carl


On Fri, Jul 17, 2020 at 12:32 AM Eric Theise  wrote:

> I'm working on an application that uses integers to represent years (the
> client assures me months and dates will never be known or used) and am
> having this same problem using an IntegerRangeField.
>
> "years_produced": "{\"bounds\": \"[)\", \"lower\": \"1935\", \"upper\":
> \"1946\"}",
>
> Baze, did you ever get to the bottom of your issues or, Carl, do you have
> any insights as to what I'm missing?
>
> Thanks, Eric
>
> On Thursday, August 15, 2019 at 10:13:05 AM UTC-7, Carl Nobile wrote:
>
>> Are you talking about incoming data? If so you should be sending ISO
>> aware date-time objects as such: 2019-05-12T16:27:34.503919-04:00
>> If you are talking about outgoing data then you should be saving in the
>> DB aware UTC date-times as python datetime objects.
>> DRF will always do the right thing if you always do the above.
>>
>> Aware means with the time zone.
>> Naive means without the time zone.
>>
>> Always always always save UTC time, but not all databases let you store
>> the time zone.
>>
>> On Thu, Aug 15, 2019 at 12:35 PM Baze Blackwood 
>> wrote:
>>
>>> It seems that DRF's default behavior is to stringify the object returned
>>> by DateRangeField. For example, this is how an entry appears in a "dates"
>>> field which uses this field.
>>>
>>> "dates": "{\"bounds\": \"[)\", \"lower\": \"2019-07-19\", \"upper\":
>>> \"2019-09-14\"}",
>>> Has anyone else experienced this behavior and/or know how to get it to
>>> preserve the object?
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django REST framework" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-rest-framework+unsubscr...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-rest-framework/7947ec40-6540-455b-b2d5-85ed176fa7dc%40googlegroups.com
>>> <https://groups.google.com/d/msgid/django-rest-framework/7947ec40-6540-455b-b2d5-85ed176fa7dc%40googlegroups.com?utm_medium=email&utm_source=footer>
>>> .
>>>
>>
>>
>> --
>>
>> ---
>> Carl J. Nobile (Software Engineer)
>> carl@gmail.com
>>
>> ---
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/38085cbf-953c-4c56-82ed-8561ac8f4576o%40googlegroups.com
> <https://groups.google.com/d/msgid/django-rest-framework/38085cbf-953c-4c56-82ed-8561ac8f4576o%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2B_mzbqYfL9Cz4ApmqxaPf7MAuDF8MeWvv2rq-G2Sw0gQ%40mail.gmail.com.


Re: Sharing validation with the admin under DRF 3

2020-07-06 Thread Carl Nobile
What @Brent said is basically correct, however, it will fail if you have
model mixins that change fields. That's because the field will not be
changed until after the full_clean() method is called.
So how to fix this? It's not too difficult. I create a mixin that just does
the full_clean() as in the following:

class ValidateOnSaveMixin:
def save(self, *args, **kwargs):
self.full_clean()
super().save(*args, **kwargs)

In your class you would do this:

class Foo(ValidateOnSaveMixin, models.Model):
from = models.IntegerField()
to = models.IntegerField()
validators = [ordervalidator]

def clean(self):
for validator in self.validators:
validator(self.__dict__)

Always be sure you put the ValidateOnSaveMixin class is just before the
models.Model and all other mixins before ValidateOnSaveMixin. Getting the
MRO correct is important here.

~Carl

On Mon, Jul 6, 2020 at 11:17 AM Brent O'Connor  wrote:

> I think all you need to do is add the following to your model.
>
> class Foo(models.Model):
>   from = models.IntegerField()
>   to = models.IntegerField()
>
>   def clean(self): if self.from > self.to:
>   raise ValidationError("`From` must be before or equal to `to`")
>
>   def save(self, **kwargs):
>   self.full_clean()
>   super().save(**kwargs)
>
>
>
>
> On Thursday, July 2, 2020 at 5:00:59 PM UTC-5, Ben Warren wrote:
>>
>> I have a question about writing reusable validation logic shared between
>> the admin and DRF. If I have this setup:
>>
>> class Foo(models.Model):
>>   from = models.IntegerField()
>>   to = models.IntegerField()
>>   def clean(self): if self.from > self.to:
>> raise ValidationError("`From` must be before or equal to `to`")
>>
>> class FooSerializer(serializers.ModelSerializer):
>>   class Meta:
>> model = Foo
>>
>> Then starting with DRF3 the clean() validation will not be called by the
>> serializer. The docs mention that I could use this mixin:
>>
>> def validate(self, attrs):
>>   model = self.Meta.model
>>   instance = Model(attrs)
>>   instance.clean()
>>
>>
>> but that it is dispreferred, and suggests "you really should look at
>> properly separating the validation logic out of the model method if
>> possible". How would I factor logic like the above so that it could be used
>> in the admin and in DRF? What if the logic gets more complex, like "field B
>> can be populated only if field A is > 7"?
>>
>> Would I do something like this?  The reach into __dict__ feels weird.
>>
>> def ordervalidator(dct):
>>if self.from > self.to:
>>   raise ValidationError # Using Django ValidationError, because the
>> model admin needs it?
>>
>> class Foo(models.Model):
>>   from = models.IntegerField()
>>   to = models.IntegerField()
>>   validators = [ordervalidator]
>>   def clean(self):
>>for validator in self.validators:
>>   validator(self.__dict__)
>>
>> class FooSerializer(serializers.ModelSerializer):
>>   class Meta:
>> model = Foo
>> validators = [ordervalidator]
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/d4d5e79b-6aa5-4afe-8b45-4ada71ef5060o%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2Bib3oqXtfY3QgHQPk%3Dtm-91FU5aXWy0obw_7T6NQxVww%40mail.gmail.com.


Re: Django Rest Framework Validation Order Issue

2020-06-30 Thread Carl Nobile
Brent, overriding the 'to_internal_value' method is normal and encouraged,
however, the 'run_validation' shouldn't generally be overridden, what you
can override is the 'validate' method which is called by 'run_validation'.
~Carl

On Tue, Jun 30, 2020 at 5:51 PM Brent O'Connor  wrote:

> For anyone that might come across this thread, I went ahead and created an
> issue  for
> this on Github.
>
> On Friday, June 26, 2020 at 5:08:03 PM UTC-5, Brent O'Connor wrote:
>>
>> I created an example project
>>  to illustrate this
>> issue, but basically if you have custom validation logic on a serializer
>> and the data has a field that isn't valid, then the errors raised are only
>> the field level errors and not the custom validation logic errors. This
>> ends up being a bad user experience because the user can fix the field
>> error and then when post another request they can end up getting errors
>> thrown in the custom validation. I'm thinking this might need to be an
>> issue added the DRF project on Github, but thought I would check here
>> first. Please see the project example for more details.
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/ea8a9b5d-a671-42b4-9cee-043f28f8efa3o%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQL2UvWyjr6UgK%2BpCDexAc%2BC%2BeBUGxAwZYyaxC3dJYwGsQ%40mail.gmail.com.


Re: Django Rest Framework Validation Order Issue

2020-06-27 Thread Carl Nobile
Then write your custom validation as a field validator and put them all in
the list in the order you want them to fire off in or you could include the
field validator checks into your custom validation method.
The problem is that DRF can only implement what the common cases are, not
all the edge cases people may need, but the hooks are there in the code to
customize it the way you want.


On Sat, Jun 27, 2020 at 4:05 PM Brent O'Connor  wrote:

> Unfortunately, that doesn't really solve the issue because you want
> field-level validation to run because you want to make sure that valid
> numbers, etc. are being sent to the API.
>
> On Sat, Jun 27, 2020 at 12:25 PM Carl Nobile 
> wrote:
>
>> It is possible to turn off the built infield errors. The empty list
>> essentially turns off al field validation. If there are multiple and you
>> don't want all turned off you would need to specify them yourself.
>>
>> Class SomeSeializer(...):
>>
>> class Meta:
>> extra_kwargs = {
>>'field_name': {'validators': []},
>>}
>>
>> On Fri, Jun 26, 2020 at 6:08 PM Brent O'Connor 
>> wrote:
>>
>>> I created an example project
>>> <https://github.com/epicserve/drf-validation-issue> to illustrate this
>>> issue, but basically if you have custom validation logic on a serializer
>>> and the data has a field that isn't valid, then the errors raised are only
>>> the field level errors and not the custom validation logic errors. This
>>> ends up being a bad user experience because the user can fix the field
>>> error and then when post another request they can end up getting errors
>>> thrown in the custom validation. I'm thinking this might need to be an
>>> issue added the DRF project on Github, but thought I would check here
>>> first. Please see the project example for more details.
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django REST framework" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-rest-framework+unsubscr...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-rest-framework/121a7ebe-4b34-4197-be60-1178730361f7o%40googlegroups.com
>>> <https://groups.google.com/d/msgid/django-rest-framework/121a7ebe-4b34-4197-be60-1178730361f7o%40googlegroups.com?utm_medium=email&utm_source=footer>
>>> .
>>>
>>
>>
>> --
>>
>> ---
>> Carl J. Nobile (Software Engineer)
>> carl.nob...@gmail.com
>>
>> ---
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django REST framework" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-rest-framework+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2BOzPQ-Xuad4OboE-%2BgXF_-uAkuxF%2B9XT5jLPiAnFJfog%40mail.gmail.com
>> <https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2BOzPQ-Xuad4OboE-%2BgXF_-uAkuxF%2B9XT5jLPiAnFJfog%40mail.gmail.com?utm_medium=email&utm_source=footer>
>> .
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/CA%2Bx7ZMq7iMmi4PaQ9aBjGaEybKWH0piWumZTOOfR5-wJOBwwZw%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-rest-framework/CA%2Bx7ZMq7iMmi4PaQ9aBjGaEybKWH0piWumZTOOfR5-wJOBwwZw%40mail.gmail.com?utm_medium=email&utm_source=footer>
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLz_RockggWs3GxXkkqoMYQ%3DWL%3DZiZ-TLuta7He2BR5aA%40mail.gmail.com.


Re: Django Rest Framework Validation Order Issue

2020-06-27 Thread Carl Nobile
It is possible to turn off the built infield errors. The empty list
essentially turns off al field validation. If there are multiple and you
don't want all turned off you would need to specify them yourself.

Class SomeSeializer(...):

class Meta:
extra_kwargs = {
   'field_name': {'validators': []},
   }

On Fri, Jun 26, 2020 at 6:08 PM Brent O'Connor  wrote:

> I created an example project
>  to illustrate this
> issue, but basically if you have custom validation logic on a serializer
> and the data has a field that isn't valid, then the errors raised are only
> the field level errors and not the custom validation logic errors. This
> ends up being a bad user experience because the user can fix the field
> error and then when post another request they can end up getting errors
> thrown in the custom validation. I'm thinking this might need to be an
> issue added the DRF project on Github, but thought I would check here
> first. Please see the project example for more details.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/121a7ebe-4b34-4197-be60-1178730361f7o%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2BOzPQ-Xuad4OboE-%2BgXF_-uAkuxF%2B9XT5jLPiAnFJfog%40mail.gmail.com.


Re: Behaviour driven development in Django rest framework.

2020-05-03 Thread Carl Nobile
I realize that this is just my opinion, however, I've been writing code for
over 40 years and Python for over 20.
There is nothing, no process, not a special package that will develop good
code for you, only well-trained engineers that follow best practices.
In Python, this means the coding standard PEP-8.
Also, read read read RFCs they are how things are supposed to work. The
next time I see credentials in the body of a request I will scream or for
that matter versioning done like this /api/v1/, use mimetypes, please.
If you are doing RESTful web services and you have not read Roy Fielding's
dissertation and understood it don't write RESTful web services.
Never give developers with five years or less experience a huge project to
do, it WILL be done poorly guaranteed.
If you must use Agile then the software architect needs to completely
decide upfront how the system will work in detail, or once again it won't
work. If you're not doing this then get out of the business.
Small teams under 8 or 9 don't need Agile just a very good lead.
Too much structure makes for bad engineers. They trust daddy too much and
will never think for themselves.
With too little structure they will surf the web all day and not write a
line of code.
OK, Nuff said.
~Carl

On Sun, May 3, 2020 at 4:09 AM Tom Victor  wrote:

> My current company is planing to switch to behaviour driven development
> also known as BDD. After a long google search I came to the conclusion that
> behave is the semi official python package for BDD in python. I am
> wondering how could we practically use along with drf.
>
> What is the correct ideal way to
>
> 1. Structure our test files.
> 2. Where should we keep the BDD feature, step files?
> 3. Which category would add fall under, unit testing, integration testing
> or acceptance  testing?
>
> Thanks
>
> Ref : https://behave.readthedocs.io/en/latest/
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/a24833b2-823f-4867-86c5-09d3943a4a85%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQK_KKhrpYN26fXkZKRqGqn5RF%2B%3DYhfy22fzSGVgXtGz5w%40mail.gmail.com.


Re: Error: User permissions

2020-05-01 Thread Carl Nobile
1st, you're doing this on a windows box, it will always be harder to
troubleshoot on windows. I'd recommend spinning up a Linux VM and doing
your work in there.
Where is the destination of the pip command? It is probably restricted on
windows.
You should be using a python VE (virtual environment) for your project that
is created in your user dir. You would never get these types of errors if
you used a VE.

Google for "python virtual environment".


On Fri, May 1, 2020 at 12:02 PM Sathri mamatha 
wrote:

>
> -- Forwarded message -
> From: sathri mamatha 
> Date: Fri, 1 May 2020, 9:27 pm
> Subject: Re: Error: User permissions
> To: 
>
>
>
> On Fri, 1 May 2020, 8:46 pm Carl Nobile,  wrote:
>
>> You would get this if you ran the command from a restricted directory.
>> You gave no details, so I cannot really say much more than this.
>> Are you using pip? Show the actual screen dump.
>>
>> On Thu, Apr 30, 2020 at 9:46 PM sathri mamatha <
>> mamathakumar1...@gmail.com> wrote:
>>
>>>   Please  tell me the solution  for this ERROR
>>>
>>> Error: While installing  numpy iam getting this error
>>>  Check --user permissions
>>>
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django REST framework" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-rest-framework+unsubscr...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-rest-framework/CAHRzh5xePj%3DjY4y9Vp0o4yFkLPey6agPL02giw-tjB325_PYZw%40mail.gmail.com
>>> <https://groups.google.com/d/msgid/django-rest-framework/CAHRzh5xePj%3DjY4y9Vp0o4yFkLPey6agPL02giw-tjB325_PYZw%40mail.gmail.com?utm_medium=email&utm_source=footer>
>>> .
>>>
>>
>>
>> --
>>
>> ---
>> Carl J. Nobile (Software Engineer)
>> carl.nob...@gmail.com
>>
>> ---
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django REST framework" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-rest-framework+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2B-iWeJ7A-ELf03SZg43HOuN-aymrD1SV04XGpg-0OyaA%40mail.gmail.com
>> <https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2B-iWeJ7A-ELf03SZg43HOuN-aymrD1SV04XGpg-0OyaA%40mail.gmail.com?utm_medium=email&utm_source=footer>
>> .
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/CAHRzh5whqJ7k3VfPgzsdWkLh6BSgv0iUbC1Q-SOX6fzNDnuqBQ%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-rest-framework/CAHRzh5whqJ7k3VfPgzsdWkLh6BSgv0iUbC1Q-SOX6fzNDnuqBQ%40mail.gmail.com?utm_medium=email&utm_source=footer>
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQKGPMkPnw23HtPp%3Du4oRUc2ZbDj7JqnKQx1Q3W%3D-C%2BvnA%40mail.gmail.com.


Re: Error: User permissions

2020-05-01 Thread Carl Nobile
You would get this if you ran the command from a restricted directory.
You gave no details, so I cannot really say much more than this.
Are you using pip? Show the actual screen dump.

On Thu, Apr 30, 2020 at 9:46 PM sathri mamatha 
wrote:

>   Please  tell me the solution  for this ERROR
>
> Error: While installing  numpy iam getting this error
>  Check --user permissions
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/CAHRzh5xePj%3DjY4y9Vp0o4yFkLPey6agPL02giw-tjB325_PYZw%40mail.gmail.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2B-iWeJ7A-ELf03SZg43HOuN-aymrD1SV04XGpg-0OyaA%40mail.gmail.com.


Re: serializer save returns ​ DoesNotExis, MultipleObjectsReturned

2020-04-29 Thread Carl Nobile
It looks like you are, for some reason, returning a dump of the objects on
the model, not the data. Something is messed up in your code. You might
want to post the sterilizer *create* and *update* methods you created.

On Wed, Apr 29, 2020 at 11:50 AM Nazish Akhtar 
wrote:

> While saving serializer I am getting *DoesNotExist* ,
> *MultipleObjectsReturned* . However objects are being saved in DB but
> signals such as post_save does not work. Custom Signal also does not work.
>
> Here is detailed error:
>
> 1
> ['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__',
> '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
> '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__',
> '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
> '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__',
> '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
> '_check_column_name_clashes', '_check_constraints',
> '_check_field_name_clashes', '_check_fields', '_check_id_field',
> '_check_index_together', '_check_indexes', '_check_local_fields',
> '_check_long_column_names', '_check_m2m_through_same_relationship',
> '_check_managers', '_check_model', '_check_model_name_db_lookup_clashes',
> '_check_ordering', '_check_property_name_related_field_accessor_clashes',
> '_check_single_primary_key', '_check_swappable', '_check_unique_together',
> '_do_insert', '_do_update', '_get_FIELD_display',
> '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order',
> '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks',
> '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val',
> '_state', 'car_category', 'car_id', 'car_model', 'car_owner',
> 'car_owner_id', 'car_registration_no', 'carimageverification',
> 'carverification', 'chassis_number', 'check', 'clean', 'clean_fields',
> 'color', 'date_error_message', 'delete', 'engine_number', 'from_db',
> 'fuel_type', 'full_clean', 'get_car_category_display',
> 'get_deferred_fields', 'get_fuel_type_display', 'get_manufacturer_display',
> 'get_owner_serial_number_display', 'get_ownership_type_display', 'km_ran',
> 'manufacturer', 'objects', 'owner_serial_number', 'ownership_type', 'pk',
> 'prepare_database_save', 'rc_back_image', 'rc_front_image',
> 'refresh_from_db', 'save', 'save_base', 'serializable_value',
> 'unique_error_message', 'validate_unique', 'verified']
> 1
> ['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__',
> '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
> '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__',
> '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
> '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__',
> '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
> '_check_column_name_clashes', '_check_constraints',
> '_check_field_name_clashes', '_check_fields', '_check_id_field',
> '_check_index_together', '_check_indexes', '_check_local_fields',
> '_check_long_column_names', '_check_m2m_through_same_relationship',
> '_check_managers', '_check_model', '_check_model_name_db_lookup_clashes',
> '_check_ordering', '_check_property_name_related_field_accessor_clashes',
> '_check_single_primary_key', '_check_swappable', '_check_unique_together',
> '_do_insert', '_do_update', '_get_FIELD_display',
> '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order',
> '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks',
> '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val',
> '_state', 'car_category', 'car_id', 'car_model', 'car_owner',
> 'car_owner_id', 'car_registration_no', 'carimageverification',
> 'carverification', 'chassis_number', 'check', 'clean', 'clean_fields',
> 'color', 'date_error_message', 'delete', 'engine_number', 'from_db',
> 'fuel_type', 'full_clean', 'get_car_category_display',
> 'get_deferred_fields', 'get_fuel_type_display', 'get_manufacturer_display',
> 'get_owner_serial_number_display', 'get_ownership_type_display', 'km_ran',
> 'manufacturer', 'objects', 'owner_serial_number', 'ownership_type', 'pk',
> 'prepare_database_save', 'rc_back_image', 'rc_front_image',
> 'refresh_from_db', 'save', 'save_base', 'serializable_value',
> 'unique_error_message', 'validate_unique', 'verified']
>
> Here is the code and error , better formatted.
> Any help would be appreciated
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/b143e59c-6b1f-43ed-b3ad-473392cbd609%40googlegroups.com
> 

Re: Is it possible to send HTTP DELETE or PATCH from DRF web page with a web browser ?

2020-04-22 Thread Carl Nobile
You asked a very basic question and the answer, in all cases, is yes. You
need to RTM (https://www.django-rest-framework.org/), it's all in there.


On Wed, Apr 22, 2020 at 10:44 AM Linovia  wrote:

> Hi,
>
> If you are referring to the browsable API, you should see a DELETE request.
> If you are unsure, check the django server logs, you’ll see a DELETE.
> The delete button is wrapped in the following form:
>
> 
> Delete
> 
>
> However browsers may not correctly show operations other than GET or POST.
>
> Regards,
> Xavier O.
> Linovia.
> Le 22 avr. 2020 à 15:41 +0200, Olivier Krief , a
> écrit :
>
> Hello,
>
> I'm discovering DRF.
>
> Is it possible to send HTTP DELETE or PATCH from DRF web page ?
>
>
>
>
>
> When I type http://foo/api/friends/3/ in my browser, I'm seeing content
> describing Friend 2 or Friend 3 instance.
>
> When I type curl -X DELETE http://foo/api/friends/2/ a DELETE request is
> sent to my Django app and everything works OK as Friend 2 is removed from
> database.
>
> When looking at Friend 3 instance, I can see a DELETE and a Delete buttons.
> When I click over DELETE then Delete buttons, a GET request is sent over
> to my Django instance.
> I would expect a DELETE request to be sent.
>
> I tried this with both Firefox 68 ESR and Chromium 57 and with both a GET
> request is sent instead of a DELETE one.
> I also tried with PATCH button: a GET request is also sent.
>
> Looking at this HTTP request capture, I do not see any evidence reflecting
> a DELETE or PATCH intent.
> Looking at page HTML source code, I can see that buttons are mapped to GET
> request with an intriguing "data-method" set to DELETE or PATCH.
>
>
> 1. Is it possible to have these browsers sending expected DELETE or PATCH
> requests ?
> Is it something that can be configured by Django ? Within browsers
> themselves ?
>
> 2. Is it possible to have these browsers still sending GET request but
> have my Django app mapping these requests to the DELETE/PATCH/whatever
> methods these requests are supposed to be mapped to ?
>
>
> Best regards
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/85f74627-1f5c-403d-845b-fcc87fea5202%40googlegroups.com
> 
> .
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/5fb29489-e0ab-4479-9a4d-21726ee5f380%40Spark
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLZaJVFMmJB-zRywLAPiS%3D%2B2mp0SWxbLguDTyXWUyS-cw%40mail.gmail.com.


Re: HTTPS resource links in DRF

2020-02-01 Thread Carl Nobile
Usually the schema in your links will reflect the schema used on the site.
It looks like your running locally in a development environment, when you
go to a production site the schema should change, assuming you use TSL in
production.
You may be able to force it while developing, but I see no reason to do
that. You can check if what I say is correct by building an Apache config
file which uses TCL and running your site through that locally.

~Carl

On Sat, Feb 1, 2020 at 9:19 AM Muzammil Hussain <
muzammil.hussain.s...@gmail.com> wrote:

> I would like to get https links for resources instead of the current http
> links.
>
> Example currently I get something like this:
> http://10.16.18.46:9000/media/tds_data/2020/2/1/6328/cat.12233.jpg
>
> what should I change in the get request in views.py
>
> def get(self, request, format=None):
> files = Files.objects.all()
> serializer = FilesSerializer(files, many=True)
> print(serializer.data)
> return Response(serializer.data)
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/616452dd-275e-48db-99d7-10f02832026c%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQJsse7pxM1agY%2B9C1iC6my%2Bwyged%3DDZHJ6MiP_dib0tQA%40mail.gmail.com.


Re: setting the default authentication to IsAuthenticated in settings.py globally

2020-01-08 Thread Carl Nobile
You may be misunderstanding what the IsAuthenticated really does. All users
that have an account in the Django application have this set to True
weather or not they are logged in. So it doesn't indicate that a person is
actually logged in or not. You will need to use other means to ensure that
only a logged-in user has access.
I personally write many permission classes for all sorts of different
authorization roles in my code. I can point you to my GitHub account where
I do this myself.
Beware you will need a way to authorize and authenticate users. So if you
are building a front end that is part of the Django app you can use
sessions. I would not recommend this if your API will be hit from other
third-party clients, in this case, you will need to set up a token system
of some sort. DRF has a very simple token system, but the best bet is to
use OAuth.

Good luck.

On Wed, Jan 8, 2020 at 5:16 PM Philip Mutua  wrote:

> Hi Everyone,
>
>
> I have set the default authentication class to I*sAuthenticated  *globally
> in settings.py file but still*, *I can still access the endpoints. what
> could be the issue? Below are the Django rest frameworks' configs in
> settings.py file.
>
>
>
> REST_FRAMEWORK = {
> 'DEFAULT_PERMISSION_CLASSESS': [
> 'rest_framework.permissions.IsAuthenticated',
> ],
> 'DEFAULT_AUTHENTICATION_CLASSES': (
> 'liquor.authentication.JSONWebTokenAuthentication',
> ),
>
> 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
> 'DEFAULT_PARSER_CLASSES': [
> 'rest_framework.parsers.FormParser',
> 'rest_framework.parsers.MultiPartParser',
> 'rest_framework.parsers.JSONParser',
> ],
> 'DEFAULT_FILTER_BACKENDS': ['
> django_filters.rest_framework.DjangoFilterBackend'],
> 'DEFAULT_PAGINATION_CLASS': '
> rest_framework.pagination.PageNumberPagination',
> 'PAGE_SIZE':100,
> 'DEFAULT_RENDERER_CLASSESS': (
> 'rest_framework.renderers.JSONRenderer',
> 'rest_framework.renderers.BrowsableAPIRenderer',
> ),
>
> }
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/1ee51459-363e-4b8a-95ed-cca62e823fca%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQJMRvYDH0tC3LRvEK2vRNPYLxrF%2BdRBhJTTc%2BOGAZtUPA%40mail.gmail.com.


Re: Upload image on json

2020-01-05 Thread Carl Nobile
As a side note never put credentials in the body of a JSON request, this is
considered to be a security risk as anything in the body can be logged. Use
one of the methods that are described here
https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication.
Basic authentication is the most common and you should always use TLS
(SSL) encryption.

~Carl

On Sun, Jan 5, 2020 at 4:10 AM Yery cs  wrote:

> Thank you.
> This answer is very helpful.
> Regards!
>
> On Sun, Jan 5, 2020 at 5:08 PM Elico  wrote:
>
>> Try here
>> https://base64.guru/developers/javascript/examples/convert-image
>>
>>
>>
>> On Sun, Jan 5, 2020, 09:35 Yery cs  wrote:
>>
>>> Yes. ReactJS
>>>
>>> On Sun, Jan 5, 2020 at 4:34 PM Elico  wrote:
>>>
 Which client code you are using? Javascript?

 On Sun, Jan 5, 2020, 07:26 Yery cs  wrote:

> How can I get image base 64 code?
>
>
>
> On Sun, Jan 5, 2020 at 10:45 AM Elico  wrote:
>
>> Hi,
>>
>> You can upload a BASE64 encoded image, for example:
>>
>> {
>> ...
>> "userprofile": {
>> "gender": "F",
>> "phone_number": "3315854644",
>> "photo":
>> "data:image/png;base64,iVBORw0KGgoNSUhEUgAAArwAAADICAYKljK9AAARbUlEQVR4Xu3dMayt2RQH8DWFSAgzzBAdMhIhIwShHEpCUKgodCphEtGilghKFYVGg9AoBFFIhGQkiGIKEjEhiGmYiYKs5Nt8Oe57787Juu+us77fSW7ufffds89av7Vn8r/7feecB8KNAAECBAgQIECAwGCBBwb3pjUCBAgQIECAAAECIfDaBAQIECBAgAABAqMFBN7R49UcAQIECBAgQICAwGsPECBAgAABAgQIjBYQeEePV3MECBAgQIAAAQICrz1AgAABAgQIECAwWkDgHT1ezREgQIAAAQIECAi89gABAgQIECBAgMBoAYF39Hg1R4AAAQIECBAgIPDaAwQIECBAgAABAqMFBN7R49UcAQIECBAgQICAwGsPECBAgAABAgQIjBYQeEePV3MECBAgQIAAAQICrz1AgAABAgQIECAwWkDgHT1ezREgQIAAAQIECAi89gABAgQIECBAgMBoAYF39Hg1R4AAAQIECBAgIPDaAwQIECBAgAABAqMFBN7R49UcAQIECBAgQICAwGsPECBAgAABAgQIjBYQeEePV3MECBAgQIAAAQICrz1AgAABAgQIECAwWkDgHT1ezREgQIAAAQIECAi89gABAgQIECBAgMBoAYF39Hg1R4AAAQIECBAgIPDaAwQIECBAgAABAqMFBN7R49UcAQIECBAgQICAwGsPECBAgAABAgQIjBYQeEePV3MECBAgQIAAAQICrz1AgAABAgQIECAwWkDgHT1ezREgQIAAAQIECAi89gABAgQIECBAgMBoAYF39Hg1R4AAAQIECBAgIPDaAwQIECBAgAABAqMFBN7R49UcAQIECBAgQICAwGsPECBAgAABAgQIjBYQeEePV3MECBAgQIAAAQICrz1AgAABAgQIECAwWkDgHT1ezREgQIAAAQIECAi89gABAgQIECBAgMBoAYF39Hg1R4AAAQIECBAgIPDaAwQIECBAgAABAqMFBN7R49UcAQIECBAgQICAwGsPECBAgAABAgQIjBYQeEePV3MECBAgQIAAAQICrz1AgAABAgQIECAwWkDgHT1ezREgQIAAAQIECAi89gABAgQIECBAgMBoAYF39Hg1R4AAAQIECBAgIPDaAwQIECBAgAABAqMFBN7R49UcAQIECBAgQICAwGsPECBAgAABAgQIjBYQeEePV3MECBAgQIAAAQICrz1AgAABAgQIECAwWkDgHT1ezREgQIAAAQIECAi89gABAgQIECBAgMBoAYF39Hg1R4AAAQIECBAgIPDaAwQIECBAgAABAqMFBN7R49UcAQIECBAgQICAwGsPECBAgAABAgQIjBYQeEePV3MECBAgQIAAAQICrz1AgAABAgQIECAwWkDgHT1ezREgQIAAAQIECAi89gABAgQIECBAgMBoAYF39Hg1R4AAAQIECBAgIPDaAwQIECBAgAABAqMFBN7R49UcAQIECBAgQICAwGsPECBAgAABAgQIjBYQeEePV3MECBAgQIAAAQICrz1AgAABAgQIECAwWkDgHT1ezREgQIAAAQIECAi89gABAgQIECBAgMBoAYF39Hg1R4AAAQIECBAgIPDaAwQIECBAgAABAqMFBN7R49UcAQIECBAgQICAwGsPECBAgAABAgQIjBYQeEePV3MECBAgQIAAAQICrz1AgAABAgQIECAwWkDgHT1ezREgQIAAAQIECAi89gABAgQIECBAgMBoAYF39Hg1R4AAAQIECBAgIPDaAwQIECBAgAABAqMFBN7R49UcAQIECBAgQICAwGsPECBAgAABAgQIjBYQeEePV3MECBAgQIAAAQICrz1AgAABAgQIECAwWkDgHT1ezREgQIAAAQIECAi89gABAgQIECBAgMBoAYF39Hg1R4AAAQIECBAgIPDaAwQIECBAgAABAqMFBN7R49UcAQIECBAgQICAwGsPECBA4GYEHoqI/Hh1RLxm+1jf+/v2kPn5d9vHLyNiff9mKrIqAQIEDiog8B508NomUCSQQS5D3IPb5/w6v5e3/Hp9Xt/bP+z+e/mzGfbuFPjy+2u9/c/8NSIePull/7jr8dd91t/t68uvn9zVug+jd2NaNf0xIl60q2/1dVXPd1vvTxHx9BZ+s54fRcSPi+ZkGQIECBxaQOA99Pg1T+D/BN6yhdf8vMLrOpXMH14nlf/YQt79JHxmF4pXQH4qIh7ZijgNxacBef/nffA9t4f1eL+NiFdtXissrwCdf86vV5jP09z9LwFZx7siIr0fi4hHrygmg++3I+LrToDPHZX7ESBwdAGB9+g7QP9HFMiQ9eYtvGbQyo8VZK/r8VxEPLv9cIa4/ens+mf6tdbp36/vX3WSugLhdeuY9nMrAK8Q/PhJgxl8v7yd/k7rXT8ECBC4MQGB98ZoLUygRGCduO5PWfehMP8bXmFznTiu08+8dnSF2fzeCrfXLWxdU5onlOs60/VY6wTzumv5ufMEcm4f3D4+sFsig+8T21zOW9m9CBAgcCABgfdAw9bqRQjkSWsGmzzhy4+Kf3q/V+N5negKtPnP5+vre93P399fgdwbn4qIT+4e9nMR8fn7W4ZHI0CAwOUJCLyXNzMVzxTIcPuFiHj7DbSX176uU9r9NaXrezfwkJa8QYEMvl+LiHW5Q84xQ2+e+roRIECAwBUCAq9tQaCHwN8i4mVnlpKBdl0nu05nfxYRv7nHKx+c+XDu1kTgYxHxpe1JhllSXtubJ8BuBAgQIHAiIPDaEgRuXyBPd394RRl5qcH+EoPTJ4Z5zdbbn91tV5CnvRl699f3vj8ivnfbhXl8AgQIdBIQeDtNQy1HFXhjRPx6az5PaNc/Twu0R90Rz7/v01+avhERH33+y7gHAQIEZgoIvDPnqqvLE/hzRLxiK/vdXnbq8gbYpOJ8Ettnt1p+ERGftpeaTEYZBAjcqoDAe6v8HpzAfwX2p7z5zXzyWgYWNwLPV+B9EfHd3Z3yXwwyCLsRIEDgsAIC72FHr/GGAh+OiG/u6spXbfhMwzqVdBkCX9xeqzerFXovY2aqJEDghgQE3huCtSyBMwVOQ28+ae0rEfGtM9dzt2ML5C9Quafy9vGI+OqxOXRPgMBRBQTeo05e350F3ra9zupjuyIz+OarNnw/In7auXi1tRPYh17/z283HgURIHA/BPzP734oewwC5wl8IiI+EhHvPLn7UxHxq4jIt/79SUT84Lzl3etAAv/eevXqDQcaulYJEPifgMBrNxDoL5BPQnpPRLw+Ih6NiHzt1XXLN6x4+fYuWxmAPTmp/zxvo8L9pTJPbK/dext1eEwCBAjcioDAeyvsHpTA2QIvjYi3RkS+qkOGmHz91dPbuvwhT37zNPjpsx/NHScJ5Jub5C9L+QS2fGtiNwIECBxGQOA9zKg1OljgvRHxhojIk+CrAnC+RNWz2+ux5tsN5y1DsRsBAgQIEDiEgMB7iDFr8mACGXrzI0+C37T1vr8MYnH8PCL+EBFPbh+/j4h8d7d8tzc3AgQIECAwRkDgHTNKjRC4o8BLIuLhiHhlRORp8OPbu7q9MCJed8W9MvRmCF6fMwDnR14j7O2ObTQCBAgQuDgBgffiRqZgAqUCefL7lu3azvV1BuK73VYAXpdFrHCcJ8ROh0vHYzECBAgQqBAQeCsUrUFgnkCG3/zISyMe2kJxBuMHr9HqCsT7E+L8OgNxhmM3AgQIECBwXwUE3vvK7cEIjBBYT4zbnwyvUHydQPyX7drhDMbrdDi/FohHbA9

Re: While running unit tests the wrong parser is being used.

2019-12-11 Thread Carl Nobile
Actually I found the problem it wasn't related to the *Content-type* or the
*Accept* headers. BTW--the *format='json'* argument generates the
*Content-Type* header.
The problem had to do with the fact that I rewrote the *ContentNegotiation*
class and there was a bug in it.

Thanks for your comment, however.
~Carl

On Tue, Dec 10, 2019 at 2:06 AM José Manuel Valdivia Romero <
josevaldiviarom...@gmail.com> wrote:

> Hi Carl,
>
> I think you are using the wrong header in your request, try to use:
> "Content-Type": "application/json"
>
> Best Regards,
>
> José Valdivia
>
> Carl Nobile  schrieb am Sa., 30. Nov. 2019, 19:15:
>
>> I'm trying to run my unit tests using JSON however I'm getting this error:
>>
>> {'detail': ErrorDetail(string='XML parse error - not well-formed
>> (invalid token): line 1, column 0', code='parse_error')}
>>
>> My settings are:
>>
>> REST_FRAMEWORK = {
>> ...
>>
>> 'DEFAULT_PARSER_CLASSES': (
>> 'rest_framework.parsers.JSONParser',
>> 'rest_framework_xml.parsers.XMLParser',
>> #'rest_framework_yaml.parsers.YAMLParser',
>> ),
>> 'DEFAULT_RENDERER_CLASSES': (
>> 'rest_framework.renderers.JSONRenderer',
>> 'rest_framework.renderers.BrowsableAPIRenderer',
>> 'rest_framework_xml.renderers.XMLRenderer',
>> #'rest_framework_yaml.renderers.YAMLRenderer',
>> ),
>> 'TEST_REQUEST_DEFAULT_FORMAT': 'json',
>> 'TEST_REQUEST_RENDERER_CLASSES': (
>> 'rest_framework.renderers.JSONRenderer',
>> 'rest_framework.renderers.MultiPartRenderer',
>> 'rest_framework.renderers.TemplateHTMLRenderer',
>> ),
>> }
>>
>> The general way I send a request is as below:
>>
>> response = client.post(uri, data=data, format='json', **{'HTTP_ACCEPT':
>> 'application/json'})
>>
>>
>> With the setup above I get the error message that I show above. For some
>> reason the after setting things to work with the JSON parser the XML parser
>> is being used.
>> Any ideas?
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django REST framework" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-rest-framework+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-rest-framework/c88e6aed-266f-4298-9323-6761309462cf%40googlegroups.com
>> <https://groups.google.com/d/msgid/django-rest-framework/c88e6aed-266f-4298-9323-6761309462cf%40googlegroups.com?utm_medium=email&utm_source=footer>
>> .
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/CABSqBgHEnqqz1vpWN01fFZD%3DgRYFQa5kii_QZrpsovUDYzS%3DKw%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-rest-framework/CABSqBgHEnqqz1vpWN01fFZD%3DgRYFQa5kii_QZrpsovUDYzS%3DKw%40mail.gmail.com?utm_medium=email&utm_source=footer>
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQK2vFFuZ2vrEDE2bXMT2Oc6_kRuT0zqrPYq5NoiUZ9vvQ%40mail.gmail.com.


Re: get_serializer_class don't work in GenericViewSet

2019-11-30 Thread Carl Nobile
It seems that you have both the

serializer_class

member object and the 

get_serializer_class

method set. Remove the 

serializer_class.


On Thursday, November 21, 2019 at 8:21:44 PM UTC-5, Cristian Benavides 
Jimenez wrote:
>
> Hi everybody,
>
> I try use a two serializers in one view inherits from *GenericViewSet* 
> with the method *get_serializer_class*
>
> Here a little piece of my code:
>
> class RandomViewSet(ListModelMixin, GenericViewSet):
> permission_classes = (IsAuthenticated, )
> filter_backends = [filters.SearchFilter, filters.OrderingFilter, ]
> search_fields = ['some_field', 'some_field', 'some_field', ]
> ordering_fields = ['pk', ]
> ordering = ['pk', ]
> lookup_field = 'pk'
> serializer_class = OneSerializer
> serializers = {
> 'list': OneSerializer,
> 'create': TwoSerializer,
> }
>
> def get_serializer_class(self, *args, **kwargs):
> print('THIS METHOD DON\'T WORK')
> return self.serializers.get(self.action)
>
>
> def create(self, request, *args, **kwargs):
>
> print('Data is not validated :(')
>
>
>
>
> Any help for this?
>
> Greetings,
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/de6e0e13-4830-4195-8fc8-7a1183fbbed2%40googlegroups.com.


Re: is_authenticated returns false in DRF, true outside DRF

2019-11-30 Thread Carl Nobile
The request.user.is_authenticated() is always true unless the requester is 
the Annonymous user.
Are you sure you logged in and that you are the requester before looking at 
that value?


On Thursday, November 28, 2019 at 8:26:29 AM UTC-5, Eric Gustavsson wrote:
>
> Hey,
>
> I've setup mozilla-django-oidc, but I'm struggling to get 
> `request.user.is_authenticated` to be true within DRF. I added a router 
> endpoint to the browseable API:
> return Response({"authenticated": request.user.is_authenticated()})
>
> As well as a response outside DRF:
> return HttpResponse(request.user.is_authenticated())
>
> After authentication. DRF returns false, outside DRF returns true. 
> mozilla-django-oidc even has a class extending DRF BasicAuthentication
>
> https://github.com/mozilla/mozilla-django-oidc/blob/master/mozilla_django_oidc/contrib/drf.py
>
> Which I added to the DRF settings:
> REST_FRAMEWORK = {
> # ...
> 'DEFAULT_AUTHENTICATION_CLASSES': [
> 'mozilla_django_oidc.contrib.drf.OIDCAuthentication',
> ]
> }
>
> This is all using 
> Django 1.11.15, but I've tested with 2.2 as well.
> djangorestframework==3.10.3
>
> What am I missing to get a user seen as authenticated within DRF?
>
> Thanks,
> Eric
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/f49aa3b1-f9b8-4a04-bf45-9657944dca74%40googlegroups.com.


While running unit tests the wrong parser is being used.

2019-11-30 Thread Carl Nobile
I'm trying to run my unit tests using JSON however I'm getting this error:

{'detail': ErrorDetail(string='XML parse error - not well-formed (invalid 
token): line 1, column 0', code='parse_error')}

My settings are:

REST_FRAMEWORK = {
...

'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
'rest_framework_xml.parsers.XMLParser',
#'rest_framework_yaml.parsers.YAMLParser',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
'rest_framework_xml.renderers.XMLRenderer',
#'rest_framework_yaml.renderers.YAMLRenderer',
),
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
'TEST_REQUEST_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.MultiPartRenderer',
'rest_framework.renderers.TemplateHTMLRenderer',
),
}

The general way I send a request is as below:

response = client.post(uri, data=data, format='json', **{'HTTP_ACCEPT': 
'application/json'})


With the setup above I get the error message that I show above. For some 
reason the after setting things to work with the JSON parser the XML parser 
is being used.
Any ideas?

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/c88e6aed-266f-4298-9323-6761309462cf%40googlegroups.com.


Re: Django is getting ASYNC, what about DRF ?

2019-11-22 Thread Carl Nobile
I do async all the time with DRF, sometimes I have DB connection issues,
but for the most part it all works fine.


On Fri, Nov 22, 2019 at 8:12 AM Xavier Ordoquy  wrote:

> What about it ?
> I don’t think DRF we use anything that is async incompatible outside
> Django itself.
>
> Regards,
> Xavier O.
> Linovia.
>
> Le 22 nov. 2019 à 14:10, Dennis  a écrit :
>
> As per Andrew Godwin presentation at DjangoCon2019 the plan is:
> - 3.0 --> ASGI server, ASGIHandler
> - 3.1 --> Async Views
> - 3.2/4.0 --> Async ORM
>
> What about DRF ?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/774dbd4d-b368-4dd5-87b6-d660f137fa3d%40googlegroups.com
> 
> .
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/375CA8DD-6326-42D3-8D8D-BF043C165D0C%40linovia.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2Bdxh5ydYsJ%3DaDBXyibkjbs251nwxJJ4-s4LYjUDoxupQ%40mail.gmail.com.


Re: Is possible to create Django Rest API without admin module ?

2019-11-02 Thread Carl Nobile
Sajan, It's best to just follow the documentation on the DRF site
https://www.django-rest-framework.org/.
The Django admin is very easy to set up and sometimes is a necessity. Just
look at the Django docs.

On Sat, Nov 2, 2019 at 12:58 PM Sajan s  wrote:

> any sample url?
>
> On Saturday, November 2, 2019 at 12:10:30 PM UTC-4, Vetti Ebinyjar wrote:
>>
>> Use CLASS BASED APIVIEW
>> Refer django rest framework APIVIEW
>> USE POST METHOD
>>
>> On Sat, Nov 2, 2019, 9:29 PM Sajan s  wrote:
>>
>>> I want create Web API like below.
>>>
>>> 1) receive  JSON request
>>> 2) internal process and insert into postgresql
>>> 3) return JSON response
>>>
>>> Can you pls share any Url which I can refer
>>>
>>> On Saturday, November 2, 2019 at 5:50:48 AM UTC-4, Anil Yadav wrote:

 what type of service you want to create

 On Sat, Nov 2, 2019 at 3:20 PM Anil Yadav  wrote:

> yes it possible
>
> On Sat, Nov 2, 2019 at 8:59 AM Sajan s  wrote:
>
>> Hey All,
>>
>> I am new to python and trying to create rest api using
>> "django-rest-framework".
>>
>> simple API ,
>>
>>- no Auth
>>- receive request
>>- get data from mysql
>>- internal process
>>- return JSON response.
>>
>> Any one help me out?
>>
>> --
>> You received this message because you are subscribed to the Google
>> Groups "Django REST framework" group.
>> To unsubscribe from this group and stop receiving emails from it,
>> send an email to django-rest-framework+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-rest-framework/8cd01caf-16c2-4684-ae4b-ffa8a5ef2160%40googlegroups.com
>> 
>> .
>>
> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django REST framework" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-rest-framework+unsubscr...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-rest-framework/f619d056-7cd3-44c4-8112-5c7cf083631e%40googlegroups.com
>>> 
>>> .
>>>
>> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/b2bca113-3e5f-4680-9f3b-07b528b5a1b0%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2B_ot6MpVeQZC78bC1LMvzhKa1SEo3J0czgKAHB5_P7Cw%40mail.gmail.com.


Re: Delete method

2019-09-25 Thread Carl Nobile
Kęstutis, there are three ways to do this, in order of preference below.

   1.  Use a different generic view make *RetrieveUpdateAPIView.*
   2. Set, at the class level in your view this class member object:
http_method_names
   = ['get', 'head', 'options',]. This will give you only the methods you
   defined.
   3. This one is clunky but generally works. Set at the class level the
   method you don't want to None.

Hope one of these works for you. Try number 1 one first.
~Carl

On Wed, Sep 25, 2019 at 8:44 AM Jakob Damgaard Møller 
wrote:

> What are we talking about?
>
> On Wed, Sep 25, 2019 at 12:34 PM Kęstutis Ramulionis <
> kestutis.ramulio...@gmail.com> wrote:
>
>> Hello, i would like to ask how to remove delete method confirmation pop up
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django REST framework" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-rest-framework+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-rest-framework/ae2d6bd1-0414-4638-b0a0-bb984db45601%40googlegroups.com
>> 
>> .
>>
>
>
> --
> Jakob Damgaard Olsen
> Tlf: 24613112
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/CAMmJSsEwALHX%3D1j8%3DMsDPmzd0fO3bS7GYF%3DzZL2hkyRBQYeWCg%40mail.gmail.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLL%3DjDACubaGh%3D9DoTb652jiPDfJ%2BgwrVMbyoEzRUc3Ug%40mail.gmail.com.


Re: Unsupported Media Type

2019-09-20 Thread Carl Nobile
You must set media type for all your endpoints or they will default to DRF
mime types.


On Fri, Sep 20, 2019 at 11:08 AM göktürk sığırtmaç 
wrote:

> While i'm overriding post method from generics.ListCreateAPIView i have
> error unsupported media type but i don't send media.
>
> Serializer file:
>
>
> class Users(serializers.Serializer):
> username = serializers.CharField(max_length=50)
> first_name = serializers.CharField(max_length=30)
> last_name = serializers.CharField(max_length=150)
> email = serializers.EmailField()
> is_staff = serializers.BooleanField()
> is_active = serializers.BooleanField()
>
>
> Post method:
>
>
> def post(self, request):
> serializer = serializers.Users(data=request.data)
>
> if serializer.valid:
> print("serializer.valid")
> return Response(serializer.data, status=status.HTTP_200_OK)
> else:
> print("ELSE -- serializer.valid")
> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
>
>
> Postman:
>
> [image: Ekran Resmi 2019-09-20 18.03.35.png]
>
> [image: Ekran Resmi 2019-09-20 18.02.22.png]
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/02a78ea9-4349-4f2c-819f-981894bad11a%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2BeaQuhjuJZqr_UxmEnH09R3wjLkXV7N_n9-UVAqyhWnw%40mail.gmail.com.


Re: Redirect

2019-09-12 Thread Carl Nobile
Gonzalo,

Yes, it's on the DRF site. Here's a link to how to build your own custom
permissions on that site.

https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions

~Carl

On Thu, Sep 12, 2019 at 8:29 PM Gonzalo Amadio 
wrote:

> Hi Carl,
>
> Is there anywhere we can read about all this permissions you have set up?
>
> They look very interesting, and I have to learn more about and how to use
> them.
>
> Best regards!
>
> El sáb., 24 ago. 2019 a las 4:57, Carl Nobile ()
> escribió:
>
>> You should use the permission structure setup within DRF. First, get the
>> `rest_conditions` package. This package will let you use AND, OR etc with
>> permissions. I wrote a lot of my own permissions also. MOF, a lot of the
>> imports you see are custom.
>>
>>
>> For example:
>>
>> from rest_framework.permissions import IsAuthenticated
>>
>> from rest_condition import C, And, Or, Not
>>
>> from inventory.common.api.permissions import (
>>IsAdminSuperUser, IsAdministrator, IsDefaultUser, IsAnyUser,
>>IsProjectOwner, IsProjectManager, IsProjectDefaultUser,
>> IsAnyProjectUser,
>>IsReadOnly, IsUserActive, CanDelete)
>> from inventory.common.api.pagination import SmallResultsSetPagination
>> from inventory.common.api.view_mixins import (
>>TrapDjangoValidationErrorCreateMixin,
>> TrapDjangoValidationErrorUpdateMixin)
>>
>>
>> class InventoryTypeList(TrapDjangoValidationErrorCreateMixin,
>> ListCreateAPIView):
>>"""
>>InventoryType list endpoint.
>>"""
>>queryset = InventoryType.objects.all()
>>serializer_class = InventoryTypeSerializer
>>permission_classes = (
>>And(IsUserActive, IsAuthenticated,
>>Or(IsAdminSuperUser,
>>   IsAdministrator,
>>   And(IsReadOnly, IsAnyProjectUser)
>>   )
>>),
>>)
>>pagination_class = SmallResultsSetPagination
>>lookup_field = 'public_id'
>>
>> ~Carl
>>
>>
>> On Fri, Aug 23, 2019 at 2:12 PM göktürk sığırtmaç 
>> wrote:
>>
>>> Hello, my UserCreate class is create user via CreateAPIView. I want to
>>> check. if user is auth, auth user directly to '/' URI.
>>>
>>>
>>> class UserCreate(generics.CreateAPIView):
>>>
>>> def __init__(self):
>>> if IsAuthenticated:
>>> print("hello")
>>> redirect('/')
>>>
>>>
>>>
>>> code above is working print method but not working redirect method.
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django REST framework" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-rest-framework+unsubscr...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-rest-framework/f5775f98-70ff-4e0a-a7f0-c608b7e136eb%40googlegroups.com
>>> <https://groups.google.com/d/msgid/django-rest-framework/f5775f98-70ff-4e0a-a7f0-c608b7e136eb%40googlegroups.com?utm_medium=email&utm_source=footer>
>>> .
>>>
>>
>>
>> --
>>
>> ---
>> Carl J. Nobile (Software Engineer)
>> carl.nob...@gmail.com
>>
>> ---
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django REST framework" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-rest-framework+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLYmtORUCMRw%3DC%2BesMi7-Rjt%2BTG3a-%2BAkocXwbzMcinyw%40mail.gmail.com
>> <https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLYmtORUCMRw%3DC%2BesMi7-Rjt%2BTG3a-%2BAkocXwbzMcinyw%40mail.gmail.com?utm_medium=email&utm_source=footer>
>> .
>>
>
>
> --
> 
> Gonzalo Amadio
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@

Re: RegisterSerializer doesn't recognize data from rest-auth/registration API, except for email data.

2019-09-12 Thread Carl Nobile
First off NEVER EVER put credentials in the body of a request. This
introduces a serious security hole (bodies get logged and the creds will be
in the log). Use the Authorization header and Basic auth then always use
HTTPS (TLS). *Authorization: Basic * See
https://en.wikipedia.org/wiki/Basic_access_authentication
Also, comparing duel passwords should be compared in the client code, not
the server backend, so they are not needed in the request.
If you use the header then the only values needed in the request is the
*email* and *company*.

~Carl

On Thu, Sep 12, 2019 at 8:59 AM Gonzalo Amadio 
wrote:

> Coould you solve this problem? What was it?
> Have you debug it.
>
> Can you give more context about the error or what you see?
>
> El vie., 19 abr. 2019 a las 22:04, 
> escribió:
>
>> Hi, I hope any of you can help me out.
>> I am trying build user registrations by using rest-auth/registration API.
>> However, after rest-auth/registration send data which has an email, a
>> company name, a user name, and etc to ResisterSerializer, it ONLY
>> recognizes an email data.
>>
>> Here is my rest-auth/registration code.
>>
>>  axios.post(`${process.env.API_ENDPOINT}rest-auth/registration/`,
>>  {
>>company: this.company,
>>username: this.username,
>>email: this.email,
>>password1: this.password1,
>>password2: this.password2
>>  }).then(res => {
>>  this.$router.push('/login')
>>})
>>.catch(function(error){
>>  this.nonFieldErrors = error.response.data
>>})
>>.finally(() => this.loading = false)
>>
>> and this is ResisterSerializer code below.
>>
>> class RegisterSerializer(serializers.Serializer):
>>company = serializers.CharField(required=True)
>>username = serializers.CharField(required=True)
>>email =
>> serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
>>password1 = serializers.CharField(required=True)
>>password2 = serializers.CharField(required=True)
>>
>>def validate_email(self, email):
>>email = get_adapter().clean_email(email)
>>if allauth_settings.UNIQUE_EMAIL:
>>if email and email_address_exists(email):
>>raise serializers.ValidationError(
>>_("A user is already registered with this e-mail
>> address."))
>>return email
>>
>>def validate_password1(self, password):
>>return get_adapter().clean_password(password)
>>
>>def validate(self, data):
>>if data['password1'] != data['password2']:
>>raise serializers.ValidationError(
>>_("The two password fields didn't match."))
>>return data
>>
>>def get_cleaned_data(self):
>>return {
>>'company': self.validated_data.get('company', ''),
>>'username': self.validated_data.get('username', ''),
>>'password1': self.validated_data.get('password1', ''),
>>'email': self.validated_data.get('email', ''),
>>}
>>
>>def save(self, request):
>>adapter = get_adapter()
>>user = adapter.new_user(request)
>>self.cleaned_data = self.get_cleaned_data()
>>adapter.save_user(request, user, self)
>>setup_user_email(request, user, [])
>>user.save()
>>return user
>>
>> class VerifyEmailSerializer(serializers.Serializer):
>>key = serializers.CharField()
>>
>>
>> Could you please give me advises.
>> Thank you very much.
>>
>>
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django REST framework" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-rest-framework+unsubscr...@googlegroups.com.
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>
> --
> 
> Gonzalo Amadio
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/CANyTv7q2ZBf8UO%2B7JdCg3td61oBxFsNOqj15%2Beazamv833DgwA%40mail.gmail.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d

Re: models.BinaryField, does not work easy as other fields

2019-09-11 Thread Carl Nobile
First, I see at least one syntax error in your code.
*fields = ('__all__')* should be *fields = '__all__'.* Although what you
have may work, it looks like you're trying to use a tuple which it isn't.

The model field *BinaryField* is, under the covers, a *CharField* with a
little extra code around it.
Your post should be sending a *Content-Type* header set to
*application/json* or something similar. You should also set an *Accept*
header to tell the backend what type of data you would like it to send back
to you.
The use of proper headers is extremely important, without them you're
asking the backend to guess what you want. This may be your problem here.

Another slight point though not relevant to your problem is that best
practices would be to keep all URIs lowercase.

~Carl


On Tue, Sep 10, 2019 at 6:18 AM Jaco  wrote:

> Hi all,
>
> I am trying to POST binary data (this case a pickled pandas frame).
> However, it seems BinaryField is not supported equal easy by the framework
> as with other FieldTypes.
>
> Using standard setup, how am I suppose to do in order to be able to send
> by binary data through POST?
> I have been through the documentation, and I cannot find anything (at
> least on a novice level) in order to get it work.
>
> pls also see active thread in Stackoverflow
>
> https://stackoverflow.com/questions/57855228/django-post-pandas-dataframe-using-api-and-pickle
>
> below code produce a "POST /api/DataFrame/ HTTP/1.1" 201 66
> however, there is no content, its empty
>
> Many thanks for some help, either by links or show and tell, please.
>
> class DataFrame(models.Model):
> df_object = models.BinaryField(blank=True, null=True)
>
>
> class DataFrameSerializer(serializers.HyperlinkedModelSerializer):
> class Meta:
> model = DataFrame
> fields = ('__all__')
>
> class DataFrameView(viewsets.ModelViewSet):
> queryset = DataFrame.objects.all()
> serializer_class = DataFrameSerializer
>
>
> import pandas as pd
> df = pd.DataFrame({'a': [0, 1, 2, 3]})
>
> import pickle
> pickled = pickle.dumps(df)
>
> import base64
> pickled_b64 = base64.b64encode(pickled)
>
> import requests
> r = requests.post('http://localhost:8000/api/DataFrame/', data = 
> {'df_object':pickled_b64})
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/5af83418-b115-4576-83fa-664a49d42079%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQJ6wmiih3Px8bMOom_krEhCjWXNXfpKV69HZaiVKhZ1Rg%40mail.gmail.com.


Re: BinaryField

2019-09-11 Thread Carl Nobile
The BoleanField is by definition a binary field if you're only looking for
a 0 and 1.
You could also override the DecimalField and make it do what you want.

~Carl

On Wed, Sep 11, 2019 at 6:35 AM Jaco  wrote:

> Hi,
>
> as BinaryField seems not supported by Django REST framework (out of the
> box)
>
> Is it possible, within documentation or else, link to a minimal basic
> example how the serializer and view need to look in order to POST binary
> data?
>
> Google nor documentation does provide clarity on the matter which is a bit
> strange as posting binary data is not a uncommon task.
> Therefore I post in this forum, if anyone knows the topic, it should be
> here. I am not asking anyone to do my work, but ask kindly for some help to
> get started/how to think.
>
>
> Thanks and regards
>
> J
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/42d71466-df64-4ec4-95bf-fbd71e047564%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQL19gSqUZAtfRt%2B%3DJoN3rFT0qgT8MCMHSjdS47SskVw-w%40mail.gmail.com.


Re: Redirect

2019-08-23 Thread Carl Nobile
You should use the permission structure setup within DRF. First, get the
`rest_conditions` package. This package will let you use AND, OR etc with
permissions. I wrote a lot of my own permissions also. MOF, a lot of the
imports you see are custom.


For example:

from rest_framework.permissions import IsAuthenticated

from rest_condition import C, And, Or, Not

from inventory.common.api.permissions import (
   IsAdminSuperUser, IsAdministrator, IsDefaultUser, IsAnyUser,
   IsProjectOwner, IsProjectManager, IsProjectDefaultUser,
IsAnyProjectUser,
   IsReadOnly, IsUserActive, CanDelete)
from inventory.common.api.pagination import SmallResultsSetPagination
from inventory.common.api.view_mixins import (
   TrapDjangoValidationErrorCreateMixin,
TrapDjangoValidationErrorUpdateMixin)


class InventoryTypeList(TrapDjangoValidationErrorCreateMixin,
ListCreateAPIView):
   """
   InventoryType list endpoint.
   """
   queryset = InventoryType.objects.all()
   serializer_class = InventoryTypeSerializer
   permission_classes = (
   And(IsUserActive, IsAuthenticated,
   Or(IsAdminSuperUser,
  IsAdministrator,
  And(IsReadOnly, IsAnyProjectUser)
  )
   ),
   )
   pagination_class = SmallResultsSetPagination
   lookup_field = 'public_id'

~Carl


On Fri, Aug 23, 2019 at 2:12 PM göktürk sığırtmaç 
wrote:

> Hello, my UserCreate class is create user via CreateAPIView. I want to
> check. if user is auth, auth user directly to '/' URI.
>
>
> class UserCreate(generics.CreateAPIView):
>
> def __init__(self):
> if IsAuthenticated:
> print("hello")
> redirect('/')
>
>
>
> code above is working print method but not working redirect method.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/f5775f98-70ff-4e0a-a7f0-c608b7e136eb%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQLYmtORUCMRw%3DC%2BesMi7-Rjt%2BTG3a-%2BAkocXwbzMcinyw%40mail.gmail.com.


Re: Unusual default serialization for DateRangeField (django.contrib.postgres.fields.DateRangeField)

2019-08-15 Thread Carl Nobile
Are you talking about incoming data? If so you should be sending ISO aware
date-time objects as such: 2019-05-12T16:27:34.503919-04:00
If you are talking about outgoing data then you should be saving in the DB
aware UTC date-times as python datetime objects.
DRF will always do the right thing if you always do the above.

Aware means with the time zone.
Naive means without the time zone.

Always always always save UTC time, but not all databases let you store the
time zone.

On Thu, Aug 15, 2019 at 12:35 PM Baze Blackwood <
milesblackwoodmu...@gmail.com> wrote:

> It seems that DRF's default behavior is to stringify the object returned
> by DateRangeField. For example, this is how an entry appears in a "dates"
> field which uses this field.
>
> "dates": "{\"bounds\": \"[)\", \"lower\": \"2019-07-19\", \"upper\":
> \"2019-09-14\"}",
> Has anyone else experienced this behavior and/or know how to get it to
> preserve the object?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/7947ec40-6540-455b-b2d5-85ed176fa7dc%40googlegroups.com
> 
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQJYFuNe3M0Ms_aT1epooMiN78foXTQcXv1wTEH%2BG3pHkQ%40mail.gmail.com.


Re: Auth

2019-08-15 Thread Carl Nobile
Humm, I've never had this issue. Have you set up the permissions on the
views correctly?
It's kind of difficult making definitive statements about this without
seeing code.

On Thu, Aug 15, 2019 at 10:38 AM göktürk sığırtmaç 
wrote:

> I was login (/admin) in my app. Later when I want to access profile
> endpoint (this endpoint have IsAuthenticated as permission)  i have 401
> error. Why?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-rest-framework+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-rest-framework/3b3b8a28-9b1e-483c-a7b8-dce9a1677ee3%40googlegroups.com
> .
>


-- 
---
Carl J. Nobile (Software Engineer)
carl.nob...@gmail.com
---

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/CAGQqDQ%2B2%3D98KweQnN7UNdT4gundzXAL6b%2BhpDrYYEOoXtJ8Fnw%40mail.gmail.com.


Re: Image file upload - process - download

2019-05-27 Thread Carl Nobile
Well, this is a Django REST Framework group, so you're not going to find a 
lot of Flask help here.

With that said, yes this should be possible in any framework, your biggest 
problem is going to be how long it takes to process the file. If it takes 
much longer than several seconds you will need to return a 202 response 
with some sort of object that says what the status is on a different 
endpoint. You will need to poll this endpoint and eventually it should 
return to you a 303 and redirect you back to where you can pick up the 
processed file. This is the way the RFCs explain how to do it.

https://tools.ietf.org/html/rfc7231#section-6.3.3

and

https://tools.ietf.org/html/rfc7231#section-6.4.4

~Carl

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/d27cf273-42f3-4c4e-89a6-d9c269b998d5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: .save() method returning an saved instance of object but object creation does not take place in DB

2019-05-27 Thread Carl Nobile
I can see a few issues here.

   1. You defined *'strt_day'* and *'end_day'* inside the *Meta* class, you 
   cannot do this. It won't work correctly.
   2. If you actually get back a real PK from the DB then the DB at least 
   thinks it got created.

Are you sure it didn't fail for some other reason?

To be honest, the scenario you propose is kind of impossible, so I don't 
know what else to suggest.

~Carl

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/4f911028-e11a-48bb-9412-7d4a6f769553%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: ThreadedListSerializer - will this cause me any problems?

2019-05-27 Thread Carl Nobile
Hi Kyle,

I'm thinking you will have reentrant issues, in other words, a single 
instance of a serializer will not be thread/process safe. If you 
*dir(instance)* you will see a whole lot of member objects that will be 
instance-specific data. Django is pretty good at handling multiple 
instances of requests, so don't try to do what Django is already doing. The 
best thing you can do to increase the speed of your request/responses is to 
do backend caching with Redis. You write code that intercepts the data 
coming from your models (or wherever the data comes from) and caches it.

~Carl

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/41b0f8c9-9180-4e2c-adf6-17eeea899415%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: PrimaryKeyRelatedField from property method serialization

2019-05-27 Thread Carl Nobile
Clara,

This is something that the DRF (Django Rest Framework) serializers should 
do auto-magically. What I'm thinking is that you do not have the correct 
settings in your settings file. I should be set to something like this:

REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'TEST_REQUEST_DEFAULT_FORMAT': 'json', 
'TEST_REQUEST_RENDERER_CLASSES': ( 
'rest_framework.renderers.JSONRenderer', 
'rest_framework.renderers.MultiPartRenderer', 
'rest_framework.renderers.TemplateHTMLRenderer', 
),
}


By adding or subtracting different renderers you can then. You will see 
that you can even setup different parsers and renderers for testing.
So I think you are trying to do in code something that the DRF does for you 
out-of-the-box.

~Carl

On Thursday, April 25, 2019 at 3:30:55 PM UTC-4, Clara Daia wrote:
>
> Hello, everyone
>
> I have a model with a complicated relationship and I am having trouble 
> serializing it.
>
> The relationship itself is not particularly relevant: my model may have a 
> history of associations with different instances of itself (think a person 
> who has dated multiple people but can only date one person at a time).
>
> The main thing is that instead of having a ForeignKey field in the model 
> for the current association, I have a *@property method* that yields the 
> *instance 
> currently associated* with it.
>
> These are the simplified models:
>
> class MyModel(models.Model):
> reference = models.CharField()
> ...
>
> @property
> def related(self):
> try:
> return RelatedHistory.objects.filter(main_model_id=self.id
> ).last().related
> except AttributeError:
> return None
>
> class RelatedHistory(models.Model):
> main_model = ForeignKey(MyModel)
> related = ForeignKey(MyModel)
> start_datetime = DatetimeField()
> ...
>
>
> I used a PrimaryKeyRelatedField in the serializer:
>
> class MyModelSerializer(serializers.ModelSerializer):
> related = serializers.PrimaryKeyRelatedField(
> queryset=MyModel.objects.all(),
> allow_null=True
> )
> ...
>
> However, I get an error in the *JSON rendering* because the serializer 
> returns *the object* instead of *the pk*.
>
> >>> serializer = MyModelSerializer(mm1)
> >>> serializer.data
> {'id': 2, 'related': }
> >>> JSONRenderer().render(serializer.data)
> Traceback (most recent call last):
>   File "/usr/local/lib/python3.6/code.py", line 91, in runcode
> exec(code, self.locals)
>   File "", line 1, in 
>   File 
> "/usr/local/lib/python3.6/site-packages/rest_framework/renderers.py", line 
> 105, in render
> allow_nan=not self.strict, separators=separators
>   File 
> "/usr/local/lib/python3.6/site-packages/rest_framework/utils/json.py", line 
> 28, in dumps
> return json.dumps(*args, **kwargs)
>   File "/usr/local/lib/python3.6/json/__init__.py", line 238, in dumps
> **kw).encode(obj)
>   File "/usr/local/lib/python3.6/json/encoder.py", line 199, in encode
> chunks = self.iterencode(o, _one_shot=True)
>   File "/usr/local/lib/python3.6/json/encoder.py", line 257, in iterencode
> return _iterencode(o, 0)
>   File 
> "/usr/local/lib/python3.6/site-packages/rest_framework/utils/encoders.py", 
> line 68, in default
> return super(JSONEncoder, self).default(obj)
>   File "/usr/local/lib/python3.6/json/encoder.py", line 180, in default
> o.__class__.__name__)
> TypeError: Object of type 'MyModel' is not JSON serializable
>
> I considered writing my own field, but I checked the `to_representation` 
> method of the PrimaryKeyRelatedField and it looks like it should work:
>
> def to_representation(self, value):
> if self.pk_field is not None:
> return self.pk_field.to_representation(value.pk)
> return value.pk
>
> Could someone point to me whether I am doing something wrong?
>
> Best regards,
>
> Clara
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-rest-framework/36d870d6-e26d-4fa6-93d1-e19d23968038%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.