Re: Field.choices get all items as json

2018-05-20 Thread Peter of the Norse
Create a view that returns json.  At least if you want to use it in an ajax 
way.  Otherwise, I would recommend just passing it as an argument to the 
templates that use it.

import json

def years(request):
return HttpResponse(json.dumps(dict(Model.YEAR_IN_SCHOOL_CHOICES)), 
content_type=‘application/json')

The dict is there to make sure you get it as an object instead of an array of 
arrays.

> On May 18, 2018, at 1:20 AM, Majid Hojati  wrote:
> 
> In fact I want to convert all of these choises into json format and then send 
> them to user 
> thanks
> 
> On Thursday, May 17, 2018 at 8:46:42 PM UTC+4:30, C. Kirby wrote:
> if you just want to put that into json do:
> import json
> 
> YEAR_IN_SCHOOL_CHOICES = (
> ('FR', 'Freshman'),
> ('SO', 'Sophomore'),
> ('JR', 'Junior'),
> ('SR', 'Senior'),
> )
> 
> serialized_year_choices = json.dumps(Model.YEAR_IN_SCHOOL_CHOICES) 
> 
> 
> 
> 
> 
> On Thursday, May 17, 2018 at 10:52:15 AM UTC-4, Majid Hojati wrote:
> Hi,
> I have a Field.choices in my model. lets say it is:
> 
> YEAR_IN_SCHOOL_CHOICES = (
> ('FR', 'Freshman'),
> ('SO', 'Sophomore'),
> ('JR', 'Junior'),
> ('SR', 'Senior'),
> )
> 
> I can access them using this method Model. YEAR_IN_SCHOOL_CHOICES  but how 
> can I convert it to a json then I can send them using a webservice ? is there 
> any good method?
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users+unsubscr...@googlegroups.com 
> .
> To post to this group, send email to django-users@googlegroups.com 
> .
> Visit this group at https://groups.google.com/group/django-users 
> .
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/be3eabf9-939a-429f-a7c8-62ba30b98981%40googlegroups.com
>  
> .
> For more options, visit https://groups.google.com/d/optout 
> .

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1CF3C717-1324-48CF-B9D2-6A62A3EFF827%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django channel 2 - Provide seperate feeds to each users every 5 second

2018-05-20 Thread Ryan Nowakowski
On Fri, May 18, 2018 at 10:28:00PM -0700, sahadev sahu wrote:
> Hello,
> 
> I am implementing a websocket application for live data feed updates to 
> each client according to their watchlist in every 5 second. Here I am 
> explaining my requirement:
> 
>1. Once user register with my application, he can view list of currency 
>pairs e.g (ETH, BTC etc)
>2. From that list, user can add one or more pairs into his watchlist.
>3. And based on user's watchlist, user should get only that data through 
>"Channel" which is in his watchlist in every 5 second
>
> Possible approach as per me:
> 
>1. Should i create multiple channel for each user ? or
>2. Is there possibility to create multiple events in single channel to 
>handle each user separately to send different feeds to each user
> 
> Note: Every feed will fetch its results from another exchange website, then 
> the end user will get that feed into their watchlist. How can i run my 
> script continuously for each user seprately 
> 
> 
> Please kindly suggest, what is the right approach to implement this kind of 
> situation.

Here's one way to do it.  Each channel should be associated with
a group[1]. There should be one group per User[2] associated via a
database model[3](called UserWebsocketGroup).  Then you can poll the
exchange website using a background task[4] that goes something like this:

def poll_exchange_site():
user_websocket_groups = UserWebsocketGroup.objects.all()
for user_websocket_group in user_websocket_groups:
currency_pairs = user_websocket_group.user.currency_pairs.all()
for pair in currency_pairs:
pair_values = get_pair_values_from_exchange(pair)
user_websocket_group.group.send({pair: pair_values})
time.sleep(5)
poll_exchange_website()


[1] http://channels.readthedocs.io/en/latest/topics/channel_layers.html#groups
[2] https://docs.djangoproject.com/en/2.0/ref/contrib/auth/#user-model
[3] https://docs.djangoproject.com/en/2.0/topics/db/models/
[4] http://channels.readthedocs.io/en/latest/topics/worker.html#

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/20180520194250.GC23641%40fattuba.com.
For more options, visit https://groups.google.com/d/optout.


Re: Message from a django beginner user

2018-05-20 Thread Alex Stelmakh
Hi, Francis. Did you try mozilla developer network ? I consider this for my 
further learning. 

вторник, 15 мая 2018 г., 23:01:59 UTC+3 пользователь Francis F. Massaquoi, 
Jr. написал:
>
> Hi, I'm Francis F. Massaquoi, Jr. with great interest in learning django 
> 2.0, which is the latest version, I have been searching on youtube for a 
> channel that have the latest version tutorial, I have not really find one, 
> can someone please help me with a pdf or website, where I can learn django 
> to the best, I have been reading some pdf, I have the basic knowledge, but 
> I need to advance my knowledge. Or if you can connect with me on skype, 
> this is my skype username: francisfmassaquoijr, or if you have a skype 
> group, you can please add me, or give me your skype username...
>
> Your urgent response will highly be appreciated. 
>
> Thanks to the admin for accepting me..
>
> We do it the django way, because it's the best way to web app 
> development.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/ed099019-e6f3-4aaf-b9bf-64b0a1a02da0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Setting up Django templates

2018-05-20 Thread Salty beggar
Hi, I'm trying to set up Templates for Django. I already have models and 
views that function, and now I'm trying to figure out a way to get an 
actual page to show for it. 

My models are

from django.db import models




class Continent(models.Model):
name = models.CharField(max_length=60, default='', unique=True)
code = models.CharField(max_length=3, default='')
 


def __str__(self):
return '%s %s' % (self.name, self.code)
 
class Meta:
ordering = ["name"]
verbose_name_plural = "continents"




class Country(models.Model):


name = models.CharField(max_length=60, default='', unique=True)
code = models.CharField(max_length=3, default='', unique=True)
continent = models.ForeignKey(Continent, default='', related_name=
'countries')
area = models.PositiveIntegerField(default=0)
population = models.PositiveIntegerField(default=0)
capital = models.CharField(max_length=60, default='')
 

 
def __str__(self):
return '%s %s %s %s %s %s' % (self.name, self.code, self.capital, 
self.population, self.area, self.continent)
 
class Meta:
ordering = ["name"]
verbose_name_plural = "countries"

and my views are 

from django.http import Http404
from django.http import HttpResponse
from django.http import JsonResponse
import json

from .models import Continent, Country


def continent_json(request, continent_code):
all_continents = Continent.objects.all()
my_dictionary = {}
for continent in all_continents:
if continent.code == continent_code:
for country in continent.countries.all():
my_dictionary[country.code] = country.name
response = JsonResponse(my_dictionary)
response.status_code = 200
callback = request.GET.get('callback')
if not callback:
return HttpResponse(response, 
content_type="application/json")
response =  '{0}({1})'.format(callback, response)
return HttpResponse(response, 
content_type="application/javascript")

raise Http404("Not implemented")

def country_json(request, continent_code, country_code):
all_countries = Country.objects.all()
for country in all_countries:
if country.code == country_code:
if country.continent.code == continent_code:
area = country.area
population = country.population
capital = country.capital 
dictionary = dict([('area', area), ('population', 
population), ('capital', capital)])
obj = json.dumps(dictionary, indent=4)
response = JsonResponse(dictionary)
response.status_code = 200  
callback = request.GET.get('callback')
if not callback:
return HttpResponse(response, 
content_type="application/json")
response =  '{0}({1})'.format(callback, response)
return HttpResponse(response, 
content_type="application/javascript")

raise Http404()

  

The views return JSON-formatted information, as you can see. What I'm 
trying to achieve in the template is implement templates that display 
countries and their data in a table on the bottom of a page. The table 
should only be visible after user requests this view with a country code, 
and above the table I'm trying to have links to all the continents in the 
database. 

 In this exercise, you need to implement templates that will display 
countries and their data in a table on the bottom of this page. The table 
should only be visible when a user has requested this view with a country 
code. Above the table there should be links to all continents in the 
database. If the user requests a page with a non existent continent code a 
404 HTTP response code should be returned.

I already have templates files for what I need to create, but I'm not sure 
how I can actually get to it. I have 2 templates I need to create: 
countrytable.html and continentmenu.html, and they're an extension of 
index.html.

index.html:

{% extends "base.html" %}
{% load staticfiles %}

{% block title %}Continents{% endblock %}

{% block header %}
{{ block.super }}


{% endblock %}

{% block content %}
If you see this, your application is correctly setup.

{% include "selectui/continentmenu.html" %}

{{ continent.name }}



  {% if continent %}
{% include "selectui/countrytable.html" %}
  {% endif %}


{% endblock %}



Here's an example what countrytable with one country would display


  

  Name
  Capital
  Population
  Area

  
  

  Sweden
  Stockholm
  9045000
  449964 km2

  


and here's an example of continentmenu.html


  Scandinavia



I'm a bit lost as to how the hierarchy between the data works in Django, so 
I'm not sure if I need to figure out a way to include the data from my 
models in the templates 

Re: Selecting data from intermediate table in prefetch_related results in duplicate rows

2018-05-20 Thread Tomáš Ehrlich
I completely forgot about `extra` method and it seems it does solve the problem:

roles = Prefetch(
‘users',
queryset=User.objects.extra(select={'role': 'users_role.role'})
)
qs = Project.objects.prefetch_related(roles))

However, I’m still curious why `annotate` doesn’t work when used inside 
`prefetch_related`.


1. Is it bug? Should it work in the same way as when used outside 
`prefetch_related`?
2. Is there a way to avoid `extra` method? It should be avoided at all cost, 
after all.


Thank you in advance!
   Tom


> 20. 5. 2018 v 11:41, Tomáš Ehrlich :
> 
> Hello,
> I have a two models (User, Project) in m2m relationship with intermediate 
> (Role) table.
> 
> When I’m selecting all users in project and I also want to select 
> corresponding role, I simply annotate one field from Role table using F 
> expression:
> 
> Users.objects.all().filter(projects__name=‘Django’).annotate(role=F(‘roles__role’))
> 
> Annotate in this case doesn’t create new join, because `roles` table is 
> already joined to filter on data from `projects` table. This works well.
> 
> 
> However, I tried to same in `prefetch_related` and I’m getting duplicate 
> rows, because there’s a new JOIN statement added. (Usecase: Selecting all 
> projects in DB with all users per project)
> 
> The SQL statement with `prefetch_related`, but without `annotate` looks like 
> this:
> 
> roles = Prefetch(
> ‘users',
> queryset=User.objects.all()
> )
> qs = Project.objects.prefetch_related(roles)
> 
> SELECT
>   ("users_role"."project_id") AS "_prefetch_related_val_project_id",
>   — other fields here
> FROM "users_user"
>   INNER JOIN "users_role" ON ("users_user"."id" = "users_role"."user_id")
> WHERE "users_role"."project_id” IN (1, 2, 3, 4, 5)
> 
> 
> As you can see, the table `users_role` is already joined, so I’m basically 
> looking for Django ORM expression which generates following SQL query:
> 
> SELECT
>   ("users_role"."project_id") AS "_prefetch_related_val_project_id”,
>   “users_role_.”role”,
>   — other fields here
> FROM "users_user"
>   INNER JOIN "users_role" ON ("users_user"."id" = "users_role"."user_id")
> WHERE "users_role"."project_id” IN (1, 2, 3, 4, 5)
> 
> 
> Unfortunatelly, following expression generates incorrect SQL:
> 
> roles = Prefetch(
> ‘users',
> queryset=User.objects.all().annotate(role=F('roles__role'))
> )
> qs = Project.objects.prefetch_related(roles)
> 
> SELECT
>   ("users_role"."project_id") AS "_prefetch_related_val_project_id",
>   "users_role"."role" AS “role”,
>   — other fields here
> FROM "users_user"
>   LEFT OUTER JOIN "users_role" ON ("users_user"."id" = "users_role"."user_id")
>   INNER JOIN "users_role" T3 ON ("users_user"."id" = T3."user_id")
> WHERE T3."project_id" IN
>   (1, 2, 3, 4, 5)
> 
> The extra `left outer join` causes duplicate entries.
> 
> 
> I’ve found one ticket (https://code.djangoproject.com/ticket/27144 
> ) which seems to be relevant, 
> but it’s old and closed.
> 
> Any ideas? Is it bug or is there really a reason to include extra JOIN? I’m 
> not very skilled in relational algebra.
> 
> Thank you in advance!
> 
> 
> Cheers,
>Tom
> 
> 
> 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/EFFACF5E-06B4-4F68-B388-83E30D8A3453%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP


Re: Please I need help on how to create a custom method for a model with list_display

2018-05-20 Thread Godson Rapture
Thanks very much. I have solved the problem.

On Sunday, May 20, 2018, Daniel Germano Travieso 
wrote:

> Hello!
>
> On your case, as stated on the official doc, you should just create a
> method on the model you want to display the ManyToMany field on the
> list_display that maybe returns the list of items from the ManyToMany
> field. Django avoids using this as it could be a potential overhead as you
> will run seperate queries on the database to fetch all the related
> many-to-many objects.
>
> But if you are feeling adventurous, just create the method that performs
> that query.
>
> i.e. On your Book model you create a method that returns the
> self.authors.all() set. Then you use that method's name on the list_display
> instead of authors.
>
> Hope it helps.
>
> On Saturday, May 19, 2018 at 3:54:17 PM UTC-3, Godson Rapture wrote:
>>
>> Please I am learning Django 2.0.4
>>
>>
>> Right now I am learning about Django Admin.
>>
>>
>> I got an error that the value of my list_display should not be a
>> ManyToMany Field.
>>
>>
>> I referred back to Django official doc and I was asked to create a custom
>> method for my model.
>>
>>
>> I tried looking for an example of how to do that, I could not see.
>>
>>
>> Here is my model.py program
>>
>>  from django.db import models
>>
>> class Publisher(models.Model):
>> name = models.CharField(max_length=30)
>> address = models.CharField(max_length=50,blank=True)
>> city = models.CharField(max_length=60,blank=True)
>> country = models.CharField(max_length=50,blank=True)
>> website = models.URLField()
>> def __str__(self):
>> return self.name
>>
>> class Author(models.Model):
>> salution = models.CharField(max_length=10)
>> first_name = models.CharField(max_length=30)
>> last_name = models.CharField(max_length=40)
>> email = models.EmailField()
>> headshot = models.ImageField(upload_to = "tmp")
>> def __str__(self):
>> return f"{self.first_name} {self.last_name}"
>>
>> class Book(models.Model):
>> title = models.CharField(max_length=100)
>> authors = models.ManyToManyField(Author)
>> publisher = models.ForeignKey(Publisher,on_delete=models.CASCADE,)
>> publication_date = models.DateField()
>> def __str__(self):
>> return self.title
>>
>> Here is my admin.py program
>>
>> from django.contrib import admin
>> from polls.models import Book, Publisher, Author
>> # Register your models here.
>>
>> class BookAdmin(admin.ModelAdmin):
>> list_display = [
>> "title",
>> "authors", #a ManyToMany Field
>>
>> ]
>>  search_fields = [
>> "Book"
>> ]
>> class Meta:
>> model = Book
>>
>> admin.site.register(Book, BookAdmin)
>>
>> Can someone please help me.
>>
>> Thanks.
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/
> msgid/django-users/56c58fb6-7074-47aa-9536-8d8027ef70a0%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAEUEpOR37QtBN72gczc9JKteiB5rBryL3vhXP1capNtc1UsLZQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Selecting data from intermediate table in prefetch_related results in duplicate rows

2018-05-20 Thread Tomáš Ehrlich
Hello,
I have a two models (User, Project) in m2m relationship with intermediate 
(Role) table.

When I’m selecting all users in project and I also want to select corresponding 
role, I simply annotate one field from Role table using F expression:

Users.objects.all().filter(projects__name=‘Django’).annotate(role=F(‘roles__role’))

Annotate in this case doesn’t create new join, because `roles` table is already 
joined to filter on data from `projects` table. This works well.


However, I tried to same in `prefetch_related` and I’m getting duplicate rows, 
because there’s a new JOIN statement added. (Usecase: Selecting all projects in 
DB with all users per project)

The SQL statement with `prefetch_related`, but without `annotate` looks like 
this:

roles = Prefetch(
‘users',
queryset=User.objects.all()
)
qs = Project.objects.prefetch_related(roles)

SELECT
  ("users_role"."project_id") AS "_prefetch_related_val_project_id",
  — other fields here
FROM "users_user"
  INNER JOIN "users_role" ON ("users_user"."id" = "users_role"."user_id")
WHERE "users_role"."project_id” IN (1, 2, 3, 4, 5)


As you can see, the table `users_role` is already joined, so I’m basically 
looking for Django ORM expression which generates following SQL query:

SELECT
  ("users_role"."project_id") AS "_prefetch_related_val_project_id”,
  “users_role_.”role”,
  — other fields here
FROM "users_user"
  INNER JOIN "users_role" ON ("users_user"."id" = "users_role"."user_id")
WHERE "users_role"."project_id” IN (1, 2, 3, 4, 5)


Unfortunatelly, following expression generates incorrect SQL:

roles = Prefetch(
‘users',
queryset=User.objects.all().annotate(role=F('roles__role'))
)
qs = Project.objects.prefetch_related(roles)

SELECT
  ("users_role"."project_id") AS "_prefetch_related_val_project_id",
  "users_role"."role" AS “role”,
  — other fields here
FROM "users_user"
  LEFT OUTER JOIN "users_role" ON ("users_user"."id" = "users_role"."user_id")
  INNER JOIN "users_role" T3 ON ("users_user"."id" = T3."user_id")
WHERE T3."project_id" IN
  (1, 2, 3, 4, 5)

The extra `left outer join` causes duplicate entries.


I’ve found one ticket (https://code.djangoproject.com/ticket/27144 
) which seems to be relevant, but 
it’s old and closed.

Any ideas? Is it bug or is there really a reason to include extra JOIN? I’m not 
very skilled in relational algebra.

Thank you in advance!


Cheers,
   Tom



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/FCD600AD-E1DE-495D-9C6B-B3E3A3F693D9%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: Message signed with OpenPGP


Re: need help

2018-05-20 Thread Umar Kambala
Page not found (404)
Request Method: GET
  Request URL:http//127.0.0.1:800/

Using the URLconf defined in mysite.urls, Django tries these URL patterns,
in this order:
1. admin/
2. personal/
The empty path didn't match any of these. This is the mge I hv been getting
when ever I run my surver on personal.py .. Need ur help
On May 2, 2018 5:28 PM, "Aditya Singh"  wrote:

> Sure it is mate
>
> On Wed, May 2, 2018, 10:51 PM Umar Kambala  wrote:
>
>> I believe its low connection
>> On May 2, 2018 5:16 PM, "Jani Tiainen"  wrote:
>>
>>> Looks like your machine doesn't have connection to (some parts) of
>>> internet for some reason, or you do have very slow connection.
>>>
>>> On Wed, May 2, 2018 at 7:46 PM,  wrote:
>>>
 please  this is the massage i keep on getting when trying to install
 django.. what do i do?


 C:\Users\Admin>pip install Django==2.0.5
 Collecting Django==2.0.5
   Retrying (Retry(total=4, connect=None, read=None, redirect=None,
 status=None)) after connection broken by 'ReadTimeoutError("
 HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read
 timeout=15)",)': /simple/django/
   Downloading https://files.pythonhosted.org/packages/23/91/
 2245462e57798e9251de87c88b2b8f996d10ddcb68206a8a020561ef7bd3
 /Django-2.0.5-py3-none-any.whl (7.1MB)
 0% || 10kB 1.2kB/s eta
 1:36:24Exception:
 Traceback (most recent call last):
   File "c:\users\admin\appdata\local\programs\python\python36-32\
 lib\site-packages\pip\_vendor\urllib3\response.py", line 302, in
 _error_catcher
 yield
   File "c:\users\admin\appdata\local\programs\python\python36-32\
 lib\site-packages\pip\_vendor\urllib3\response.py", line 384, in read
 data = self._fp.read(amt)
   File "c:\users\admin\appdata\local\programs\python\python36-32\
 lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 60,
 in read
 data = self.__fp.read(amt)
   File 
 "c:\users\admin\appdata\local\programs\python\python36-32\lib\http\client.py",
 line 449, in read
 n = self.readinto(b)
   File 
 "c:\users\admin\appdata\local\programs\python\python36-32\lib\http\client.py",
 line 493, in readinto
 n = self.fp.readinto(b)
   File 
 "c:\users\admin\appdata\local\programs\python\python36-32\lib\socket.py",
 line 586, in readinto
 return self._sock.recv_into(b)
   File 
 "c:\users\admin\appdata\local\programs\python\python36-32\lib\ssl.py",
 line 1009, in recv_into
 return self.read(nbytes, buffer)
   File 
 "c:\users\admin\appdata\local\programs\python\python36-32\lib\ssl.py",
 line 871, in read
 return self._sslobj.read(len, buffer)
   File 
 "c:\users\admin\appdata\local\programs\python\python36-32\lib\ssl.py",
 line 631, in read
 v = self._sslobj.read(len, buffer)
 socket.timeout: The read operation timed out

 During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
   File "c:\users\admin\appdata\local\programs\python\python36-32\
 lib\site-packages\pip\basecommand.py", line 215, in main
 status = self.run(options, args)
   File "c:\users\admin\appdata\local\programs\python\python36-32\
 lib\site-packages\pip\commands\install.py", line 324, in run
 requirement_set.prepare_files(finder)
   File "c:\users\admin\appdata\local\programs\python\python36-32\
 lib\site-packages\pip\req\req_set.py", line 380, in prepare_files
 ignore_dependencies=self.ignore_dependencies))
   File "c:\users\admin\appdata\local\programs\python\python36-32\
 lib\site-packages\pip\req\req_set.py", line 620, in _prepare_file
 session=self.session, hashes=hashes)
   File "c:\users\admin\appdata\local\programs\python\python36-32\
 lib\site-packages\pip\download.py", line 821, in unpack_url
 hashes=hashes
   File "c:\users\admin\appdata\local\programs\python\python36-32\
 lib\site-packages\pip\download.py", line 659, in unpack_http_url
 hashes)
   File "c:\users\admin\appdata\local\programs\python\python36-32\
 lib\site-packages\pip\download.py", line 882, in _download_http_url
 _download_url(resp, link, content_file, hashes)
   File "c:\users\admin\appdata\local\programs\python\python36-32\
 lib\site-packages\pip\download.py", line 603, in _download_url
 hashes.check_against_chunks(downloaded_chunks)
   File "c:\users\admin\appdata\local\programs\python\python36-32\
 lib\site-packages\pip\utils\hashes.py", line 46, in
 check_against_chunks
 for chunk in chunks:
   File "c:\users\admin\appdata\local\programs\python\python36-32\
 lib\site-packages\pip\download.py", line 571, in 

Re: Managing multiple user types in Django

2018-05-20 Thread Mike Dewhirst

On 20/05/2018 1:45 PM, Daniel Germano Travieso wrote:
There is no really definitive approach to handle this, and you could 
do it either way.
Either option works, but for a philosofical point of view, if there is 
no significant difference between the user types, the first approach I 
tend to believe is the most logical one.


However, as a optimal approach, to think on all possible overheads you 
may encounter on your system, I believe the second option is best, as 
it isolates authentication methods to a specific and stablished module 
provided by django, avoiding you the hassle of maybe having to 
override user-specific methods.


On my projects I tend to lean towards User + Profile approach.

On the point of view of performance, the User + Profile approach has 
de disadvantage of requireing a database join in order to retrieve 
user-specific information.


The official django doc has a view on this very subject

https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#specifying-a-custom-user-model 
:


" *Model design considerations*

Think carefully before handling information not directly related to 
authentication in your custom user model.


It may be better to store app-specific user information in a model 
that has a relation with the user model. That allows each app to 
specify its own user data requirements without risking conflicts with 
other apps. On the other hand, queries to retrieve this related 
information will involve a database join, which may have an effect on 
performance."





I think that is a good start and it certainly guides my design. In my 
overall approach I try and ignore performance and instead bend over 
backwards to reflect the real-world relationships. I really don't care 
about extra joins until performance is proven to be inadequate.


I have been told often enough that performance problems are the best 
problems to have because you can generally throw inexpensive hardware 
resources at them until they go away. Much better than the software 
being too difficult to change as the business evolves.


For example, if a user has a role the role should apply to the user not 
to the profile. Putting the role into a 1:1 profile prevents the user 
from having more than one role. In real life people can multi-task.


I have adopted the Django auth group system as role. It lets me keep 
profile data in profile and roles with permissions in groups. I also 
have a bunch of is_author(), is_editor(), is_consumer() methods in view 
utils so I can do non-permission related stuff as well.


Mike


Hope it helps!


On Wednesday, May 16, 2018 at 11:53:58 AM UTC-3, Bill Torcaso wrote:


I inherited a system which has one User model, and a Profile model
that is 1-to-1 with User.  The type-of-user information is carried
in a required "role" property in the Profile.  I think that is a
well-established approach.

I am curious to hear what people think of the tradeoffs between
(User + Profile) and (User-base-class + subclasses).

On Tuesday, May 15, 2018 at 12:41:50 PM UTC-4, Vijay Khemlani wrote:

I would make a UserType table and have a foreign key from your
user model to it, or maybe just have an enumerated type in
your user model depending on how much custom logic there is to
each user type.

On Tue, May 15, 2018 at 11:50 AM Frankline 
wrote:

Hello Everyone,

I am developing an API based on Django Rest Framework
. Currently I have
4 user types i.e. Buyer, Merchant, Insurer, and Admin.

The system I'm developing has an *API endpoint* and a
*Dashboard* view.

Each of the above user types have different fields and may
need to login to the system at one point, so having one
user model is the best way to go. Note that, a user can
only be of one type.

However, only the merchant will be actively using the API
endpoint.

My question is then, how will I be able to manage the
different user types in the system?

My current options are:

1.

 1. classBaseUser(AbstractBaseUser):
 2. ...
3.
 4. classBuyer(BaseUser):
 5. ...
6.

 1. classMerchant(BaseUser):
 2. ...
3.

 1. classInsurer(BaseUser):
 2. ...


2.

 1. fromdjango.db importmodels
 2. fromdjango.contrib.auth.models importUser
3.
 4. classBuyer(models.Model):
 5. user =models.OneToOneField(User)
6.
 7. classMerchant(models.Model):
 8. user =models.OneToOneField(User)
9.

 1. classInsurer(models.Model):
 2. user =models.OneToOneField(User)

 

Re: Standard approach

2018-05-20 Thread Mike Dewhirst

On 20/05/2018 3:52 AM, Melvyn Sopacua wrote:

On donderdag 17 mei 2018 00:44:32 CEST Mike Dewhirst wrote:


More advanced users tend to focus on the more advanced problems and
that's the way it should be.

Not always true. You tend to focus on things that show research and effort.
The level of competence then doesn't matter. It just so happens that anyone
who loadshttp://localhost:8000/  during the tutorial and gets a 404, then
tells the group the tutorial is wrong, clearly doesn't show research (asked
and answered a gazillion times) nor effort (read the tutorial again to see
your mistake, ans yes, it's possible to read over it again and again and not
see it, which is why you should use the search-before-asking algorithm).

So it looks as though more advanced users focus on more advanced problems, but
that certainly isn't the case - it just coincides with the fact that beginner
problems are often thrown into the group without any thought or research.


That is a very fair point Melvyn - and diplomatically very well put.



And can I just say, sometimes with an attitude unbecoming of someone who wants
others to spend time on his/her problems. But that's the nature of Open Source
communities.


I agree. But it doesn't happen very often on this list.


This is rather elaborate, but should be any forum's charter:
http://www.catb.org/esr/faqs/smart-questions.html


I'm not so sure wrt this forum. The first paragraph in that page 
indicates to me it applies to ancient forums like some of the old Linux 
lists where the "tough love" approach is very popular. In this forum, I 
think the culture is historically more gentle and professionally 
diplomatic. As you are proving :)


My focus in this thread was to maybe find a way to help newcomers who 
have difficulty with documentation (and maybe with language) but for any 
reason. You have to admit such people exist.


I do admit there are some lazy ones who fit the description in the 
abovementioned first paragraph but they are surely children.


On reflection we probably only need another dot point "Other Django 
resources" appended to the "First steps" list - 
https://docs.djangoproject.com/en/1.11/#first-steps


The link might say ... "Books, videos, training, tutorials" and point to 
a summary page somewhere which further points to youtube videos from 
conference sessions, tutorial videos, various books, training sites and 
websites such as Django Girls and so on. Perhaps also the Django 
tutorial source code nicely commented with links to the docs?


As I said earlier, I don't know where such a page should be hosted nor 
how it should be laid out or updated but I'm sure if the community feels 
it is valuable someone will see an opportunity and step up. Maybe it 
already exists?


Then newcomers asking questions which more or less prove they haven't 
looked at the docs - for whatever reason sometimes legitimate, sometimes 
not - could be pointed to that page perhaps with an additional 
recommendation for a particular resource to consume first.


I think I've probably said enough ...

Cheers

Mike

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9de9e0e8-fd78-1efc-0b4a-1805e74b979b%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.