Django - Updating multiple models from a form - Data does not saved

2017-04-12 Thread Bernardo Garcia


I have a custom User model to manage some profiles user: is_student, 
is_professor and is_executive


In this model, in addition, I have the get_student_profile(),
get_professor_profile() andget_executive_profile() methods to get the user 
profiles data of each user from my different views.


class User(AbstractBaseUser, PermissionsMixin):

email = models.EmailField(unique=True)
username = models.CharField(max_length=40, unique=True)
slug = models.SlugField(max_length=100, blank=True)
is_student = models.BooleanField(default=False)
is_professor = models.BooleanField(default=False)
is_executive = models.BooleanField(default=False)

def get_student_profile(self):
student_profile = None
if hasattr(self, 'studentprofile'):
student_profile = self.studentprofile
return student_profile

def get_professor_profile(self):
professor_profile = None
if hasattr(self, 'professorprofile'):
professor_profile = self.professorprofile
return professor_profile

def get_executive_profile(self):
executive_profile = None
if hasattr(self, 'executiveprofile'):
executive_profile = self.executiveprofile
return executive_profile


In addition each profile user is_student, is_professor and is_executive have 
their own model in where I manage their own data:



class StudentProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, 
on_delete=models.CASCADE)

slug = models.SlugField(max_length=100,blank=True)
origin_education_school = models.CharField(max_length=128)
current_education_school = models.CharField(max_length=128)
extra_occupation = models.CharField(max_length=128)
class ProfessorProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, 
on_delete=models.CASCADE)
slug = models.SlugField(max_length=100,blank=True)

class ExecutiveProfile(models.Model):
user = 
models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
slug = models.SlugField(max_length=100,blank=True)


Is of this way that in my User model I override the save() method to denote 
that the usernamefield of an user which is created, to be equal in their 
value to the slug belonging to the profile user which will take that user (
StudentProfile, ProfessorProfile, ExecutiveProfile):



def save(self, *args, **kwargs):
user = super(User,self).save(*args,**kwargs)

# Creating an user with student, professor and executive profiles
if self.is_student and not 
StudentProfile.objects.filter(user=self).exists() \
and self.is_professor and not 
ProfessorProfile.objects.filter(user=self).exists() \
and self.is_executive and not 
ExecutiveProfile.objects.filter(user=self).exists():
student_profile = StudentProfile(user=self)
student_slug = self.username
student_profile.slug = student_slug

professor_profile = ProfessorProfile(user=self)
professor_slug = self.username
professor_profile.slug = professor_slug

executive_profile = ExecutiveProfile(user=self)
executive_slug = self.username
executive_profile.slug = executive_slug

student_profile.save()
professor_profile.save()
executive_profile.save()
# And so for all possibles profile combinations


To these three profiles which I have three forms in where their own fields 
are generated


class StudentProfileForm(forms.ModelForm):
class Meta:
model = StudentProfile
fields = ('origin_education_school', 'current_education_school',
'extra_occupation')
class ProfessorProfileForm(forms.ModelForm):
class Meta:
model = ProfessorProfile
fields = ('occupation',)
class ExecutiveProfileForm(forms.ModelForm):
class Meta:
model = ExecutiveProfile
fields = ('occupation', 'enterprise_name', 
'culturals_arthistic','ecological')



I access to view profile to user through of this URL:


url(r"^profile/(?P[\w\-]+)/$",
views.account_profiles__update_view,
name='profile'
),


In my function based view account_profiles__update_view() I am managing the 
request of the user, and creating the form instances (StudentProfileForm, 
ProfessorProfileForm, ExecutiveProfileForm) according to the profile to 
user (is_student, is_professor and is_executive)



@login_requireddef account_profiles__update_view(request, slug):
user = request.user
# user = get_object_or_404(User, username = slug)

# empty list
_forms = []
if user.is_student:
profile = user.get_student_profile()
_forms.append(forms.StudentProfileForm)
if user.is_professor:
profile = user.get_professor_profile()
_forms.append(forms.ProfessorProfileForm)
if user.is_executive:
profile = user.get_executive_profile()

Binding data to one o many forms from one view - BadHeaderError at - Header values can't contain newlines ()

2017-04-08 Thread Bernardo Garcia

I have the following forms to each user profile

class UserUpdateForm(forms.ModelForm):
class Meta:
widgets = {'gender':forms.RadioSelect,}
fields = ("username", "email", "is_student",   
"is_professor", "is_executive",)
model = get_user_model() #My model User

class StudentProfileForm(forms.ModelForm):
class Meta:
model = StudentProfile
fields = ('origin_education_school',current_education_school',
'extra_occupation')

class ProfessorProfileForm(forms.ModelForm):
class Meta:
model = ProfessorProfile
fields = ('occupation',)

class ExecutiveProfileForm(forms.ModelForm):
class Meta:
model = ExecutiveProfile
fields = ('occupation', 'enterprise_name', 
'culturals_arthistic','ecological')

I have an URL which call to my AccountProfilesView class based view which 
create an instance of the previous forms according to the user profile:

url(r"^profile/(?P[\w\-]+)/$",
views.AccountProfilesView.as_view(),
name='profile'
),


My AccountProfilesView  is this:

I this moment, from the AccountProfilesView class based view I am create 
the different instances of each one of these forms, according to the 
user profile, then, if an user have the is_student profile their related 
form will be generated, and so, of this way to is_professor  and 
is_executive profiles

If an user have the three profiles (is_student, is_professor,is_executive ) 
in one single form will be created or rendered the fields of the three 
forms associated to each user profile related.

class AccountProfilesView(LoginRequiredMixin, UpdateView):
# All users can access this view
model = get_user_model()
#success_url = reverse_lazy('dashboard')
template_name = 'accounts/profile_form.html'
fields = '__all__'

def get_context_data(self, **kwargs):
context = super(AccountProfilesView, 
self).get_context_data(**kwargs)
user = self.request.user

if not self.request.POST:
if user.is_student:
profile = user.get_student_profile()
context['userprofile'] = profile
context['form_student'] = forms.StudentProfileForm()
if user.is_professor:
profile = user.get_professor_profile()
context['userprofile'] = profile
context['form_professor'] = forms.ProfessorProfileForm()
print ("profesor form is", context['form_professor'])
if user.is_executive:
profile = user.get_executive_profile()
context['userprofile'] = profile
context['form_executive'] = forms.ExecutiveProfileForm()
return context

def post(self, request, *args, **kwargs):
self.object = self.get_object()
context = super(AccountProfilesView, self).post(request, *args, 
**kwargs)
user = self.request.user
# if self.request.method == 'POST':
if user.is_student:
context['form_student'] = forms.StudentProfileForm(
self.request.POST)
elif user.is_professor:
context['form_professor'] = forms.ProfessorProfileForm(
self.request.POST)
elif user.is_executive:
context['form_executive'] = forms.ExecutiveProfileForm(
self.request.POST)
return context

def form_valid(self, form):
context = self.get_context_data(form=form)
user = self.request.user
user = form.save()
if user.is_student:
student = context['form_student'].save(commit=False)
student.user = user
student.save()
if user.is_professor:
professor = context['form_professor'].save(commit=False)
professor.user = user
professor.save()
if user.is_executive:
executive = context['form_executive'].save(commit=False)
executive.user = user
executive.save()
return super(AccountProfilesView, self).form_valid(form)

def get_success_url(self):
return reverse('dashboard')

 And in my template, I have the following small logic:


{% csrf_token %}
{% if userprofile.user.is_student %}

My Student Profile data
{% bootstrap_form form_student %}
{% endif %}
 

{% if userprofile.user.is_professor %}
My Professor Profile data
{% bootstrap_form form_professor %}
{% endif %}

   

Accessing to objects of a dynamic way in django template

2016-12-04 Thread Bernardo Garcia


I have the following class based view in which I perform to queryset:

class PatientDetail(LoginRequiredMixin, DetailView): 

   model = PatientProfile 

   template_name = 'patient_detail.html' 

   context_object_name = 'patientdetail' 

   

   def get_context_data(self, **kwargs): 

   context=super(PatientDetail, self).get_context_data(**kwargs) 
   *queryset= 
RehabilitationSession.objects.filter(patient__slug=self.kwargs['slug']) 
*
* context.update({'patient_session_data': queryset,}) *
return context

When I acces the value of patient_session_data key sent, in my template:

{% extends "base.html" %} 

{% block content %} 

{{patient_session_data}} 
{% endblock content %}

I get this three QuerySet objects

, 
, ]>


I want access to specific attibute named upper_extremity of my 
RehabilitationSession model, then I make this:


{% for upperlimb in patient_session_data %} 

{{upperlimb.upper_extremity}} 

{%endfor%}

And I get this in my template:

Izquierda Izquierda Izquierda

This mean, three times the value, because my queryset return me three 
objects. This is logic.

For access to value of a separate way I make this in my template:

{{patient_session_data.0.upper_extremity}}

And I get:

Izquierda


*My goal*

I unknown the amount of querysets objects RehabilitationSession that will 
be returned by the queryset executed in my PatientDetail

 cbv, because the number is dynamic, may be any amount of objects returned.


I want read the value content of each patient_session_data upper_extremity and 
accord to the value make something in my template,

But I want read it of a dynamic way,without use {{
patient_session_data.<0-1-2-3>.upper_extremity}}


For example in a hypotetical case:


#if all objects returned have same value in upper_extremity 

{% if patient_session_data.upper_extremity == 'Izquierda' %} 

 

  Segmentos corporales a tratar

  Codo - mano - falange 

 

{%endif%}



I think that I have count the amount of objects and make with them some 
actions, because I don't have clear ... 


How to can I access of a individual way to the objects returned of a 
dynamic way without matter the objects number returned?

-- 
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/c17e25b2-cbce-4401-8065-9704054648e7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


WOrking with checkbox Multiple Select FIeld - Django Admin

2016-10-29 Thread Bernardo Garcia
HI, friends.

Someone know how to work with a field that allow perform a multiple 
selection in a field?, like a checkbox. In django admin,

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/670c3379-cea2-4819-91e8-5fbe804d1c88%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


How to read the json file of a dinamical way in relation to their size structure

2016-10-10 Thread Bernardo Garcia


I have the following JSON file named ProcessedMetrics.json which is 
necessary read for send their values to some template:


 {
  "paciente": {
"id": 1234,
"nombre": "Pablo Andrés Agudelo Marenco",
"sesion": {
  "id": 12345,
  "juego": [
{
  "nombre": "bonzo",
  "nivel": [
{
  "id": 1234,
  "nombre": "caida libre",
  "segmento": [
{
  "id": 12345,
  "nombre": "Hombro",
  "movimiento": [
{
  "id": 1234,
  "nombre": "flexion",
  "metricas": [
{
  "min": 12,
  "max": 34,
  "media": 23,
  "moda": 20
}
  ]
}
  ]
}
  ],
  "___léeme___": "El array 'iteraciones' contiene las vitorias o 
derrotas con el tiempo en segundos de cada iteración",
  "iteraciones": [
{
  "victoria": true,
  "tiempo": 120
},
{
  "victoria": false,
  "tiempo": 232
}
  ]
}
  ]
}
  ]
}
  }}



Through of the following class based view I am reading a JSON file:

class RehabilitationSessionDetail(LoginRequiredMixin,DetailView):
model = RehabilitationSession
template_name = 'rehabilitationsession_detail.html'

def get_context_data(self, **kwargs):
context=super(RehabilitationSessionDetail, 
self).get_context_data(**kwargs)
is_auth=False

user = self.request.user
if user.is_authenticated():
is_auth=True

with open('ProcessedMetrics.json') as data_file:
session_data=json.loads(data_file.read())

#Sending a data to template
   context.update({'is_auth':is_auth,
   'session_data':session_data
 })
   return context


In my template rehabilitationsession_detail.html I put my tag of this way:

{{session_data.paciente.sesion.juego}} 

Then I get the document json in my template:




In my template, I want get the dictionary(before json document) values of a 
separate way such as follow:










The idea is that without matter the nested levels of the json document I 
can get the values. 


Sometimes, the json document will have more identation levels in their 
structure and other times will be a json document more simple


I would that independently of the json document size (if this have more 
than one item in your arrays) will be possible read and get all the values.

I try accessing to the specific item from the RehabilitationSessionDetail view 
of this way:


segment = 
data["paciente"]["sesion"]["juego"][0]["nivel"][0]["segmento"][0]["nombre"]


And this works, but not always I will get the same json document structure.

In summary, How to can I get the values (nested and parents) of my json 
document for send them to the template?

I hope can be clear in my question. Any orientation is highly graceful



-- 
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/c5256c63-03e3-42ff-9e05-41b181292ee4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django Admin actions with select optgroup

2016-03-30 Thread Bernardo Garcia
When you talk about of optgroup you mean the choicegroup?
In affirmative case, this can be that you looking 
.. https://docs.djangoproject.com/en/1.9/ref/models/fields/#choices 

Also is possible that MultipleSelectField can be useful for you?
In affirmative case, this thread can be useful...
https://groups.google.com/forum/#!topic/django-users/yOo4B9NCfes

I don't kow if these resources be useful for you.
Anything I will be pending 


On Wednesday, March 30, 2016 at 1:17:58 PM UTC-5, Edgar Gabaldi wrote:
>
> Hi everybody,
>
> Someone know if is possible or have a way to change the default action 
> select by a select with optgroup?
>

 

-- 
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/f7b998ad-b861-4c30-a827-9c9a3567f1e0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Deploy static assets to heroku from local machine - can't open file 'manage.py': [Errno 2] No such file or directory

2016-03-30 Thread Bernardo Garcia


I am trying deploy my assets files to heroku and I get this output in my 
command line interface:

(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku run python 
manage.py collectstaticRunning python manage.py collectstatic on 
neurorehabilitation up, run.5168
python: can't open file 'manage.py': [Errno 2] No such file or directory
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ 



It's strange for me, due to I am currently in the directory/folder in which 
the manage.py file is located

I've applied chmod +x manage.py and try again and this is the output again:



(nrb_dev) ➜ neurorehabilitation_projects git:(master) ✗ chmod +x manage.py (
nrb_dev) ➜ neurorehabilitation_projects git:(master) ✗ heroku run ./manage.py 
collectstatic Running ./manage.py collectstatic on neurorehabilitation 
up, run.8892 bash: ./manage.py: No such file or directory (nrb_dev) ➜ 
neurorehabilitation_projects git:(master) 


When i execute the git push heroky master command without deplu my asset 
static files before  I get this

remote:  $ python manage.py collectstatic --noinput
remote:Traceback (most recent call last):
remote:  File "manage.py", line 10, in 
remote:execute_from_command_line(sys.argv)
remote:  File 
"/app/.heroku/python/lib/python3.4/site-packages/django/core/management/__init__.py",
 line 353, in execute_from_command_line
remote:utility.execute()
remote:  File 
"/app/.heroku/python/lib/python3.4/site-packages/django/core/management/__init__.py",
 line 345, in execute
remote:self.fetch_command(subcommand).run_from_argv(self.argv)
remote:  File 
"/app/.heroku/python/lib/python3.4/site-packages/django/core/management/base.py",
 line 348, in run_from_argv
remote:self.execute(*args, **cmd_options)
remote:  File 
"/app/.heroku/python/lib/python3.4/site-packages/django/core/management/base.py",
 line 399, in execute
remote:output = self.handle(*args, **options)
remote:  File 
"/app/.heroku/python/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py",
 line 176, in handle
remote:collected = self.collect()
remote:  File 
"/app/.heroku/python/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py",
 line 98, in collect
remote:for path, storage in finder.list(self.ignore_patterns):
remote:  File 
"/app/.heroku/python/lib/python3.4/site-packages/django/contrib/staticfiles/finders.py",
 line 112, in list
remote:for path in utils.get_files(storage, ignore_patterns):
remote:  File 
"/app/.heroku/python/lib/python3.4/site-packages/django/contrib/staticfiles/utils.py",
 line 28, in get_files
remote:directories, files = storage.listdir(location)
remote:  File 
"/app/.heroku/python/lib/python3.4/site-packages/django/core/files/storage.py", 
line 299, in listdir
remote:for entry in os.listdir(path):
remote:FileNotFoundError: [Errno 2] No such file or directory: 
'/app/neurorehabilitation/settings/static'


I cannot understand the reason by which my heroku toolbet cannot locate my 
manage.py file

Somebody what is the reason about it?

-- 
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/fdf9063f-4dad-4b5d-a511-b0502157731c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Deploy Django to Heroku - Push rejected

2016-03-26 Thread Bernardo Garcia


I am trying deploy my Django application to heroku and I get an error when 
I perform git push heroku master command


My structure directory is the following





And the content of requirements/production.txt is:

-r base.txt
gunicorn==19.4.5
dj-database-url==0.4.0


requirements/base.txt have this content:


Django==1.9.2
djangorestframework==3.3.2
Pillow==3.1.1
psycopg2==2.6.1
Markdown==2.6.5
django-filter==0.12.0
django-storages-redux==1.3
django-suit==0.2.16
django-boto==0.3.9
django-multiselectfield==0.1.3


The process that I am perform for deploy to my app to heroku is the 
following and the error is push rejected:


(uleague) ➜  pickapp git:(master) ✗ heroku create fuupbol --buildpack 
heroku/python
Creating fuupbol... done, stack is cedar-14
Setting buildpack to heroku/python... done
https://fuupbol.herokuapp.com/ | https://git.heroku.com/fuupbol.git
(uleague) ➜  pickapp git:(master) ✗ git remote -v
heroku  https://git.heroku.com/fuupbol.git (fetch)
heroku  https://git.heroku.com/fuupbol.git (push)
origin  https://bgarc...@bitbucket.org/bgarcial/pickapp.git (fetch)
origin  https://bgarc...@bitbucket.org/bgarcial/pickapp.git (push)
(uleague) ➜  pickapp git:(master) ✗ git push heroku master
Counting objects: 195, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (92/92), done.
Writing objects: 100% (195/195), 516.34 KiB | 0 bytes/s, done.
Total 195 (delta 93), reused 195 (delta 93)
remote: Compressing source files... done.
remote: Building source:
remote: 
remote: -> Using set buildpack heroku/python
remote: 
remote:  ! Push rejected, failed to detect set buildpack heroku/python
remote: More info: 
https://devcenter.heroku.com/articles/buildpacks#detection-failure
remote: 
remote: Verifying deploy
remote: 
remote: !   Push rejected to fuupbol.
remote: 
To https://git.heroku.com/fuupbol.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/fuupbol.git'
(uleague) ➜  pickapp git:(master) ✗


I follow the getting started tutorial for deploy in heroku web page 

 and 
in their samples, the requirements.txt and the settings.py were as a 
isolated files in the root project and not nested under folders as a 
settings/ folder or a requirements /folder

This have related for my error of push rejected ?



-- 
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/5d683621-9fb3-4ddc-8f5a-58297350b4f9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Deploy Django to Heroku - Push rejected

2016-03-20 Thread Bernardo Garcia
I am trying deploy my Django application to heroku and I get an error when 
I perform git push heroku master command

Do you know the reason which I get this error?


uleague) ➜ pickapp git:(master) ✗ git push heroku masterCounting objects: 195, 
done.Delta compression using up to 8 threads.Compressing objects: 100% (92/92), 
done.Writing objects: 100% (195/195), 516.34 KiB | 0 bytes/s, done.Total 195 
(delta 93), reused 195 (delta 93)
remote: Compressing source files... done.
remote: Building source:
remote: 
remote: 
remote: ! Push rejected, no Cedar-supported app detected
remote: HINT: This occurs when Heroku cannot detect the buildpack
remote: to use for this application automatically.
remote: See https://devcenter.heroku.com/a...
remote: 
remote: Verifying deploy...
remote: 
remote: !   Push rejected to shielded-crag-57385.
remote: To https://git.heroku.com/shielde...! [remote rejected] master -> 
master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/shielde...
(uleague) ➜ pickapp git:(master) ✗

I have the following structures directory:




I follow the getting started tutorial for deploy in heroku web page 

 and 
in their samples, the requirements.txt and the settings.py were as a 
isolated files in the root project and not nested under folders as a 
settings/ folder or a requirements /folder

This have related for my error of push rejected ?


-- 
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/37fec548-9274-4383-8a72-04f55f9e2ed6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: MultipleCharField

2016-03-08 Thread Bernardo Garcia
Hi RAfael.

I am using this app for multi select 
fields https://github.com/goinnn/django-multiselectfield
which perform a render the options like checkbox of multiple selection in 
the django admin forms

You should install it of this way

1. Download the tar.gz file from 
https://pypi.python.org/pypi/django-multiselectfield
2. Inside of your virtual environment execute pip install 

3. Specify 'multiselectfield' in the INSTALLED_APPS in settings.py

view this 
source 
http://stackoverflow.com/questions/27332850/django-multiselectfield-cant-install

When you run the Django Server, if you are using Django 1.9.2 you see this 
warning 

site-packages/multiselectfield/db/fields.py:45: RemovedInDjango110Warning: 
SubfieldBase has been deprecated. Use Field.from_db_value instead.
  return metaclass(cls.__name__, cls.__bases__, orig_vars)

THis warning is related with this, but I unknown how to fix for the context 
of multiselectfield package application.


Another alternatives for multiselects fields are:
https://github.com/PragmaticMates/django-clever-selects
https://github.com/theatlantic/django-select2-forms
https://github.com/kelvinwong-ca/django-select-multiple-field
https://github.com/digi604/django-smart-selects which I am also using it! 
this works models based in ManyToMany relationships.

I hope that these resource are useful for you.

Best Regards.



 
On Friday, March 4, 2016 at 3:38:05 PM UTC-5, Rafael Macêdo wrote:
>
> Sou iniciante em Django e gostaria de saber se há algum tipo de campo na 
> classe Model semelhante ao MultipleChoiceField da classe Form.
>
> Obrigado desde já.
>

-- 
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/5eeb00db-664b-4c60-90eb-f8f7f7997c7a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Handling fields with values that depend on a value from previous file

2016-03-02 Thread Bernardo Garcia


I want handling fields' values which depend on a value from another field


Currently I am working with django-smart-selects 
 but I have this problems 



Reading, in the issues and the web is possible that django-smart-selects have 
some problems related or similar to the mine. 



Do you know some application in Django whcih I can work for handling 
fields' values which depend on a value from another field ?


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/60ecf184-ab34-4537-acdf-2f1f40a1325b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: problem deploying two apps

2016-03-02 Thread Bernardo Garcia
Hi frocco

May be this post can ve useful for you, althought instead of uwsgi use 
gunicorn 
http://michal.karzynski.pl/blog/2013/10/29/serving-multiple-django-applications-with-nginx-gunicorn-supervisor/

On Tuesday, March 1, 2016 at 11:56:57 AM UTC-5, frocco wrote:
>
> Hi,
>
> I followed this
> https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/modwsgi/
>
> First app works fine, if I deploy the second app, the settings conflict 
> and images are not rendered.
>
> [code]
> Alias /static /var/www/django/track/static
>
> 
> Require all granted
> 
>
> 
> 
> Require all granted
> 
> 
>
>
> 
> Require all granted
> 
>
> WSGIDaemonProcess track 
> python-path=/var/www/django/track:/usr/lib/python2.7/site-packages
> WSGIProcessGroup track
> WSGIScriptAlias /track /var/www/django/track/track/wsgi.py 
> process-group=track
> [/code]
>
> [code]
> Alias /static /var/www/django/coffee/static
>
> 
> Require all granted
> 
>
> 
> 
> Require all granted
> 
> 
>
>
> 
> Require all granted
> 
>
> WSGIDaemonProcess coffee 
> python-path=/var/www/django/coffee:/usr/lib/python2.7/site-packages
> WSGIProcessGroup coffee
> WSGIScriptAlias /coffee /var/www/django/coffee/coffee/wsgi.py 
> process-group=coffee
>
>
> [/code]
>

-- 
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/bcb39068-2d4c-490f-bdcc-5eceb1e0ac5b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


django-smart-selects: ChainedManyToManyField value not selected after saving data via django admin

2016-03-02 Thread Bernardo Garcia


I am working with django-smart-selects 
 via django admin form. 
The idea that I have is try a model chaining or deployment of value fields 
accord to previous value in a previous separate field.


Accord to the first option value selected in the first field, I want that 
in the second field some values be deployed and which be of selection 
multiple. In fact, this idea I got it accomplished.


I have the following small level design approach for this:






The code that is related to the above design is this:

class AffectedSegment(models.Model):
SEGMENTO_ESCAPULA = 'ESCAPULA'
SEGMENTO_HOMBRO = 'HOMBRO'
SEGMENTO_CODO = 'CODO'
SEGMENTO_ANTEBRAZO = 'ANTEBRAZO'
SEGMENTO_CARPO_MUNECA = 'CARPO_MUNECA'
SEGMENTO_MANO = 'MANO'
SEGMENTO_CHOICES = (
(SEGMENTO_ESCAPULA, u'Escápula'),
(SEGMENTO_HOMBRO, u'Hombro'),
(SEGMENTO_CODO, u'Codo'),
(SEGMENTO_ANTEBRAZO, u'Antebrazo'),
(SEGMENTO_CARPO_MUNECA, u'Carpo/Muñeca'),
(SEGMENTO_MANO, u'Mano'),
)
affected_segment = models.CharField(
   max_length=12, 
   choices=SEGMENTO_CHOICES, 
   blank=False, verbose_name='Segmento afectado'
   )

class Meta:
verbose_name = 'Segmentos corporale'

def __str__(self):
return "%s" % self.affected_segment
class Movement(models.Model):
type = models.CharField(
  max_length=255,
  verbose_name='Tipo de movimiento'
  )
corporal_segment_associated = models.ManyToManyField(
  AffectedSegment, blank=False, 
  verbose_name='Segmento corporal asociado'
  )

class Meta:
verbose_name = 'Movimiento'

def __str__(self):
return "%s" % self.type
class RehabilitationSession(models.Model):
affected_segment = models.ManyToManyField(
  AffectedSegment,
  verbose_name='Segmento afectado'
  )
movement = ChainedManyToManyField(
  Movement, #chaining model
  chained_field = 'affected_segment',
  chained_model_field = 'corporal_segment_associated',
  verbose_name='Movimiento')



Until this section all this O.K.

*MY CHALLENGES*


*1. *When I save one movement (model Movement chained) which are related to 
affected segment (affected_segment in AffectedSegment model and 
ManyToManyField in RehabilitationSession model) , after I going to this row 
or rehabilitation sessions instance via admin and the movement that I 
select before is not selected, despite of that this is saved and I can 
explore via transitivity relationship the value inside my postgresql 
database.



In this video , I've been exploring the 
database records and showing the behavior of my form in which is denoted my 
inconvenient

I can see that this bug/error/issue or inconvenient was happen to 
others https://github.com/digi604/django-smart-selects/issues/112


*2.* Other inconvenient is that when I select more of than one affected 
segment, in the movements field. just are deployed the values related with 
the first affected segment selected and the movements associated to the 
second selected are not deployed ...

The explanation is the following accord to this picture:




When I select one second affected segment (segmento afectado field, *CODO* 
option 
in the red square number one), I want that the movements/exercises 
associated to these second affected segment that it's *CODO*


Currently, just are deployed the movements of Descenso,Elevación, 
Protracción y Retracción (options shown in the green square number two) and 
these are only or correspond to the first option of affected segment 
selected which is ESCÁPULA in the red square number one


In this video  I show you this in detail.


How I can do this I want?


In some sense, in the AffectedSegment model .. should be able to know the 
option (something seem to get_element_by_id in html?) is selected for know 
when one second option is selected and shown the movements of together 
options (affected segments selected)?


I hope that post a videos don't be a problem or inconvenient


Any support or orientation would be appreciated



-- 
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 

Re: API REST - Url's Serialized models don't work with the hostname of my production server - Django Rest Framework

2016-02-23 Thread Bernardo Garcia
Hi James. 
Thanks for your attention and the stackoverflow reference

I try setup the headers in my nginx configuration file but I don't get 
success

My /etc/nginx/sites-enabled/myproject file I had so:

server {
server_name yourdomainorip.com;
access_log off;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header X-Forwarded-Host $server_name
proxy_set_header X-Real-IP $remote_addr;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM 
NAV"';
}
}


According to the 
reference 
http://stackoverflow.com/questions/19669376/django-rest-framework-absolute-urls-with-nginx-always-return-127-0-0-1
 
my /etc/nginx/sites-enabled/myproject file I stayed so:

server {
server_name yourdomainorip.com;
access_log off;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM 
NAV"';
}
}

But, the result was a bad request (400) how to you can see here 
http://ec2-52-90-253-22.compute-1.amazonaws.com/ 

What is the order in which I should setup the headers?
Thanks
On Tuesday, February 23, 2016 at 4:51:16 PM UTC-5, James Schneider wrote:
>
>
>
> On Tue, Feb 23, 2016 at 6:03 AM, Bernardo Garcia <boti...@gmail.com 
> > wrote:
>
>> Hi everyone Djangonauts
>> :)
>>
>> Currently I am exposing a Django application (for the momento is just 
>> thier users schema) with Django Rest Framework and happen that each 
>> serialized model, in the url attribute, I have is the localhost machine 
>> address development and don't take the hostname of my production server 
>> machine which is located in amazon like as EC2 instance
>>
>>
>> In this picture can detailed it.
>>
>
> Nginx is proxying the end-users' request to http://127.0.0.1:8000, which 
> is where Gunicorn is running. Gunicorn has no idea that there is a proxy in 
> front of it, so it assumes that the request is being sent by the server 
> itself, to the server itself. Gunicorn then passes along the Host header to 
> Django/DRF, which in turn uses it to generate the URL's that you are 
> getting.
>
> You need to tell Nginx to send the correct headers to indicate to Gunicorn 
> that the connection is being proxied, and the correct address to use. See 
> this SO: 
>
>
> http://stackoverflow.com/questions/19669376/django-rest-framework-absolute-urls-with-nginx-always-return-127-0-0-1
>
> -James
>

-- 
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/740b268b-df39-4b2d-bd81-33217a154de0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: API REST - Url's Serialized models don't work with the hostname of my production server - Django Rest Framework

2016-02-23 Thread Bernardo Garcia
Felipe, give me a couple of minutes and I tell to you, but If you see my 
first post in this thread, the api links is related with the serializers.py 
file, in the urls.py files the router.register sentence and the views.py 
the ViewSet class

In this post   is detailed 
... 
http://stackoverflow.com/questions/35565749/api-rest-urls-serialized-models-dont-work-with-the-hostname-of-my-production
 
and in the djangorestframework tutorial explain how to 
doing http://www.django-rest-framework.org/tutorial/quickstart/

On Tuesday, February 23, 2016 at 12:39:49 PM UTC-5, Fellipe Henrique wrote:
>
> Sorry to reply your post, but.. how do you show all api link? there's any 
> settings for these? I asking because, when I try on my api, show me 404 
> page...
>
>
>
>
> T.·.F.·.A.·. S+F
> *Fellipe Henrique P. Soares*
>
> e-mail: > echo "lkrrovknFmsgor4ius" | perl -pe \ 
> 's/(.)/chr(ord($1)-2*3)/ge'
> *Fedora Ambassador: https://fedoraproject.org/wiki/User:Fellipeh 
> <https://fedoraproject.org/wiki/User:Fellipeh>*
> *Blog: *http:www.fellipeh.eti.br
> *GitHub: https://github.com/fellipeh <https://github.com/fellipeh>*
> *Twitter: @fh_bash*
>
> On Tue, Feb 23, 2016 at 12:42 PM, Bernardo Garcia <boti...@gmail.com 
> > wrote:
>
> Avraham, so yes, efectively ...
>
> This is my gunicorn_config.py
>
> command = '/opt/uleague/bin/gunicorn'
> pythonpath = '/opt/uleague/pickapp'
> bind = '127.0.0.1:8000'
> workers = 3
>
>
> I will should in the directive bind put the  internal ip address of my 
> machine?
> I have some doubts
>
>
>- The internal ip address of my machine is 172.31.60.141
>
>
> root@ip-172-31-60-141:/etc/nginx/sites-enabled# ifconfig 
> eth0  Link encap:Ethernet  HWaddr 12:73:40:a8:59:99  
>   inet addr:172.31.60.141  Bcast:172.31.63.255  Mask:255.255.240.0
>   inet6 addr: fe80::1073:40ff:fea8:5999/64 Scope:Link
>   UP BROADCAST RUNNING MULTICAST  MTU:9001  Metric:1
>   RX packets:220239 errors:0 dropped:0 overruns:0 frame:0
>   TX packets:76169 errors:0 dropped:0 overruns:0 carrier:0
>   collisions:0 txqueuelen:1000 
>   RX bytes:238957069 (238.9 MB)  TX bytes:13656430 (13.6 MB)
>
> loLink encap:Local Loopback  
>   inet addr:127.0.0.1  Mask:255.0.0.0
>   inet6 addr: ::1/128 Scope:Host
>   UP LOOPBACK RUNNING  MTU:65536  Metric:1
>   RX packets:53064 errors:0 dropped:0 overruns:0 frame:0
>   TX packets:53064 errors:0 dropped:0 overruns:0 carrier:0
>   collisions:0 txqueuelen:0 
>   RX bytes:16846573 (16.8 MB)  TX bytes:16846573 (16.8 MB)
>
> root@ip-172-31-60-141:/etc/nginx/sites-enabled# 
>
> But in my dashboard console, the dns public of my ec2 instance is:
> ec2-52-90-253-22.compute-1.amazonaws.com, in fact, you can copy this url 
> in a browser...
>
> I don't know that value of address put in my gunicorn_config.py in the 
> directive bind.
> I put the internal ip address but does not work my server deployment
>
> And my nginx configuration is the following:
>
> /etc/nginx/sites-enabled/myproject , in which I unknown if in the 
> server_name and proxy_pass directives I should fix some values too..
> server {
> *server_name yourdomainorip.com <http://yourdomainorip.com>;*
> access_log off;
> location / {
> *proxy_pass http://127.0.0.1:8000 <http://127.0.0.1:8000>;*
> proxy_set_header X-Forwarded-Host $server_name;
> proxy_set_header X-Real-IP $remote_addr;
> add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM 
> NAV"';
> }
> }
>
>  
>
>
>
>
>
> On Tuesday, February 23, 2016 at 9:37:50 AM UTC-5, Avraham Serour wrote:
>
> are you using a config file for gunicorn? in the example it tells to use:
>
> bind = '127.0.0.1:8001'
>
> are you binding to 127.0.0.1 ?
>
> On Tue, Feb 23, 2016 at 4:33 PM, Bernardo Garcia <boti...@gmail.com> 
> wrote:
>
> Hi Mr. Avraham Serour thanks for the attention
>
> In my amazon ec2 production server I am running my Django Application 
> using nginx, and gunicorn accord to this tutorial 
> https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-django-with-postgres-nginx-and-gunicorn
>
> python manage.py runserver is used just in my local development machine
>
> On Tuesday, February 23, 2016 at 9:25:36 AM UTC-5, Avraham Serour wrote:
>
> are you running django using manage.py runserver?
>
>
> On Tue, Feb 23, 2016 at 4:03 PM, Bernardo Garcia <boti...@gmail.com> 
> wrote:
>
> Hi everyone Djangonauts
> :)
>
> Currently I am expos

Re: API REST - Url's Serialized models don't work with the hostname of my production server - Django Rest Framework

2016-02-23 Thread Bernardo Garcia
Avraham, so yes, efectively ...

This is my gunicorn_config.py

command = '/opt/uleague/bin/gunicorn'
pythonpath = '/opt/uleague/pickapp'
bind = '127.0.0.1:8000'
workers = 3


I will should in the directive bind put the  internal ip address of my 
machine?
I have some doubts


   - The internal ip address of my machine is 172.31.60.141
   

root@ip-172-31-60-141:/etc/nginx/sites-enabled# ifconfig 
eth0  Link encap:Ethernet  HWaddr 12:73:40:a8:59:99  
  inet addr:172.31.60.141  Bcast:172.31.63.255  Mask:255.255.240.0
  inet6 addr: fe80::1073:40ff:fea8:5999/64 Scope:Link
  UP BROADCAST RUNNING MULTICAST  MTU:9001  Metric:1
  RX packets:220239 errors:0 dropped:0 overruns:0 frame:0
  TX packets:76169 errors:0 dropped:0 overruns:0 carrier:0
  collisions:0 txqueuelen:1000 
  RX bytes:238957069 (238.9 MB)  TX bytes:13656430 (13.6 MB)

loLink encap:Local Loopback  
  inet addr:127.0.0.1  Mask:255.0.0.0
  inet6 addr: ::1/128 Scope:Host
  UP LOOPBACK RUNNING  MTU:65536  Metric:1
  RX packets:53064 errors:0 dropped:0 overruns:0 frame:0
  TX packets:53064 errors:0 dropped:0 overruns:0 carrier:0
  collisions:0 txqueuelen:0 
  RX bytes:16846573 (16.8 MB)  TX bytes:16846573 (16.8 MB)

root@ip-172-31-60-141:/etc/nginx/sites-enabled# 

But in my dashboard console, the dns public of my ec2 instance is:
ec2-52-90-253-22.compute-1.amazonaws.com, in fact, you can copy this url in 
a browser...

I don't know that value of address put in my gunicorn_config.py in the 
directive bind.
I put the internal ip address but does not work my server deployment

And my nginx configuration is the following:

/etc/nginx/sites-enabled/myproject , in which I unknown if in the 
server_name and proxy_pass directives I should fix some values too..
server {
*server_name yourdomainorip.com;*
access_log off;
location / {
*proxy_pass http://127.0.0.1:8000;*
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM 
NAV"';
}
}

 





On Tuesday, February 23, 2016 at 9:37:50 AM UTC-5, Avraham Serour wrote:
>
> are you using a config file for gunicorn? in the example it tells to use:
>
> bind = '127.0.0.1:8001'
>
> are you binding to 127.0.0.1 ?
>
> On Tue, Feb 23, 2016 at 4:33 PM, Bernardo Garcia <boti...@gmail.com 
> > wrote:
>
>> Hi Mr. Avraham Serour thanks for the attention
>>
>> In my amazon ec2 production server I am running my Django Application 
>> using nginx, and gunicorn accord to this tutorial 
>> https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-django-with-postgres-nginx-and-gunicorn
>>
>> python manage.py runserver is used just in my local development machine
>>
>> On Tuesday, February 23, 2016 at 9:25:36 AM UTC-5, Avraham Serour wrote:
>>>
>>> are you running django using manage.py runserver?
>>>
>>>
>>> On Tue, Feb 23, 2016 at 4:03 PM, Bernardo Garcia <boti...@gmail.com> 
>>> wrote:
>>>
>>>> Hi everyone Djangonauts
>>>> :)
>>>>
>>>> Currently I am exposing a Django application (for the momento is just 
>>>> thier users schema) with Django Rest Framework and happen that each 
>>>> serialized model, in the url attribute, I have is the localhost machine 
>>>> address development and don't take the hostname of my production server 
>>>> machine which is located in amazon like as EC2 instance
>>>>
>>>>
>>>> In this picture can detailed it.
>>>>
>>>>
>>>> <http://i.stack.imgur.com/bDUfR.png>
>>>>
>>>>
>>>>
>>>> How to make for the url of each model that I've serialized take the 
>>>> hostname of the production machine in which the application is deployed? 
>>>> In 
>>>> this case, an amazon ec2 instance ...
>>>>
>>>>
>>>> These are my serialized models userprofiles/serializers.py 
>>>>
>>>>
>>>> from django.contrib.auth.models import Groupfrom .models import User, 
>>>> PlayerProfile, CoachProfile, ViewerProfilefrom rest_framework import 
>>>> serializers
>>>> # Serializers define the API representation# Exponse the model and their 
>>>> fieldsclass UserSerializer(serializers.HyperlinkedModelSerializer):
>>>> class Meta:
>>>> model = User
>>>> fields = ('url','id', 'username', 
>>>> 'password','first_name','last_name','e

Re: API REST - Url's Serialized models don't work with the hostname of my production server - Django Rest Framework

2016-02-23 Thread Bernardo Garcia
Hi Mr. Avraham Serour thanks for the attention

In my amazon ec2 production server I am running my Django Application using 
nginx, and gunicorn accord to this 
tutorial 
https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-django-with-postgres-nginx-and-gunicorn

python manage.py runserver is used just in my local development machine

On Tuesday, February 23, 2016 at 9:25:36 AM UTC-5, Avraham Serour wrote:
>
> are you running django using manage.py runserver?
>
>
> On Tue, Feb 23, 2016 at 4:03 PM, Bernardo Garcia <boti...@gmail.com 
> > wrote:
>
>> Hi everyone Djangonauts
>> :)
>>
>> Currently I am exposing a Django application (for the momento is just 
>> thier users schema) with Django Rest Framework and happen that each 
>> serialized model, in the url attribute, I have is the localhost machine 
>> address development and don't take the hostname of my production server 
>> machine which is located in amazon like as EC2 instance
>>
>>
>> In this picture can detailed it.
>>
>>
>> <http://i.stack.imgur.com/bDUfR.png>
>>
>>
>>
>> How to make for the url of each model that I've serialized take the 
>> hostname of the production machine in which the application is deployed? In 
>> this case, an amazon ec2 instance ...
>>
>>
>> These are my serialized models userprofiles/serializers.py 
>>
>>
>> from django.contrib.auth.models import Groupfrom .models import User, 
>> PlayerProfile, CoachProfile, ViewerProfilefrom rest_framework import 
>> serializers
>> # Serializers define the API representation# Exponse the model and their 
>> fieldsclass UserSerializer(serializers.HyperlinkedModelSerializer):
>> class Meta:
>> model = User
>> fields = ('url','id', 'username', 
>> 'password','first_name','last_name','email','is_active',
>>   
>> 'is_staff','is_superuser','last_login','date_joined','is_player','is_coach',
>>   'is_viewer','photo',)
>> class GroupSerializer(serializers.HyperlinkedModelSerializer):
>> class Meta:
>> model = Group
>> fields = ('url', 'name')
>>
>> class PlayerProfileSerializer(serializers.HyperlinkedModelSerializer):
>> class Meta:
>> model = PlayerProfile
>> fields = ('url', 'user','full_name','position',)
>> class CoachProfileSerializer(serializers.HyperlinkedModelSerializer):
>> class Meta:
>> model = CoachProfile
>> fields = ('url', 'user','full_name',)
>> class ViewerProfileSerializer(serializers.HyperlinkedModelSerializer):
>> class Meta:
>> model = ViewerProfile
>> fields = ('url', 'user','full_name','specialty')
>>
>>
>>
>> This is my urls.py global file (not belont to userprofiles application 
>> that contain all the serialized models.)
>>
>>
>> from django.conf.urls import url, includefrom django.contrib import admin
>> from .views import home, home_files
>> from rest_framework import routersfrom userprofiles import views
>> # Router provide an easy way of automatically determining the URL conf
>> router = routers.DefaultRouter()
>> router.register(r'users', views.UserViewSet)
>> router.register(r'groups', views.GroupViewSet)
>> router.register(r'players', views.PlayerProfileViewSet)
>> router.register(r'coachs', views.CoachProfileViewSet)
>> router.register(r'views', views.ViewerProfileViewSet)
>>
>>
>> urlpatterns = [
>> url(r'^admin/', admin.site.urls),
>> url(r'^$', home, name='home'),
>>
>> url(r'^(?P(robots.txt)|(humans.txt))$',
>> home_files, name='home-files'),
>>
>> # Wire up our API using automatic URL routing.
>> url(r'^api/v1/', include(router.urls)),
>>
>> # If you're intending to use the browsable API you'll probably also want 
>> to add REST framework's
>> # login and logout views.
>> url(r'^api-auth/', include('rest_framework.urls', 
>> namespace='rest_framework'))] 
>>
>>
>>
>> And this is my userprofiles/views.py file in where I have expose the 
>> models serializeds
>>
>>
>> from django.shortcuts import renderfrom django.contrib.auth.models import 
>> Groupfrom .models import User, PlayerProfile, CoachProfile, ViewerProfile
>> from rest_framework import viewsetsfrom .serializers import UserSerializer, 
>> GroupSerializer, PlayerProfileSerializer, CoachProfileSerializer, 
>> ViewerProfileSerializer
>> # Create your views here.
>&

API REST - Url's Serialized models don't work with the hostname of my production server - Django Rest Framework

2016-02-23 Thread Bernardo Garcia
Hi everyone Djangonauts
:)

Currently I am exposing a Django application (for the momento is just thier 
users schema) with Django Rest Framework and happen that each serialized 
model, in the url attribute, I have is the localhost machine address 
development and don't take the hostname of my production server machine 
which is located in amazon like as EC2 instance


In this picture can detailed it.






How to make for the url of each model that I've serialized take the 
hostname of the production machine in which the application is deployed? In 
this case, an amazon ec2 instance ...


These are my serialized models userprofiles/serializers.py 


from django.contrib.auth.models import Groupfrom .models import User, 
PlayerProfile, CoachProfile, ViewerProfilefrom rest_framework import serializers
# Serializers define the API representation# Exponse the model and their 
fieldsclass UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url','id', 'username', 
'password','first_name','last_name','email','is_active',
  
'is_staff','is_superuser','last_login','date_joined','is_player','is_coach',
  'is_viewer','photo',)
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')

class PlayerProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = PlayerProfile
fields = ('url', 'user','full_name','position',)
class CoachProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = CoachProfile
fields = ('url', 'user','full_name',)
class ViewerProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ViewerProfile
fields = ('url', 'user','full_name','specialty')



This is my urls.py global file (not belont to userprofiles application that 
contain all the serialized models.)


from django.conf.urls import url, includefrom django.contrib import admin
from .views import home, home_files
from rest_framework import routersfrom userprofiles import views
# Router provide an easy way of automatically determining the URL conf
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'players', views.PlayerProfileViewSet)
router.register(r'coachs', views.CoachProfileViewSet)
router.register(r'views', views.ViewerProfileViewSet)


urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', home, name='home'),

url(r'^(?P(robots.txt)|(humans.txt))$',
home_files, name='home-files'),

# Wire up our API using automatic URL routing.
url(r'^api/v1/', include(router.urls)),

# If you're intending to use the browsable API you'll probably also want to 
add REST framework's
# login and logout views.
url(r'^api-auth/', include('rest_framework.urls', 
namespace='rest_framework'))] 



And this is my userprofiles/views.py file in where I have expose the models 
serializeds


from django.shortcuts import renderfrom django.contrib.auth.models import 
Groupfrom .models import User, PlayerProfile, CoachProfile, ViewerProfile
from rest_framework import viewsetsfrom .serializers import UserSerializer, 
GroupSerializer, PlayerProfileSerializer, CoachProfileSerializer, 
ViewerProfileSerializer
# Create your views here.
# Viewsets define the behavior of the viewclass 
UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
class PlayerProfileViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows players to be viewed or edited.
"""
queryset = PlayerProfile.objects.all()
serializer_class = PlayerProfileSerializer
class CoachProfileViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows coachs to be viewed or edited.
"""
queryset = CoachProfile.objects.all()
serializer_class = CoachProfileSerializer
class ViewerProfileViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows viewers to be viewed or edited.
"""
queryset = ViewerProfile.objects.all()
serializer_class = ViewerProfileSerializer


Any orientation or support about it, I will be grateful :)

-- 
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 

Re: Amazon + Django each 12 hours appears that [Errno 5] Input/output error

2016-01-07 Thread Bernardo Garcia
Hi, luisza14

You have the reason, I had my project in DEBUG=True in production, and the 
main problem was a print sentence in some of my CBV's in the code in 
production
Here, recently I can write how to fix 
this 
http://stackoverflow.com/questions/34643170/amazon-django-each-12-hours-appears-that-errno-5-input-output-error/34667148#34667148
using also the reference that you provide me.

Thanks so much
:)

On Thursday, January 7, 2016 at 11:07:44 AM UTC-5, luisza14 wrote:
>
> Are you deploy your EC2 django instance in debug mode ? 
>
> For me this the reference for deploy 
> http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/
> .
>
>
> 2016-01-07 9:48 GMT-06:00 Bernardo Garcia <boti...@gmail.com 
> >:
>
>> This is my error, which again I get despite that yesterday was solved 
>> restarting my server
>>
>>
>> <https://lh3.googleusercontent.com/-Z-at9G4Jl9E/Vo6IjK9AB1I/DII/1n93yoVQm08/s1600/ec2.png>
>>
>> This error did reference to some function of my application
>>
>>
>> Environment:
>> Request Method: GETRequest URL: http://localhost:8000/accounts/profile/
>> Django Version: 1.9Python Version: 3.4.3Installed 
>> Applications:['django.contrib.admin',
>>  'django.contrib.auth',
>>  'django.contrib.contenttypes',
>>  'django.contrib.sessions',
>>  'django.contrib.messages',
>>  'django.contrib.staticfiles',
>>  'crispy_forms',
>>  'django_extensions',
>>  'storages',
>>  'userprofile']Installed 
>> Middleware:['django.middleware.security.SecurityMiddleware',
>>  'django.contrib.sessions.middleware.SessionMiddleware',
>>  'django.middleware.common.CommonMiddleware',
>>  'django.middleware.csrf.CsrfViewMiddleware',
>>  'django.contrib.auth.middleware.AuthenticationMiddleware',
>>  'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
>>  'django.contrib.messages.middleware.MessageMiddleware',
>>  'django.middleware.clickjacking.XFrameOptionsMiddleware']
>>
>>
>> Traceback:
>> File 
>> "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/core/handlers/base.py"
>>  in get_response
>>   149. response = 
>> self.process_exception_by_middleware(e, request)
>> File 
>> "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/core/handlers/base.py"
>>  in get_response
>>   147. response = wrapped_callback(request, 
>> *callback_args, **callback_kwargs)
>> File 
>> "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/views/generic/base.py"
>>  in view
>>   68. return self.dispatch(request, *args, **kwargs)
>> File 
>> "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/utils/decorators.py"
>>  in _wrapper
>>   67. return bound_func(*args, **kwargs)
>> File 
>> "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/contrib/auth/decorators.py"
>>  in _wrapped_view
>>   23. return view_func(request, *args, **kwargs)
>> File 
>> "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/utils/decorators.py"
>>  in bound_func
>>   63. return func.__get__(self, type(self))(*args2, 
>> **kwargs2)
>> File 
>> "/home/ubuntu/workspace/neurorehabilitation-system/userprofile/mixins.py" in 
>> dispatch
>>   7. return super(LoginRequiredMixin, self).dispatch(request, *args, 
>> **kwargs)
>> File 
>> "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/views/generic/base.py"
>>  in dispatch
>>   88. return handler(request, *args, **kwargs)
>> File 
>> "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/views/generic/base.py"
>>  in get
>>   157. context = self.get_context_data(**kwargs)
>> File 
>> "/home/ubuntu/workspace/neurorehabilitation-system/userprofile/views.py" in 
>> get_context_data
>>   50. print (user.is_physiotherapist)
>> Exception Type: OSError at /accounts/profile/Exception Value: [Errno 5] 
>> Input/output error
>>
>> At the end in the line 50 is referenced a get_context_data() function 
>> which is inside of a class based view that inherit of TemplateView CBV
>>
>> but in my console the server require restart and when I did this, the 
>> error was solved of a magic way ..
>>
>>
>> In addition I had this error yesterday, I restart my 

Re: Amazon + Django each 12 hours appears that [Errno 5] Input/output error

2016-01-07 Thread Bernardo Garcia
This is my error, which again I get despite that yesterday was solved 
restarting my server

<https://lh3.googleusercontent.com/-Z-at9G4Jl9E/Vo6IjK9AB1I/DII/1n93yoVQm08/s1600/ec2.png>

This error did reference to some function of my application


Environment:
Request Method: GETRequest URL: http://localhost:8000/accounts/profile/
Django Version: 1.9Python Version: 3.4.3Installed 
Applications:['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'crispy_forms',
 'django_extensions',
 'storages',
 'userprofile']Installed 
Middleware:['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Traceback:
File 
"/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/core/handlers/base.py"
 in get_response
  149. response = self.process_exception_by_middleware(e, 
request)
File 
"/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/core/handlers/base.py"
 in get_response
  147. response = wrapped_callback(request, *callback_args, 
**callback_kwargs)
File 
"/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/views/generic/base.py"
 in view
  68. return self.dispatch(request, *args, **kwargs)
File 
"/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/utils/decorators.py"
 in _wrapper
  67. return bound_func(*args, **kwargs)
File 
"/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/contrib/auth/decorators.py"
 in _wrapped_view
  23. return view_func(request, *args, **kwargs)
File 
"/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/utils/decorators.py"
 in bound_func
  63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/ubuntu/workspace/neurorehabilitation-system/userprofile/mixins.py" 
in dispatch
  7. return super(LoginRequiredMixin, self).dispatch(request, *args, 
**kwargs)
File 
"/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/views/generic/base.py"
 in dispatch
  88. return handler(request, *args, **kwargs)
File 
"/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/views/generic/base.py"
 in get
  157. context = self.get_context_data(**kwargs)
File "/home/ubuntu/workspace/neurorehabilitation-system/userprofile/views.py" 
in get_context_data
  50. print (user.is_physiotherapist)
Exception Type: OSError at /accounts/profile/Exception Value: [Errno 5] 
Input/output error

At the end in the line 50 is referenced a get_context_data() function which 
is inside of a class based view that inherit of TemplateView CBV

but in my console the server require restart and when I did this, the error 
was solved of a magic way ..


In addition I had this error yesterday, I restart my server, and today I 
have again the error.

There is some problem with EC2 infraestructure with Django (I don't think 
so) or the problem is more for my application side?

I don't think so that the function get_context_data() of my application be 
the problem ...

On Wednesday, January 6, 2016 at 4:55:57 PM UTC-5, Bernardo Garcia wrote:
>
>
>
> I recently setup and deploy an Amazon EC2 instance for deploy my django 
> project.
>
> I  was interacting with my application via browser when I get this error 
> in the browser:
>
>
> errno 5 input/output error django 
>
>
> This error did reference to some function of my application, but in my 
> console the server require restart and when I did this, the error was 
> solved of a magic way ..
>
>
> I've search this error and I found this ticket reported 
> https://code.djangoproject.com/ticket/23284
>
>
> This report is very similar to my error ...
>
> Although I don't know if this error back inside 12 hours, I restart my 
> server and this was solved and now all it's work O.K.
>
>
>
> When one bug is declared as invalid in Django 
> <https://code.djangoproject.com/ticket/23284>
>
> What does it mean? 
>
>
> There is some problem with EC2 infraestructure with Django (I don't think 
> so) or the problem is more for my application side?
>
>
> Thanks
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe fr

Re: Working with Django signals

2016-01-06 Thread Bernardo Garcia
=models.CASCADE)
#active = models.BooleanField(default=True)
name = models.CharField(max_length=64)
# Enter the username as slug field@receiver(post_save, sender = 
settings.AUTH_USER_MODEL)def post_save_user(sender, instance, **kwargs):
slug = slugify(instance.username)
User.objects.filter(pk=instance.pk).update(slug=slug)



Of this way, is possible create an user which have all the combinations 
possible (medical, physiotherapist, patient)

Thanks for the recommendations :)

On Thursday, December 31, 2015 at 12:14:06 PM UTC-5, luisza14 wrote:
>
> I suggest you to change the user creation form to set the three attributes 
> that you need (Is medical, is physuitherapist, is patient), so in the first 
> form (when you create the user) you will have usernarme, password, 
> Is_medical, is_physuitherapist, is_patient.
>
> Take a look 
>
>- 
>
> https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.forms.UserCreationForm
>- 
>
> https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-the-existing-user-model
>- 
>
> https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model
>
> Or extends admin class in save_model function.
>
> 2015-12-30 17:14 GMT-06:00 Bernardo Garcia <boti...@gmail.com 
> >:
>
> I have a custom users schema in Django for work with roles or users type, 
> creating an application named userprofile which will be or will setup my 
> custom user model.
>
> In my settings.py I have the following configuration:
>
> INSTALLED_APPS = [
> ...
> 'userprofile',]#Custom model Users
> AUTH_USER_MODEL = 'userprofile.User'
>
>
> I customize my User class (userprofile/models.py) that inherit of the 
> AbstractUser class for add some fields to my User model due to my 
> requirements demanded me.
>
> I also create these another models for roles/profile users (MedicalProfile, 
> PatientProfile, PhysiotherapistProfile) with their own fields or 
> attributes
>
>
> In addition MedicalProfile, PatientProfile, PhysiotherapistProfile have a 
> OneToOneField relationship with my custom model/class User so:
>
>
> from __future__ import unicode_literals
> from django.conf import settingsfrom django.contrib.auth.models import 
> AbstractUserfrom django.db import models
> #from django.contrib.auth import get_user_model
>
> from django.dispatch import receiverfrom django.db.models.signals import 
> post_save
>
> # Extending Django's default User# 
> https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-django-s-default-user#
>  We inherit from AbstractUser class to add some fields/attibutes to our user 
> model# 
> https://github.com/django/django/blob/master/django/contrib/auth/models.py#L297#
>  Differentes between AbstractUser and AbstractBaseUser# 
> http://stackoverflow.com/questions/21514354/difference-between-abstractuser-and-abstractbaseuser-in-djangoclass
>  User(AbstractUser):
> is_medical = models.BooleanField(default=False)
> is_physiotherapist = models.BooleanField(default=False)
> is_patient = models.BooleanField(default=False)
> slug = models.SlugField(max_length=100, blank=True)
> photo = models.ImageField(upload_to='avatars', null = True, blank = True)
>
>
> # We get the profiles user according with their type
> def get_medical_profile(self):
> medical_profile = None
> if hasattr(self, 'medicalprofile'):
> medical_profile=self.medicalprofile
> return medical_profile
>
> def get_patient_profile(self):
> patient_profile = None
> if hasattr(self, 'patientprofile'):
> patient_profile = self.patientprofile
> return patient_profile
>
> def get_physiotherapist_profile(self):
> physiotherapist_profile = None
> if hasattr(self, 'physiotherapistprofile'):
> physiotherapist_profile = self.physiotherapistprofile
> return physiotherapist_profile
>
> # We redefine the attributes (create db_table attribute) in class Meta to 
> say to Django
> # that users will save in the same table that the Django default user 
> model
> # 
> https://github.com/django/django/blob/master/django/contrib/auth/models.py#L343
> class Meta:
>
> db_table = 'auth_user'
> class MedicalProfile(models.Model):
> user = models.OneToOneField(settings.AUTH_USER_MODEL, 
> on_delete=models.CASCADE)
> #active = models.BooleanField(default=True)
> name = models.CharField(max_length=64)
>
> class PatientProfile(models.Model):
> user = models.OneToOneField(settings.AUTH_USER_MODEL, 
> on_delete=models.C

Amazon + Django each 12 hours appears that [Errno 5] Input/output error

2016-01-06 Thread Bernardo Garcia




I recently setup and deploy an Amazon EC2 instance for deploy my django 
project.

I  was interacting with my application via browser when I get this error in 
the browser:


errno 5 input/output error django 


This error did reference to some function of my application, but in my 
console the server require restart and when I did this, the error was 
solved of a magic way ..


I've search this error and I found this ticket 
reported https://code.djangoproject.com/ticket/23284


This report is very similar to my error ...

Although I don't know if this error back inside 12 hours, I restart my 
server and this was solved and now all it's work O.K.



When one bug is declared as invalid in Django 


What does it mean? 


There is some problem with EC2 infraestructure with Django (I don't think 
so) or the problem is more for my application side?


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/69701d06-2bb3-439f-b2bb-81ff67a21f43%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Working with Django signals

2015-12-30 Thread Bernardo Garcia


I have a custom users schema in Django for work with roles or users type, 
creating an application named userprofile which will be or will setup my 
custom user model.

In my settings.py I have the following configuration:

INSTALLED_APPS = [
...
'userprofile',]#Custom model Users
AUTH_USER_MODEL = 'userprofile.User'


I customize my User class (userprofile/models.py) that inherit of the 
AbstractUser class for add some fields to my User model due to my 
requirements demanded me.

I also create these another models for roles/profile users (MedicalProfile, 
PatientProfile, PhysiotherapistProfile) with their own fields or attributes


In addition MedicalProfile, PatientProfile, PhysiotherapistProfile have a 
OneToOneField relationship with my custom model/class User so:


from __future__ import unicode_literals
from django.conf import settingsfrom django.contrib.auth.models import 
AbstractUserfrom django.db import models
#from django.contrib.auth import get_user_model

from django.dispatch import receiverfrom django.db.models.signals import 
post_save

# Extending Django's default User# 
https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-django-s-default-user#
 We inherit from AbstractUser class to add some fields/attibutes to our user 
model# 
https://github.com/django/django/blob/master/django/contrib/auth/models.py#L297#
 Differentes between AbstractUser and AbstractBaseUser# 
http://stackoverflow.com/questions/21514354/difference-between-abstractuser-and-abstractbaseuser-in-djangoclass
 User(AbstractUser):
is_medical = models.BooleanField(default=False)
is_physiotherapist = models.BooleanField(default=False)
is_patient = models.BooleanField(default=False)
slug = models.SlugField(max_length=100, blank=True)
photo = models.ImageField(upload_to='avatars', null = True, blank = True)


# We get the profiles user according with their type
def get_medical_profile(self):
medical_profile = None
if hasattr(self, 'medicalprofile'):
medical_profile=self.medicalprofile
return medical_profile

def get_patient_profile(self):
patient_profile = None
if hasattr(self, 'patientprofile'):
patient_profile = self.patientprofile
return patient_profile

def get_physiotherapist_profile(self):
physiotherapist_profile = None
if hasattr(self, 'physiotherapistprofile'):
physiotherapist_profile = self.physiotherapistprofile
return physiotherapist_profile

# We redefine the attributes (create db_table attribute) in class Meta to 
say to Django
# that users will save in the same table that the Django default user model
# 
https://github.com/django/django/blob/master/django/contrib/auth/models.py#L343
class Meta:

db_table = 'auth_user'
class MedicalProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, 
on_delete=models.CASCADE)
#active = models.BooleanField(default=True)
name = models.CharField(max_length=64)

class PatientProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, 
on_delete=models.CASCADE)
#active = models.BooleanField(default=True)
name = models.CharField(max_length=64)

class PhysiotherapistProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, 
on_delete=models.CASCADE)
#active = models.BooleanField(default=True)
name = models.CharField(max_length=64)

"""
So we’re defined a signal for the User model, that is triggered every time a 
User instance is saved

The arguments used in the create_profile_for_new_user  are:
   sender: the User model class
   created: a boolean indicating if a new User has been created
   instance: the User instance being saved
"""@receiver(post_save, sender=settings.AUTH_USER_MODEL)#def 
create_profile_for_new_user(sender, instance, created, **kwargs):def 
create_profile_for_new_user(sender, instance, created, **kwargs):
user = instance
# - Begin debug--
import ipdb
#ipdb.set_trace()
#
if created:
#ipdb.set_trace()
if user.is_medical:
ipdb.set_trace()
profile=MedicalProfile(user=instance)
profile.save()
"""
This signal checks if a new instance of the User model has been created,
and if true, it creates a Profile instance with using the new user instance.
"""


*My Question*

I want to focus my question in relation about of the post_save signal 
operation, this mean in the create_profile_for_new_user() method:


@receiver(post_save, sender=settings.AUTH_USER_MODEL)def 
create_profile_for_new_user(sender, instance, created, **kwargs):
user = instance
# - Begin debug--
import ipdb
#
if created:
if user.is_medical:
ipdb.set_trace()