Re: where to report django issues?

2019-09-22 Thread James Schneider
>From the main website: https://code.djangoproject.com/

Also from the FAQ:

https://docs.djangoproject.com/en/2.2/faq/help/#i-think-i-ve-found-a-bug-what-should-i-do

https://docs.djangoproject.com/en/2.2/internals/contributing/bugs-and-features/#reporting-bugs

HTH,

-James

On Sun, Sep 22, 2019, 10:53 AM MW  wrote:

> unlike other github project, there is no "issues" link on
>
> https://github.com/django/django
>
>
> I'm wondering where to report django (source code) issues?
>
> 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 view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/2228313e-f816-4386-aa0d-6ebdff5963da%40googlegroups.com
> 
> .
>

-- 
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/CA%2Be%2BciWtPzafHcUqy%3DG7J%2BfGVBq_-jKev4rAX0r2DRqkzPnm%2BQ%40mail.gmail.com.


Re: Reverse for 'modification' with no arguments not found issue

2019-08-31 Thread James Schneider
>
> The line with a problem is that one
>
> return render(request, 'insertion/modification.html', locals())
>
>
>
> And I really can't figure it out why, according the fact that "locals()"
> contains my variable and even if I send directly my variable instead, I get
> the same !
>

There's probably a URL tag in that template that is missing a variable or
has a typo in the variable reference. The error is complaining about a
reverse call, not a render call. It might be in a different part of the
traceback or error page. You need to look closer at the original error
page, it probably cites something in the modification.html template, and
you didn't post that one.

-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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciXbr%3DtVaF5HredGqGK0LQ_9SiHuNKcv1%2Be0HFn1cX-zEQ%40mail.gmail.com.


Re: Reverse for 'modification' with no arguments not found issue

2019-08-28 Thread James Schneider
On Wed, Aug 28, 2019, 2:00 AM Ali IMRANE  wrote:

> Thanks James for your help.
>
> Indeed, I tought about that problem but I already managed to see an number
> on an other page, as well as using that ID to read information behind my
> informations (as you can see in the third line I gave on "lire.html"). A
> number is printed. How can I know that it is an *int* and not a *string*
> use in there ?
>

In the template it won't matter whether it is an int or a string, it gets
implicitly converted to a string for the regex match anyway.



>> # Nous pourrions ici envoyer l'e-mail grâce aux données
>> # que nous venons de récupérer
>> envoi = True
>> redirect(home)
>>
>>
What is the home variable in the redirect statement above? It isn't defined
in your view. I think that will need an extra argument. What line is the
traceback actually complaining about?

-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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciUugGMgB6JhMkLpYc59s7%3DFi6ES3ccvRgPk%2BtXNCX2DxA%40mail.gmail.com.


Re: page not found but url exists

2019-08-26 Thread James Schneider
> Using the URLconf defined in bnt.urls, Django tried these URL patterns,
> in this order:
>
>1. admin/
>2. [name='home']
>3. /login [name='clogin']
>4. /login/customer [name='cpage']
>5. /register [name='cregister']
>6. /register/customer [name='cpage']
>
> The current path, register, didn't match any of these.
>


I'm assuming your template has a typo in the {% url %} tag referencing
'register' instead of 'cregister'.

The rest of the error page should indicate the line that is making the URL
name resolution call.

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


Re: reload the page and the logged in user converted to the admin

2019-08-24 Thread James Schneider
> request.user there is a current user, but if I reload the page, the
> currennt user converted to the admin ?
> Enter code here...
> def countries_rate(request):
> auth_user = request.user
> if request.user.is_authenticated:
> auth_user = request.user
> if (user_rate.objects.filter(user_id=auth_user).delete()):
> print(auth_user,' OK deleted .')
> formset = countriesFormset(request.POST or None)
>


Not sure if it's related, but is there a reason you immediately delete the
logged-in user as soon as the page loads? Even before any forms are
submitted?

-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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciUTY%3DyMCqqRVQWPQyaq7%3D7D2-Zs-3wNK0HfH%2BCXRURkAQ%40mail.gmail.com.


Re: Get queryset outside models.py

2019-08-23 Thread James Schneider
>
>
> I would like to know if it is possible to retrieve *models*.mymodel
> instance from outside the models.py to retrieve a queryset.
>

Yes, a vast majority of the time you'll be retrieving instances from your
views and templates. There are only a few cases where you would retrieve
instances within models.py.


> I want to make a selection in a specific model but I am not inside the
> model.
>

In almost all cases you will NOT be inside of the code for the model when
pulling instances from the database.


> I need to perform some update in my action  model but the information is
> in another entity.
>
> I tryed to use Manager (mymodel = models.Manager() but I havn't found any
> function to get an specific queryset from Manager.
>
> Could someone help me with this issue?
>

Without the specific code you are using, I can't comment on what issue you
are having, however, the one line you provided doesn't appear to follow the
convention if you are replacing the default model manager. More information
can be found here:


https://docs.djangoproject.com/en/2.2/topics/db/managers/#custom-managers


However, given the other questions you are asking, I doubt you have need
for a custom model manager at this stage. I have a feeling you are
implementing it simply to address other built-in functionality you want
that you may not be aware of how to access. I could be wrong, though.

I'd recommend running through the official tutorial, as that covers the
information to answer your questions and broaden your understanding in some
detail.


https://docs.djangoproject.com/en/2.2/intro/tutorial01/



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


Re: Hello, everybody! I've tried using FormMixin with DetailView and I get error 405 on post method. Can anybody help me? Thanks a lot.

2019-08-22 Thread James Schneider
Post the full error message and/or traceback reported by the server when
the error occurs.

-James

On Thu, Aug 22, 2019, 12:31 PM Catalina Popescu <
catalina.t.pope...@gmail.com> wrote:

> views.py
>
> class BookDisplay(DetailView):
> model = Book
> template_name = 'books/book_detail.html'
>
> def get_context_data(self, **kwargs):
> context = super().get_context_data(**kwargs)
> context['form'] = WishBookForm()
> return context
>
> class WishBook(SingleObjectMixin, FormView):
> form_class = WishBookForm()
> template_name = 'books/book_detail.html'
> model = Status
>
> def post(self, request):
> if not request.user.is_authenticated:
> return HttpResponseForbidden()
> self.object = self.get_object()
> return super().post(request)
>
> def get_success_url(self):
> return reverse('books/book_detail', kwargs = {'pk': self.object.pk
> })
>
>
> class BookDetail(View):
> def get(self, request):
> view = BookDisplay.as_view()
> return view(request)
>
> def post(self, request):
> view = WishBook.as_view()
> return view(request)
>
> forms.py
>
> class WishBookForm(forms.Form):
> status = forms.ChoiceField(choices=Status.GIVEAWAY_STATUS[:2],
> initial='Cu chef de ducă')
>
>
> --
> 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/231fd7dc-3bf2-465c-993b-c476b0ca4dc1%40googlegroups.com
> 
> .
>

-- 
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/CA%2Be%2BciX1baRiKGuYZZcjdMeDyPpicaiqk9aP2fyLMnQEBFQdDw%40mail.gmail.com.


Re: Reverse for 'modification' with no arguments not found issue

2019-08-22 Thread James Schneider
>
> lire.html
> ...
>type="button">Editer larequête
> ...
>
> urls.py
> path('edit/', views.view_modif, name='modification'),
> error :
> NoReverseMatch at /edit/1
>
> Reverse for 'modification' with no arguments not found. 1 pattern(s) tried: 
> ['edit/(?P[0-9]+)$']
>
> Request Method: GET
> Request URL: http://127.0.0.1:8000/edit/1
> Django Version: 2.0
> Exception Type: NoReverseMatch
> Exception Value:
>
> Reverse for 'modification' with no arguments not found. 1 pattern(s) tried: 
> ['edit/(?P[0-9]+)$']
>
> Exception Location: /usr/lib/python3.7/site-packages/django/urls/resolvers.py
> in _reverse_with_prefix, line 632
> Python Executable: /usr/bin/python
>



The error is saying you have no arguments to the {% url %} tag. Make sure
that req.id is actually resolving to an integer value.

Templates are fun when they mask missing values like that. You already have
it displayed earlier in the template. Comment out the {% url %} tag and see
if a number is displayed in your template.

-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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciWV4K7%2BvTb8q8sGQBnbsY9t4srQK%2BH_NSZMCKSNp6KnAA%40mail.gmail.com.


Re: Syntax Error django, python issue

2019-07-28 Thread James Schneider
On Sun, Jul 28, 2019, 10:54 AM Kean  wrote:

> Hi Chetan
>
> pls see setup below
>

It looks like you may have copied in the ellipses (...) from the example.
Remove those lines and try again.

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


Re: How to set (global) context value from a templatetag?

2019-07-28 Thread James Schneider
>
>
>
> from django.template import RequestContext; rc = RequestContext(request)
>
>
> rc contains all the context that had been passed on to TemplateResponse
> within the view, o I want to add few more there from the template tag and
> just cant figure out how.
>
> Thanks a lot for any ideas!
>

First thing that comes to mind:

https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/#setting-a-variable-in-the-context


If you'll be using these same variables in a majority of your templates,
then I'd recommend looking at a custom template context processor:

https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/#setting-a-variable-in-the-context

That way you can define constants in you application code and have them
automatically pulled in as template variables in all your templates without
having to repeat a template tag in every template.

-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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciVc6t6NCVgHOGX_WUpgBnkVe%2BtxF-8gG6-i5Ou-G_4Rbg%40mail.gmail.com.


Re: Running pending migrations in Middleware

2019-07-28 Thread James Schneider
On Sun, Jul 28, 2019, 12:47 AM David Grant  wrote:

> Anyone see any problems with running migrations in Middleware?
>

What's the actual problem you are trying to solve by doing this? This is a
bad idea for a number of reasons, and I can't think of any good ones.

-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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciU%3DL5K-sBT6PkeUk4MpQYxxrSVLDLQ%3DZE2MmTF76BY7Uw%40mail.gmail.com.


Re: Accessing request from form

2019-05-31 Thread James Schneider
>
> Don't beat yourself up :)
>

It's actually slightly cathartic and humbling to do that every once in a
great while. ;-)


> No-one stops looking and just waits for the answer. You have to assume
> your own motivation to find it is stronger than everyone else's. It is just
> good manners to report back so others can stop looking. And it would be bad
> manners to say you fixed it without revealing the fix.
>

Yeah, that's a pet peeve of mine so I made sure to include the answer.


> Actually, no-one else even looks unless they are particularly interested
> or they encountered the same problem within recent memory.
>

Can't say I'm not guilty of doing that as well. I'm a college lecturer in
one of my many positions, so I do like the academic challenge that some of
these questions pose, even if I haven't needed it myself. However, on more
than one occasion I have run into one of the landmines that I've helped out
on in the past, and it's saved me a fair amount of time.


> Except you. You have helped me more than once in the past and I appreciate
> it. Thank you. Ten extra points!
>

Haha, thanks. I'll take the points. I wish I had the time to be more active
on this list, but the wife says I have to pay attention to her and the
kids, and I'm only allowed to have 2 jobs and 1 hobby. Luckily my current
hobby overlaps with Django so here I am.

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


Re: Accessing request from form

2019-05-30 Thread James Schneider
I always dread being the guy that responds to his own thread with "Hey
guys, I fixed it."

At any rate, I'm currently stuck having to create relatively empty
> ModelForm shell classes for the simple reason of including a form mixin
> that grabs the request before __init__() (because the ModelForm complains
> if I don't), and overrides save() to save the fields with the user object,
> in addition to specifying the form_class in the CBV along with a view mixin
> for sending the request over via get_form_kwargs(). It's quite a process,
> especially when dealing with multiple models. I could drop a significant
> amount of code if I could flag the CBV to include the request with the form
> initialization. Heck, there could even be some magic to have the form
> associate the user with specific fields on save from the view as
> form_kwargs.
>
> Or am I making things hard on myself? Thanks.
>

For the use case above, I had an epiphany did some more experimenting and
figured out how to update the audit fields without needing to mangle a
Form/ModelForm, entirely from the CBV:

 def form_valid(self, form):
form.instance.updated_by = self.request.user
return super().form_valid(form)

Fully compatible with an implicit ModelForm, and only 3 lines of code!

This is an easy drop in a view mixin, which I already have for other
overrides anyway. However, this feels really gross, and I feel like I'm
violating some prime directive by attaching data to an instance that was
not validated by the form. I think I can forgive myself since the data I'm
attaching is coming from Django and not some other source, and I have to
assume Django handles these things properly.

Of course while writing this message, I then stumbled on this exact
solution buried in the Django docs:

https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-editing/#models-and-request-user

So, feel free to ignore me. I will grant myself a point for coming up with
the same solution already blessed by the Django devs. I'm also deducting a
point from myself for not RTFM properly, so I break even.

-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/CA%2Be%2BciVKk6V6gpwF5FW8%3D-1ib%3D-xj6UX4-cceL3Fco12BpkfUg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Accessing request from form

2019-05-30 Thread James Schneider
Does anyone know a philosophical reason (or I suppose a technical one,
although I don't think that's the case) why the request is not made
available by default in ModelForms when using CBV's?

Almost all of the models I use have "audit" fields (created_by, updated_by,
etc.) that reference the current logged in user. A ModelForm has no access
to the current request, and as such can't update these fields without a
User object. I have other use cases as well, but this one is probably the
most prevalent among other developers.

At any rate, I'm currently stuck having to create relatively empty
ModelForm shell classes for the simple reason of including a form mixin
that grabs the request before __init__() (because the ModelForm complains
if I don't), and overrides save() to save the fields with the user object,
in addition to specifying the form_class in the CBV along with a view mixin
for sending the request over via get_form_kwargs(). It's quite a process,
especially when dealing with multiple models. I could drop a significant
amount of code if I could flag the CBV to include the request with the form
initialization. Heck, there could even be some magic to have the form
associate the user with specific fields on save from the view as
form_kwargs.

Or am I making things hard on myself? Thanks.

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


Re: set python 3.6.8 default in my ubuntu

2019-05-22 Thread James Schneider
No
On Wed, May 22, 2019, 10:22 AM johnpaul mulongo 
wrote:

>
>
> On Wednesday, May 22, 2019 at 3:48:16 PM UTC+3, omar ahmed wrote:
>>
>> hello ..
>> just finished my first project with django but i can not publish it
>> because my default python is python 2.7.12 and Heroku now does not support
>> it ..
>> now i installed python 3.6.8  how can i set it as default python
>> version to make my projects with virtualenv ?
>> thanks in advance
>>
>
> You could also try to check out pyenv .
> It's a pretty handy when dealing with python versions.
>
> --
> 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/7d9828d2-eaae-4f78-a551-b612edd89080%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

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


Re: Sponsor subdomain pointing to part of our Django site?

2018-06-04 Thread James Schneider
On Mon, Jun 4, 2018, 12:37 PM Melvyn Sopacua  wrote:

> On maandag 4 juni 2018 20:40:03 CEST Richard Brockie wrote:
>
> > On Mon, Jun 4, 2018 at 9:01 PM Melvyn Sopacua 
> wrote:
>
> > > This isn't a problem. Neither url nor reverse is capable of returning
> URLs
>
> > > with hostnames, at least not that I'm aware of. Only
> django.contrib.site
>
> > > <
> https://docs.djangoproject.com/en/2.0/ref/contrib/sites/#getting-the-curr
>
> > > ent-domain-for-display> module can do this for out-of-band
> communications.
>
> >
>
> > Aha - there's an error in how I posed the question. I was confusing the
> url
>
> > and reverse() outputs with the links as interpreted by a browser.
>
> >
>
> > If http_host is ''subdomain.sponsor.url" we are at the site using the
>
> > sponsor's alias which maps to a unique "/year/slug/" on our site (just
> one
>
> > of many). In this case, we require the output of {% url %} and reverse()
> to
>
> > have 2 possibilities:
>
> >
>
> > 1. Normal operation (with our default http_host): returns the full path:
>
> > "/year/slug/some/more/path/"
>
> > 2. Sponsor http_host: returns a trimmed path: "/some/more/path". Here
>
> > "/year/slug" is suppressed as it is built into the
>
> > ''subdomain.sponsor.url" alias.
>
> >
>
> > I hope this clarifies what we think we need to do
>
>
>
> Aha! Now I get it! This should be solveable at the WSGI layer:
>
>
>
> PATH_INFO
>
> The remainder of the request URL's "path", designating the virtual
> "location" of the request's target within the application. This may be an
> empty string, if the request URL targets the application root and does not
> have a trailing slash.
>
>
>
> See https://www.python.org/dev/peps/pep-0333/
>
>
>
> A URL rewrite or proxy at the webserver level should work as well. It may
> take a bit of experimenting.
>


Would URL rewrites solve this? How does that affect URL's generated in the
template?

It sounds like a separate 'site' with the sites framework is needed, along
with a modified urls.py that does not include the year and slug in the path.

Your might be able to use the existing urls.py by making the year and slug
optional in the regex. When using the sponsored site, you would pass along
extra context to the URL dispatcher that includes the year/slug or whatever
data is being assumed by the usage of the sponsor URL.

Basically, you need two different paths to the same resource, dependent on
the domain name or site in question.

Why not just leave the year and slug in and save yourself the extra work?
Is the vanity path a requirement or just 'nice to have'?

-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/CA%2Be%2BciVucZjzfOxfRwwJijUc%2BxpNVgJWJO%3Dc%2Bg_Ygo-t3tXdcQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Is it possible to instantiate a model (create an object) and flag the instance as unsaveable?

2018-06-02 Thread James Schneider
On Sat, Jun 2, 2018, 6:14 PM Bernd Wechner  wrote:

> I'd like to instantiate a model, and play around with it, but ensure it's
> never saved. At bare minimum instantiate it, play around with it then
> delete it, but ideally disable saving somehow. I imagine I can override
> save() on the instance, but am wondering if anyone has experience doing
> this or if there's a canonical method for doing it. I'll experiment but in
> the mean time fishing as I said for experience and any standard methods out
> there.
>

One way to make an obvious indication that the model instance is read-only
is to use a proxy model of the original, with all the saving bits turned
off. Keeps a nice separation of code while utilizing inheritance, and
allows usage of the original/standard behavior.

IMO, overriding the save() method in the proxy model is probably the
cleanest way to prevent an accidental save by a signal, etc.

https://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models

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


Re: Django UnicodeDecodeError

2018-04-17 Thread James Schneider
>
> iit's all right in unbuntu,but maybe something wrong with my windows.
>

Every time someone posts an error like this, it is because the hostname of
the machine contains a non-ASCII character. What is the hostname?

-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/CA%2Be%2BciVPYPRAo%2Bv1WVvit_U9pcqFUGnJpWSks%2BS%3D0rq9jNgzRA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Stripping HTML tags and replacing for newlines

2018-04-17 Thread James Schneider
>
>
> Now when I send the emails I of course want to send both text content and
> HTML. My idea from the beginning was to take my HTML content and strip the
> HTML tags and then send that. I did this via the django utils that strip
> tags. Now this works, HOWEVER I don't get any newlines for my  and
>  tags.
>
> I was wondering if anyone has had any similar issues and has found a good
> solution? What I want to do is strip all of the html tags and at the same
> time replace the  and  tags.
>

Why not regex substitute all of the tags you listed with newlines before
stripping the HTML out? I say use regex because you can do things like
specify multiple tags and account for things like case sensitivity.

I would also look at a Python HTML to plain text conversion library,
something like this:

https://github.com/aaronsw/html2text/blob/master/README.md

Never needed something like this, but looks interesting.

-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/CA%2Be%2BciVF2nFyF%2BfH74vaeYtFutsmdCxjtMf%3D9JhcHNrRD5njdg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Can you people explain why the def _str_() method is used below?

2018-01-06 Thread James Schneider
https://docs.djangoproject.com/en/2.0/intro/tutorial02/#playing-with-the-api


https://docs.djangoproject.com/en/2.0/ref/models/
instances/#django.db.models.Model.__str__


-James



On Jan 6, 2018 8:32 PM,  wrote:

from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()

def __str__(self):  # __unicode__ on Python 2
return self.name
class Author(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()

def __str__(self):  # __unicode__ on Python 2
return self.name
class Entry(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
n_comments = models.IntegerField()
n_pingbacks = models.IntegerField()
rating = models.IntegerField()

def __str__(self):  # __unicode__ on Python 2
return self.headline

-- 
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/ms
gid/django-users/4f8a3ff4-b0aa-4357-bff2-3ca1dc907de3%40googlegroups.com

.
For more options, visit https://groups.google.com/d/optout.

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


Re: How to delete all the objects which are referring the current object without DELETE_CASCADE

2018-01-04 Thread James Schneider
On Jan 3, 2018 4:29 AM, "Jani Tiainen"  wrote:

Hi,

As I posted on other thread you can do that using meta api.

But why you want to do that manually. DELETE_CASCADE does the same thing
exactly.



While I don't know the motivations of the OP, one reason you may want to do
this is for auditing purposes. There may be a requirement to track
additions and removals of records. I don't think a cascade delete would
capture enough information in such a case, even with a high level of
transaction logging.

-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/CA%2Be%2BciUtvGbtJt-kpDgv-muDnv7wgnDna9dhONfN%2BpJH8T-FmQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django storing byte string for image

2018-01-03 Thread James Schneider
On Jan 3, 2018 6:16 PM,  wrote:



As i am doing a django rest framework API for IOS mobile app currently, my
>> partner told me that he will sent me a byte string for image. Then i have
>> to convert the byte into image when a user request it.
>
>


Storing the file in the DB (be it an image or otherwise) is generally
considered bad practice because it bloats the database, can't be used
against searches, and may cause row results to be bloated if they include
the column containing the file.

Having the image in the DB also makes it difficult for other programs to
interact with the files. A common operation is to automatically generate
thumbnail versions of images for previews of a larger image.

I don't mean to store it into database. Its just i do not know how to do it
>> as there isnt much post online which talk about storing byte string.
>
>
You are better off storing the file directly on the hard drive using
Django's standard file fields, which simply stores the location of the file
on the hard drive along with some other Meta data.


I understand that storing byte string/images ? is a bad design, However, i
do not know which field to use first. From what i know, only ImageField and
FileField have the (upload_to=) save to path function. Thus i am stuck here
having no idea on what field to use.


You have a choice. If you store the raw byte string in a local file without
converting it, use a File fields. If you plan to convert the file to a real
image format before saving it, use an ImageField.

If there is no other reason to convert it and there is a chance that the
file will not be accessed later (or infrequently), then you may be able to
save some processing by not converting the file until it is later accessed,
converting it on the fly as you serve it out. If the images are likely to
be accessed later or more than once, it's probably better to convert them
up front so you can perform a straight file transfer later, which will be
cheaper on resources in the long run.


I also have another question , is storing byte string consider as storing
images ? As from my understanding, byte is not image, it is only after i
convert it then it becomes an image.


You're likely receiving a base 64 encoded byte string (or some variant of
that).

It doesn't matter what format the bytes will ultimately take on, it's still
a bad idea for the reasons I outlined above.

Django does have a BinaryField if you really have your heart set on it:

https://docs.djangoproject.com/en/2.0/ref/models/fields/#binaryfield

-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/CA%2Be%2BciX9T%2B%3Do0774kuoKiMeEU2cFTHO%2BsHQTfLuC961RUF_tuw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: I can't print a queryset value.

2018-01-02 Thread James Schneider
My other problem is when using a queryset value in my method:

This works:

insert_to_db(id)


But this does not:

insert_to_db(id, result)



Any help would be greatly appreciated :)


What is the insert_to_db function? That's probably where your issue is.
Without that code, there probably isn't much that anyone can tell you.

-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/CA%2Be%2BciVSCWBoF7rE143uL9N_Zp%3DiON1-Lrtz5FxxVcDC%3DxbhKw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: 404 for some matching urls too (Version 2)

2018-01-02 Thread James Schneider
On Dec 31, 2017 7:26 AM, "Sundararajan Seshadri"  wrote:

Thanks for the support and responses.

The error was due to an interesting line of code.

I had a middleware where I used:

match = resolve(request.get_full_path()) and this was causing the error I
mentioned.(get_full_path returns the query string too.)

I replaced it with

match = resolve(request.path_info)

and it is now working fine. Something to do with internal working? Any
simple explanation for my curiosity will be welcome.

Thanks everybody.


To me, this seems like intended and correct behavior. The URL dispatcher
does not normally receive paths that include the query string. The query
string is parsed separately and populates other portions of the request
object such as request.GET and request.POST.

https://docs.djangoproject.com/en/2.0/topics/http/urls/#
what-the-urlconf-searches-against

I'm not familiar with the resolve() function, but I assume it is calling
the Django URL dispatch process.

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


Re: Django: text, font, and style

2018-01-01 Thread James Schneider
On Jan 1, 2018 6:01 PM, "Malik Rumi"  wrote:

I'm sorry, James. What the heck is 'steering' in this context?


It's not, my phone auto corrected it to steering. It was supposed to be
'string'.

-- 
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/CA%2Be%2BciWXeUy8UCfkbXBaWdqETDBJL-D3doW80gJD-OH%3DTOn4ww%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django: text, font, and style

2018-01-01 Thread James Schneider
Have you verified that object.content contains un-escaped (raw) HTML? Is it
possible that the steering is being escaped before it is saved?


s/steering/string/

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


Re: Django: text, font, and style

2018-01-01 Thread James Schneider
On Jan 1, 2018 2:29 PM, "Malik Rumi"  wrote:

Well, as I said at the beginning, I don't seem to 'get' autoescape and
safe. For example, I put this in my template:

{{ object.content|linebreaks|safe }}

But the result in my web page is:

 Friday, November 17, 2017


Have you verified that object.content contains un-escaped (raw) HTML? Is it
possible that the steering is being escaped before it is saved?

What is the raw output from object.content in the shell?

Is content a real field on the model it is it a property or method that
potentially returns pre-escaped HTML? You may be marking the strings as
safe, but it appears that they may already be escaped before they hit the
template.


-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/CA%2Be%2BciUj0BkpqeqH%3Diaovsruftx%2BBK0mYhco1XW%3DMTxSZamV8w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: 404 for some matching urls too (Version 2)

2017-12-29 Thread James Schneider
admin/ [name='index']
admin/ login/ [name='login']
admin/ logout/ [name='logout']
admin/ password_change/ [name='password_change']
admin/ password_change/done/ [name='password_change_done']
admin/ jsi18n/ [name='jsi18n']
admin/ r/// [name='view_on_site']
.. (corresponds to the tables defined)
admin/ ^(?Prsi|auth)/$ [name='app_list']
login/ [name='login']
logout/ [name='logout']
authissue [name='authissue']
.

The current path, admin/login/?next=/admin/, didn't match any of these.


It looks like you have two different URL's named 'login'. Try changing one
of them so that they are unique.

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


Re: Still having trouble with django-filebrowser

2017-12-28 Thread James Schneider
However, the same treatment fails on my Windows runserver dev platform.
Brand new virtualenv for Py27 and Py36 still fail to show the little browse
link on the right-hand end of the Source field.


Have you verified that your Windows virtualenv is not including the global
system Python libraries as well? There may be a conflict at the system
level outside if your virtualenv. Inspecting the search path should reveal
where Python is looking.

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


Re: How to parse json and display it in CBV.

2017-12-27 Thread James Schneider
On Dec 27, 2017 1:02 PM, "tango ward"  wrote:

Follow up question. Apologies for the continuation.

I tried integrating the API from OpenDOTA https://api.opendota.com/api/h
eroes.

my code:

import requests
import json

url = requests.get('https://api.opendota.com/api/heroes')
res = url.json()

when I typed in 'res' in my terminal, it returns a List of dictionaries.
Now, is it possible to turn this list to a dictionary? Apologies for the
confusion, I am confuse as well.


The terms you are looking for are serialization (converting Python objects
to JSON) and deserialization (converting JSON to Python objects).

If you're using requests, and you can successfully run the .json() method,
then you successfully converted the JSON to a native Python structure.

In this case, you are requesting a list of heroes, so you received a list
back. You'll need to find the hero you want in the list using the standard
methods of working with Python lists, access that element, and then you'll
have access to the dict for that hero.

There is probably a way to get a single dict for a specific hero from the
API, but I'm not familiar with their API structure. You'll need to revert
to their API documentation to determine the correct URL structure.

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


Re: Search results in template

2017-12-26 Thread James Schneider
*And the result:*


!DOCTYPE This is the first page

   -

   ('2017-10-09 Incentive, a further review', 0.151982)
   -

   ('2017-11-14 Pulling The Trigger', 0.151982)
   -

   ('2017-10-05 A Failure of Incentive?', 0.121585)
   -

   ('2017-10-20 spider refactor', 0.121585) And now for something
   completely different...
   -

  :
  -

  :
  -

  :
  -

  :
  -



<<>>


So this looks like a variable problem, but I don't claim to understand
that, either. I mentioned earlier on this thread that different variables
gave me different results, but everyone says that can't be it.



Ah. Are you still chaining .values_list() to your query in the view? That
would explain the output above.

The loop is built with the assumption that we have full objects from the
ORM, but because we chained .value_list(), we're actually getting a list of
tuples containing two values.

Your templates are built in the same manner. Can you run the second loop
again with .values_list() removed from the query in the view?

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


Re: Search results in template

2017-12-26 Thread James Schneider
The template context says I have a queryset


I see it there. Can you post up the model for Entry?




And so does the selection


Yes. It appears that you will have 4 results in your queryset.



I put print statements in the view:

##
Quit the server with CONTROL-C.
This is the value of query:  SearchQuery(eaa)
This is the value of QuerySet:  
[26/Dec/2017 18:57:31] "GET /serp/?q=eaa HTTP/1.1" 200 66580

##


At this point, the view doesn't appear to be the problem. We need to start
tracking things down in the template code.




Note this is all done through my simple html search form, defined in the
template. My Django Form, SearchBox(), does absolutely nothing, as if it
isn't connected to anything. I don't understand what the problem there is,
I can't show that this is related or not. I do know I'd rather have the
functionality than a pretty form.


No reason you can't have both, but let's work on the result display issue
first.

An ordinary ListView of all objects works normally, as does my DetailView.
I have tried several times to re-write views.serp as a cbv with
get_context_data, but either context or request or Searchbox() end up being
undefined, or an ImportError.


Are you overriding get_context_data() correctly? It doesn't sound like it.


Finally, a screenshot of my search page, with four spaces for the 4 entries
that correctly correspond to the query 'eaa'. They just aren't there.


This is where the problem is, I think.

You should set up a simple loop in your template:


{% for obj in QuerySet %}
{{obj}}
{% empty %}
No results
{% endfor %}

If that works, you should go deeper per your Entry model:



{% for obj in QuerySet %}
{{obj.name}}: {{obj.weight}}
{% empty %}
No results
{% endfor %}

I'm using name and weight as an attribute of Entry, but you should use
something that matches your model definition. I think the issue is that you
are not referring to your model correctly within the search results within
the template.

-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/CA%2Be%2BciWvgD7-RnqWJvpKrpYvd2SB2TGwOW2bj4UOcKbtMJVR%3Dg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Search results in template

2017-12-24 Thread James Schneider
On Dec 23, 2017 5:36 PM, "Malik Rumi"  wrote:

FIRST, James, let me say how much I *greatly* appreciate you hanging in
there and trying to help me.


No worries.

2nd, as to your two points about the html:
   a. This template, serp_list.html, is identical to ktab_list.html, except
that serp_list has the title 'SEARCH' at the top and some bolierplate text
about this being the search results page. Other than that they are
identical, including the template for loop.
   serp_list is supposed to be called by localhost/serp/, which points
to views.serp, which is an FBV.
   ktab_list is a vanilla implementation of ListView, called by
localhost/index/, and it shows all Entry objects as you would expect.
   The header you see is the blog post header, ie, this is where the
title and the get absoulte url to the detail page is supposed to go. On
/index/ that works like it should. On serp, well, that's why I am here.
  b. Your second point is probably well taken, that the for loop should
completely wrap the article, and that might explain why the author and
comments part of the last three posts were not the same font as the first
post. I have changed that in the html, but it has not changed the result.


Hooray, at least I've gotten something right. ;-


3rd, just because things weren't complicated enough, now I am getting
inconsistent results. Whereas before I got views.serp called, a db query
with 4 results, on the right template, now I am getting a value error
('returns None' - how's that for a news flash?). The only difference is
that I downloaded the free version of pycharm to see if their visual
debugger would help me. So calling the page through pycharm, instead of the
regular terminal, is the only difference, and I don't think that should
make a difference. But either way, I still have no result on my page - and
oh yea, pycharm says the same thing my print statements did - that the
query was there and pulled up the expected objects. They just won't show up
on the template.


Confused. You mentioned PyCharm affected the results but then indicated the
same results?


4th, I don't know how relevant this is, but the form which created the
search box has the form action = '/serp/', but despite that, if I use the
search box in /index/, I stay on /index/ and just get the query attached to
the end of that url, rather than /serp/ plus the query. I have to manually
type in /serp/ to get  views.serp called. When it stays on  /index/ plus
the query, the result shown are just Entry.objects.all(), as you would
expect on a ListView. Any thoughts on that? Is it related? Why isn't my
form action working? THANKS!




A few (possibly dumb) questions:

Have you verified that the serp.html page is the one actually being
rendered? DDT can verify this.

Have you confirmed the context being provided to the template actually
contains the variables and query results you are expecting? DDT can also
verify this.

Can you do something simple like {{ object_list }} in your template just to
see if anything is printed? When doing quick troubleshooting I like to do
this:

|{{ object_list }}|

That way if I see || in the template (and source), I know the variable is
empty.

Do you have any non-standard middleware or template context processors
enabled?

Are your forms set to use a method of GET or POST? Sounds like GET but just
want to verify.

When you are on /index/ and you search, does the runserver console show a
hit against /serp/ (per the form action) or is it simply a hit against
/index/ again? Or is there a redirect for some reason?

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


Re: Search results in template

2017-12-22 Thread James Schneider
> 
> 
>   
>   {% for object in object_list %}
>   {{ object.title 
> }}
>   
>   
>   
>class="day">{{object.chron_date}}
>class="month">{{object.clock}} 
>   
>  by 
>  22 
> comments
>   
>   
>   
>   {{ object.content|truncatewords:30 }}
>   
>class="icon-tags"> tag 1, tag 2,  href="#">long tag 3
>   Read More
>   
> 
>   
>   {% endfor %}
> Any assistance in getting the search results to show up greatly appreciated.--
>
>
There is still an issue with the HTML from what I can see, your {% for %}
loop starts within an  tag, but the  tag is within the
{% for %} loop, so you are trying to create multiple article entries, but
only the first has an opening  tag. Not sure how/if that affects
the display of the results.

The point from my previous goof still stands, do your results show within
the rendered page HTML, but just aren't being displayed?

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


Re: Search results in template

2017-12-22 Thread James Schneider
Here's your problem. Your results are being entered in to your header and
not in to the body of the HTML. I bet if you look at the source code of the
rendered page, they're all there.


Scratch that, I'm thinking of  not .

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


Re: Search results in template

2017-12-22 Thread James Schneider



{% for object in object_list %}
{{ object.title 
}}



Here's your problem. Your results are being entered in to your header and
not in to the body of the HTML. I bet if you look at the source code of the
rendered page, they're all there.

-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/CA%2Be%2BciXhETi9wDRgDSiRKkpT4QoTrPA%3Dpt_KJzU1JZ-K2uTGVA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Search results in template

2017-12-20 Thread James Schneider
On Dec 19, 2017 5:12 PM, "Malik Rumi"  wrote:

I am implementing search on a local Django project: Django 1.11.5, Python
3.6.3, Ubuntu 16.04. My issue is getting the search results onto the
template.

I am using standard CBV for everything else in the site, but for this one I
wrote my own. It uses the same template as my ListView, which shows all
objects fine.



def serp(request):
if request.method == 'GET' and 'searchbox' in request.GET:
q = request.GET.get('searchbox')
query = SearchQuery(q)
object_list = Entry.objects.annotate(
rank=SearchRank(F(
'search_vector'), query)).filter(
search_vector=query).order_by(
'-rank').values_list('title', 'rank')
return render(request, 'serp_list.html', {'object_list': object_list})


Django Debug Toolbar reports everything went as expected. The right
template and view were called, as well as the right db query. I had
previously tested this query in the shell, and it pulls up a 4 element
queryset, as it should.


Your view has a bug. If the first 'if' statement returns false, then the
view fails because the 'q' variable is never set, and your viewer will get
a 500 error. I think the two lines following the 'q =' line should be
indented inside of the if statement, and object_list should be set to an
empty list by default before the 'if' statement.

You should also ensure that this view is the one that is actually being
called by the URL dispatcher.

Checking what is in the template context with the DDT is the next step. If
the template context is incorrect, then you'll need to debug within your
view to determine where/why the context is not being set correctly.

'object_list' is a generic variable name used by list CBV's in the template
context, but should be available to FBV's since there is no magic context
creation.

-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/CA%2Be%2BciUMp_1%2B7b%2BdOa7Xej5r4f1F%2B514Qh4%3Dsr2ue5%3DwpXAcFQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Many to Many fields and through table

2017-12-19 Thread James Schneider
On Dec 19, 2017 1:53 PM, "Mark Phillips"  wrote:

Is there any downside to creating a through table in a many to many
relationship when there isn't any "extra" related data, but there might be
in the future?

I have read that migrating from a simple m2m relationship to a m2m with a
through table takes some jumping through hurdles, so I am considering
creating the through table now in case "the powers that be" (ie end users!)
decide we need some extra data for the relationship in the future.

Thanks!


I don't believe there is any downside other than the extra few lines
required for the intermediary model definition. Functionally it is the same
AFAIK.

-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/CA%2Be%2BciV39kaHL%2BMwqdR_sba%3DrzehBw-5C5V8LqCoESiMkTBbHQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django picks up wrong urs in application urs.py

2017-12-18 Thread James Schneider
On Dec 18, 2017 7:19 PM, "Tsuyoshi Takahashi" 
wrote:

when application urs.py decribed as below

urlpatterns = [
url('card', views.card),
url('welcome', views.welcome),
url('cards', views.cards),
]

Django picks up "url('card', views.card)" when I enter
"http://localhost:8000/firstApp/cards/"; and
"http://localhost:8000/firstApp/card/";.


To me, this is expected and correct behavior.

Django will take the first match, not necessarily the best match. The word
'card' is contained in both 'card' and 'cards', and I believe Django uses
re.match() or a similarly behaving regex parser. Since your 'card' URL is
defined first, it matches. As you've shown, changing the order produces the
desired result.

The real fix is to properly terminate your URL regular expressions to match
as you desire so that the order doesn't matter. Try defining your URL's
like this:

urlpatterns = [
url(r'card/$', views.card),
url(r'welcome/$', views.welcome),
url(r'cards/$', views.cards),
]


The extra /$ at the end indicates that the URL will end with a /. That
should be enough to differentiate the requests.

See the URL dispatcher documentation:

https://docs.djangoproject.com/en/2.0/topics/http/urls/

If you aren't familiar with regular expressions, also see the Python re
module documentation:

https://docs.python.org/3.4/library/re.html

-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/CA%2Be%2BciVP-VtBNEhMQT%3DZnO35BK7BSo_rNSJ1xUvRaesZHuQknQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Model Design Questions

2017-12-17 Thread James Schneider
On Dec 16, 2017 4:46 PM, "Mark Phillips"  wrote:

I am building an electronic document management system using django and
mysql. The purpose of this system is to catalog and retrieve electronic
documents. There is no inventory of the physical documents. There are about
3,000 documents (photos, pdfs, videos) now, and that number could double in
the next year. The purpose of the site is to search for a set of documents
that share some given set of metadata values. I am wrestling with the model
design for the metadata part of this project.

I have identified about 30 internal metadata types particular to these
documents, and not related to any standards. If I use Dublin Core, there
are 71 types, but I would not need all of them, and there is some overlap
with the 30 internal metadata types - say another 25 types. Schema.org also
has an interesting set of metadata tags, and some may be applicable to this
project, and using that standard as well, could bring the number of types
to 75.


While I'm not familiar with these collections of metadata values that you
mentioned, if there is any chance that you'll need such standardization for
interoperability with external systems and/or standardized reporting, I'd
recommend going with the one that best fits your data. Amending extra
columns would give you the flexibility to add other attributes that don't
fit a particular standard.


As I see it, I have three options.

Option 1 - traditional database design, with metadata types as columns, and
values in rows. The document model would have approx 50 - 80 fields, and
one could expect out of 3,000 documents about 50-70% of the values are
Null.

This option is the most straight forward to create. I have no idea what the
performance would be for django and mysql, searching for a set of documents
in a model with 50-80 fields and 3,000 entries, where 60% are Null. Is this
a feasible design, or do I need to think of another way to model this
metadata? Will this scale to 6,000 documents? What if I need to add another
metadata standard to the site in the future? (I am not looking for job
security in this project)


With the numbers you are taking about here, you'll see zero performance
hit. Circle back around when you get close to hundreds of columns and/or
millions of rows.

Just be sure that you have heavy indexing enabled on all columns that will
be commonly used in search queries. This sounds like a high-volume read and
low-volume write database, which is the best kind. At the size you're
talking about, you can probably have the entire thing cached in memory and
make it super fast.



Option 2 - some sort of EAV design, with a table that has document_id,
metadatatype_id, and metadatavalue_id. I have read all sorts of posts about
the evils of EAV, but they seem to have peaked about 8 years ago, and now I
am seeing some posts that even recommend this design approach.

Is this approach a better fit for my particular application? Will it scale
to the numbers of documents and metadata I am thinking about? I really
don't want to go to the dark side if I can help it.


I have no experience with EAV design, but from a quick read, your concerns
about scale appear to be the opposite of what you think. I don't think you
have enough data to introduce the complexity of EAV and see any benefit.
EAV is designed for highly optimized Big Data databases that have millions
or billions of rows.


Option 3 - A hybrid solution that I have also read about. Put the more
common metadata types as fields in the model (columns in the database
table), and then JSON-ize the rest of the metadata for that document in a
string field in the model. This seems to put a rather large burden on the
application code when searching for a set of documents with a particular
set of metadata values.

The performance cost of this method seems to depend heavily on the
distribution of metadata types in the entire document set, and being smart
enough to pick the best common ones. If there were a set of metadata types
that span 90% of the the documents, then this would probably be a good
solution. Span only 25% of the documents, and there is a lot of comparing
values in the JSON string.


This one has potential, but it would need to be a judgement call on your
part. If you are hitting the JSON attributes for more than 25% (or whatever
threshold you choose) of your standard searches, then you'll need to add
more columns.


Thanks for any insights/recommendations you can provide!


Have you thought of using a document store database like MongoDB? It would
appear your use case is perfect for it. Of course you wouldn't have the
advantage of the Django ORM, but I wouldn't let that keep you from using
the right tool. There should be swaths of sites on it and dealing with your
exact use case. To me, trying to crowbar this in to an RDBMS (even Postgres
with HSTORE support) seems rigid, and would force you to customize every
single piece of the search process. Other indexing tools l

Re: No Reverse Match Exception

2017-12-17 Thread James Schneider
Update

It gives the No Reverse Error. I dont seem to understand why


Instead of User.id, try user.id, capitalization matters.


Trying not to confuse things, but in this instance you may instead want to
use object.id, since you may be referring to a different User object than
the one that is logged in. I made an assumption that the view will be only
modifying the logged in user.

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


Re: No Reverse Match Exception

2017-12-17 Thread James Schneider
On Dec 17, 2017 12:30 AM, "yingi keme"  wrote:

The problem is that, it works perfectly when i put the number on the
template like this

Update

But when i do

Update

It gives the No Reverse Error. I dont seem to understand why


Instead of User.id, try user.id, capitalization matters.

{% url 'Update' pk=user.id %}

The default context variable provided by django.contrib.auth is 'user' in
the template context, not 'User', which I'm assuming you are using.

Since the 'User' variable does not exist in your template context, it
resolves to '' (empty string), meaning that you are passing a PK of '' to
your view, which it is unhappy with. This is evidenced in the error message
you originally posted with an empty string showing as the argument to the
URL resolver:

Reverse for 'Update' with arguments '('',)' not found. 1 pattern(s)
tried: ['Core/UpdateMe/(?P\\d+)/$']


HTH,

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


Re: Passing parameters to SOAP Zeep client

2017-11-28 Thread James Schneider
On Nov 28, 2017 1:20 AM, "giuseppe ricci"  wrote:

I'm using Zeep library to query a SOAP webservice wrote in Java.
My piece of the wsdl file is:


This is the Django users mailing list, so we probably won't be of much
help. You should investigate the support forums for Zeep.

I piloted a small program using it a year or so ago, but I don't have much
experience with it as the project went south for other reasons. Neat
library to handle the awfulness that is SOAP.


ValidationError at /soapclient/
Missing element utenteApplicativo (creaCarrello.GestioneCarrelliRequest)
The problem it seems the manner of passing the parameters. With this other
manner:

call=client.service.creaCarrello(', {11223344, {'causale':'prova',
'codiceEnte':'CCIAA_MI', \
'importo':2, 'importoImposta':1, 'importoTotale':3, 'importoUnitario':2,
'quantitaItem':1, 'tipoContabilizzazione':'TA'}, },)

I receive the error: unhashable type: 'dict'.

Can you help me to understand what is the correct manner to pass these
parameters to the zeep client? There are a set of parameters inside another
set..Is it supported by zeep?
Thanks.

If memory serves, yes, you can nest parameters and values in a request,
pretty sure I've done it. However, your code is not using nested
dictionaries. It appears you are missing a dict key (and possibly a '
unless that's from sanitizing the code). The way your code stands, the
second parameter is a Python set, and the second element of that set is a
dict, which can't be hashed. Hashing is required for sets, but not for
dicts.

Most likely you meant for the set to be a dict, but forgot to include the
keys. I think Zeep exclusively used dicts and lists in their method calls
to ease XML serialization, unless something has changed recently.

But again, you'll find better help on the Zeep forums.

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


Re: reg:not able to open registration form web page

2017-11-18 Thread James Schneider
Here's how I would modify the view:


views.py


def SignUpFormView(request):
user_form = 'SignUpForm'
template_name = 'test.html'


Delete the above two lines. It appears you are mixing class-based and
function-based views. In this case, you are using a function-based view.


if request.method == 'POST':
form = user_form(request.POST)

Should be: form = SignUpForm(request.POST)


if form.is_valid():
form.save()
#username = form.cleaned_data.get('username')
#password = form.cleaned_data.get('password')
#email = form.cleaned_data.get('email')
#user.save()

You can remove these commented lines, it appears as though you were trying
to build the user object manually. Your firm can likely do this for you.

return render(request, template_name, {'form':form})


If the form is valid, then you should redirect to another page/view, not
return to the same page. This is a common and almost required pattern with
form submissions.

return HttpResponseRedirect('/signup_complete/')

The '/signup_complete/' should resolve to another page in your urls.py and
usually displays a message saying that the user was successfully signed up.
You can use any URL here that can be resolved by your urls.py.




else:
SignUpForm()

 This line just instantiates a new form object and then throws it away. It
should be used in the event that request.method is not 'POST' and you
generate a new, empty form for use in your template.

form = SignUpForm()



return render(request, 'user_info/about.html')


You aren't passing the form object that you are creating to your template
context, which is why it isn't rendering in your template.

return render(request, 'user_info/about.html', {'form': form})







test.html
-


As far as your template goes, remove everything within the 
definition and start with this:


{% csrf_token %}
{{ form.as_p }}
sign up 




Try these notifications and let me know how that works.

If you haven't already, I would try running through the Django tutorial,
which covers how to handle forms and other components of Django.

https://docs.djangoproject.com/en/1.11/intro/tutorial01/

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


Re: reg:not able to open registration form web page

2017-11-16 Thread James Schneider
On Nov 15, 2017 8:32 AM, "'Amitesh Sahay' via Django users" <
django-users@googlegroups.com> wrote:

Hello Members,

I am new to Django, and trying to create a mock Django registration page. I
am using default Django "User" model to do that, and I am not customizing
anything. Its a very simple form with 3 fields as follows:

'username','password','email'. Below are my python and html code details:


Snip...

views.py


def SignUpFormView(request):
user_form = 'SignUpForm'

template_name = 'test.html'

if request.method == 'POST':
form = user_form(request.POST)
if form.is_valid():
form.save()
#username = form.cleaned_data.get('username')
#password = form.cleaned_data.get('password')
#email = form.cleaned_data.get('email')
#user.save()
return render(request, template_name, {'form':form})


else:
SignUpForm()

return render(request, 'user_info/about.html')


Snip...

My issue is, when trying to launch the "register" page, its not going
inside "if" condition in views.py, rather its going directly to "else"
condition.

I am tried many things under my reach, but couldn't resolve the issue, and
stuck for 2 weeks now.
Any help would be appreciated.


There are several issues with the view composition. Please refer to the
docs here and verify your syntax matches the example:

https://docs.djangoproject.com/en/1.11/topics/forms/#the-view

Your template code also suggests that you are seeing duplicate form fields
(or perhaps they are being rendered in the source but aren't visible). It's
also possible that the Django form is not being created correctly in the
first place, which is why you need to manually render the form fields, when
the {{ form.as_p }} should be doing that for you.

If you are submitting the form and getting the behavior you describe, I'm
guessing that the if statement isn't being skipped, but the values being
submitted do not match the form object in Django, causing it to fail
validation, meaning that the second if statement is coming back False.

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


Re: Manager isn't available; 'auth.User' has been swapped for 'common.User'

2017-11-15 Thread James Schneider
On Nov 15, 2017 8:18 PM, "Mike Dewhirst"  wrote:

Any hints appreciated. I'm stumped. Traceback at the end.

Many thanks

Mike

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - -

I have a custom user based on AbstractUser plus a UserProfile model as
follows:

#common.models
from django.conf import settings
from django.contrib.auth.models import AbstractUser, Group, UserManager
from django.db import models
from django.utils.encoding import python_2_unicode_compatible


@python_2_unicode_compatible
class User(AbstractUser):

objects = UserManager()

class Meta:
abstract = False


Dumb question. I'm assuming you've set AUTH_USER_MODEL to use your new user
model?

Also, the Django contrib user model has a meta option for swappable,
perhaps you need to set that since you are overriding the Meta class?

class Meta:
abstract = False
swappable = True


Your Meta could also inherit from AbstractUser.Meta. Or better yet, since
abstract = False by default, just remove the entire Meta class and let the
defaults reign.

I have seen several tickets where the devs are playing with this option,
calling it a 'stealth new feature' and leaving it undocumented
intentionally, but it has something to do with changing out the user model
on existing projects.

-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/CA%2Be%2BciUZ4fThf2wc25eMaENAh58vvBU-YuYJ1hBUBAFE1%3DRZ7g%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


RE: Download a file on Django and delete it after return

2017-11-14 Thread James Schneider
On Nov 14, 2017 3:04 PM, "Matthew Pava"  wrote:

We can download PDFs in our project.

We start out generating the PDF on the server.  We read the contents of it
into a variable to put it into memory.  Then we delete the file on the
server (it’s still in memory), and the response is itself the PDF document.


Note that this strategy has two potentially negative side effects:

1. The original file is no longer available for a second attempt to
download in the event the first attempt fails. This may be fine if the file
is generated every time as part of the request.

2. Loading the file in to memory is usually find for smaller sites, but
high traffic sites can run in to memory resource issues.

You can also have a cron job delete files every so often based on their
age, rather than deleting them as part of the immediate response cycle.
That would save on memory, if that's a concern.

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


Re: Rails User management system to django user management system for REST API

2017-11-12 Thread James Schneider
On Nov 11, 2017 10:55 PM, "Asif Saifuddin"  wrote:

Hi,

I have and existing live project running on rails. I have to expose the
API's using django for now. I have generated models and edited them to
create django model and mapping and exposed some API locally.

I have one issue which is confusing my mind.

That is how would I use the existing users/authors etc from DB to django
User management system?

Any suggestion would be appreciated.


You would likely have to recreate the users on the Django side based on a
data dump from Rails. That part should be easy to do. If Rails does not use
a compatible password hash algorithm, then you probably can't copy the
password haha over. If that's the case, generate random passwords (or set
them as unusable, which I think Django supports) and force password resets.

If you want to authenticate against the existing Rails database, you'll
need to write a custom Django authentication back-end that knows how to
retrieve the Rails credentials and authenticate the user.

This could include an API call from Django to Rails to log in to the Rails
application. Once the user successfully logs in to the Rails app, I would
recommend creating the user locally in Django automatically (using the
password that just worked against Rails). If you have the built-in auth
system listed before your custom back-end, then the next time the user logs
in, they'll authenticate directly against Django, effectively migrating the
user transparently, and Django does not need to talk to Rails again for
that user. Note that the user will now unknowingly have two sets of
credentials, and changing the password on one system will not sync with the
other.

You can also potentially use Django to dip in to the Rails database, but
that would be much more messy.

SSO is also an option, although there's a fair amount of infrastructure
needed for that.

The API call is probably the easiest way to move the users over. Users who
don't migrate themselves by logging in can later be manually migrated by
creating users and forcing password resets, like I mentioned.

In any event, you'll probably be writing a custom authentication back-end.

https://docs.djangoproject.com/en/1.11/topics/auth/customizing/


-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/CA%2Be%2BciWWzNu4RXqxuVJR%2BnXZHxXPLrxZAhV_iOh-q%3Dc3JDPt0w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Callback Function Not running

2017-11-12 Thread James Schneider
But this callback function dont get to run. The API is to issue a  GET http
request to the url specified as my callback url.

The url specified is 'https://Jshhhtoo.localtunnel.me/callback/blue-cap'

And in my urls.py i have this pattern

url(r'^callback/(?P[-\w]+)/$', call_back, name='callback'),


Your regex is looking for a trailing slash. Try this URL or fix your regex:

https://Jshhhtoo.localtunnel.me/callback/blue-ca
p/

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


Re: Django raising error - hostname doesnot match.

2017-11-10 Thread James Schneider
On Nov 10, 2017 3:45 AM, "Rahul Paul"  wrote:

Hi,

I am using requests package to send a post request to an API within my
application.

I am using the request as :

*requests.post("https://xx.xxx.xxx.xxx/my-admin/api/api2
", data=data)*

where "xx.xxx.xxx.xxx" is the IP of my server on which this API is hosted.

When I am trying to call this API from my application, django is raising
an  exception as follows:

*SSLError: hostname 'xx.xxx.xxx.xxx' doesn't match 'xxx.com
'*

But when I put the domain name in the request i.e. "xxx.com", it gives me
proper result. Also when I put verify=False along with the request, my
application gives me proper result even with IP addess in the request.
However the very same API is returning proper result with both --- IP
address and domain name.


This is how SSL/TLS works. The certificate is based on the domain name in
the CN or SAN fields. It will never work with just an IP address and a
valid publicity signed certificate. If your CA is signing certificates with
IP's instead of or in addition to names, I would start a campaign to have
them shut down.


My server has a CA signed certificate but the DNS have forward entry but
doesnot have a PTR entry. I have also verified with digicert.com and found
that when I am entering the domain name, it is giving proper IP address but
when I am giving IP address, it is not able to resolve the domain name.

This API was functioning working correctly with IP address when we had self
signed certificate.


No, it didn't. That would indicate that you imported the self-signed CA
certificate into your trusted CA store. It would also mean that the
certificate was generated using the IP as the value of the CN or SAN. No
SSL library does that without a lot of coaxing, if it's even possible
anymore.



Also I am using nginx-gunicorn to run my application.

Please help me with understanding why this is happening and what are the
best possible solutions for this problem.


There is no problem to solve, you are just experiencing the joys of SSL,
and there are many. ;-)

Just make it a point to use the name.

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


Re: Unable to use custom StaticFilesStorage

2017-11-03 Thread James Schneider
On Wed, Nov 1, 2017 at 11:35 AM, Stodge  wrote:

> I'm trying to add an extra directory for each app that will contain
> Javascript/CSS files. I created a custom storage.py in my app containing a
> copy of the code from Django's AppDirectoriesFinder class, but I changed
> source_dir from "static" to "catalog". I'll include the Django code with
> the modified source_dir so no-one has to check the source code:
>
> class AppCatalogStorage(FileSystemStorage):
> """
> A file system storage backend that takes an app module and works
> for the ``catalog`` directory of it.
> """
> prefix = None
> source_dir = 'catalog'  <--- changed, was 'static'
>
>
> def __init__(self, app, *args, **kwargs):
> """
> Returns a static file storage if available in the given app.
> """
> # app is the actual app module
> mod = import_module(app)
> mod_path = os.path.dirname(upath(mod.__file__))
> location = os.path.join(mod_path, self.source_dir)
> super(AppCatalogStorage, self).__init__(location, *args, **kwargs)
>
>
>
> I added this to my settings file:
>
> STATICFILES_STORAGE = (
>
> 'myapp.storage.AppCatalogStorage',
> 'django.contrib.staticfiles.storage.StaticFilesStorage'
> )
>
>
> My understanding here is that I can then do:
>
> (Assuming my app name is fred)
>
> fred/catalog/js/someJavascript.js
> fred/catalog/css/someStylesheet.css
>
>
> I also assumed they would then be accessible as:
>
> /static/fred/js/someJavascript.js
> /static/fred/css/someStylesheet.css
>
>
> However, neither file is available at the expected URL. Did I
> misunderstand something?
>
>
Quite honestly, instead of doing all of this work, why not just
amend STATICFILES_DIRS with the location of your extra folder? Or just use
the designated 'static/app_name' location for your JS files? Seems like a
ton of trouble now and in the future to try and implement your own file
structure. A symlink from catalog -> static/fred would also have the same
effect if you are on a Linux system.

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


Re: return jwt token as json

2017-11-03 Thread James Schneider
   if user:
   payload = {
   'id': user.pk,
   'username': user.username,
   'staff': user.email,
   'exp': datetime.utcnow()


I think that datetime.utcnow() returns a datetime object, not a string, and
I don't think it can be serialized directly. You should try converting that
object to a string in the right format. As a test, substitute a static
string containing a date and time in whatever format you need. I'm not in
front of an interpreter so I can't test, but this seems to back up my
theory:

https://code-maven.com/serialize-datetime-object-as-json-in-python


Forgot to mention, you may also want to take a look at the built-in JSON
encoder, which handles datetime objects:

https://docs.djangoproject.com/en/1.11/topics/serialization/#djangojsonencoder

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


Re: return jwt token as json

2017-11-03 Thread James Schneider
On Oct 31, 2017 4:36 AM, "Rakhee Menon"  wrote:



class Login(APIView):

   def post(self, request, *args, **kwargs):
   import ipdb;ipdb.set_trace()
   username = request.POST.get('username')
   password = request.POST.get('password')
   user = Person.objects.get(username=username, password=password)
#user = user[0]
   #import ipdb;ipdb.set_trace()
   if user:
   payload = {
   'id': user.pk,
   'username': user.username,
   'staff': user.email,
   'exp': datetime.utcnow()


I think that datetime.utcnow() returns a datetime object, not a string, and
I don't think it can be serialized directly. You should try converting that
object to a string in the right format. As a test, substitute a static
string containing a date and time in whatever format you need. I'm not in
front of an interpreter so I can't test, but this seems to back up my
theory:

https://code-maven.com/serialize-datetime-object-as-json-in-python

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


Re: do i always have to reload/return render a page to show the errors? if i press go back on browser, i see screens with the error message

2017-11-02 Thread James Schneider
On Thu, Nov 2, 2017 at 12:57 PM, fábio andrews rocha marques <
fabioandrewsrochamarq...@gmail.com> wrote:

> To use django forms is to use the django Form class and it's components on
> a view? How will this solve the issue? If i use the components, don't i
> have to re-render the page when a user makes an error on the form?
>
>
Are you submitting and rendering the information entirely via JavaScript?
That would be the only case where you may get errant messages on the same
page where the user submitted the form. You'll need to examine your JS
workflow, as that is not a Django issue.

You'll integrate the form usage within your view. The Django tutorial
covers this using both function-based views and class-based views. You
should do this even when submitting the information via AJAX/JS, but the
page doesn't necessarily need to be redirected because your JS will handle
re-rendering the page properly. I'd recommend the Django Rest Framework
package in that case.

-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/CA%2Be%2BciVaD43g-u4tXc_Org%3DnX6%2BJuAdu1w%3Dtq0viQ9RA5gWYvQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Re-runnable sql scripts in the migrations framework

2017-11-02 Thread James Schneider
On Nov 2, 2017 4:01 AM, "Chris Wedgwood"  wrote:

Hi

As part of my deployment process I want to be able to have some db
scripts that are re-runnable

For example I have some internal configuration tables that I would
like to be able to change values with a merge statement in the same
file but not have to create a new migration file

I suppose my question is does the migration framework allow for
re-runnables?

If not can anyone recommend a good approach for this?


I have no idea what you are actually trying to achieve, but it sounds like
a custom management command may be able to get you there:

https://docs.djangoproject.com/en/1.11/howto/custom-management-commands/

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


Re: do i always have to reload/return render a page to show the errors? if i press go back on browser, i see screens with the error message

2017-10-31 Thread James Schneider
On Oct 31, 2017 11:02 AM, "fábio andrews rocha marques" <
fabioandrewsrochamarq...@gmail.com> wrote:

How did you use the never_cache? Because if i just put @never_cache before
the def of my view: def cadastrarprofessor(request):, it's like it doesn't
do anything (i am on the login page, I go to the registration page, inform
a name of a user that already exists, click "register", the system
refreshes the page telling me that the user already exists and when i press
the "back button" from the browser, it goes back to the registration page
with empty fields, which is not what iwant. I want to go back to the login
page, the page before the registration). Do I have to use @never_cache and
remove all the return render from my function? What should i return instead?


I would recommend you remove any modifications related to caching. Caching
is not your issue, and in most cases should only be tuned in specific
circumstances, and after your intended functionality is implemented and
working. Refer to my other thread for a different direction.

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


Re: do i always have to reload/return render a page to show the errors? if i press go back on browser, i see screens with the error message

2017-10-31 Thread James Schneider
On Oct 30, 2017 4:46 PM, "fábio andrews rocha marques" <
fabioandrewsrochamarq...@gmail.com> wrote:

Let's say i have a "register a new user" View and on this page, when the
user forgets to inform a password or a username, i show a message to him on
the same page saying "you forgot the password". The way i do this is by
doing this(on my View.py in a function called cadastrarprofessor):

nomeusuario = request.POST['usuario'] #username
nomesenha = request.POST['senha'] #password
nomeemail = request.POST['email'] #email

if not nomeusuario:
return render(request,'cadastro.html',{'cadastrorealizadocomsucesso':
False, 'error_message': "informe um usuário",
'nomeemailcadastro':nomeemail, 'nomesenhacadastro':nomesenha})
elif not nomesenha:
return render(request,'cadastro.html',{'cadastrorealizadocomsucesso':
False, 'error_message': "informe uma senha", 'nomeemailcadastro':nomeemail,
'nomeusuariocadastro':nomeusuario})
elif not nomeemail:
return render(request,'cadastro.html',{'cadastrorealizadocomsucesso':
False, 'error_message': "informe um email", 'nomesenhacadastro':nomesenha,
'nomeusuariocadastro':nomeusuario})

And my template for this page(cadastro.html) is like this:

Cadastro

{% csrf_token %}
Usuário: 
{% if nomeusuariocadastro %}

{% else %}

{% endif %}


... (DO THE SAME TO SENHA/PASSWORD AND EMAIL)





{% csrf_token %}

{% if cadastrorealizadocomsucesso is True %}cadastro realizado com
sucesso!{% endif %}
{% if error_message %}{{ error_message }}{% endif %}

So, every time the user forgets to mention a username or email or password
in this screen, i use render to redirect the user to the same page but this
time displaying a error_message. Let's say he did forget to fill the
textfield with a username... he goes back to the same page and sees the
error message. After that, let's say everything is right and he finally
registers a new user, he sees "cadastro realizado com sucesso"(sucessfully
registered new user) and stays on the same page. But when he goes back a
page(pressing "back" on the browser), instead of going back to the page
before the cadastro.html, he goes back to the same page cadastro.html but
displaying the error message for the "you forgot to mention your username".
I don't want him to go back to the same page with error message, i want to
make him go back to my main menu.


There is very little that you can do to prevent this type of behavior when
the user presses the back button.

After the user successfully authenticates, they should be redirected to the
proper landing page by using an HTTP 302 redirect. This is very common and
baked in to all of the generic form handling views provided by Django. If
the page is redirected, then the user will encounter a warning pop up from
the browser asking if they want to resubmit the data. Generally this is
enough to scare users away from using the back button, but even if they do
continue through the warning, they'll simply reauthenticate and be
redirected to the same landing page, again.

If that is not happening, them your form processing workflow is incorrect.

>From your view, you aren't using Django forms at all. I would highly
encourage you to do so, especially to better understand how form data
should be processed and validated, and how to properly handle responses
back to the client. The Django tutorial covers this topic.

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


Re: Creating a server problem

2017-10-30 Thread James Schneider
On Oct 30, 2017 9:09 AM, "md fahad"  wrote:

Hey I am just new to django
i have a problem using the term "from django.http import HttpResponce it is
showing error to it
so plz help me out


Check your spelling:

from django.http import HttpResponse

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


Re: MultipleChoiceField records down choices as a list, but CharField converts them to a list?

2017-10-30 Thread James Schneider
On Thu, Oct 26, 2017 at 7:54 AM, Jack  wrote:

> I have a model field for choosing multiple options.  Here is the code for
> models and forms:
>
> *models.py:*
> CONDO_APARTMENT = 'Condo Apartment'
> DETACHED_HOUSE = 'Detached House'
> SEMI_DETACHED = 'Semi-detached'
> TOWNHOUSE = 'Townhouse'
>
> PROPERTY_TYPE = (
> (CONDO_APARTMENT, 'Condo Apartment'),
> (DETACHED_HOUSE, 'Detached House'),
> (SEMI_DETACHED, 'Semi-detached'),
> (TOWNHOUSE, 'Townhouse'),
> )
>
> property_type = models.CharField(max_length=50, help_text="You can
> select more than 1 option")
>
>
> *forms.py:*
> property_type = forms.MultipleChoiceField(widget=forms.SelectMultiple,
> choices=BuyerListing.PROPERTY_TYPE)
>
>
> Let's assume the selected choices were 'Condo Apartment' and
> 'Semi-detached'.  The value stored on my database is this - ['Condo
> Apartment', 'Semi-detached']
>


Given your model definition, that means that a Python list object was
converted to a string and stored in a single database field, which means
that you no longer have a list, you have a Python string that looks like a
list.

If your model can have multiple values associated to a single object for a
single field, consider a M2M relationship with a table containing all of
the available options.



>
> Now this is in a list format, which makes sense, but it seems to have been
> converted to a string.  When I try to call on property_type in a .html
> document...
>
> {% for property in model.property_type %}
> {{ property }}
> {% endfor %}
>


This is slightly confusing. Is 'model' a context variable that you are
providing in your view? I'm assuming this refers to the object being pulled
from the DB. If that's the case, then this code is roughly equivalent to
the following:

for x in "['Condo ap'":
print(x)


You likely just need {{ model.property_type }} given your model definition.



>
> The result is displayed in singular characters, like this:
>
> [
> '
> C
> o
> n
> d
> o
>
> a
> p
>


Happens a lot in templates when they go too deep with the {% for %} tags.



> .. and so on.  Instead I want the result to be the values in the list,
> like this:
>
> Condo apartment
> Semi-detached
>
> How do I do this?  I tried experimenting with different model field types
> but CharField seems like the only appropriate one for MultipleChoiceField.
>


I think you're intermixing Model fields and Form fields, both of which have
very different functions. I did the same thing when I first started with
Django:

https://docs.djangoproject.com/en/1.11/ref/models/fields/
https://docs.djangoproject.com/en/1.11/ref/forms/fields/

These are not interchangeable as they have different purposes.

It's not necessarily clear what you are trying to do. Your template code
indicates one thing, and your textual description another.

According to your template code, you are simply displaying a static
unordered list of text blurbs on the page, no form elements involved. From
your other descriptions,  you are trying to display a select form control
with multiple options in it. A bit more guidance here would result in a
better answer.

-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/CA%2Be%2BciVDYn%2B1x4%2BF3bDu1rc%2B0pbj%2BVyZFtUXGJm9inNdZ6i2rw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django 11 ImproperlyConfigured: AUTH_USER_MODEL refers to model 'authex.UserProfile' that has not been installed

2017-10-29 Thread James Schneider
>
>   File "/Library/Python/2.7/site-packages/django/contrib/auth/forms.py",
> line 22, in 
> UserModel = get_user_model()
>   File "/Library/Python/2.7/site-packages/django/contrib/auth/__init__.py",
> line 198, in get_user_model
> "AUTH_USER_MODEL refers to model '%s' that has not been installed" %
> settings.AUTH_USER_MODEL
> django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to
> model 'authex.UserProfile' that has not been installed
>
>
> Any ideas ? Thanks !
>
>
Does INSTALLED_APPS in your settings.py file contain an entry for 'authex'?

-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/CA%2Be%2BciXaOovzY%3DM455AcmAM5H4jbffYT9F_%3DxsTDgMjxtS4h7A%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Passing 3 user inputs as argument in url, for a search form

2017-10-25 Thread James Schneider
On Wed, Oct 25, 2017 at 11:29 AM, Jack  wrote:

> I am building a search form where the user inputs 3 values on a form, and
> I search the database for all records that match the 3 inputs.  Right now I
> am stuck on the user input part.
>
> If you look at my *urls.py*, you will see that I tried to put 3 keywords
> arguments in there.  Then I tried to pass the 3 keyword arguments in the
> url tag with variables from my *forms.py*.  I think this is where things
> went wrong but I'm not sure.  I don't know if the .html file can use
> variables from *forms.py*
>
> Basically what I'm trying to do is to take the 3 user inputs, and pass
> them as arguments in the URL.  Right now I'm getting:
>
> NoReverseMatch at /
>
> Reverse for 'search-results' with keyword arguments '{'pt': '', 'nb': '', 
> 'nw': ''}' not found. 1 pattern(s) tried: 
> ['search?(?P\\w+)&(?P\\w+)&(?P\\w+)']
>
>
>
> *urls.py*
> url(r'^search?(?P\w+)&(?P\w+)&(?P\w+)',
> views.IndexSearchResults.as_view(), name='search-results')
>
>
This is not the correct usage of the URL dispatcher. It should look
something like this:

url(r'^search$', views.IndexSearchResults.as_view(), name='search-results')

The URL dispatcher does not match on GET arguments within the URL, that's
left for the request object to parse.

https://docs.djangoproject.com/en/1.11/topics/http/urls/#what-the-urlconf-searches-against



*views.py*
> class IndexSearchResults(generic.ListView):
> template_name = 'search-results.html'
>
>
The view is where your GET arguments will be processed. Note that if you
are submitting the form directly to the URL above, then no validation of
the form values will be performed. If you want those values to be
validated, you should submit to a FormView to validate the results and
redirect to this search page with the GET arguments in tow. I'd imagine
that both strategies are common, since sending bad values to search against
usually just results in bad searches. The ORM takes care of most of the
security concerns in this case.

You will want to override get_queryset() to add in your GET arguments for
filtering after retrieving them from the request object. The GET arguments
are automatically captured in to a QueryDict attached to the request:

https://docs.djangoproject.com/en/1.11/ref/request-response/#querydict-objects

So, in your IndexSearchResults view:

def get_queryset(self):
queryset = super().get_queryset()

# I can do something fancy with lists of tuples to cut down on the
code, but this is more readable
pt = self.request.GET.get('pt')
nb = self.request.GET.get('nb')
nw = self.request.GET.get('nw')

if pt:
queryset = queryset.filter(property_type=pt)
if nb:
queryset = queryset.filter(number_of_bedrooms=nb)
if nw:
queryset = queryset.filter(number_of_washrooms=nw)

return queryset


This should return a queryset to the view that will filter down the list of
objects matching the GET arguments.



>
> *models.py*
> Class BuyerListing(models.Model):
>  BEDS_OPTION = (
> (BEDS_0, '0 [Studio/Bachelor]'),
> (BEDS_1, '1'),
> (BEDS_1_1, '1+1'),
> (BEDS_2, '2'),
> (BEDS_2_1, '2+1'),
> (BEDS_3, '3'),
> (BEDS_3_1, '3+1'),
> (BEDS_4, '4'),
> (BEDS_5, '5'),
> (BEDS_5_1, '5+'),
> )
>
>  WASH_OPTION = (
> (WASH_1, '1'),
> (WASH_2, '2'),
> (WASH_3, '3'),
> (WASH_4, '4'),
> (WASH_5, '5'),
> (WASH_5_1, '5+'),
> )
>
> PROPERTY_TYPE = (
> (CONDO_APARTMENT, 'Condo Apartment'),
> (DETACHED_HOUSE, 'Detached House'),
> (SEMI_DETACHED, 'Semi-detached'),
> (TOWNHOUSE, 'Townhouse'),
> )
>
> property_type = models.CharField(max_length=50)
> number_of_bedrooms = models.CharField(max_length=50, default=BEDS_0)
> number_of_washrooms = models.CharField(max_length=50, default=WASH_1)
>

This might be correct, but generally you would use an IntegerField or
FloatField here rather than CharFields for the number of beds/baths. I'm
not aware of any exceptions where a number would not be used, but you may
know of some. Searching will be slightly faster using real number fields,
and you'll be able to filter using queries for 'more than 2 bedrooms' etc.,
which you can't do with CharFields. I'd imagine that is a desired feature.

 -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/CA%2Be%2BciWAitr%3DkgJuAgACzC%2BFAn4wBcaDiF9qEsOC5ne0fkkHPA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Adding several user models

2017-10-25 Thread James Schneider
> When you say 'share the database', are you referring to the same database
> server but separate database instances? Or are you expecting both projects
> to access the same tables in the same database instance?
>

It will be the same tables in the same database instance.


You like to live dangerously don't you? ;-)

That fact actually changes my perspective quite a bit. Typically with
separate but integrated projects, one project holds the actual user data,
and the other keeps a copy of a minimal subset of meta data, enough to
identify the user in the other application when necessary. That was my
assumption for my original response.

If they share the same underlying table, then they'll definitely need to be
in sync, and I would definitely recommend having a common model definition
between the two projects. You should probably pick one of the projects as
the 'master' where the migrations for that project will handle the
Participants table, and the other project model will be marked as unmanaged
to avoid migrations being needed. The likely candidate is the Participants
project since it has the more complicated functionality associated with its
user model.



>
>
> All of those issues aside, I wouldn't start with an abstract model
> inheriting from AbstractUser. I would create a clean abstract model
> inheriting from models.Model, and copy everything from AbstractUser over to
> your new abstract user model. Your Admin project would then define a
> concrete user model that inherits directly from your new abstract user
> model. Over in the Participant project, your concrete model would inherit
> from the abstract model created in the Admin project, and also
> from AbstractBaseUser and the PermissionsMixin, just like AbstractUser
> does. This way, you have a single model controlling what fields are made
> available in both applications, but only the Participant project model
> contains the extra machinery to use that model to authenticate/authorize
> users. The copy/paste operation probably violates DRY for some purists, but
> you'll likely be modifying those fields at some point anyway, so I consider
> it a necessary evil.
>

I agree with this setup - however I would like more fine grained
permissions in the admin project.


Sure, but having the models set up in such a way shouldn't prevent that.
The Participant objects are not real end users in that context (or at
least, I'm assuming they can't log in), just regular models, so they won't
need permissions assigned to them. It would be a combination of assigning
correct permissions to your Admin users and filtering the views and
serializers appropriately.

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


Re: Adding several user models

2017-10-24 Thread James Schneider
On Oct 24, 2017 3:46 AM, "Andréas Kühne"  wrote:

Hi all,

I would love to pick your collective brains for a second. I am working on
an application that will be first and foremost an administration system. As
such there will be very few users in the system. It will have a front end
developed in angular 5 and a Django rest framework backend.

I have got the solution up and running currently and it works as I think it
should. However - now I have another idea that I would like to hear your
opinions on.

Connected to this system we will also have other portals where a user will
be able to login - NOT the same user as the user that logs onto the
administration system - but an entirely different concept (a participant).
These portals will probably be running on another machine (but not
necessarily) and can have their own user concept. This application will
also be more of a traditional Django project with a standard view and
template driven design.

I am thinking about creating the Participant model separate from the User
(they are different concepts) and therefore was wondering if it would be
possible to create the Participant model based on an AbstractUser from
django contrib auth and then in the portal project use that as the user
model?


Short answer is yes, with caveats, but it may not be recommended.

The long answer: There's no technical reason that a model defined in one
project cannot serve as a reference for another project. The common code
just needs to be accessible from both projects. This works the same way as
any other Python library, because after all, Django models are just Python
code.

There are logical and design issues with doing it, though. A change in the
Admin project for the abstract user model will now propagate to the
Participant project, possibly in a negative way. You'll need to execute
tests for both your Admin and Participant projects whenever changes are
made to that model. Adding new features is usually easy, but deprecating
code can be a nightmare, as you now have two code bases that need to be
analyzed rather than one. You've also directly coupled the two projects
together from a semantic versioning standpoint. Even with no changes to the
Participant project, a change to the abstract model in the Admin project
now forces a migration for the Participant project (if a field is
modified), and likely a version bump for the Participant project so that
those running your software pick up the changes, even though there were no
modifications made to the Participant project itself.

I'd ask how important it is that these two models be coupled in such a way?
Granted, adding common fields between the two is handy, but for the reasons
above, it can be dangerous. It's likely that the Admin project only needs a
very small subset of the fields that the Participant project needs, and the
Admin app has no use for any of the authentication/authorization backend
functionality that gets dragged along with AbstractUser.

Has anyone every done anything similar? Is this idea completely wrong? Any
other things that I should think about?


Yes, in the sense that developing a 3rd party app for both projects is
effectively what you are doing. These are the same issues faced by 3rd
party app developers for Django, where a 1-line change in a 3rd party
module requires a migration for anyone that is using the app.

It's not necessarily wrong, there are just a number of issues to consider
with the coupling between the projects that you'll be creating.


My main reason behind this idea is that the applications will share the
database, but be completely different projects and shouldn’t necessarily
share a web app? Is this also a wrong idea or does this sound sane?


When you say 'share the database', are you referring to the same database
server but separate database instances? Or are you expecting both projects
to access the same tables in the same database instance?


All of those issues aside, I wouldn't start with an abstract model
inheriting from AbstractUser. I would create a clean abstract model
inheriting from models.Model, and copy everything from AbstractUser over to
your new abstract user model. Your Admin project would then define a
concrete user model that inherits directly from your new abstract user
model. Over in the Participant project, your concrete model would inherit
from the abstract model created in the Admin project, and also
from AbstractBaseUser and the PermissionsMixin, just like AbstractUser
does. This way, you have a single model controlling what fields are made
available in both applications, but only the Participant project model
contains the extra machinery to use that model to authenticate/authorize
users. The copy/paste operation probably violates DRY for some purists, but
you'll likely be modifying those fields at some point anyway, so I consider
it a necessary evil.

IMO, the number of fields that actually need to be shared between the
projects is quite small (less than a do

Re: DoesNotExist behavior in db.models query.py

2017-10-23 Thread James Schneider
On Oct 23, 2017 4:06 PM, "'Aaron C. de Bruyn' via Django users" <
django-users@googlegroups.com> wrote:

The difference between .filter() and .get() is definitely 'by-design'.

When you filter through a list of objects, you could end up with zero,
one, or many objects returned.

When you call .get(), you are basically saying "I want to get exactly
*one* record".  If the record is not found, it is considered an error.

One additional difference is that .filter() returns a list of zero or
more objects whereas .get() returns the object you requested or it
throws an error.


A further distinction is that .filter() returns a single Queryset object,
not a list of objects found via the query. It is only converted to a true
list of objects when it is used (lazy), meaning that the query to the DB is
delayed until the last possible moment. This allows for chaining of
multiple .filter() calls or other ORM operations to be appended before the
DB query is executed.

A .get() call returns the actual object, meaning that you can't chain other
filters on to it.

A small distinction, but can land you in trouble if the database state
changes between the creation of a Queryset object and when it is actually
executed.

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


Re: How to store a key to a something that can be either a person or an organization?

2017-10-23 Thread James Schneider
On Oct 21, 2017 2:06 AM, "Antonis Christofides" <
anto...@djangodeployment.com> wrote:

Hello James,

You are right that the correct term in everyday language for the superclass
of organization and person is "entity". However, I didn't want to name it
"entity" in the code, because, really, "entity" is a different thing in
programming, it's a term like "object". It would be very confusing. The
reason I didn't name it LegalEntity is exactly that it might not be legal.
I chose to invent a new term, "Lentity", which ensures that someone will
not (mis)understand it just by looking at the name and will necessarily
look it up.

IMO if you name things in such a complicated fashion that others have to
look them up, they probably aren't very good names. Even worse that you've
arbitrarily shortened the name non-intuitively. I don't like it, but if it
works for you, more power to you.

I think that my design is "correct" from a theoretical point of view.
Inheritance is the way to solve such a problem in OOP, and multi-table
inheritance is the way to solve this problem in relational databases.
That's what the books say anyway.

Usually, but in this case, your OOP design also influences your DB schema,
which has different implications and philosophy to consider. RDB's don't
support the concept of inheritance AFAIK.

In theory, theory and practice are the same. In practice they differ. :-)

Always.

My design generally works and I'm quite satisfied with it. This doesn't
mean it's without problems. So, for example, the original definition of
Lentity in an app of mine was this:

class Lentity(models.Model):

def __str__(self):
try:
return str(self.person)
except Person.DoesNotExist:
return str(self.organization)

This code makes no sense. You should not be referring to models directly.
Everything should be relative to self. It should be as simple as return
self.name, with a property called name on each child model that returns the
correct field.
Or don't bother overriding it at all at this level and override it properly
in each child model.


class Meta:
 verbose_name_plural = 'Lentities'

Then, when I had too many persons and organizations, I had to use
raw_id_fields in the admin, and for this I had to make this change:

Not sure why having a larger list prompted the use of raw ID fields.
Usually it's the opposite.

class Lentity(models.Model):
# descr is a redundant field; see save() for more information.
descr = models.CharField(max_length=111, blank=True, editable=False)

def __str__(self):
try:
return str(self.person)
except Person.DoesNotExist:
return str(self.organization)

def save(self, *args, **kwargs):
# descr is a redundant, calculated field that is automatically filled
# in during save(). We introduce this redundancy because there is
# currently no other way in which the Django admin can sort lentities,
# i.e. we can use descr as a field in "ordering" or "get_ordering", but
# it's not possible to use an expression. (We need the Django admin to
# manage lentities in general, as well as persons and organizations, in
# order to make it possible to use raw_id_fields in AuthorInline.)
self.descr = str(self)
super(Lentity, self).save(*args, **kwargs)

class Meta:
verbose_name_plural = 'Lentities'

So I had to put Lentity in the admin, ensuring users have no permissions to
edit or delete or create "Lentity" directly, and I told users to just
ignore that. (I'm can't tell whether these problems are worse than having
two fields plus a discriminator field in the admin).


There are some weird design issues here that I don't have time or context
to comment on. Seeing the words 'redundant' and 'field' in the same
sentence worries me as far as database schema design goes. But if it is
working for you...

-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/CA%2Be%2BciWD8oqUss5GHN1%3DzoLoZqVLC47vJxHxuGL%2BADDngZmWtg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: I may found a bug

2017-10-23 Thread James Schneider
On Oct 21, 2017 7:12 PM, "otloal"  wrote:

Hi, I think I may discovered a bug in django, but I’m not sure
[03:19am] The bug is this: 1. You make a ManyToManyField related the same
model in wich you are creating the field
[03:20am] Example:
[03:21am]
>
> class WhatEver(models.Model):
>
> field = models.ManyToManyField(‘Whatever’, related_name=‘related_rel_
> name’)
>
> [03:22am] this creates an appname_whatever table and and an
appname_whatever_fields table in the database that contains to fields:
*from_whatever_id* and *whatever_id*
[03:24am] Obviously takes the word *from_* in the first field to difference
from the second field
[03:24am] The bug:
[03:24am] If I change the field in the model to b.e

> field = models.ManyToManyField(AnotherObject, related_name=‘related_rel_
> name’)


[03:26am] and I make migrations and migrate, the db table field
*whatever_id* changes to *anotherobject_id*, but the field
*from_whatever_id* *remains intact*
[03:28am] when you use the relation in your proyect you get an error like
"theres no appname_whatever_fields.*whatever_id*"
[03:28am] I had to rename manually from_whatever_id to whatever_id
[03:28am] Check it, please


I'm pretty lost in the generalizations you are using. If I follow it right,
though, it sounds like the DB structure is updated properly.

I have no idea what appname_whatever_fields.whatever_id would even refer to
in a real example, but it doesn't appear to be the relation you are
referring to. I also have no idea what you renamed. I'm assuming the DB
table column but that doesn't make any sense.

-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/CA%2Be%2BciVdq0AEdWm_DYBCLA%3DpqJW7N1Wk9UyZM57AwEF%3D4kr_Uw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Generating a unique 10 digit ID for each model instance

2017-10-23 Thread James Schneider
On Oct 22, 2017 9:29 AM, "Andréas Kühne"  wrote:

Hi,

When you say "globally unique" - I am supposing you mean within your
application?

What you need to do is set a field to be the primary key, see :
https://docs.djangoproject.com/en/1.11/topics/db/models/#
automatic-primary-key-fields


Not necessarily. The field only need be unique, but does not need to be the
primary key, and probably shouldn't be IMO. Data (in this case, an
arbitrary ID) should not be used for the internal linkage of the DB. That's
what PK's are for. What if the ID needs to be changed later? All of the
relations would also need to be updated, leading to a large headache at
best.


However - it would be simpler to use the standard primary key auto id
field, and then add another field to hold your unique ID in it. This could
then be created on the pre_save signal and you could write something that
randomly generates the unique ID field. See https://docs.
djangoproject.com/en/1.11/topics/signals/


Again, I have to disagree. This shouldn't be a pre_save signal. What
happens when a model save() fails due to a race condition where another
object grabs the ID that was generated in the pre_save signal? The save()
function is likely the best place, or maybe a post_save function that
generates the ID and updates the existing record with a unique ID value.
That way the model can save its data and be 'assigned' an ID as the next
operation. I would personally determine and assign everything in the model
save() function, though, and make it one operation with logic to handle
collisions.

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


Re: Generating a unique 10 digit ID for each model instance

2017-10-23 Thread James Schneider
On Oct 22, 2017 4:36 PM, "Mark Phillips"  wrote:

I thought python's uuid.uuid4 guaranteed a unique value. Am I missing
something?

Mark


>From a practical perspective, you are correct, uuid.uuid4() will create a
unique value every time. There is no guarantee, though, as eventually
you'll run out of values with enough iterations. You probably have a better
chance of being struck by lightning 6 times in a row, though, before you
get a UUID4 collision.

However, the OP is generating a 7 digit integer, meaning that UUID4 is out.

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


Re: Generating a unique 10 digit ID for each model instance

2017-10-23 Thread James Schneider
On Oct 22, 2017 8:52 AM, "Jack Zhang"  wrote:

Let's say I have a model called 'Dogs'.  Users can create instances of
Dogs.  For every Dogs instance that is created, I want to assign a globally
unique ID to it.  The ID will be 3 capitalized letters followed by 7
numbers.  E.g. ABC1234567, POZ2930193

What is the easiest way to go about doing this?  I looked into UUID but it
generates a longer string.  Keep in mind that the ID must be globally
unique - so after one has been created, it should not be created again.


A unique index constraint on the field will ensure that duplicate values
are not allowed. There are several ways to go about doing this. Will the
ID's be sequential or random?

If sequential, all of your save operations where an ID is created should be
within transaction blocks. ORM operations like .last() come in handy to
determine the next available ID.

One option to consider is splitting the ID into two model fields, one for
the 3 character prefix, and the second for the numerical suffix. The "ID"
would then be presented to the end user as the concatenation of the two
fields. Doing this provides two advantages. Searching against a text string
is slow compared to a numerical search. An ID provided by the user is then
searched within the DB using the two fields after being easily split in
Python, taking advantage of native type indexing in the DB. Secondly, you
can choose to take advantage of the DB's auto-increment functionality on
the second field. The DB is way more efficient for tracking that. Sure, it
will start with 1 and work its way up, but to make a 7 digit number out of
that, you just pad it with six zeros before combining it with the prefix
just before you display it to the user. It wouldn't matter what the prefix
value is at that point. All you would need is the 7 digit code (which would
contain mostly zeros at first) to find any record. The prefix would simply
be for human interpretation. This strategy does have the side affect of two
prefixes never having the same suffix, meaning you'll never have an ID
value of ABC001 and POZ001 at the same time. This does limit you to
a total of 9,999,999 items between all of your prefixes though.

If it will be random, then you simply have a math.random(1,1000)
function, but you'll need extra logic to determine uniqueness and handle
collisions. I'd still recommend breaking it up in to two fields if you know
that is always going to be the format of your ID. Keep in mind that if you
go the random route, you can never delete a record once it has been created
to ensure that the ID is not reused. In this case, the .exists() method is
your friend, or you can use the insertion strategy I mentioned in my other
thread.

-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/CA%2Be%2BciV2kN%2BoGy3mGakH-pzZGLQt-OG4ZYPfbA2%3DSyTSk2gtYA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Generating a unique 10 digit ID for each model instance

2017-10-22 Thread James Schneider
On Oct 22, 2017 12:29 PM, "Andréas Kühne" 
wrote:

Hi,

I think you are correct with your pseudocode - you can do a
Model.objects.filter(unique_code==random_code).count() - and then loop on
that. It should work.


I wouldn't do this, it can lead to a race condition where you can possibly
end up with duplicate ID's if two objects are being inserted at the same
time.

Ensure that you have a unique index on the ID column, then just create your
ID and try to insert it into the DB. Let the DB determine whether or not it
is unique, it is much better at this than any Python code you can write. If
it falils, catch the insertion error, change the ID, and try again.

Even if you did do this, you should use .exists() rather than .count().

Either way, your code should be prepared to deal with the potential for
duplicate ID's being inserted in to the database.

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


Re: Django Forms

2017-10-21 Thread James Schneider
Since each form is set to only allow you to select 1 multiple choice
option, if I add many forms in one page, I can only select one option
overall. So if I answer question 1, I can't answer any of the other
questions without it unselecting question 1's answer.

Does anyone know how to fix this?


If that's the case you are not formatting the form correctly. Each form set
should contain it's own radio group of answers so that an answer may be
selected for each one. Post up the template code you're using.

-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/CA%2Be%2BciXzQ0sh1d6MLdq48c4nSpaqgR0tCg%2BXQLAX0j%3DmfMtXJg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to store a key to a something that can be either a person or an organization?

2017-10-21 Thread James Schneider
What I do is I create a superclass that I call Lentity (short for "legal
entity", despite the fact that it could refer to a group of people and is
not
necessary legal) and the two subclasses Person and Organization, with
multi-table inheritance.


Seems silly to name a model as such given that it can easily be
nonrepresentative of the data in the table.

Is it an abstract class? If yes, why not just call it Entity? A legal
status can easily be represented by a field in the model.

If a Person and Organization are treated the same, you can also use just an
Entity table with a field designating the type of Entity, such as 'person'
or 'organization'. Querying all Person and Organization objects would then
constitute only a single query, rather than two queries, one for each model
type. If you add other similar models, you also increase the number of
queries required to pull all of the objects, whereas a field designation
allows you to pull some or all objects regardless of type.

There are a ton of reasons to keep them separate, though, so your design
may still be correct.

-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/CA%2Be%2BciX21jrrdceNoq4VpthKoc%2BH-g2LbOs%3D4xkV5HKxo0cVJA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to store a key to a something that can be either a person or an organization?

2017-10-21 Thread James Schneider
On Oct 20, 2017 4:15 AM, "Jani Tiainen"  wrote:

Hi.

I've resolved such a case with two nullable fkeys and a discriminator field
to tell which one fkey is used.


Another option that is slightly safer is to override the save() method to
set the opposing FK to None every time the model is saved. Your
'discriminator' is then based on which field is populated. It helps avoid
situations where a cascade deletion of the foreign object leaves your model
with no FK associations, but the model is still marked with a
discriminator, and the lack of an FK value can incur a bug. It's one less
field to set with the same net result.

There are use cases for a discriminator field though (ie calling functions
dynamically, or a status that can't be determined by presence or lack of
data, etc.), so you may still have a good solution. I just prefer to
minimize the fields that I'm managing.

-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/CA%2Be%2BciUk95Kben-4bKUEwPSzQiBFqKWGSy%2BXJiUFTa_4SuPUqw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Tutorial part 4 - get_queryset

2017-10-17 Thread James Schneider
On Oct 17, 2017 4:44 AM, "tking"  wrote:


Hi,

I've decided to teach myself Django and I'm enjoying the tutorial which
I've so far found exceptionally detailed but I'm a bit confused by the
get_queryset function in the IndexView class.

Essentially my question is what calls this function?


I always recommend taking a look at the Classy CBV's site, it greatly helps
demystify CBV's:


https://ccbv.co.uk/projects/Django/1.11/django.views.generic.list/ListView/

One if the disadvantages of CBV's is the unintuitive flow and how all of
the pieces work together. It takes a bit of experience to get used to it.
In short, though, it works like this for most CBV's:

1. The .as_view() call from urls.py calls .dispatch().
2. The .dispatch() calls then calls the appropriate function based on the
HTTP verb that was used in the request, usually .get().
3. The .get() call then calls .get_queryset().
4. The .get_queryset() call then either returns the value of self.queryset,
or returns a generic Model.objects.all() (based on self.model) as a
fallback.



Is it automatically called when the class is used?  I appreciate this is
part of a generic view and it's a built-in function, so that makes some
sense to me, but it's not clear.


Yes, in most cases, if a CBV is used. See above.


I've looked elsewhere in the documentation, at the generic views in
particular and whilst get_queryset is used in another example, I see that
it isn't a mandatory requirement, as other examples have just a model or
queryset assignment, the latter of which shows a filtered assignment.

So is the get_queryset just a way of automatically creating a queryset
attribute?


By default, it will return the value of queryset= if set, otherwise it will
return a generic queryset of .all() based on your model= attribute.

This method is often overridden by custom views to modify the queryset and
include things like custom sorting and filtering based on GET or POST
values from the request.


I'm not seeing any advantage to this at present to a more simple, queryset
=


It's a shortcut way to define a custom static queryset in a view.

Say that you had a view that listed only activated Widgets, which had a
model field of 'activated' that was set to True if a particular Widget was
activated. Your view can then set your queryset like this:

queryset = Widget.objects.filter(activated=True)

And with a single line in the view, you can now display a list of Widget
objects that are activated, rather than listing all of them.

HTH,

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


Re: How do I request a new feature in 1.11.x?

2017-10-10 Thread James Schneider
On Oct 10, 2017 8:50 PM, "Chris Beck"  wrote:

So there is a new feature being worked on in the master branch:
https://code.djangoproject.com/ticket/28668 (adding ON CONFLICT DO NOTHING
support to bulk_create)
How might I add a request that that feature be included in a future 1.11
release if possible? Since 1.11 is the last Python2 release and will be
around for a few more years are new features being contemplated?

Cheers,
Chris


This is the end-users list, and most of the devs that would make such a
decision aren't watching. You may have better luck with a solid answer on
the Django dev list.

Personally, I would follow up directly within the ticket. The activity a
ticket has is an informal indication of community interest and may garner
more attention from the devs.

I believe that releases are feature locked, but given the deprecation of
2.7 support being a major blocker for upgrade to some environments, there
may be a cause for an exception to backport features.

I'm not a dev, though, just a guy who occasionally writes code. My opinions
mean nothing and I'm fine with that. ;-)

-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/CA%2Be%2BciWUExY99q%3DndG%3DVkM61x0VYrWBp5NXWBNGCgfnOzV0y%3DQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: LDAPSearch Troubleshooting

2017-10-10 Thread James Schneider
On Oct 10, 2017 12:38 PM, "Ken Jenney"  wrote:

Good catch! I just fixed it and re-tried and it works now. I had to get
past the group search but ultimately my mispellings caught me up. Thanks
for all the help James!


Nice. Glad to have helped.

Interestingly enough, your original post has the correct dc= value (I'm
assuming), so it must have been accidentally modified amidst the
troubleshooting you were doing.

-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/CA%2Be%2BciU9a7XJrqz9%2Bja96oXvzvetOjW-QeLnWiuDND9W-8PWLg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: LDAPSearch Troubleshooting

2017-10-10 Thread James Schneider
On Oct 10, 2017 11:55 AM, "Ken Jenney"  wrote:

I fixed the DN for the service account:

AUTH_LDAP_BIND_DN = "UID=netbox,CN=users,DC=kenset,DC=priv"

I've tried at least a 100 different things so far and nothing is getting me
there.

from django_auth_ldap.config import LDAPSearch, PosixGroupType
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("dc=kensnet,dc=priv",
ldap.SCOPE_SUBTREE, (objectClass=posixGroup)")



I also just noticed that the dc= values are different between your BIND_DN
and GROUP_SEARCH as well.

kensnet vs. kesnet

-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/CA%2Be%2BciWRc%3Dk-LGQ3L_1uGx_s9YLZtpUHUtz96NkkhdwM9HPRZA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: django project avoid reload page where work algorithm

2017-10-09 Thread James Schneider
On Oct 8, 2017 11:25 AM, "Xristos Xristoou"  wrote:





> In the background celery worker picks your task and executes it. It
> doesn't matter how long that takes. Once task is completed worker waits for
> next task.
>
> Every task gets id which you can return to frontend and then for example
> using ajax call you could query if task is ready and inform user about
> progress or completition.
>
>
>> can you show some example with my code ?is easy to bulid ?



It is not necessarily trivial to implement Celery or any sort of batch
processor. It requires a separate server demon that may not be supported on
your hosting platform. I'd suggest combing through the docs for Celery and
the specific Django documentation for it, which includes many examples.

http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html

-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/CA%2Be%2BciVC_hQtE3AAp%2Bps%3D0hfyEGFBxWiND1u_m9N1Dve1aBXjQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: LDAPSearch Troubleshooting

2017-10-09 Thread James Schneider
On Oct 8, 2017 9:44 PM, "Ken Jenney"  wrote:

1) I'm using a service account. I verified the DN's by connecting using
Apache Directory Studio.


I'm assuming this means that you only verified that your intended DN
strings are valid and that the passwords for both the service account and
your user account are correct?

2) I just promoted the service account user but I'm still facing the same
error.
3) Logging is not helping: it's only reiterating what the original error is
telling me: Caught LDAPError while authenticating ken:
INVALID_CREDENTIALS({'desc': 'Invalid credentials'},) I added logging by
adding this to the config:


I'd be interested to see what the Synology says. You may need to increase
the logging verbosity.




Couple other questions:

a) What do you have listed in AUTHENTICATION_BACKENDS? I'm assuming you
have both the LDAP module and the built-in back-end listed in that order
since you are requesting groups?

a.1) Is it possible that your initial authentication is failing against
LDAP but succeeding against the local authentication back-end, potentially
leading you to believe that LDAP is partially working when it isn't?

a.2) Do you see the service account successfully authenticating on the
Synology upon login at least once?

b) Is this the correct DN for your service account?

AUTH_LDAP_BIND_DN = "CN=netbox,CN=users,DC=kensnet,DC=priv"

Shouldn't that be uid=netbox?

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


Re: tox?

2017-10-09 Thread James Schneider
On Oct 8, 2017 3:21 PM, "Christophe Pettus"  wrote:

On a Django-related project I maintain, someone's submitted a PR that
includes a tox.ini file.  I'll admit I've not used tox before; how standard
is it for Django testing?  I like the idea of being able to run tests
against multiple versions in parallel, but I don't want to require a tool
for testing unless it's very widely used.


I'm not familiar with Tox or it's usage, but in general, I wouldn't make it
a requirement for an end user, and possibly not even for a contributor of a
PR.

IMO, a unit test should only rely on the base test framework included with
Django. An extension like Tox (based on the information blurb above) should
take those tests and run them in multiple environments automatically in a
dedicated test environment that you manage. An end user should be able to
run your tests against their specific environment without it, along with PR
authors for simple bugfix patches. Code standards should be clearly
published and outlined, and should include comprehensive enough information
that all target environments will pass the same tests, ie requiring Py2/Py3
compatibility, PEP 8, and so on.

Larger PR's that introduce new functionality or significant code changes
should be required to utilize something like Tox before being
submitted/accepted, but as long as that is also clearly documented, any dev
providing code at that level shouldn't have an issue complying.

OTOH, it's presumably your software, and if you like it and want everything
tested to that degree before it reaches the PR stage, that's your call.
Larger projects may require this to filter out the number of PR's that
people file, but you also run the risk of missing out on good patches that
an author didn't submit because they didn't feel like deploying and
learning a new test suite.

As a rebuttal against my own argument for not requiring it, Django does
ship with built-in Tox support, although I'm sure other configuration is
required:

https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/
unit-tests/#running-tests-using-tox

Just my $0.02...

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


Re: LDAPSearch Troubleshooting

2017-10-08 Thread James Schneider
On Oct 8, 2017 7:33 PM, "Ken Jenney"  wrote:

I've got LDAPSearch configured to work with my Synology Directory Server.
Users can authenticate fine but when I try to map a user to a group I get
INVALID_CREDENTIALS:


Are you binding to LDAP using the users' credentials, or do you have a
service account? It appears you have a service account configured, but I
can't tell whether or not it is in use based on the settings you provided.

Have you:

a) Verified the DN being used against the Synology NAS for the user and
group authentication requests? This can be found in the Synology auth logs.
b) Verified that the account in use has permission to traverse that portion
of the LDAP schema, including a user being able to query their own groups,
or the service account being able to list other users' groups?
c) Increased the logging level for Django and specifically for the Django
LDAP package you are using to examine what is happening?

This issue will likely be illuminated very easily by the detailed logs on
each side of the connection.

-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/CA%2Be%2BciUG%2Bo935-HOupJanmPDKq%3D7_EyHp_fj%2BVmMFPmpP0EKRg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Implementation Advice: Categories and Product Specifications

2017-10-05 Thread James Schneider
On Oct 2, 2017 11:07 AM, "Paul"  wrote:

I have Product and Categories. A product can be in multiple categories and
off course a Category have multiple products.


Many to many relationship,  likely with a custom 'through' model so you can
attach other fields to the intermediary model.


The Categories can have Subcategories’ which can have Subcategories. I used
a Category Model with a circular Foreign Key.


I'd recommend tracking a category hierarchy using an MPTT model a la
django-mptt or django-treebeard.


Each Product can have specifications/attributes based in which Categories
is.

An attribute should be a separate model tied to one or more categories in
this case.


So the specifications are of the products but depends on the Categories.

I'm assuming that a product will have other attributes in addition to those
added by the categories. Those should tie back to the aforementioned
attribute model.

 Your product model should define a method that pulls attributes from both
categories and the product itself to return a single list,  or perhaps a
tuple containing a list/dict of category attributes and a list/dict of
product specific attributes,  if you need them separate.


I can’t add the specifications as Products attributes because they depend
on categories, and the user can change categories.

Then don't.

I can’t add them as attributes per Category because the value are/can be
different for each product.


Then you'll need an intermediary table (M2M) between Product, Category, and
Attribute with one or more additional value columns.


Also an attribute/specification can appear in multiple Categories.

Doesn't matter if everything is related in the DB correctly.


I want also to search for a Product filtering by attributes.

See the big M2M table I mentioned above.


I think I need a separate Attribute Model that is linked (foreign key) to
both Product and Category.


Yes.


Also a way of “protection” in case a Product change categories, a Product
and/or a Category is deleted.


What is the optimal approach as flexibility and performance ?


The crux of your issue boils down to the design of the table that ties
together the product, categories, and attributes a b7 the associated values
for those attributes. Your validation logic is probably going to be
insanely complicated unless your attributes can only contain certain values
for all products. If some attribute values are only available based on the
presence/value of other attributes,  your validation logic will quickly
grow out of control without a good design and detailed definition of your
business logic,  and even then...

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


Re: There is any way to prevent cascade delete on FK field, without using signal?

2017-10-04 Thread James Schneider
On Oct 4, 2017 4:36 AM, "Fellipe Henrique"  wrote:

I read the docs, but doesn't work for me... still delete the record... I
looking something directly to model, not using view... there's any way to
do that?


What exactly did you "do"? The on_delete keyword is applied at the model
level, not the view.

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


Re: QueryDict and unicode

2017-10-04 Thread James Schneider
On Oct 2, 2017 1:53 PM, "Alexey Lozickiy" 
wrote:

Hi all,

Why is it so that QueryDict for PY3 handles input query string different
from PY2 (part of __init__ of QueryDict from Django 1.11.5):

if six.PY3:
if isinstance(query_string, bytes):
# query_string normally contains URL-encoded data, a subset of
ASCII.
try:
query_string = query_string.decode(encoding)
except UnicodeDecodeError:
# ... but some user agents are misbehaving :-(
query_string = query_string.decode('iso-8859-1')
for key, value in limited_parse_qsl(query_string, **parse_qsl_kwargs):
self.appendlist(key, value)
else:
for key, value in limited_parse_qsl(query_string, **parse_qsl_kwargs):
try:
value = value.decode(encoding)
except UnicodeDecodeError:
value = value.decode('iso-8859-1')
self.appendlist(force_text(key, encoding, errors='replace'),
value)

Firstly, for PY3 decoding is done only once, for entire query string, while
for PY2 query is parsed first, and then each value is decoded separately.
Secondly, for PY3 query_string is being decoded only if it is of bytes
type. Why there is no such check for PY2? Why not to decode only if it's
not unicode?



I'm probably unqualified to answer this, but I'll try anyway.

The difference likely comes down to the change in string handling in Python
3. Py3 makes a distinction between character strings and byte strings.

The limited_parse_qsl() likely can/will only handle Unicode-escaped
(URL-encoded) character strings in Py3, as opposed to handling byte strings
transparently (that decode to Unicode-escaped strings) in Py2. I'm guessing
that the magic implicit translation/decoding between bytes and characters
no longer occurs in Py3 (for good and well-documented reasons), so care
must be taken to perform the decoding manually. You'll notice that the
values are not decoded a second time for Py3.


With such implementation it is not possible to pass unicode object that
contains non-ascii characters to QueryDict.


Given the first comment in the code, if the data is not properly URL
encoded to begin with, then I would expect that the parsing function for
the values to explode, meaning that you can't pass a true Unicode string
with characters beyond the ASCII range because it isn't expected at this
stage. To me, that's expected and desired behavior since a QueryDict is
expecting to be provided with a properly formatted/URL-encoded query.

The fix would be to URL-encode your true
Unicode string prior to passing it to a QueryDict. That should allow
support of Unicode characters with higher code points.

Basically, the Internet revolves around ASCII being the lowest common
denominator.

Someone please correct me if I'm wrong.

-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/CA%2Be%2BciWQH_sQdoboTGtPmZ-28i9ihXguhOST662vR-eg%2B%2BYB9w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: django.urls.exceptions.NoReverseMatch: Reverse for 'index' not found. 'index' is not a valid view function or pattern name.

2017-09-28 Thread James Schneider
On Sep 27, 2017 8:59 PM, "harsh sharma"  wrote:

i m a noob in django And i dont know why i am getting this error

my views.py file:

from django.shortcuts import render,render_to_response
from django.http import HttpResponse
from all.models import ALL
from django.template import RequestContext
# Create your views here.
def home(request):
return render(request, 'index.html', {'ne': ne})


def technology(request):
return HttpResponse('hello')

def index(request):
assert isinstance(request , HttpResponse)

return render(request, 'index.html') .

my url file

url(r'^$', all.views.index),
url(r'^technology', all.views.index),
url(r'^index$', all.views.home),
url(r'^admin/', admin.site.urls),
]


None of the code you posted would have triggered such an error.

What is contained in the template that is being rendered when the error is
shown?

My guess is that you have something like {% url 'index' %} inside of your
template, but you don't have any URL patterns named 'index' shown.

-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/CA%2Be%2BciW8Q_xLN_TWJ%3Ds4-ArQ-tfvcopZNJduFucfZ0xfXNaBNw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Guidance for contributing to django

2017-09-25 Thread James Schneider
On Sep 25, 2017 2:05 PM, "KUNAL SINGHAL"  wrote:

As our minor project for the year, we were asked to contribute to Django.
However, the problem with this is that I don't really know where to start.
I have read the documentation, but still need guidance about what to do,
specifically:
1. Low-level features that can be added to Django in around a month's time.
2. Existing issues that I can fix with my limited hold on coding and how to
go about it.(I possess intermediate coding skills)
3. Any other way I can contribute to the project as novice

I would be really grateful if someone could mentor our project.
Thanks



This page spells out everything you need to know and where to get started:

https://docs.djangoproject.com/en/dev/internals/contributing/

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


Re: Rendering DataBase Image File

2017-09-25 Thread James Schneider
On Sep 24, 2017 11:55 AM, "yingi keme"  wrote:

Okk. I will like to know how to set the MEDIA_ROOT and MEDIA_URL.?

And then, my images are uploaded to a directory named 'img' inside my
static files directory. Does it affect how you set the MEDIA_ROOT and
MEDIA_URL?


Yes. The location you've chosen for these images is likely incorrect, or at
the very least, impractical.

By default, an image file associated with a models.ImageField is stored in
MEDIA_ROOT/ and not in your STATIC directory.

The files within your STATIC directory should not change in production, and
ideally should be served by your web server directly and not through
Django. STATIC is for the files needed for the site structure such as CSS,
JavaScript, logo images, etc. End-user files should not be placed there.

MEDIA_ROOT should be set to a location that can be written to by the web
server that is not in any of your STATIC locations (Django will complain if
it is). This value is an absolute path in the server file system.

MEDIA_URL should be set to whatever URL path prefix should be used to
trigger the web server to provide a file. This value is something that will
prefix the path to the file in the URL used by the browser.

In you case, using a MEDIA_URL value of '/media/', an image URL might look
like http://example.com/media/img/my_image.jpg. The web server would then
map that request to download //img/my_image.jpg.

See these links:
https://docs.djangoproject.com/en/1.11/ref/settings/#media-root
https://docs.djangoproject.com/en/1.11/ref/settings/#media-url

So, nobody can really "tell" you what they should be set to since it tends
to be environment specific.

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


Re: capturing url pattern from html forms

2017-09-23 Thread James Schneider
On Sep 23, 2017 1:27 PM, "Mel DeJesus"  wrote:

Unfortunately, I didn't show my entire URLpatterns list, and the ^item/$
 seems to interfere with the ^$ of the previous:  Any suggestions for a
work around? thanks again.

from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.urlpatterns import format_suffix_patterns
from durham_app import views

urlpatterns = [
# Examples:
url(r'^admin/', include(admin.site.urls)),

url(r'^$', views.index, name='index'),
url(r'^item/$', views.item_detail, name='item_detail'),
url(r'^items/', views.ItemList.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)



There isn't really a reason that any of those URL patterns would interfere
with each other. I'd change the last one to r'items/$', but otherwise they
look fine.

What do you mean by 'interfere'?

-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/CA%2Be%2BciU_e0k8eLpt%2BjJvRGFPsg%2B_Gota6F5Z0omrm9-xhg1dgQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: best practices for location of start up code

2017-09-23 Thread James Schneider
On Sep 22, 2017 2:58 PM, "Larry Martell"  wrote:

We have some code we want to run 1 time when our django app is
started. What is the best place for this? I tried putting it in my
app's config function, but from there I get:

*** AppRegistryNotReady: Apps aren't loaded yet.


Once as in only when the app is initially deployed, or once every time the
web server process is started?

Note that if you place code to run every time the web process is started,
that it will run for every process, and most web servers spawn multiple
processes.

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


Re: Django - Best option to check file types, even fake or without extensions

2017-09-22 Thread James Schneider
On Sep 21, 2017 11:23 PM, "Paul"  wrote:

I'm trying to validate mime types of files uploaded with a predefined list
of validate mime types.


I need to do the check the file in the buffer before save, even if they are
faked or no extensions.

You're better off specifying what you do want rather than trying to filter
out what you don't.

What other non OS dependent solutions that can check if the file is faked
or with no extension exist ? (pdf,doc,docs,csv,xls,xlsx, ods,odt,odm)

Devise minimal tests for each type of file that you may expect. For
example, a CSV shouldn't contain raw binary data, and should be readable by
the csv Python lib. A PDF file should be readable by a PDF lib, etc.

Use simple logic to filter out likely bad files. For example, it would be
rare for an MS Excel file to be missing it's extension, so any tests you
devise to check for Excel should be skipped if the file has no extension
(and therefore, the file can never be flagged as type MS Excel). Using
other libs like mimetypes can also quickly narrow down the tests you'd need
to run. All of the pertinent tests should pass with high confidence before
associating a MIME type. File size caps also can be useful.

Duck typing is your friend here, and heavy exception handling will be
needed.

To reiterate what Melvyn mentioned, you should probably only do this if the
file type validation is absolutely necessary. If files are shared among
users, virus scanning and interception may be advised.


-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/CA%2Be%2BciUMK-dBk_baJ%2BnkEMYb5TbPGdDoyuA%3DAJ6%3DGqfyqOYN_w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: coming back to register user page after not filling a text field is causing the already filled text fields come with an annexed "/" at the end of the values

2017-09-21 Thread James Schneider
On Thu, Sep 21, 2017 at 11:07 AM, fábio andrews rocha marques <
fabioandrewsrochamarq...@gmail.com> wrote:

> Solved it: If i remove the "/" from all my  tags, it's solved.
> Before:
>  nomeusuariocadastro }}/>
> After:
>  nomeusuariocadastro }}>
>


You should be encapsulating the value of "value" in quotes:



If you did that, you can also leave the / in place. I think it was
interpreting the / as part of the value= rather than the closing of the tag
due to the missing quotation marks.

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


Re: Mark as deleted instead of actually deleting in DeleteView

2017-09-21 Thread James Schneider
On Sep 21, 2017 2:39 AM, "Rakhee Menon"  wrote:

Hello Everyone ,
Can anyone tell me how to write views where, when clicked  on delete button
the data shouldn't get deleted only the flag should turn 0

Just use a standard update view that toggles the field that you are using
for the object status. You can make the buttons on the form say whatever
you'd like.

I would also recommend overriding the default model manager to
automatically exclude objects that have been "deleted" if that makes sense
for your project. Otherwise you'll need to remember to exclude those
deleted objects manually everywhere.

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


Re: How to install mod_wsgi after upgrading to python3.5 from python2.7

2017-09-15 Thread James Schneider
On Sep 15, 2017 2:04 AM, "BIJAL MANIAR"  wrote:


Hi,
I had a production application running with Python2.7 and Django1.11
through Apache and mod_wsgi.
Now I have upgraded to Python3.5 and created virtual env. pip install
mod_wsgi is giving below error.

(p3_venv) bash-4.1# pip install mod_wsgi
Collecting mod_wsgi
  Downloading mod_wsgi-4.5.18.tar.gz (2.5MB)
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
  File "", line 1, in 
  File "/tmp/pip-build-_hbwnbp5/mod-wsgi/setup.py", line 164, in

'missing Apache httpd server packages.' % APXS)
RuntimeError: The 'apxs' command appears not to be installed or is not
executable. Please check the list of prerequisites in the documentation for
this package and install any missing Apache httpd server packages.


You're likely missing the development libraries needed to build Apache
itself. Mod_wsgi needs to link with those during it's installation process.



Since mod_wsgi was already installed for Python2.7 how do I reinstall
mod_wsgi. Do I need to re install within virtual environment or at system
level. Any links/list of steps will be helpful.
Any help would be appreciated.


That is very dependent on your environment and how much control you want
over the patch and update process. You'll need to remove the 2.7 version of
mod_wsgi, or at the very least, prevent Apache from loading it. It cannot
be loaded at the same time as another mod_wsgi instance using a different
Python version.

You'll need to either use your system package manager to install the py3
version of mod_wsgi and hope that it matches your python version, or build
it yourself (as you are trying to do) from a virtualenv that will run your
project. Once that completes, you'll need to point Apache at the new module
you've built. It's not necessarily trivial. Start with the official guide,
or look for one specific to your OS:

https://modwsgi.readthedocs.io/en/develop/installation.html

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


Re: django custom authentication

2017-09-15 Thread James Schneider
,


However, when i try to access my homepage,i expect it to render my custom
login page(login.html). But it always say TemplateDoesNotExist.
I also tried putting the template folder inside an app. But the login page
doesnt get rendered still.

I need help urgently.Thanks

The error page should list all of the locations where the template engine
searched, and the name of the file it was looking for (assuming
DEBUG=True). Make sure the file exists in one of those locations, and that
the user running the Django server process (probably yours if using
runserver locally) has access to read the file.

With out the traceback or any of the specific error information, there
isn't much more anyone can tell you.

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


Re: View to download a tar archive

2017-09-14 Thread James Schneider
On Sep 14, 2017 3:48 PM,  wrote:

Hey guys,

I'm trying to make a view so that my users can download a compressed tar
archive.  I've seen a ton of examples about downloading files yet cannot
seem to find anything regarding tar.  Anyone want to drop me an awesome
example?


for a simple file I have

def download_file(request, pk):
my_model = SomeModel.objects.get(pk=pk)
file_path = my_model.get_file_path()

if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="")
response['Content-Disposition'] = 'inline; filename=' + os.path.
basename(file_path)
return reponse



There isn't anything special about serving different types of files. The
only trick is to specify the correct MIME type if you know it (which you do
in this case, application/x-tar). Then it's just a matter of using inline
or attachment (recommended) for the content disposition header.

https://docs.djangoproject.com/en/1.11/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment

https://docs.djangoproject.com/en/1.11/howto/outputting-csv/#using-the-python-csv-library

Or better yet, hand the file transfer off to the web server process, where
it belongs.

http://voorloopnul.com/blog/serving-large-and-small-files-with-django/



-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/CA%2Be%2BciX%2B-rXTGiqdtifzJX5e%3DdEHE8YF%2BVnYyZd3H9%2BgDhL3uA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: More bizarre URL behaviour after deploying

2017-09-14 Thread James Schneider
The technical issue is that a URL like this:

http://domain.tld/script/path

is split into these two variables by Lighttpd:

SCRIPT_NAME: /script
PATH_INFO: /path

and Django wants this:

SCRIPT_NAME:
PATH_INFO: /script/path


Your example is a bit misleading/lacking. Both of these scenarios can be
correct (or incorrect) based on the web server process configuration.

I did a bit of digging and it looks like lighttpd >= 1.4.23 supports
a "fix-root-scriptname" directive that appears to exactly solve your
problem. Have you tried that?

https://redmine.lighttpd.net/issues/729#note-11
https://xn--tigreray-i1a.org/Using%20MoinMoin%20with%20lighttpd%20for%20a%20root%20wiki

That directive doesn't appear to be documented very well anywhere else.

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


Re: type object 'Story' has no attribute 'object'

2017-09-11 Thread James Schneider
On Sep 11, 2017 7:20 AM, "harsh sharma"  wrote:

why i m getting this
error  :-type object 'Story' has no attribute 'object'


this is my views.py file:

from django.shortcuts import render,render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from .models import *
from django.http import HttpResponse,HttpRequest
# Create your views here.



def home(request):

story = Story.object.all()
return render_to_response('show.html',{'story':story})



The first line of your home() view should be this:

story = Story.objects.all()

The default model manager creates an 'objects' attribute that is plural.

-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/CA%2Be%2BciXL4G7k6x71_hwZ5%3DfVMauu%3Dv3NNuSoxxgOatB-hvOyMw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Using data migration to create initial users errors

2017-09-09 Thread James Schneider
On Sep 7, 2017 10:36 AM, "Tim Huang"  wrote:

Hi Melvyn,


I am lack of knowledge how to use model manager. Would you mind give a
quick example? Thanks

- timh


There's a fairly substantial doc page for model managers:

https://docs.djangoproject.com/en/1.11/topics/db/managers/

-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/CA%2Be%2BciW56%3DDBb4gQKFKfPM%2BbKwsQXPX5WfHLRohgukDgf11spQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to pre-load model data?

2017-09-09 Thread James Schneider
On Sep 9, 2017 8:59 AM, "Derek"  wrote:

"If you dump data directly in to models or the database, then you risk
dumping in data that hasn't been evaluated by your application which may
produce subtle bugs of the worst kind where things work in dev and break in
prod because your input channel is different."

If this is happening its because you have poor validation on your model
clean(s). You should NEVER just rely on a form to check data for you (at
least beyond very basic sanitation); that logic properly belongs with the
model.  We import direct from spreadsheets to models (note - NOT direct to
the database) because we make use of such logic.


That's not what I'm saying. Validation at the model level should apply to
all instances of the model in any situation. Validation at the form level
can be much more context specific. The two levels of validation are not
mutually exclusive, rather they are complementary.

I'm not saying that there shouldn't be model validation. Quite the
opposite, there absolutely should be. I'm saying that the import of the
data should follow the same workflow as an end-user would enter it to
ensure the data appears correct in the context that it is being entered
where possible.

I'm simple cases, a model is only implemented in a single context (in only
one spot in the application and only via one form). Model and form
validation would usually be the same. In advanced cases, the same model can
be referenced via multiple pages, and each page may place a different set
of restrictions on what data may be entered or how it is formatted. This is
typical when a model is related to several other models.

Hypothetically, if you have a Widget model, it may have a long list of
available colors to choose from in a choices= list. The model validation
would be responsible for ensuring that the color selected is one of the
available colors in the entire list of colors available.

However, Widgets may only be available in red and blue when paired with a
FooBar model. The form for FooBarWidgets would then limit the color choices
to just red and blue, and would validate that the color submitted is one of
those. The model validation wouldn't complain, because red and blue are in
the long list of colors available.

Importing the data directly to the model could potentially mean that a
Widget paired with a FooBar can be set to green, which is invalid. The
model validation wouldn't help in this case, because green is technically a
valid color for widgets, but in the context of FooBars, it isn't.

That's why I mentioned that you need to be 150% confident in your data
generation when importing via the ORM directly to avoid "impossible" data
in your models, which is worse than missing data IMO.

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


Re: How to pre-load model data?

2017-09-08 Thread James Schneider
On Sep 8, 2017 12:12 PM, "Mark Phillips"  wrote:

Thanks for all your replies and helpful suggestions. To answer some of your
questions -

1. Where is the data coming from? - It is textual data in a
spec/spreadsheet. The data is a lot of meta data (name and one or more
values) for describing attributes of scanned documents. There is what I
would call a "base set" of data, which means it is what we can think of now
based on a review of a representative set of documents. However, as new
documents are imported into the application, there may be other types of
metadata with multiple values that will have to be created on the fly
(hence the need for the admin forms to add meta date in the future). The
import function I need is a one-off function. We need it as we develop the
models and test them against various documents. Sometimes it is easier to
just delete the database and rebuild it when we are developing the app than
to back out certain migrations. So a simple way to populate the metadata
for development purposes, and then one time when we go into production is
what we are looking for. Currently, we have 24 metadata names, and each one
can have one to 20 values.


I use a management command to do exactly that: drop the database, create
the database, run migrations, and populate the database with a fair bit of
data. I use FactoryBoy to generate hundreds of fake users and other objects
upon reset.

http://factoryboy.readthedocs.io/en/latest/orms.html

If the files are only being used for development, and should not normally
be loaded in to the database, then I would definitely recommend a separate
management command rather than building the fixture/fake data loading
process directly in to the migrations.



2. The manage.py loaddata is an appealing option. However, it will take
further effort to convert the spreadsheet data to any of the formats for
this option. I think a csv file reader is more suitable for our purposes.


If it is simple data that is being some what auto generated, I'd consider
writing a FactoryBoy definition so you can generate 1 or thousands of
entries on demand.


3. I will have to think about the validation concepts. These are simple
name-value pairs, so it is not clear what I am validating against, unless
it is detecting duplicates.


Forms can do all sorts of validation. Duplicate detection of one of them.
Value formatting and type checking is another. You may have some integer
values that should only be within a certain range (ie a person can't be
29,000,000 years old, or maybe they can, who knows...). Forms are where
input is filtered and massaged to match the business logic in your models.

If you dump data directly in to models or the database, then you risk
dumping in data that hasn't been evaluated by your application which may
produce subtle bugs of the worst kind where things work in dev and break in
prod because your input channel is different.


4. I am also looking into a spreadsheet -> csv file > mysql load data as
perhaps the easiest way to complete this project. The spreadsheet is easy
to create and update the metadata with the least effort, and then it is
pretty automatic from the spreadsheet to the database.

I am open to other suggestions!


I'd recommend FBoy and eliminate Excel entirely if I could. Otherwise an
Excel parser would be my next choice.

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


  1   2   3   4   5   6   7   8   >