Monday, August 31, 2015

Re: TIME ZONE DJANGO SAVE DATETIMEFIELD

On Mon, Aug 31, 2015 at 5:37 PM, Serena <serenity.luna@gmail.com> wrote:
> I understand what you say, when I started working with Django I thought
> exactly the same, it is more convenient that the date is saved with a time
> zone and then the conversions are made, and also knew that the gap was
> precisely because those 4:30 in my timezone, but the problem is not to show
> the data to the user, but as I make my queries so that the filtered data is
> correct, since my dates are obvious questions, I'll put my concern examples:
>
> The date does not place the customer, we do not control them. Each time an
> invoice is added, the date placed in my controller using:
> >> factura = Factura()
> >> factura.fecha = timezone.now ()
> >> factura.save ()
>
> For example I consult my templates from sales day, and was shown to the
> customer in my template:
> 1. Add invoice number 6 on August 31, 2015 at 18:48
> 2. Add Invoice Number 7 on August 31, 2015 at 18:48
> 3. Add Invoice Number 8 on August 31, 2015 at 19:32
>
> But Database I remain as follows:
> 1. Invoice number 6 Date: 08/31/2015 23:18:07
> 2. Invoice number 6 Date: 08/31/2015 23:31:25
> 3. Invoice number 6 Date: 01/09/2015 00:02:17
>

This helped my understanding immensely. Thank you.

You know what is odd though, the DB entries for 2 and 3 seem to be
using a different format (MM/DD/YYYY and DD/MM/YYYY respectively). It
may be right if the data for 3 is really from January, though.

>
> So if I want to consult the invoices (today August 31, 2015):
>
> >> Factura.objects.filter (fecha__startswith = timezone.now (). Date ())
>
> only leave me the invoice number 6 and number 7 because the number 8
> corresponds to another day.


Ahh, there's the problem. You are performing a string match against
the beginning of the date string, not an actual comparison of dates
and times (ie is 04:00 later than 05:00, etc.). This is both slow, and
inaccurate, as you've experienced. Django will perform a numerical
comparison of the datetime's behind the scenes within the database,
which should yield faster and accurate results.

>
> Is there any way of making the request and that django conversion made
> directly (with some function)? or I have to do the conversion?
>
> I hope I was more explicit. And much I appreciate your time.

Django will do the hard stuff, but you need to feed it the right
information in order to do so. My understanding is that you want to
see all of the bills (class Factura) that have a date falling in
between 00:00 and 23:59 (a 24 hour period for 1 day) in your local
timezone (or more specifically, the default timezone of the server).

I'm no timezone expert, but here is how I came up with performing the query:

import datetime
from django.utils import timezone

# date today, default (server) timezone
d = timezone.localtime(timezone.now(),
timezone=timezone.get_default_timezone()).date()

# grab the date, stripping away the current time
naive_start_date = datetime.datetime(d.year, d.month, d.day)

# create a timezone aware datetime object with a time of 00:00
(beginning of the day) by only providing the date
local_start_datetime = timezone.make_aware(naive_start_date,
timezone=timezone.get_default_timezone())

# create a timedelta object of 1 day
one_day = datetime.timedelta(days=1)

# calculate 1 day in the future from the start datetime
local_end_datetime = local_start_datetime + one_day

# query, use >= for start time since we start at 00:00 and < since
we use 00:00 of next day
bills = Factura.objects.filter(fecha__gte=local_start_datetime,
fecha__lt=local_end_datetime)


Most of this is just generating a date for the right
calendar/numerical day (based on the local timezone) and creating a
datetime for midnight (morning) of that day. The rest is pretty
simple. Hopefully this also accounts for DST and other timezone
anomalies beyond my comprehension.

I would also highly recommend that you install the pytz module. Django
will use it if it is available, and will make your timezone handling
even more accurate. (See #3
https://docs.djangoproject.com/en/1.8/topics/i18n/timezones/#faq )

Hopefully you can just copy/paste that into your shell and it'll come
up with the right results. Seems to work on my local machine.
Obviously if you want a different day you'll just need to come up with
a different naive_start_date.

Well, I learned a lot answering your question, hope you do too, lol.

-James

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

Re: TIME ZONE DJANGO SAVE DATETIMEFIELD

I understand what you say, when I started working with Django I thought exactly the same, it is more convenient that the date is saved with a time zone and then the conversions are made, and also knew that the gap was precisely because those 4:30 in my timezone, but the problem is not to show the data to the user, but as I make my queries so that the filtered data is correct, since my dates are obvious questions, I'll put my concern examples:

The date does not place the customer, we do not control them. Each time an invoice is added, the date placed in my controller using:
   >> factura = Factura()
   >> factura.fecha = timezone.now ()
   >> factura.save ()

For example I consult my templates from sales day, and was shown to the customer in my template:
     1. Add invoice number 6 on August 31, 2015 at 18:48
     2. Add Invoice Number 7 on August 31, 2015 at 18:48
     3. Add Invoice Number 8 on August 31, 2015 at 19:32

But Database I remain as follows:
     1. Invoice number 6 Date: 08/31/2015 23:18:07
     2. Invoice number 6 Date: 08/31/2015 23:31:25
     3. Invoice number 6 Date: 01/09/2015 00:02:17


So if I want to consult the invoices (today August 31, 2015):

 >> Factura.objects.filter (fecha__startswith = timezone.now (). Date ())
 
only leave me the invoice number 6 and number 7 because the number 8 corresponds to another day.

Is there any way of making the request and that django conversion made directly (with some function)? or I have to do the conversion?

I hope I was more explicit. And much I appreciate your time.

El lunes, 31 de agosto de 2015, 18:41:00 (UTC-4:30), James Schneider escribió:


On Aug 31, 2015 2:58 PM, "Serena" <sereni...@gmail.com> wrote:
>
> No doubt that django is acting correctly. I understand what you tell me about it, then I know I can do conversions to the date shown in the templates have my time zone, but it is not what I want. Because when I do queries on bills for closing Z does not work, even when I have to close and tell me which corresponds to another day. by the same gap that you commented.
> If you do the cierreZ day: 2015/08/30 19:00 (client time), with the gap that I have tells me the date is 2015/08/31 1:00 (server time), that is already being done the next day, which is incorrect.
>

Is it possible that is correct? If you are saying that 2015/08/30 19:00 [server timezone] is the same date/time as 2015/08/31 1:00 [other timezone], then what you are seeing appears to be correct. Without actual offsets to work with and what you were expecting, it is a bit difficult to say for sure.

Can you answer the following?

  • How are you controlling the user timezone for display purposes?
  • Are the users entering naive date/times (with no timezone specifier) in forms, and is the server [possibly incorrectly] assuming that the data entered is in the servers' timezone, when the user intended that the date/time is their own local time? Or is the timezone selector in your form being ignored?
  • Have you validated that the server is storing the correct date/times in the database, either as the default timezone or (preferably) as the correct UTC? For example, 2015/08/30 19:00 in America/Caracas -4:30 is actually stored in the database as 2015/08/30 23:30 UTC. 
  • When you are displaying a bill, what time was entered by the user (including TZ), what time was stored in the database, what time is being displayed, and what were you expecting to be displayed?

At this point it is a matter of troubleshooting what you are putting in vs. what you are getting out of the system, and figuring out where the breakdown is. Dates/times are not easy to deal with, and all of us have probably run into a similar issue at some point.

> Ah, excuse my English.
>

No worries, you're doing pretty well.

-James

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

Re: TIME ZONE DJANGO SAVE DATETIMEFIELD


On Aug 31, 2015 2:58 PM, "Serena" <serenity.luna@gmail.com> wrote:
>
> No doubt that django is acting correctly. I understand what you tell me about it, then I know I can do conversions to the date shown in the templates have my time zone, but it is not what I want. Because when I do queries on bills for closing Z does not work, even when I have to close and tell me which corresponds to another day. by the same gap that you commented.
> If you do the cierreZ day: 2015/08/30 19:00 (client time), with the gap that I have tells me the date is 2015/08/31 1:00 (server time), that is already being done the next day, which is incorrect.
>

Is it possible that is correct? If you are saying that 2015/08/30 19:00 [server timezone] is the same date/time as 2015/08/31 1:00 [other timezone], then what you are seeing appears to be correct. Without actual offsets to work with and what you were expecting, it is a bit difficult to say for sure.

Can you answer the following?

  • How are you controlling the user timezone for display purposes?
  • Are the users entering naive date/times (with no timezone specifier) in forms, and is the server [possibly incorrectly] assuming that the data entered is in the servers' timezone, when the user intended that the date/time is their own local time? Or is the timezone selector in your form being ignored?
  • Have you validated that the server is storing the correct date/times in the database, either as the default timezone or (preferably) as the correct UTC? For example, 2015/08/30 19:00 in America/Caracas -4:30 is actually stored in the database as 2015/08/30 23:30 UTC. 
  • When you are displaying a bill, what time was entered by the user (including TZ), what time was stored in the database, what time is being displayed, and what were you expecting to be displayed?

At this point it is a matter of troubleshooting what you are putting in vs. what you are getting out of the system, and figuring out where the breakdown is. Dates/times are not easy to deal with, and all of us have probably run into a similar issue at some point.

> Ah, excuse my English.
>

No worries, you're doing pretty well.

-James

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

Re: TIME ZONE DJANGO SAVE DATETIMEFIELD

No doubt that django is acting correctly. I understand what you tell me about it, then I know I can do conversions to the date shown in the templates have my time zone, but it is not what I want. Because when I do queries on bills for closing Z does not work, even when I have to close and tell me which corresponds to another day. by the same gap that you commented.
If you do the cierreZ day: 2015/08/30 19:00 (client time), with the gap that I have tells me the date is 2015/08/31 1:00 (server time), that is already being done the next day, which is incorrect.

Ah, excuse my English.

El lunes, 31 de agosto de 2015, 16:39:16 (UTC-4:30), James Schneider escribió:
> Hello is the first time I write on the list, I have little time learning
> Django and presented me a drawback. I have a model called Bill, which has a
> field called date of sale, and I need to store the date and time of the sale
> but the client time, and now it is keeping the server time. As I keep the
> date and time correctly in the model?
> I have some variables in established settings:
>
> USE_TZ = True
> TIME_ZONE = 'America / Caracas'
>
> /********************models.py   ***********/
>
> class Factura(models.Model):
>       fecha = models.DateTimeField()

Have you validated that the time being stored is incorrect? I'm
willing to bet that the date and time in the database is actually
being stored in UTC, but the output in the templates is being
displayed with the undesired offset. Check out this page on handling
output of DateTime fields:

https://docs.djangoproject.com/en/1.8/topics/i18n/timezones/#time-zone-aware-output-in-templates

https://docs.djangoproject.com/en/1.8/topics/i18n/timezones/#default-time-zone-and-current-time-zone

Actually that whole page is a good read. Basically you need to ensure
that your DateTime is being saved in UTC (or at the very least,
everything being stored has an offset attached to it so that the
correct date/time/timezone can be calculated). Django is probably
already doing that, but you'll need to set the current time zone for a
particular user so that the templates output the right DateTime.

-James

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

Are django signals triggered within migrations?

Hi,

I'm doing some data migrations (creating new model instances) in the migrations files and I have a couple of receivers on the `post_save` signal for the models I am creating instances.
From what I have seen, it seems that the signals are not triggered within the migration. Is that true? Is that something documented anywhere?

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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/05bdd05e-7888-4c8f-884a-d878d3340c6e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: load drf from different location

What you probably want is a Python virtualenv, or venv for Python3.

https://virtualenv.pypa.io/en/latest/
https://docs.python.org/3/library/venv.html

There are a ton of virtualenv tutorials out there for pretty much
every platform.

-James

On Mon, Aug 31, 2015 at 8:18 AM, Prabath Peiris
<prabath@peirisclothing.com> wrote:
>
> Hi
>
> This is the problem I am trying to solve. I have a VM which has all the
> django + other required packages are installed (including the
> rest_framework). I usually ssh to the VM and then run the following command
>
> PYTHONPATH=/all/the/paths runserver 127.0.0.1:8000
>
> Now I want to mount the rest_framework to my local machine and and put some
> debug code to understand how to framework is working. what I like to do is
> this, I installed the rest_framework module in to my local directory (in VM)
> and I would like to load the rest_framework from the local install instead
> from the systemwide install ( I do not want to edit the systemwide install).
>
> How can I tell the django or pythonpath to load only rest_framework from
> somewhere else.
>
> Thank You
> Prabath
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscribe@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/f9b2b2f8-bc67-4e4d-a634-c4850abf840e%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

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

Re: TIME ZONE DJANGO SAVE DATETIMEFIELD

> Hello is the first time I write on the list, I have little time learning
> Django and presented me a drawback. I have a model called Bill, which has a
> field called date of sale, and I need to store the date and time of the sale
> but the client time, and now it is keeping the server time. As I keep the
> date and time correctly in the model?
> I have some variables in established settings:
>
> USE_TZ = True
> TIME_ZONE = 'America / Caracas'
>
> /********************models.py ***********/
>
> class Factura(models.Model):
> fecha = models.DateTimeField()

Have you validated that the time being stored is incorrect? I'm
willing to bet that the date and time in the database is actually
being stored in UTC, but the output in the templates is being
displayed with the undesired offset. Check out this page on handling
output of DateTime fields:

https://docs.djangoproject.com/en/1.8/topics/i18n/timezones/#time-zone-aware-output-in-templates

https://docs.djangoproject.com/en/1.8/topics/i18n/timezones/#default-time-zone-and-current-time-zone

Actually that whole page is a good read. Basically you need to ensure
that your DateTime is being saved in UTC (or at the very least,
everything being stored has an offset attached to it so that the
correct date/time/timezone can be calculated). Django is probably
already doing that, but you'll need to set the current time zone for a
particular user so that the templates output the right DateTime.

-James

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

TIME ZONE DJANGO SAVE DATETIMEFIELD

Hello is the first time I write on the list, I have little time learning Django and presented me a drawback. I have a model called Bill, which has a field called date of sale, and I need to store the date and time of the sale but the client time, and now it is keeping the server time. As I keep the date and time correctly in the model?
I have some variables in established settings:

USE_TZ = True
TIME_ZONE = 'America / Caracas'

/********************models.py   ***********/

class Factura(models.Model):
      fecha = models.DateTimeField()

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

Re: Best practice when designing an api (with Django)


Thank you for an informative answer ;-)

 
> To get the author information for the authors of the book with ID=7. In my
> view I have used:
>
>     book = Book.objects.get( pk = 7 )

Where exactly did you use this? Can you post up a copy of the view?

This was currently only a construction in my head; and not literally from an existing view. You have answered the question firmly further down.
 
> [...] ust use the ordinary Model/ORM methods.

^^^ This one. ^^^

Clear answer!


 

You can use repeated calls, but at that point you are trying to eat
your own dog food using a straw. 

Well - that does not sound terribly efficient.
 
Have you gone through the DRF tutorial? 

I'm in the process - very pleasent documentation by the way.


Thank's again - Joakim

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

Re: Best practice when designing an api (with Django)

>
> I have been maintaining a small Django based website for some time. It is
> mostly based on conventional views returning HTML, but both to support
> JavaScript interactivity and to interact with a traditional desktop
> application I am gradually creating a REST based API. Up until now I have
> created the REST endpoints manually, but I now I intend to look into the
> Django Rest Framework (DRF) and try to do things more properly. Now - the
> question where I would appreciate some guidance boils down to: "How much
> should I use my own http based API internally?". Assume I have two django

The answer is "where it makes sense to do so". For the most part, this
means any area that requires partial page updates via AJAX calls.
Unless you are rendering everything via JS (for example, as part of an
SPA), the full page loads should probably be handled via the standard
Django rendering process rather than pulling objects via AJAX and
rendering client side. Usually that is simpler to manage.

> models 'Author' and 'Book', each book can have several authors and of course
> each author can write several books - i.e. this is a many to many
> relationship:
>
> class Author(models.Model):
> ....
> books = models.ManyToManyfield( "Book", ...)
>
> class Book(models.Model):
> ....
>
> It is then natural(?) to configure the urls:
>
> /books/1 - Get information about the book with ID=1
> /authors/7 - Get information about the author with ID=7

Yes, this is a typical layout, or at least it falls in line with the
URL schemes I normally use.

>
> But let us say that I wanted to create the endpoint:
>
> /books/7/authors
>
> To get the author information for the authors of the book with ID=7. In my
> view I have used:
>
> book = Book.objects.get( pk = 7 )

Where exactly did you use this? Can you post up a copy of the view?

>
> To get the right book, now I want the author details. As I see it I have two
> approaches to get the author details:
>
> I can just use the ordinary Model/ORM methods.

^^^ This one. ^^^

> I can use my own http api - and "loopback" repeated calls to: /authors/$ID
>
> On the one hand I strongly believe in the "eat your own dogfood" principle,
> but on the other hand it feels a bit over the top to issue http calls in
> this situation? Grateful for comments from experienced API desginers.

You can use repeated calls, but at that point you are trying to eat
your own dog food using a straw. There are much more efficient
methods. :-D

API's can handle multiple objects as easily as standard Django views.
In this case, you are querying for a list of authors for a specific
book. Your queryset would look like this:

# using the book object you created earlier
book_authors = book.author_set.all()

# or a single queryset to pull in everything
book_authors = Book.objects.get(pk=7).author_set.all()

Have you gone through the DRF tutorial? It shows examples of pulling
and serializing a list of users in a single query, very similar to
pulling a list of authors related to a book.

http://www.django-rest-framework.org/tutorial/quickstart/

-James

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

Re: Using ModelForms

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2

iQIcBAEBCAAGBQJV5KdtAAoJEH2EY3tf/UcFMQ4P/j/3+Xsd66FlEcuxukcsi+yU
X6SKWNYF16CO1NUR4NGZJm+cEypdwQy5fjgYdBlbZbHvELhrgrWRIew2894pUAzK
zACZkyyGh+fplxtQh9H0kCBn5D2QBPs1IvHHMzSmFYJ3sTix/CLWkgoYnYrnC1FA
o+ODeOgpsHXzoqwzOI9KZMcD2zulifLUGOqE4ITtnTJf60pnm5nitv57AJLlHtlv
F4KoOmsDJ52ZRD353hmZbSaXeET/9fLGyYzu+KRMZEeFNGgO8gicDnj/p3RauT7f
JRrktx7AI+aK3Y2TxVkUVE47fN6/PtoH9erQPjikPH/jqPirAv3/VAHJvjKEy06j
npUrKeEpyVLSzfvGcsVuPWLZKbMtXBhfaAWnAckbPhrUSjWynWnB8+iMEK4syAkL
dEFQ2aKW5Lm7yrBeNItxLtlWHFQJI/ykTNailNRnyctoyA1ekIHCBsHT9zVE7X7i
DS6hldM6p8d/5R5fmpHG4CrgKU7zzv1vAoUXBpQTFrGvCsWw9IPPeqCZ1NYcY71z
KoBQE3kLViPlHMphhVJVlR2DKq/emfJ7nPcsvkkOP1QlzqUrhU4Cbe71QKRv8AXJ
1OnxDO5Bd5c17sLrMmdBQW5ti8+Rz58MMZpIxrGlSiPs76XwyfbBadvEfVNgu5fc
O3++wVgaR585sdsWdt/p
=s05C
-----END PGP SIGNATURE-----
On 25/08/15 01:25, Sait Maraşlıoğlu wrote:
> default = timezone.now()

Beware, timezone.now() will be evaluated once when the module is loaded,
not on save if you might think.
Use default = timezone.now without calling it to get the current value
on save.

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

Form with MultipleChoiceField

Hi, Django beginner here.  I'm trying to use a form with a MultipleChoiceField, but any choice that is selected doesn't seem to be processed.

Here is my form (very simple):


Here is my view:



And here is my template, which I'm sure is correct.



I notice there is a problem since when I print "picked" in the view, the console returns "None," even if one or more choices are selected.
Also, how do I work with "picked" if the form is working? Is it a Queryset? A list?
 
Thank you!



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

Best practice when designing an api (with Django)

Hello;

[ This question might be more about general principles for API design than Django, but since Django is my tool of choice - and my context of understanding, I am posting it here.]

I have been maintaining a small Django based website for some time. It is mostly based on conventional views returning HTML, but both to support JavaScript interactivity and to interact with a traditional desktop application I am gradually creating a REST based API. Up until now I have created the REST endpoints manually, but I now I intend to look into the Django Rest Framework (DRF) and try to do things more properly. Now - the question where I would appreciate some guidance boils down to: "How much should I use my own http based API internally?". Assume I have two django models 'Author' and 'Book', each book can have several authors and of course each author can write several books - i.e. this is a many to many relationship:

    class Author(models.Model):
         ....
         books = models.ManyToManyfield( "Book", ...)

    class Book(models.Model):
         ....

It is then natural(?) to configure the urls:

/books/1       - Get information about the book with ID=1
/authors/7    - Get information about the author with ID=7

But let us say that I wanted to create the endpoint:

/books/7/authors

To get the author information for the authors of the book with ID=7. In my view I have used:

    book = Book.objects.get( pk = 7 )

To get the right book, now I want the author details. As I see it I have two approaches to get the author details:

  1. I can just use the ordinary Model/ORM methods.
  2. I can use my own http api - and "loopback" repeated calls to: /authors/$ID
On the one hand I strongly believe in the "eat your own dogfood" principle, but on the other hand it feels a bit over the top to issue http calls in this situation? Grateful for comments from experienced API desginers.


Joakim

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

Re: What are the disadvantages of using a custom user model?

Thanks Gergely. Your last sentence says it all. I'm going with a custom user model.

On Monday, August 31, 2015 at 9:06:16 AM UTC+3, Gergely Polonkai wrote:

Hello,

is it the fields or the functionality you don't need? If it is really the functionality, you shouldn't bother; just don't use it. If some of the fields, then it worths an evaluation on why you don't need them, if you will have only a few users (e.g. a company internal app), then again, don't bother. If you will have tons, you should go with custom users, although be warned that changing the user model while the project is live is a real PITA.

Best,
Gergely

On 31 Aug 2015 06:11, "a.esmail" <abdulla...@gmail.com> wrote:
Hello,
I am evaluating whether it is better to use a custom user model in django or just extend django.contrib.auth.models.User.
The default User model offers a lot of the functionality that I don't need in my project and doesn't have a lot of fields that I will need.

My question is, what should I be worried about when using a custom User model?

One thing I can think of is, some plugins/apps might require django's built-in User model to function properly.
Any other issues I should be aware of?

Thank you,

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/049a9bbd-a2c0-4aa8-a65c-8bda8849cba9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

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

passwort reset next url

Hi,

I have implemented my own password reset by overwriting the templates of django.contrib.auth
If I go to the login page e.g. /login I usually have a GET parameter "next" where I want to be redirected after successful login.
If I have forgotten my password, I would like to jump into the password reset process, but be able to use the next parameter after successful password reset and provide a link to /login?next=… to guide the user back to the login page in the sam manner, as before.

How can I do this?

kind regards

Hinnack

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

Re: What are the disadvantages of using a custom user model?

Thank you James.
That was an extremely helpful answer.
Highly appreciated.

On Monday, August 31, 2015 at 10:36:06 AM UTC+3, James Schneider wrote:
> Hello,
> I am evaluating whether it is better to use a custom user model in django or
> just extend django.contrib.auth.models.User.

In either case, you are still using a custom user model. The latter is
just one of the strategies to implement the former.

> The default User model offers a lot of the functionality that I don't need
> in my project and doesn't have a lot of fields that I will need.
>

Be cautious in adding fields to the user model. Convention dictates
that only data specific to authenticating the user (username,
password, etc.), or data that would be used on [almost] every single
request (first/last/given name). Other details that would fit better
within a user profile should be stored as such in a separate table
using a OneToOne field back to the custom user model. An example of
that data might be gender or age/birthday, since most requests from
that user will likely not require that information, and it should be
pulled intermittently on-demand rather than for every request/response
cycle.

> My question is, what should I be worried about when using a custom User
> model?

Assuming everything is built correctly, probably not a whole lot. The
core business logic surrounding the custom user model should match
what is currently available (creating/deleting, setting
active/inactive, etc.). Those are the touch points for 3rd party apps
(or should be, anyway). See the AbstractBaseUser class (which contains
the minimal set of fields and methods that all user models should
contain) for 1.8.4 here:

https://github.com/django/django/blob/1.8.4/django/contrib/auth/models.py#L195

All of the extra fields that most folks override live in AbstractUser,
most 'custom' user models are probably a copy of AbstractUser that has
been reworked per their requirements (but still inherits from
AbstractBaseUser).

Read the docs thoroughly (both for Django and any 3rd party apps that
may interact directly with the custom user model, which should be
relatively few), custom user models can be tricky for the more
complicated cases.

> One thing I can think of is, some plugins/apps might require django's
> built-in User model to function properly.

If you find an app that requires the use of the built-in User model,
you probably shouldn't use it. Django has had support for custom user
models since 1.5, which was quite a while ago, and plenty of time for
3rd party apps to catch up.

> Any other issues I should be aware of?
>

If you create a custom authentication backend in addition to your
custom user model, you may run into trouble with other apps that may
expect certain things to be there (same rules apply here as to custom
user models). If all you are doing is adding or suppressing fields in
your custom user model without modifying the authentication backend,
then you should be fine. You may be required to provide a custom auth
backend if your custom user model is something more than a couple of
extra fields.

The authentication backend does have a few "required" behaviors, but
that is all listed in the docs if you are so inclined.

Any decent apps with that deep of a dependency will likely provide a
disclaimer that specific functionality is expected on the user model
or authentication backend. Unless you go way off the reservation,
though, you should be fine.

TL;DR; The large majority of 3rd party apps won't care or even know
that you are using a custom user model, as long as it is implemented
correctly.

-James

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

HTTP is dead! Django is dead! Flask is not yet born! The age of comet the age of node! :p Dirty JavaScript has taken over!

Just kidding, Love Python Love Django. <3

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

load drf from different location


Hi 

This is the problem I am trying to solve. I have a VM which has all the django + other required packages are installed (including the rest_framework). I usually ssh to the VM and then run the following command 

PYTHONPATH=/all/the/paths runserver 127.0.0.1:8000

Now I want to mount the rest_framework to my local machine and and put some debug code to understand how to framework is working. what I like to do is this, I installed the rest_framework module in to my local directory (in VM) and I would like to load the rest_framework from the local install instead from the systemwide install ( I do not want to edit the systemwide install). 

How can I tell the django or pythonpath to load only rest_framework from somewhere else. 

Thank You 
Prabath 

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

Re: Ajax in Django

Ajax are just normal HTTP requests. You can write a view in your code which returns data from db. If it is a post requests then make sure you're adding "csrfmiddlewaretoken" in the ajax data. 

On Mon, 31 Aug 2015 at 19:30 jasir1903 <jasir1903@gmail.com> wrote:
How to retrive Data from Db in Django to Template using Ajax? I am new to Django i need to retrive the data WITHOUT PAGE REFRESH USING AJAX please help me with that..

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

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

Ajax in Django

How to retrive Data from Db in Django to Template using Ajax? I am new to Django i need to retrive the data WITHOUT PAGE REFRESH USING AJAX please help me with that..

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

Re: Best Practices for transferring email form data to web server

That worked.

I was not aware of the csrf exempt directive.

My email form works the way that I want.

On Friday, August 28, 2015 at 5:22:46 PM UTC-4, pythonista wrote:


I have created a form that works fine for GETS and POSTS through the browser.

I have embedded the form with a GET (action) in the email, and the data gets transferred to the server as expected.

The email POST looks like it needs a csrf token.
Is there anyway to generate this and embed it on the fly as hidden?

What are the best practices for capturing and submitting form data from emails.
POST or GET

In my case the data is not sensitive information.


Thanks in advance

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

Re: What is the best way to dynamically build and insert templatetags from data?

Hi,

From the doc https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#writing-custom-template-tags
Have you looked at registering one template tag with parameters? That seems to cover your example, but I appreciate it's probably much simpler than the actual use case.

Otherwise, the bit where you register your tags should, as I understand the docs, located in foobar_app/templatetags/dynamic_tags.py, next to a __init__.py.

And then the code should be something along the lines of:
from django import template  
from django.conf import settings
register = template.Library()
for register in settings.DYN_TAGS:      register.simple_tag(lambda : register['data'], name=register['name'], takes_context=True)
# In the templates:

    {% load dynamic_tags %}
    {% foo %}

I haven't tested it, but should be close enough. I would be curious on the things you try to do with that though.

On Sunday, 30 August 2015 02:35:31 UTC+1, Val Neekman wrote:
What is the best way to dynamically build and insert templatetags from some data in settings.py

# .... in settings.py
DYN_TAGS = [
    {
        'name': 'foo',
        'data': {
             'code': 200,
             'says': 'Foo here',
        }
    },
    {
        'name': 'bar',
        'data': {
             'code': 401,
             'says': 'Bar here',
        }
    }
]

# ... in:  foobar_app/__init__.py

from django.conf import settings
for tag in settings.DYN_TAGS:
   # register tags


####### The above should be equal to #########
# if we had an app called foobar_app and it had a templatetags directory
# .... in:  foobar_app/templatetags/foo.py
  @register.assignment_tag(takes_context=True)
  def foo(context):
    return {'code': 200, 'says': 'Foo here'}

# .... in:  foobar_app/templatetags/bar.py
  @register.assignment_tag(takes_context=True)
  def bar(context):
    return {'code': 401, 'says': 'Bar here'}

Please note that the data is made up to help with the question.
Django 1.8+ answers would be great.

Thanks,
Val

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

How to insert session User id in database .?

I am trying to insert session login user id in database... here is my code

view.py

from django.shortcuts import render,redirect, Http404
from django.forms import ModelForm

# Create your views here.

from marketing.forms import EmailForm
from marketing.models import MarketingMessage, Slider
from .models import Product, ProductImage,Book,Category,Product
from products.models import Product


class DealsForm(ModelForm):
    class Meta:
        model = Product
        fields = ['title','description','category','price','sale_price','slug','active','update_defaults','user']
        exclude = ('user',)
        



def deals(request, template_name='products/deals.html'):
    form = DealsForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('home')
    return render(request, template_name, {'form':form})



Model.py file


from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User


class Book(models.Model):
    name = models.CharField(max_length=200)
    pages = models.IntegerField()
    email = models.CharField(max_length=200)
   
    
    def __unicode__(self):
         return self.name



class Category(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(null=True, blank=True)
slug = models.SlugField(unique=True)
featured = models.BooleanField(default=None)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)


def __unicode__(self):
return self.title

      
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(null=True, blank=True,max_length=200)
category = models.ManyToManyField(Category, null=True, blank=True)
price = models.DecimalField(decimal_places=2, max_digits=100, default=29.99)
sale_price = models.DecimalField(decimal_places=2, max_digits=100,\
null=True, blank=True)
slug = models.SlugField(unique=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
update_defaults = models.BooleanField(default=False)
user = models.ForeignKey(User)   

def __unicode__(self):
return self.title

class Meta:
unique_together = ('title', 'slug')

def get_price(self):
return self.price

def get_absolute_url(self):
return reverse("single_product", kwargs={"slug": self.slug})

def my_view(request):
            product = DealsForm.save(commit=False)
            product.user = request.username
            product.save()


class ProductImage(models.Model):
product = models.ForeignKey(Product)
image = models.ImageField(upload_to='products/images/')
featured = models.BooleanField(default=False)
thumbnail = models.BooleanField(default=False)
active = models.BooleanField(default=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)

def __unicode__(self):
      return self.product.title




class VariationManager(models.Manager):
def all(self):
return super(VariationManager, self).filter(active=True)

def sizes(self):
return self.all().filter(category='size')

def colors(self):
return self.all().filter(category='color')


VAR_CATEGORIES = (
('size', 'size'),
('color', 'color'),
('package', 'package'),
)


class Variation(models.Model):
product = models.ForeignKey(Product)
category = models.CharField(max_length=120, choices=VAR_CATEGORIES, default='size')
title = models.CharField(max_length=120)
image = models.ForeignKey(ProductImage, null=True, blank=True)
price = models.DecimalField(max_digits=100, decimal_places=2, null=True, blank=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
objects = VariationManager()

def __unicode__(self):
return self.title



def product_defaults(sender, instance, created, *args, **kwargs):
if instance.update_defaults:
categories = instance.category.all()
print categories
for cat in categories:
print cat.id
if cat.id == 1: #for t-shirts
small_size = Variation.objects.get_or_create(product=instance, 
category='size', 
title='Small')
medium_size = Variation.objects.get_or_create(product=instance, 
category='size', 
title='Medium')
large_size = Variation.objects.get_or_create(product=instance, 
category='size', 
title='Large')
instance.update_defaults = False
instance.save()
#print args, kwargs

post_save.connect(product_defaults, sender=Product)



can someone help me..? 








 

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

Re: I have error like Type Error save() takes at least 2 arguments (1 given) in Django project.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2

iQIcBAEBCAAGBQJV5DX2AAoJEH2EY3tf/UcFgrwQAIPyB6nkKVJwDbavGScggG5/
LQglF0i2taAQWPqg9l3HEN0/cVKOcKb10KG+SjsKurgcy9LIGG9O5cZIE1OjEftJ
shqjRS5DeCYDB4exhMPVtoBkf2v9UW3vb4OGWGXGEP8HOFTXibR0kNhplsKGTjrd
Aj2uKnz81lpMlwDR/94B/yNDWJ38wf5lDBwpsOpEZ5tWv9YEcjefRgfQk8simlGI
d2eQL9qGZkIEbc50Pa1WBUFnWZWKX0NBrjUHRt/sJ4H5p9Ylnxi+8JzemGevg8mx
ph4MelCRJdZNnGjN+BA8rIQAjmy2XVsAcvZr1cV1WVtXkuXCwr9qBZqOpDKv2jjO
zUljIKjj72lmc34SY42yj0JdV5Pr6VnM8vf6E1yNkiHyr9Va1emQ5uq2atTJ5DTn
Sv5PrGHD7ght82CbSzewVVywbuHVXXg5q70nIFFVfxg2k5mXTk32eMuRxKng0UjH
uKFOKgo+kl2aoJ5lxCIjhso2JuY2BrgidAB+WICyZb5kNWb9gquq9LjM2U2MPW0j
pviLs82S5uk+RlRX7pcRwqIbs2QNMLifYKBmj2A7NjqIxk9aincAYwCU9JYDXuZ4
deqF6rUxt9mXEnTdG0X9jyA7tHEpbRyXOIbZRmw+8amGND2+8cDKIjn8Tn1en0LD
CuJ1V77EoUbtQp48ndA7
=81ua
-----END PGP SIGNATURE-----
On 31/08/15 12:10, Remaze Vs wrote:
> def save(self,request,*args,**kwargs):

You defined save to take a second positional argument, so it's no wonder
it crashes if you call .save()
If you need the request in the save method you have to pass it,
otherwise remove the request parameter.

See docs for .save() overwrite:
https://docs.djangoproject.com/en/1.8/ref/models/instances/#django.db.models.Model.save

regards,
Florian

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

Re: I have error like Type Error save() takes at least 2 arguments (1 given) in Django project.

On Mon, Aug 31, 2015 at 03:10:09AM -0700, Remaze Vs wrote:
>view.py file
>
>
>class DealsForm(ModelForm):
> class Meta:
> model = Product
> fields = ['title','description','category','price','sale_price','slug','active','update_defaults','user']
> exclude = ('user',)
>
>
>
>model.py file
>
>
>
>class Product(models.Model):
> title = models.CharField(max_length=120)
> description = models.TextField(null=True, blank=True,max_length=200)
> category = models.ManyToManyField(Category, null=True, blank=True)
> price = models.DecimalField(decimal_places=2, max_digits=100, default=29.99)
> sale_price = models.DecimalField(decimal_places=2, max_digits=100,\
> null=True, blank=True)
> slug = models.SlugField(unique=True)
> timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
> updated = models.DateTimeField(auto_now_add=False, auto_now=True)
> active = models.BooleanField(default=True)
> update_defaults = models.BooleanField(default=False)
> user = models.ForeignKey(User)
>
> def __unicode__(self):
> return self.title
>
> class Meta:
> unique_together = ('title', 'slug')
>
> def get_price(self):
> return self.price
>
> def get_absolute_url(self):
> return reverse("single_product", kwargs={"slug": self.slug})
>
> def save(self, request, *args, **kwargs):
> obj = super(DealsForm, self).save(commit=False, *args, **kwargs)

Why "DealsForm"??

Also: you might want to share the traceback in the full future.

> obj.user = request.user
> obj.save()
>
>
>Can you solve this problems ?

/Markus

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


--

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

I have error like Type Error save() takes at least 2 arguments (1 given) in Django project.

view.py file


class DealsForm(ModelForm):      class Meta:          model = Product          fields = ['title','description','category','price','sale_price','slug','active','update_defaults','user']          exclude = ('user',)


model.py file


class Product(models.Model):      title = models.CharField(max_length=120)      description = models.TextField(null=True, blank=True,max_length=200)      category = models.ManyToManyField(Category, null=True, blank=True)      price = models.DecimalField(decimal_places=2, max_digits=100, default=29.99)      sale_price = models.DecimalField(decimal_places=2, max_digits=100,\                                              null=True, blank=True)      slug = models.SlugField(unique=True)      timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)      updated = models.DateTimeField(auto_now_add=False, auto_now=True)      active = models.BooleanField(default=True)      update_defaults = models.BooleanField(default=False)      user = models.ForeignKey(User)           def __unicode__(self):          return self.title        class Meta:          unique_together = ('title', 'slug')        def get_price(self):          return self.price        def get_absolute_url(self):          return reverse("single_product", kwargs={"slug": self.slug})        def save(self, request, *args, **kwargs):          obj = super(DealsForm, self).save(commit=False, *args, **kwargs)          obj.user = request.user           obj.save() 

Can you solve this problems ?  

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