New model_mommy release + Deprecation Warning

2019-10-22 Thread Bernardo Fontes
Hi to all Django users,

Maybe a few people from the group use model_mommy lib to help with your
tests fixtures. As one of the maintainers of the project, I'm here to
announce its latest and final release 2.0.0 because the lib is now called
*model_bakery*.

All the information to help you to migrate your project from model_mommy to
model_bakery and the reasons behind this renaming can be found here:
https://model-mommy.readthedocs.io/en/latest/

Thanks,

-- 
Bernardo Fontes
http://berinfontes.com
http://pessoas.cc
Skype: bernardoxhc
+55 11 98398 2378

-- 
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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAHiHhz%2B2pkdFjJpdG0UtY53RqVG0Y55x%3DziyJmFHOBRj7c%3DfeA%40mail.gmail.com.


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

Re: How to Process Multi Step Forms in Django?

2015-05-05 Thread Bernardo Brik
Hi Ken,
The problem with using Session is that the data will still be there when
you finish your “wizard". You have to manually delete it. It is state,
which is not good. Each request to your server should be an decoupled
operation. It’s ok to store in Session global state, like the current
language or user data, but I would not save something that belongs to a
“wizard”. What happens next time the same user runs the wizard? You have to
worry about that and makes your code complex.

You can encode the data form form1 view in the query string you redirect to
form2. It might be tricky since we are talking about formsets. You can use
urllib.urlencode, you pass a dict:
url = reverse('form2')
querystring = urllib.urlencode({ ... })
return HttpResponseRedirect('%s?%s' % (url, querystring))

Then in your form2 view you get the data from request.GET
key1 = request.GET[ ... ]

On Tue, May 5, 2015 at 1:48 PM, Ken Nguyen <etekni...@gmail.com> wrote:

> Hi Bernardo,
>
> I appreciate the feedback.  I've heard of many ways to pass data between
> methods in views such as session, write to a file, or use formwizard.  It
> is still a problem accessing the session from the "cleaned_data"?  This is
> my first time hearing about query string, care to explain or giving me an
> example of how it works?  In the meantime, I'll read up on it.
>
> Thanks,
> Ken
>
> P.S. - In some part of my code, you may notice the "location"parameter.
> You can ignore it or not include it in my code.  I was cut and paste so I
> didn't catch it.
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/django-users/jnDIOT4dNqQ/unsubscribe.
> To unsubscribe from this group and all its topics, 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 http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/181d8f1d-9728-400b-bac7-ddc205214dcc%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/181d8f1d-9728-400b-bac7-ddc205214dcc%40googlegroups.com?utm_medium=email_source=footer>
> .
>
> For more options, visit https://groups.google.com/d/optout.
>



-- 
Bernardo Brik

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAO2FqvxN6eQfkpLh4HB1-aGrW%2BB%2B8BU3FkuaZaZrFsysmHQRxA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to Process Multi Step Forms in Django?

2015-05-05 Thread Bernardo Brik
Hi Ken,
This is a good solution.
I like the part that you are redirecting instead of rendering directly
form2 from form1 view, that was a code smell that I missed.
I don’t like that you are using Session to save the data. You could run
into problems of having to invalidate that, clean data, when to do it, etc.
You should still redirect, but you could pass the data from form1 to form2
via query string.

On Tue, May 5, 2015 at 5:02 AM, Ken Nguyen <etekni...@gmail.com> wrote:

> I've finally figured it out after weeks of troubleshooting and here's how
> I do it.
>
> In the original post, my views takes in the request from form1 and renders
> it to form2.  I would get the dreadful "Management Form Data is Missing"
> error no matter what I did and it led to asking a bunch of questions on
> here.  I decided to isolate the 2 forms to see if that rendered.  It took a
> few tries before getting both forms and templates to work separately.  What
> I noticed was form1.html's action was equal to "none" which was what I
> wanted.  It would render and posted the form with the errors to itself
> without redirecting to another page.  I then discovered that the address
> was still hooked to form1 instead of form2 after it had rendered.  In
> another word when form1 rendered the data to form2, the address was still
> on userinfo/form1.html when it should have been userinfo/form2.html in
> order for action to call the correct form in views.  The magic that I used
> to fix the issue was *HttpResponseRedirect*.  I saved the data retrieved
> from form 1 in a session and recovered it from beginning of form 2.  I used
> session to render data from form 2 instead of rendering directly from form
> 1.
>
> *Changes to form1 in views.py*
>
>- Save the data in a session for access in different part of views
>- Re-direct to form2 instead of render data from form1
>
> def form1 (request):
> ...
> if formset.is_valid ():
> location = request.POST ['site']
> data = formset.cleaned_data
>
> request.session ['names'] = data
>
> return HttpResponseRedirect ('form2')
> ...
>
> *Changes to form2 in views.py*
>
>- Retrieve data from session
>- Do something with data from form2.   For my case, I merged both
>dictionary into one.
>
> def form2 (request):
>
> data = request.session ['names']
> ...
> if checkbox_formset.is_valid ():
> for i, form in enumerate (checkbox_formset.cleaned_data):
> data [i].update (form)  # This will give me a list of
> name dictionary with the checkbox appended
>
>   context = {'data': data}
> return render (request, 'userinfo/success.html', context)
> else:
> checkbox_formset = CheckBoxFormSet (prefix = 'checkbox')
>
>  context = {'checkbox_formset': checkbox_formset, 'data': data,
> 'location': location}
>  return render (request, 'userinfo/form2.html', context)
>
>
> *form2.html*
>
> 
> 
> 
> 
> {% load staticfiles %}
> 
> Confirmation
> 
> 
> Submitted Entries:
> {% csrf_token %}
> 
>   
> Firstname
> Lastname
> Location
> Overwrite
> Index
>   
>   {% for info in data %}
>   
> {{ info.first_name }}
> {{ info.last_name }}
> {{ location }}
> {{ checkbox_formset.management_form }}
> 
>  name="checkbox-{{ forloop.counter0 }}-overwrite" type="checkbox"/>
> {{ forloop.counter0 }}
>   
>   {% endfor %}
> 
> 
> 
> Cancel
> 
> 
> 
> 
>
> All there's left to do is create a template for success.html
>
> 
> 
> 
> 
> Success
> 
> 
> Submitted Entries:
> 
> {% for info in data %}
> {{ info.first_name }} {{ info.last_name }} {{
> info.overwrite }}
> {% endfor %}
> 
> Add more names
> 
> 
>
> Hope this will help some stragglers.  Nevertheless, thanks to Bernardo for
> helping me all along.
>
>  --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/django-users/jnDIOT4dNqQ/unsubscribe.
> To unsubscribe from this group and all its topics, 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 http://groups.google.com/group/django-users.
> To view thi

Re: How to Process Multi Step Forms in Django?

2015-05-04 Thread Bernardo Brik
Hi Ken,
You are getting this error because you are missing this line in your
template: {{ formset.management_form }}
Take a look into the documentation:
https://docs.djangoproject.com/en/1.8/topics/forms/formsets/#using-a-formset-in-views-and-templates

You need to carry the information to your second view. If you don’t include
first_name and last_address as fields in the second form, the information
won’t get to your second view, when you post. That’s why I suggested
rendering them as hidden inputs. Your Checkbox form also need to have the
fields.

This is what I mean:

class NameForm (forms.Form):
first_name = forms.CharField (required = False)
last_name = forms.CharField (required = False)

class CheckBox (NameForm):
overwrite = forms.BooleanField (required = False)


And on the template:


{{ info.first_name }}
{{ info.last_address }}





Let me know if this helps.
cheers,

On Mon, May 4, 2015 at 3:50 PM, Ken Nguyen <etekni...@gmail.com> wrote:

> Thank you for the input.  I've already tried what you've suggested but
> still the same result, "Management Form Data is Missing."  It's not going
> to know the "first_name" and "last_name" the second time around since I
> have the variable
>
> {{ info.first_name }} and {{ info.last_name }}
>
> My* form2.html* currently looking like so:
>
> {% for info in data %}
> 
>  ="nameform-{{ forloop.counter0 }}-first_name" type="hidden" value="{{
> info.first_name }}" />
>  name="nameform-{{
> forloop.counter0 }}-last_name" type="hidden" value="{{ info.last_name }}"
> />
> {{ info.first_name }}
> {{ info.last_name }}
>  value="1">
> 
> {% endfor %}
>
>
> When you say inherit from form1 and just add the checkboxes, can you
> elaborate that?  How do I inherit it?  Do you mean just replicate the first
> form and add checkboxes to it?
>
> Thanks,
>
> Ken
>
>
> On Saturday, May 2, 2015 at 1:24:22 PM UTC-7, Bernardo Brik wrote:
>>
>> You should add the same fields (first_name and address) to form2 and
>> render them with hidden inputs.
>> You can try to make form2 inherit from form1 and just add the checkbox.
>>
>> On Friday, May 1, 2015 at 9:58:28 PM UTC-3, Ken Nguyen wrote:
>>>
>>> I've made some attempted to use formwizard but there wasn't much
>>> documentation about it so I decided to stay with the basic. I've
>>> successfully obtained and display the data from the first form to the
>>> second form and added some checkbox next to the data to allow user to
>>> choose whether to overwrite or ignore the duplicate data found in the
>>> backend process. The problem I have is the second form doesn't know how
>>> retrieve the data of the first form after hitting "Confirm" button. The
>>> form2.html template invalidated the data completely since it called itself
>>> again by the form action after submitting the data. Is there a way to solve
>>> this or a better approach to this?
>>>
>>> *forms.py*
>>>
>>> class NameForm (forms.Form):
>>> first_name = forms.CharField (required = False)
>>> last_name = forms.CharField (required = False)
>>>
>>> class CheckBox (forms.Form):
>>> overwrite = forms.BooleanField (required = False)
>>>
>>> views.py
>>>
>>> def form1 (request):
>>>
>>> NameFormSet = formset_factory (NameForm, formset = BaseNodeFormSet, 
>>> extra = 2, max_num = 5)
>>>
>>> if request.method == 'POST':
>>>
>>> name_formset = NameFormSet (request.POST, prefix = 'nameform')
>>>
>>> if name_formset.is_valid ():
>>> data = name_formset.cleaned_data
>>>
>>> context = {'data': data}
>>> return render (request, 'nameform/form2.html', context)
>>> else:
>>> name_formset = NameFormSet (prefix = 'nameform')
>>>
>>>  context = {..}
>>>
>>>  return render (request, 'nameform/form1.html', context)
>>>
>>> def form2 (request):
>>>
>>> CheckBoxFormSet = formset_factory (CheckBox, extra = 2, max_num = 5)
>>>
>>> if request.method == 'POST':
>>>
>>> checkbox_formset = CheckBoxFormSet (request.POST, prefix = 
>>> 'checkbox')
>>>
>>> if checkbox_formset.is_valid ():
>>>

Re: Template syntax issues w dict

2015-05-02 Thread Bernardo Brik
just a small correction – lose the parens after items:
{% for org, num in attendees_per_org.items %}

On Friday, May 1, 2015 at 4:48:25 AM UTC-3, ADEWALE ADISA wrote:
>
> If I can understand your code, of seems you want a table of : Institution 
> | Number of attendees
> So if am right u can achive it this way :
>
> {% for org, num in attendees_per_org.items() %}
> 
> {{ org }}
> {{ num }}
> 
>   {% endfor %}
>
> Since your dataset is a dictionary, u need to use key,value to get 
> elements in both side. Also items() is also required.
> On May 1, 2015 8:22 AM, "Lachlan Musicman"  
> wrote:
>
>> Hola,
>>
>> Django shell gives right results, template doesn't: code here
>>
>> http://dpaste.com/1NJEKD8
>>
>> What am I doing wrong?
>>
>> L.
>>
>> -- 
>> 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...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at http://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/CAGBeqiN78i37JA9UJov7%2BAVbJzRt4c5YCX3em2XvN-QmefxSvg%40mail.gmail.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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d130722e-737a-4116-8522-1ddf64d697f5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to Process Multi Step Forms in Django?

2015-05-02 Thread Bernardo Brik
You should add the same fields (first_name and address) to form2 and render 
them with hidden inputs.
You can try to make form2 inherit from form1 and just add the checkbox.

On Friday, May 1, 2015 at 9:58:28 PM UTC-3, Ken Nguyen wrote:
>
> I've made some attempted to use formwizard but there wasn't much 
> documentation about it so I decided to stay with the basic. I've 
> successfully obtained and display the data from the first form to the 
> second form and added some checkbox next to the data to allow user to 
> choose whether to overwrite or ignore the duplicate data found in the 
> backend process. The problem I have is the second form doesn't know how 
> retrieve the data of the first form after hitting "Confirm" button. The 
> form2.html template invalidated the data completely since it called itself 
> again by the form action after submitting the data. Is there a way to solve 
> this or a better approach to this?
>
> *forms.py*
>
> class NameForm (forms.Form): 
> first_name = forms.CharField (required = False)
> last_name = forms.CharField (required = False)
>
> class CheckBox (forms.Form):
> overwrite = forms.BooleanField (required = False)
>
> views.py
>
> def form1 (request):
>
> NameFormSet = formset_factory (NameForm, formset = BaseNodeFormSet, extra 
> = 2, max_num = 5)
>
> if request.method == 'POST':
>
> name_formset = NameFormSet (request.POST, prefix = 'nameform')
>
> if name_formset.is_valid ():
> data = name_formset.cleaned_data
>
> context = {'data': data}
> return render (request, 'nameform/form2.html', context)
> else:
> name_formset = NameFormSet (prefix = 'nameform')
>
>  context = {..}
>
>  return render (request, 'nameform/form1.html', context)
>
> def form2 (request):
>
> CheckBoxFormSet = formset_factory (CheckBox, extra = 2, max_num = 5)
>
> if request.method == 'POST':
>
> checkbox_formset = CheckBoxFormSet (request.POST, prefix = 'checkbox')
>
> if checkbox_formset.is_valid ():
> data = checkbox_formset.cleaned_data
>
> context = {'data': data}
> return render (request, 'nameform/success.html', context)
>
> else:
> checkbox_formset = CheckBoxFormSet (prefix = 'checkbox')
>
>  return HttpResponse ('No overwrite data.')
>
>
>
> *form2.html*
>
>
> 
> 
> 
> 
> {% load staticfiles %}
> 
> User Information
> 
> 
> User Information:
> 
> 
> 
> 
> First Name
> Last Name
> Overwrite
> 
> {% for info in data %}
> 
> {{ info.first_name }}
> {{ info.last_address }}
>  value="1">
> 
> {% endfor %}
> 
> 
> 
> 
> 
> Cancel
> 
> 
> 
>
>

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/17542f06-9ddd-4e6d-a42f-7f7023ce8c41%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Occasional IntegrityError on m2m fields using PostgreSQL

2012-11-01 Thread Bernardo
Hello guys,

I can't detect any pattern, maybe 1 in each 1000 thousands edit of a 
certain model returns an IntegrityError on a m2m field. Most of the times 
this field wasn't even modified. When a model is saved I believe django 
always wipes the m2m field and then readds the items, right? I saw django 
calls clear() and then add()s the items. My code then fails with:

IntegrityError: duplicate key value violates unique constraint 
"app_model_m2m_field_key"

It seems like the add of items is performed before the items are cleared, 
which is very weird. I've tried to reproduce it but it's very hard, only 
happens occasionally. Any idea what could cause it? Could maybe setting 
auto commit solve this problem? Thanks in advance

Cheers,
Bernardo

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/OtS2XH-XyioJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Best approach for multiple sites in a single deployment?

2012-04-10 Thread Bernardo
I would like to create a subdomain based authentication system, like the 
one on 37signals, freshbooks, codebase, etc. The objective is to do 
something like smaller but in far smaller scale (I suppose a maximum of 
100-1000 blogs). All other models (blog posts, comments, etc) already have 
a foreign key to Site. 

1. How can I allow different users to have the same username in different 
sites? How can I make so that when a user logs in, he logged in to a 
specific site (logging on blog A does not log you to blog B).

For allowing the same username in different sites I guess I'd have to write 
my own authentication backend and a new model for User, as I don't see how 
the default User model would fit. Is this a good approach? 

2. Is there anyway to make the sites framework fetch the current site based 
on the subdomain instead of the settings? Or am I seeing this the wrong way?

My plan was to use a single deployment for everything and use the sites 
framework, but as far as I've understood, the sites framework relies on the 
settings.SITE_ID parameter, which would be the same for a single 
deployment. What would be a good approach here? Creating a new settings 
file for each new blog?

Many thanks in advance!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/zQimMoWFGNUJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Decorator aware Django

2011-12-15 Thread Bernardo
> Use Class-based views[1] and subclass them as needed?

Earlier today I saw a blog talking about that. I haven't read
everything, but seems that it is what I want.
I still need to see how to combine multiple Class based views to treat
my data.
Thanks!

Bernardo


On Dec 15, 3:48 pm, Andre Terra <andrete...@gmail.com> wrote:
> On Thu, Dec 15, 2011 at 11:51 AM, Bernardo <jbv...@gmail.com> wrote:
> > but I
> > wanted a easier way to render data from multiple return points in a
> > same function without calling another thing multiple times...
>
> Use Class-based views[1] and subclass them as needed?
>
> Cheers,
> AT
>
> [1]http://django.me/cbv

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Decorator aware Django

2011-12-15 Thread Bernardo
> @app.route("/")
> def hello():
>  return "Hello World!"

That's not what I want to do. I like how views are handled, but I
wanted a easier way to render data from multiple return points in a
same function without calling another thing multiple times...

> Now I have to overcome this feeling with ORMs

ORMs are great. I've already spent too many years writing SQL by hand
and I regret the time I lost.


Regards
Bernardo


On Dec 14, 7:57 pm, Matej Cepl <mc...@redhat.com> wrote:
> On 13.12.2011 15:14, Javier Guerra Giraldez wrote:
>
> > for me, is opposed to the "explicit is better than implicit" in the
> > Zen of Python.  not a bad thing on itself, but something to be careful
> > about.   (and, personally, it's a big part of why i like Django so
> > much better than RoR)
>
> I am a complete newbie in the world of webapps, but exactly this was the
> reason why I left Flask. Nothing against them, but
>
> @app.route("/")
> def hello():
>      return "Hello World!"
>
> looks to me like a wrong to do things and yes “explicit is better than
> implicit” (or “No magic allowed!”) was something I was thinking about.
>
> What I liked about the first look at Django was that it looks just like
> a Python app not playing any tricks on me.
>
> Now I have to overcome this feeling with ORMs (be it the Django one or
> SQLAlchemy) ... but there is probably not a better way how to do this.
>
> Just my €0.02
>
> Matěj

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Decorator aware Django

2011-12-13 Thread Bernardo
Hi Russel,

> Returning HTTPResponse also provides a data formatting constraint that
> your approach doesn't have. At each level of  Django view, you know
> you're going to get a HTTP Response.

Yes, now it makes sense the view working only with HTTP request and
responses and the decorators will only work with some kind of specific
information that will not be the same for each decorator.

Being strict, the view (the decorated function) will always return an
HTTP response, but in another (more abstract) layer... I think I'll
need to find some balance in this technique.

Hi Javier,

> for example, make a (generic) view that simply calls a data gathering
> function (which is not a view) and hands the result to a HTML
> template, and another (generic) view that calls the same function but
> returns a different (XML? JSON? Pickle?) representation.

I don't know if I understand what you're saying but the decorator
approach is working exactly like that but instead of calling these
generic views, I decorate my view with it.
Could you explain me that with a simple snippet?

Regards,
Bernardo

On Dec 13, 12:14 pm, Javier Guerra Giraldez <jav...@guerrag.com>
wrote:
> hi,
>
> Russel explained the real reasons of why your proposal doesn't fit so
> good in Django.
>
> still, this snippet:
>
> On Mon, Dec 12, 2011 at 7:49 PM, Bernardo <jbv...@gmail.com> wrote:
> >        - The framework, within reason, should deduce as much as
> > possible from as little as possible.
> >    That last phrase tells everything I'm trying to explain.
>
> for me, is opposed to the "explicit is better than implicit" in the
> Zen of Python.  not a bad thing on itself, but something to be careful
> about.   (and, personally, it's a big part of why i like Django so
> much better than RoR)
>
> now, thinking a little more on what seems to be good: separating the
> 'data gathering' part of a view from the presentation part, I think it
> should be handled at a slightly different level.
>
> for example, make a (generic) view that simply calls a data gathering
> function (which is not a view) and hands the result to a HTML
> template, and another (generic) view that calls the same function but
> returns a different (XML? JSON? Pickle?) representation.
>
> paired with a middleware and some shortcuts in the urls.py, you can
> have nicely separated concerns and DRYness.
>
> --
> Javier

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Decorator aware Django

2011-12-12 Thread Bernardo
I've been working lately (not my choice!) with Pylons and the terrible
Genshi as template system.
The thing is: for the next project I wanted to use something better
and the first thing I could think of was Django.

I spent the last weaks reading documentation (FAQs, installation,
templates, models and so on) and It feels like
I'm in the right path.

One thing the project I was working had and I liked was lots of
decorators on top of controllers (what you people call views - and
makes sense)
Something like that:

#-

@require_permission('login')
@expose_xhr('admin/data/index.html', 'admin/data/table.html')
@paginate('media', items=20)
@observable(events.Admin.DataController.index)
def index(self, page=1, search=None, filter=None):
"""
Home page for ... bla bla
"""
filter = Person.query.options(orm.undefer('comment_count'))
tag = 

return {
'base': self.info,
'search': search,
'search_form': search_form,
'media_filter': filter,
'tag': tag,
}

#-

It feels right to make the controller returns only the data to be
rendered/serialized instead of a HTTP response. Not doing that makes
it a lot aware of things it shouldn't be and make it easy to repeat
code.

As I said, I'm new to Django and couldn't find out if it had something
like that by default (Pylons dindn't had much of that though).
The things I found was decorators to check request methods (and that's
also great).

So I started writing myself those decorators, because I was already
used to work with them.

As I was teaching myself to use the framework, I realized that using
decorators that way fits in Django philosophies pretty well:
- The framework should be consistent at all levels -> Using
decorators it's easy do make it work
- Django apps should use as little code as possible -> Views only
return data. Decorators render the data to the user
- Don’t repeat yourself:
- The framework, within reason, should deduce as much as
possible from as little as possible.
That last phrase tells everything I'm trying to explain.

A decorator e.g. `@render('page.html')` could get the output of the
view and render to a template using the request information as
"RequestContext" without the view programmer bothering with calling
something like `render_to_response`.

Another decorator could receive 'json' or 'xml' as argument and grab
an serializer to return HTTP data to a Ajax request using the correct
mimetype to avoid making the programmer remember this kind of
information (or even how to instantiate the serializer class).

Well, these were my thoughts and feel free to think otherwise. I would
appreciate to know if something is being done in this direction.


Sorry for the long post!
Bernardo

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Testing if a receiver is connected to a signal

2011-05-05 Thread Bernardo Fontes
Hello everybody,

I resolved this problem by looking at Djangos Signal's code and
understanding its structure. The signal has an attribute called receivers
which has stored references to its receivers function that were connect to
it. When the send function is called, the signal just call this function
which are in this receivers list. So, I created a setUpClass and a
tearDownClass that does a monkey patch with my signal. It's like this:


class YourTestClass(TestCase):

@classmethod
def setUpClass(cls):
cls.signal_receivers = my_signal.receivers
my_signal.receivers = []


@classmethod
def tearDownClass(cls):
my_signal.receivers = cls.signal_receivers

Hope I could help!

-- 
Bernardo Fontes
http://www.bernardofontes.net
bernardo...@gmail.com <falecom...@bernardofontes.net>
Skype: bernardoxhc
(21) 9629 1621

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Testing if a receiver is connected to a signal

2011-04-19 Thread Bernardo Fontes
Hi,

I'm having this problem too. Does anyone knows a good strategy to
handle this problem?

On 21 fev, 17:50, Vinicius Mendes  wrote:
> Hi,
>
> I want to test if a receiver function is connected to a signal in django,
> but I don't want other receivers from other apps to be called when my test
> runs.
>
> I thought of verifying if my callback function is in the receivers list of
> the signal, but this list stores the receivers in a strange way.
>
> Any ideas?
>
> Atenciosamente,
> Vinicius Mendes
> Engenheiro de Computação
> Globo.com

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



User Inheritance and i18n

2009-11-11 Thread Bernardo

Hello guys!
After following this tutorial (http://scottbarnham.com/blog/2008/08/21/
extending-the-django-user-model-with-inheritance/) to be able to
extend the default user class of Django, the i18n module stopped
working. I gave the new model that inherits from User the name
CustomUser. When I try to switch to a language with a form that calls
the setlang view from (r'^i18n', include('django.conf.urls.i18n')) I
get the following error:
"No CustomUser matches the given query."

Is there anything I can do to get i18n working again?

Thanks in advance,
Bernardo

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---