Monday, July 31, 2017

Re: How can I add attrs in ModelChoiceField?

Now I know it use forms.Select(),however I add attrs whth class ,but it doesn't work!
Gategory = ModelChoiceField(queryset=GoodsType.objects.all())
widgets = {
'Gategory' : forms.Select(attrs={'class' : "form-control",
}),
}

-->>>
<select id="id_Category" name="Category">\n<option value="" selected="selected">---------</option>\n<option value="1">\u5168\u90e8</option>\n<option value="2">\U0001f436</option>\n</select>



在 2017年8月1日星期二 UTC+8上午10:59:12,李余通写道:
Hello,Everyone,
I know charField can use
forms.TextInput(attrs={'class' : 'form-control',
}),
or
forms.Textarea(attrs={'class' : "form-control",
'rows' : 3 ,
})

to set widgets

but ModelChoiceField?
I have no idea,Django telled me "'module' object has no attribute 'ChoiceInput'"
when i use
forms.ChoiceInput
and "__init__() got an unexpected keyword argument 'attrs'" when i use ModelChoiceField


Can you help me?
Thank you very much?

--
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+unsubscribe@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/3728c5f6-723f-4896-a897-4beb7c4b4747%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Django tutorial part 4: 'utf8' codec can't decode byte 0xa0 in position 22431

Hi everyone, 

I am a Django newbie and started the Tutorial. I followed all steps so far but I am stuck at the part 4. 
So far I've written 3 templates. 

1. file:///C:/Python27/Django/mysite/polls/templates/polls/detail.html

<h1>{question.question_text }}</h1>

 

{% if error_message %}<p><strong>{error_message }}</strong></p>{% endif %}

 

<form action="{% url 'polls:vote' question.id %}" method="post">

{% csrf_token %}

{% for choice in question.choice_set.all %}

    <input type="radio" name="choice" id="choice{forloop.counter }}" value="{{ choice.id }}" />

    <label for="choice{forloop.counter }}">{{ choice.choice_text }}</label><br />

{% endfor %}

<input type="submit" value="Vote" />

<

/form>


2. file:///C:/Python27/Django/mysite/polls/templates/polls/index.html


{% if latest_question_list %}

    <ul>

    {% for question in latest_question_list %}

        <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

    {% endfor %}

    </ul>

{% else %}

    <p>No polls are available.</p>

{% endif %}


 3. file:///C:/Python27/Django/mysite/polls/templates/polls/results.html


<h1>{question.question_text }}</h1>

 

<ul>

{% for choice in question.choice_set.all %}

    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>

{% endfor %}

</ul>

 

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>



just like explained in the tutorial. 


When I wan to run it on the server I get the error: 



UnicodeDecodeError at /polls/1/

'utf8' codec can't decode byte 0xa0 in position 22431: invalid start byte
Request Method:GET
Request URL:http://127.0.0.1:8000/polls/1/
Django Version:1.11.3
Exception Type:UnicodeDecodeError
Exception Value:
'utf8' codec can't decode byte 0xa0 in position 22431: invalid start byte
Exception Location:C:\Python27\lib\codecs.py in decode, line 314
Python Executable:C:\Python27\python.exe
Python Version:2.7.13
Python Path:
['C:\\Python27\\Django\\mysite',   'C:\\Windows\\system32\\python27.zip',   'C:\\Python27\\DLLs',   'C:\\Python27\\lib',   'C:\\Python27\\lib\\plat-win',   'C:\\Python27\\lib\\lib-tk',   'C:\\Python27',   'C:\\Python27\\lib\\site-packages']
Server time:Tue, 1 Aug 2017 16:03:11 +1000

Unicode error hint

The string that could not be encoded/decoded was: yes'>��� </


I see the same when I encode my html files with utf-8 in word. 


Unfortunately I don't know how to fix this. I've read many threats but none of them really helped me to solve this issue.

Has anyone experienced a similar problem and can help me? 



--
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+unsubscribe@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/4360a617-289d-4e4c-8f60-b7dda65e1fda%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

How can I add attrs in ModelChoiceField?

Hello,Everyone,
I know charField can use
forms.TextInput(attrs={'class' : 'form-control',
}),
or
forms.Textarea(attrs={'class' : "form-control",
'rows' : 3 ,
})

to set widgets

but ModelChoiceField?
I have no idea,Django telled me "'module' object has no attribute 'ChoiceInput'"
when i use
forms.ChoiceInput
and "__init__() got an unexpected keyword argument 'attrs'" when i use ModelChoiceField


Can you help me?
Thank you very much?

--
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+unsubscribe@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/2f1dcb5f-cf3c-4dca-8403-1dcdfcef0bf4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Getting response code 302 instead of 200 while testing a url

Hi James,

Thanks for the reply!

As in the setup function for my tests i have already created a Post object then how just visiting a url i.e '/update/' and 'delete/' of that object can be a considered 'POST' request.

Also Is there any way to capture the inbetween changing process of status code i.e from 302 to 200 ? I have tried Postman but it was giving 200 staus code for visiting the 'update' url of the post that i had already created.

As you mentioned it is hard to debug without reading code, what part of code more should i send ?


Mannu

On Fri, Jul 28, 2017 at 10:43 AM, James Schneider <jrschneider83@gmail.com> wrote:

The problem here is that my test cased passed for the first 2 functions i.e. "test_post_list" and "test_post_create" but now working for other two test functions i.e "test_post_update" and "test_post_delete". What might be the problem ?

The setup function that i made is supposed to create a object of model named "Post", then what might be the problem ?

Actually,  that's probably a valid/correct response. In general, when sending a POST request, a redirect (the 302) is returned by a view to another landing page (where you would then receive a 200), where the successful message is displayed to the user. This is done to prevent the user from submitting the form multiple times by clicking the back button (the browser presents the "are you sure you want to send this data again?" message). 

The generic create/update views included with Django have this behavior. 

Without seeing the views, it's hard to tell for sure. 

-James 

--
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/uZ1oGmHWWB8/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users+unsubscribe@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/CA%2Be%2BciWSCD9hK_cViYgFJuFOXFvC%2Bp1Wxz1oMFuHOySvhZYnAw%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+unsubscribe@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/CAEDhgmjskEG8sZ9BxsuxvVxRFAD1tDehptxDh%3D0f9ELdP3Ek_w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Re: Dos Modelos en un formulario django

Hola que tal.

Si es posible.
Checa este video : https://codigofacilito.com/videos/18-curso-django-crud-con-dos-formularios-parte-2

Creo que es lo que buscas.

Saludos.


On Thursday, July 27, 2017 at 5:38:43 PM UTC-5, Nelson Fernando Garcia Gomez wrote:
hola Buenas soy algo nuevo en django y me anima aprender cada vez mas,l bueno mi inquietud es la siguiente 
como puedo enlazar dos modelos a un formulario 
tengo como modelos usuarios y características y donde el modelo características tiene una relacion models.OneToOneField
con usuarios, quisiera saber como puedo trabajar estos dos modelos en un solo formulario con un solo submit  
espero sea claro bueno en fin deseo es crear un solo formulario para recoger datos para estos dos modelos y hay si almacenarlos.
gracias por su colaboración  :) 



Declinación de Responsabilidades: Los servicios de MISENA son soportados tecnológicamente por © Google y ofrecidos por el Servicio Nacional de Aprendizaje – SENA de manera gratuita a los aprendices e instructores de programas de formación titulada, las opiniones que contenga este mensaje son exclusivas de su autor y no representan la opinión del Servicio Nacional de Aprendizaje o de sus autoridades. El receptor deberá verificar posibles virus informáticos que tenga el correo o cualquier anexo, razón por la cual el SENA no es responsable de los daños causados por cualquier virus transmitido en este correo electrónico.

Los contenidos, textos, imágenes, archivos enviados en este mensaje son responsabilidad exclusiva del remitente y no reflejan ni comprometen de ninguna manera a la institución. No se autoriza el uso de esta herramienta para el intercambio de correos masivos, cadenas o spam, ni de mensajes ofensivos, de carácter político, sexual o religioso, con fines de lucro, con propósitos delictivos o cualquier otro mensaje que se considere indebido o que vaya en contra de la Ley.

--
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+unsubscribe@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/d803c907-65e4-40b7-86b1-f894101b47e4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Embed template of app inside page

Hi everyone I create an app call account to manage users on my website, I create using the Django authentication system, this app works fine, I can log in, register, change the password and edit the user.
 I have a link to register and log in, but now I want to show to register form in a normal page on my website ... How to embed the register.html  in a page that I create in the back end!

Any idea about that! this is possible.

this is my template edit when I call from http://127.0.0.1:8000/account/register/


and I want to show this form here http://127.0.0.1:8000/forms/create_account


this is a normal page that I create in the back end 


Thanks in advances!

This is my link

--
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+unsubscribe@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/fc70fa80-3b83-4675-bb2e-e065d83a8242%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Django form needs pagination and saved data - how????

Super advice - thanks very much, James! Appreciate your help.

Jim

On Jul 30, 2017, at 5:55 PM, James Schneider <jrschneider83@gmail.com> wrote:



On Jul 30, 2017 4:50 PM, "Jim Illback" <subaru_87@hotmail.com> wrote:
Thanks for your reply, James. Appreciate it. BTW, if you check my template, the button is within the form tags, but you probably are right on the JS - I don't know JS much at all so just copied other people's code.

I thought that's how you're supposed to program in JS? Been doing it that way for years. ;-)


I may be mistaken, but I think the wizard link below requires a "static" or semi-static forms flow path (form1, form2, …, formlast). Generally, when you do pagination, there is no preset number of pages - it depends upon the data being requested or available. So, I think that option would not work. But, if I'm wrong, I'd love to know. Thanks.

By default, yes, it is expecting a known number of steps for more simple processes. However, it has all of the hooks necessary to create a fully dynamic flow. I did a dynamic flow back when this package was still in Django core, but I doubt the process has changed much.


And, as for using Java just so you can use Django, doesn't that raise the obvious question - so why use Django? 

I'm not sure what you're referring to here. I don't think that I mentioned Java specifically, nor would I have reason to.

Perhaps a mistaken interpretation of my reference to an SPA? This is what I meant:



To try to illustrate that my issue is a common business issue, here's a scenario that is exactly the same situation and one used by almost everyone:

A new car purchase site needs the user to pick the car and model. Then, that data stays static throughout the transaction. However, the user might want different options (tires, engines, transmission types, etc.). And, those options are always too many for one page, so they must be done using pagination. When all the options are reviewed - or maybe just one page of options or two or… - then the final idea is to show the user the car's price, have all the selections chosen listed out for the user to review, and ask for further actions like "do you want to purchase this car?". 

Are these types of business scenarios just not in Django's wheelhouse? 


The level of dynamic content generation required for all of those steps will likely be complex, possibly even complicated, for any generic framework to handle. The Django formtools can handle the scenario you've listed, but your code organization and naming standard will need to be strongly enforced to keep the various steps separate.

The workflow you've mentioned isn't necessarily complicated at a high level, the step decisions are rather binary. Either a person wants to select different tires, or doesn't and accepts the default selection. The code in formtools for step selection is usually that simple "if they wanted different tires in a previous step, now show them this form for tires", almost a one-liner (for each step).

Honestly, the biggest issue will be displaying the multiple pages of options, which is somewhat a separate issue. 

There are several strategies. You can display multiple form pages across multiple requests, keeping the results of each along the way, which complicates your back end code. Before the influx of JS and HTML5, this was rather common. 

The newer approach is to use JS to pull all of the possible options, and handle the UI and pagination within JS, perhaps in a pop up modal window. The data is retrieved via an API call, and once a selection is made by the user, either a form is executed containing all of the possible options that the user selected. 

Datatables.js might be a good option for this, as it can also handle the dynamic pagination of options surprisingly well, and plays excellent with Bootstrap. Heck, you can probably use DT with either strategy. It would definitely ease the logic for the server based form wizard, and likely save you a ton of JS scripting for an SPA-like display.

If it were me, I'd investigate Datatables.js with the Bootstrap integration and pagination. It's relatively easy to implement (I, like yourself, am averse to JS), and provides killer functionality with minimal custom JS (mostly single minimal function calls to control ordering of table columns). Once you have that working, try integrating the table with a form combined with pagination, I think that will be the silver bullet you're looking for.


-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+unsubscribe@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/CA%2Be%2BciV46BEkatAmD9kGX5ugdfmZn7GQsfnjbdte5cey4YxC4w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Re: failed of installing MySLQ

Personally I'd go with SQLite first. Every additional thing you require someone to learn up-front is another obstacle in their path; they can learn how ot manage MySQL or PostgreSQL later on, but first they need to be able to learn about Django.

--
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+unsubscribe@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/CAL13Cg-fX-L86u7-PNOGwx6bbEtcFVq9JJwXH%2BKna_FFAKTZPQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Re: Error message on 'django.urls.exceptions.NoReverseMatch'

Hello James

Thanks for your help. That solved the problem.

Ron

--
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+unsubscribe@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/51c4118b-c881-4e08-b083-5db2ef674702%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: failed of installing MySLQ

I don't completely agree with Antonis. If you want MySQL in production, you will have to learn how to install it an use it at sometime. 

With that said, you will probably get more help with installing MySQL in a MySQL forum. Check these out - https://forums.mysql.com/. The Newbie forum or the Install and Repo forum might be your best place to start. Then come back here for questions about Django - we can help you with getting Django to work with MySQL once MySQL is installed and working.

Once MySQL is installed, you may want to try a tutorial about how to use it - https://www.tutorialspoint.com/mysql/. Finally, the Django tutorial is very well written and you will learn a lot from it - https://docs.djangoproject.com/en/1.11/intro/tutorial01/. There are many free Python online tutorials, just google for those and find the one that matches your learning style. 

Finally, I don't think installing MySQL requires visual C++, but I am not an expert.

Mark

On Mon, Jul 31, 2017 at 2:35 AM, Antonis Christofides <antonis@djangodeployment.com> wrote:

Hello,

since you aren't experience, start easier and use SQLite. Mostly everyone (even the experienced people) usually use SQLite in development.

Regards,

Antonis

Antonis Christofides  http://djangodeployment.com
On 2017-07-30 15:46, ahagbes89 wrote:
I have not much experiences in Python. I have installed Django  but the installation of the data base (MySQL) fails
It is displayed that windows visual c++ is required. I don't know how to do.
Thank
--
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+unsubscribe@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/0e53b86b-9a3a-4c76-82b9-6410472c00e8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@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/be2a66b7-6360-3919-0ac1-5cb832e455b4%40djangodeployment.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+unsubscribe@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/CAEqej2OJP8ZnN4syOSgSAo5swtxkj8xq8WxARdUg2gD6f1riEQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Re: Group Permissions programmatically

Hello

Thank you for the suggestion! Let me adapt the approach and see.

Regards

Sent from my iPhone

On Jul 31, 2017, at 20:28, Александр Христюхин (roboslone) <roboslone@gmail.com> wrote:

Hi,

Why don't you use the same approach that is generally used with users? I mean you connect a signal to your User/Group model, that changes permission for created objects, like so:

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_user_permissions(instance=None, created=None, **kwargs) -> None:
    if created:
        instance.user_permissions.add(...)  # add actual Permission objects here

On 31 Jul 2017, at 10:23, Frank Semaganga <semaganga@gmail.com> wrote:

Hi!

I am having a challenge . My aim is to be able to assign some group permissions when the group is created. In admin.py I have a custom GroupAdmin class  on which I have the function save customized but the challenge is everything else get saved and reflected on admin page including user permissions(if i set permissions to the user direct) but the group permissions seems to be saved but when I go to admin page they are not assigned.

Can you share you experience !


        permits = Permission.objects.filter(content_type__app_label='myapp')

        ####Saved but not updated on Admin page
        obj.permissions=permits
        obj.save()


        #####Works Perfect and changes seen on admin page
        user = User.objects.create_user('username12', '', 'password')
        user.groups.add(obj)
        user.user_permissions=perms
        user.is_staff=True
        user.save()


obj is an object of Group.


Regards

--
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+unsubscribe@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/f862d504-99fa-4a1f-a6ea-523ba4cca67a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
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/E0dE_GOvl_0/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users+unsubscribe@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/D062C2C9-125E-4DB0-85F6-E818CE6EB8F0%40gmail.com.
For more options, visit https://groups.google.com/d/optout.

Re: Group Permissions programmatically

Hi,

Why don't you use the same approach that is generally used with users? I mean you connect a signal to your User/Group model, that changes permission for created objects, like so:

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_user_permissions(instance=None, created=None, **kwargs) -> None:
    if created:
        instance.user_permissions.add(...)  # add actual Permission objects here

On 31 Jul 2017, at 10:23, Frank Semaganga <semaganga@gmail.com> wrote:

Hi!

I am having a challenge . My aim is to be able to assign some group permissions when the group is created. In admin.py I have a custom GroupAdmin class  on which I have the function save customized but the challenge is everything else get saved and reflected on admin page including user permissions(if i set permissions to the user direct) but the group permissions seems to be saved but when I go to admin page they are not assigned.

Can you share you experience !


        permits = Permission.objects.filter(content_type__app_label='myapp')

        ####Saved but not updated on Admin page
        obj.permissions=permits
        obj.save()


        #####Works Perfect and changes seen on admin page
        user = User.objects.create_user('username12', '', 'password')
        user.groups.add(obj)
        user.user_permissions=perms
        user.is_staff=True
        user.save()


obj is an object of Group.


Regards

--
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+unsubscribe@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/f862d504-99fa-4a1f-a6ea-523ba4cca67a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: failed of installing MySLQ

Hello,

since you aren't experience, start easier and use SQLite. Mostly everyone (even the experienced people) usually use SQLite in development.

Regards,

Antonis

Antonis Christofides  http://djangodeployment.com
On 2017-07-30 15:46, ahagbes89 wrote:
I have not much experiences in Python. I have installed Django  but the installation of the data base (MySQL) fails
It is displayed that windows visual c++ is required. I don't know how to do.
Thank
--
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+unsubscribe@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/0e53b86b-9a3a-4c76-82b9-6410472c00e8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Group Permissions programmatically

Hi!

I am having a challenge . My aim is to be able to assign some group permissions when the group is created. In admin.py I have a custom GroupAdmin class  on which I have the function save customized but the challenge is everything else get saved and reflected on admin page including user permissions(if i set permissions to the user direct) but the group permissions seems to be saved but when I go to admin page they are not assigned.

Can you share you experience !


        permits = Permission.objects.filter(content_type__app_label='myapp')

        ####Saved but not updated on Admin page
        obj.permissions=permits
        obj.save()


        #####Works Perfect and changes seen on admin page
        user = User.objects.create_user('username12', '', 'password')
        user.groups.add(obj)
        user.user_permissions=perms
        user.is_staff=True
        user.save()


obj is an object of Group.


Regards

--
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+unsubscribe@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/f862d504-99fa-4a1f-a6ea-523ba4cca67a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Sunday, July 30, 2017

Re: Django form needs pagination and saved data - how????



On Jul 30, 2017 4:50 PM, "Jim Illback" <subaru_87@hotmail.com> wrote:
Thanks for your reply, James. Appreciate it. BTW, if you check my template, the button is within the form tags, but you probably are right on the JS - I don't know JS much at all so just copied other people's code.

I thought that's how you're supposed to program in JS? Been doing it that way for years. ;-)


I may be mistaken, but I think the wizard link below requires a "static" or semi-static forms flow path (form1, form2, …, formlast). Generally, when you do pagination, there is no preset number of pages - it depends upon the data being requested or available. So, I think that option would not work. But, if I'm wrong, I'd love to know. Thanks.

By default, yes, it is expecting a known number of steps for more simple processes. However, it has all of the hooks necessary to create a fully dynamic flow. I did a dynamic flow back when this package was still in Django core, but I doubt the process has changed much.


And, as for using Java just so you can use Django, doesn't that raise the obvious question - so why use Django? 

I'm not sure what you're referring to here. I don't think that I mentioned Java specifically, nor would I have reason to.

Perhaps a mistaken interpretation of my reference to an SPA? This is what I meant:



To try to illustrate that my issue is a common business issue, here's a scenario that is exactly the same situation and one used by almost everyone:

A new car purchase site needs the user to pick the car and model. Then, that data stays static throughout the transaction. However, the user might want different options (tires, engines, transmission types, etc.). And, those options are always too many for one page, so they must be done using pagination. When all the options are reviewed - or maybe just one page of options or two or… - then the final idea is to show the user the car's price, have all the selections chosen listed out for the user to review, and ask for further actions like "do you want to purchase this car?". 

Are these types of business scenarios just not in Django's wheelhouse? 


The level of dynamic content generation required for all of those steps will likely be complex, possibly even complicated, for any generic framework to handle. The Django formtools can handle the scenario you've listed, but your code organization and naming standard will need to be strongly enforced to keep the various steps separate.

The workflow you've mentioned isn't necessarily complicated at a high level, the step decisions are rather binary. Either a person wants to select different tires, or doesn't and accepts the default selection. The code in formtools for step selection is usually that simple "if they wanted different tires in a previous step, now show them this form for tires", almost a one-liner (for each step).

Honestly, the biggest issue will be displaying the multiple pages of options, which is somewhat a separate issue. 

There are several strategies. You can display multiple form pages across multiple requests, keeping the results of each along the way, which complicates your back end code. Before the influx of JS and HTML5, this was rather common. 

The newer approach is to use JS to pull all of the possible options, and handle the UI and pagination within JS, perhaps in a pop up modal window. The data is retrieved via an API call, and once a selection is made by the user, either a form is executed containing all of the possible options that the user selected. 

Datatables.js might be a good option for this, as it can also handle the dynamic pagination of options surprisingly well, and plays excellent with Bootstrap. Heck, you can probably use DT with either strategy. It would definitely ease the logic for the server based form wizard, and likely save you a ton of JS scripting for an SPA-like display.

If it were me, I'd investigate Datatables.js with the Bootstrap integration and pagination. It's relatively easy to implement (I, like yourself, am averse to JS), and provides killer functionality with minimal custom JS (mostly single minimal function calls to control ordering of table columns). Once you have that working, try integrating the table with a form combined with pagination, I think that will be the silver bullet you're looking for.


-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+unsubscribe@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/CA%2Be%2BciV46BEkatAmD9kGX5ugdfmZn7GQsfnjbdte5cey4YxC4w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Re: Django form needs pagination and saved data - how????

Thanks for your reply, James. Appreciate it. BTW, if you check my template, the button is within the form tags, but you probably are right on the JS - I don't know JS much at all so just copied other people's code.

I may be mistaken, but I think the wizard link below requires a "static" or semi-static forms flow path (form1, form2, …, formlast). Generally, when you do pagination, there is no preset number of pages - it depends upon the data being requested or available. So, I think that option would not work. But, if I'm wrong, I'd love to know. Thanks.

And, as for using Java just so you can use Django, doesn't that raise the obvious question - so why use Django? 

To try to illustrate that my issue is a common business issue, here's a scenario that is exactly the same situation and one used by almost everyone:

A new car purchase site needs the user to pick the car and model. Then, that data stays static throughout the transaction. However, the user might want different options (tires, engines, transmission types, etc.). And, those options are always too many for one page, so they must be done using pagination. When all the options are reviewed - or maybe just one page of options or two or… - then the final idea is to show the user the car's price, have all the selections chosen listed out for the user to review, and ask for further actions like "do you want to purchase this car?". 

Are these types of business scenarios just not in Django's wheelhouse? 


On Jul 30, 2017, at 4:51 AM, James Schneider <jrschneider83@gmail.com> wrote:



On Jul 28, 2017 5:56 PM, "Jim Illback" <subaru_87@hotmail.com> wrote:
I use the latest versions of Django, python, bootstrap3, and crispy forms for this project.

I am trying to present a list of flashcards to a user, sorted by category (e.g., Math, Vocabulary, etc.). Then, I want the user to check either the full category or individual flashcards to be added to their practice account. 

To maintain user inputted checkboxes on multiple pages, I must use POST. But, pagination only uses GET. So, a hack on pagination is to wrap the Next/Previous buttons in a sub-form and POST using the buttons. This works for pagination, but then my normal "I'm done, submit this session and process the updates" button - my submit button - does nothing: no GET, no POST, nothing. 

How can I enable pagination, multiple screen data accumulation across pages, and final submission of the session when complete? 

I can't speak to your submit button issue, other than either a piece of JavaScript is getting in the way, or the button is located outside of a <form> tag.

As for the rest of your troubles, it really sounds like you need a form wizard framework, which is what I think you mean by "pagination". Django used to ship one as part of the contrib package, but has since moved it out to it's own separately maintained app.


It handles keeping data state across multiple form submissions, along with dynamic form additions/omissions based on previous steps.

Another option you may consider is developing this process like a single-page-application, where all of the data and forms are managed via JS, and the final collection of data is submitted as a single blob to the server for permanent storage. That's obviously over simplified, but I hope you catch my meaning.

-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+unsubscribe@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/CA%2Be%2BciVCh5oEr3rHLEUB4L%3Dpus_bL8H%2BxpmCev5syjes_XOBDg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

GeoDjango distance lookup on Subquery: AttributeError: 'tuple' object has no attribute 'extend'

Good evening,

I'm having a problem doing a distance lookup on a Subquery. I always get an AttributeError (see above).

Put simply, I have a table of Locations where a User may have many Locations (one-to-many). Now, I want to look up which users were close to a Point at a specific time, i.e., get the newest Location which is equal or older than my lookup time T for each user and do a distance query to only include users close by. I chose to do this with a Subquery, but correct me if my approach is not optimal.

This error is triggered in django/contrib/gis/db/models/lookups.py", line 143.
Interestingly, sql_params is a Tuple in this case, which of course doesn't allow .extend() to be called. However, I am not proficient enough to fully understand the stacktrace, especially at which point sql_params suddenly becomes a Tuple instead of a List, which it should be.

Full stacktrace at the bottom of this post.

Simplified reproduction:

models.py
from django.contrib.auth.models import User
from django.contrib.gis.db import models

class Location(models.Model):
    user
= models.ForeignKey(User, on_delete=models.CASCADE,
                             related_name='locations')
    location
= models.PointField()
    created_at
= models.DateTimeField(auto_now=True)




views.py or in shell
from datetime import timedelta
from django.contrib.auth.models import User
from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D
from django.db.models import OuterRef, Subquery
from django.utils import timezone

from .models import Location

some_time
= timezone.now() - timedelta(days=1)
some_location
= Point(49.1, 110.2)
radius
= D(m=1000)

# get the a location for each user which is less than or equal
# to our lookup time some_time
locations
= Location.objects \
                   
.filter(user=OuterRef('pk'),
                            created_at__lte
=some_time) \
                   
.order_by('-created_at')

# select the users which were close by at our lookup time some_time
# this yields the attribute error.
users
= User.objects \
           
.annotate(location_at_time=Subquery(
                                         locations
.values('location')[:1])
                     
) \
           
.filter(location_at_time__distance_lte=(some_location, radius))

# interestingly, this similar query without a subquery works
users
= User.objects \
           
.filter(location__location__distance_lte=(some_location, radius))


when running pdb in django/contrib/gis/db/models/lookups.py in GISLookup.as_sql(),  the values of some variables are these:

(Pdb) sql_params
(datetime.datetime(2017, 7, 30, 22, 5, 44, 866379, tzinfo=<UTC>),)   # <-- Tuple!
(Pdb) lhs_sql
'(SELECT U0."location" FROM "api_location" U0 WHERE (U0."user_id" = (V0."id") AND U0."created_at" <= %s) ORDER BY U0."created_at" DESC LIMIT 1)'
(Pdb) rhs_sql
'%s'
(Pdb) rhs_params
[<django.contrib.gis.db.backends.postgis.adapter.PostGISAdapter object at 0x11275d4a8>, 1000.0]

the next command sql_params.extend(rhs_params) then fails, obviously.

So I suppose there's something fishy going on due to the Subquery.

Would love some help, as I'm pretty much just starting out with Django (and Python) and my source code reading skills are very limited.

Thanks! :)


Full stacktrace:

Traceback (most recent call last):
  File "myproject/philter/tests/test_api.py", line 284, in test_play
    response = self.create_game(self.users[0])
  File "myproject/philter/tests/test_api.py", line 248, in create_game
    response = self.game_view(request)
  File "myproject/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "myproject/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "myproject/venv/lib/python3.6/site-packages/rest_framework/views.py", line 489, in dispatch
    response = self.handle_exception(exc)
  File "myproject/venv/lib/python3.6/site-packages/rest_framework/views.py", line 449, in handle_exception
    self.raise_uncaught_exception(exc)
  File "myproject/venv/lib/python3.6/site-packages/rest_framework/views.py", line 486, in dispatch
    response = handler(request, *args, **kwargs)
  File "myproject/philter/api/views.py", line 149, in post
    possible_question_count = questions.count()
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/query.py", line 364, in count
    return self.query.get_count(using=self.db)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 499, in get_count
    number = obj.get_aggregation(using, ['__count'])['__count']
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 463, in get_aggregation
    outer_query.add_subquery(inner_query, using)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/sql/subqueries.py", line 209, in add_subquery
    self.subquery, self.sub_params = query.get_compiler(using).as_sql(with_col_aliases=True)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 420, in as_sql
    where, w_params = self.compile(self.where) if self.where is not None else ("", [])
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 373, in compile
    sql, params = node.as_sql(self, self.connection)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/sql/where.py", line 79, in as_sql
    sql, params = compiler.compile(child)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 373, in compile
    sql, params = node.as_sql(self, self.connection)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 96, in as_sql
    return super(RelatedIn, self).as_sql(compiler, connection)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/lookups.py", line 381, in as_sql
    return super(In, self).as_sql(compiler, connection)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/lookups.py", line 170, in as_sql
    rhs_sql, rhs_params = self.process_rhs(compiler, connection)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/lookups.py", line 372, in process_rhs
    return super(In, self).process_rhs(compiler, connection)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/lookups.py", line 229, in process_rhs
    return super(FieldGetDbPrepValueIterableMixin, self).process_rhs(compiler, connection)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/lookups.py", line 100, in process_rhs
    sql, params = compiler.compile(value)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 373, in compile
    sql, params = node.as_sql(self, self.connection)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 420, in as_sql
    where, w_params = self.compile(self.where) if self.where is not None else ("", [])
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 373, in compile
    sql, params = node.as_sql(self, self.connection)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/sql/where.py", line 79, in as_sql
    sql, params = compiler.compile(child)
  File "myproject/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 373, in compile
    sql, params = node.as_sql(self, self.connection)
  File "myproject/venv/lib/python3.6/site-packages/django/contrib/gis/db/models/lookups.py", line 143, in as_sql
    sql_params.extend(rhs_params)
AttributeError: 'tuple' object has no attribute 'extend'


--
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+unsubscribe@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/e7ccec2f-244c-424f-9603-f532931c5109%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.