Unable to get the locale encoding in Ubuntu 12.04, Apache/2.4.7, libapache2-mod-wsgi-py3, Python 3.4, Django 1.86

2015-11-06 Thread Abhijit Nandy
I am trying to setup a simple Django app using this tutorial:
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04

My configuration is:
Ubuntu 12.04, Apache/2.4.7, libapache2-mod-wsgi-py3, Python 3.4, Django 1.86

I keep getting the following error in the apache log whenever I try to 
access the server using its IP:

ImportError: No module named 'encodings'
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
[Sat Nov 07 01:26:56.505373 2015] [core:notice] [pid 20920:tid 
140075144152960] AH00051: child pid 21716 exit signal Aborted (6), possible 
coredump in /etc/apache2
[Sat Nov 07 01:26:56.505478 2015] [core:notice] [pid 20920:tid 
140075144152960] AH00051: child pid 21717 exit signal Aborted (6), possible 
coredump in /etc/apache2
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'

My virtual hosts file looks as follows:

 

ServerAdmin 
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/public_html

Alias /static /home/admin/myproject/static

Require all granted




Require all granted



WSGIDaemonProcess myproject 
python-path=/home/admin/myproject:/home/admin/myproject/myprojectenv/lib/python3.4/site-packages
WSGIProcessGroup myproject
WSGIScriptAlias / /home/admin/myproject/myproject/wsgi.py

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

  
   
Note: There were no errors while setting up Django in the virtualenv. It 
may be a problem with the PythonPath, buI think I have specified it 
correctly via the python-path option in the WSGIDaemonProcess directive.

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


n00b question about displaying data in order by day

2015-11-06 Thread Becka R.
Hi --

I'm building a scheduling app for my burning man camp.  There are seven 
days (Mon-Sun), and each day has two meals, and people can sign up for the 
available shifts. 

Here's my table:


class mealShifts(models.Model):
Sunday = "Sunday"
Monday = "Monday"
Tuesday = "Tuesday"
Wednesday = "Wednesday"
Thursday = "Thursday"
Friday = "Friday"
Days = (
(Sunday, "Sunday"),
(Monday, "Monday"),
(Tuesday, "Tuesday"),
(Wednesday, "Wednesday"),
(Thursday, "Thursday"),
(Friday, "Friday"),
)
Breakfast = "Breakfast"
Dinner = "Dinner"
Meals = (
(Breakfast, "Breakfast"),
(Dinner, "Dinner"),
)
Chef = "Chef"
Sous_Chef = "Sous-Chef"
KP ="KP"
Shifts = (
(Chef, "Chef"),
(Sous_Chef, "Sous_Chef"),
(KP, "KP"),
)
assigned = models.BooleanField(default=False)
day = models.CharField(max_length = 10, choices=Days, default=Sunday)
meal = models.CharField(max_length = 10, choices=Meals, default=Dinner)
shift = models.CharField(max_length = 10, choices=Shifts, default=KP)
camper = models.OneToOneField(User)

class Meta:
unique_together = ("day", "meal", "shift")

def __str__(self):
return '%s %s %s %s'%(self.day, self.meal, self.shift, self.camper)



And my views function:

def signup(request):

shifts = mealShifts.objects.all()

username = None

if not request.user.is_authenticated():

return 

if request.method == 'POST':

form = MealForm(request.POST)

if form.is_valid():

shift = form.save(commit=False)

shift.camper = request.user

shift.save()

return redirect('signup')


else:

form = MealForm()

return render_to_response('signup.html', 

RequestContext(request, {'form':form,'shifts':shifts, 
'username':username},))


 
And here's the part of the template that displays the shifts:


Shifts





{% for shift in shifts %}

{{shift.camper}} {{shift.day}} {{ shift.meal }} 

{% endfor %}









How can I display the data in the template so the shifts are sorted by day, 
and then by meal?

Thank you,

Becka

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


Spatialite for GeoDjango can't be loaded on Ubuntu Wily Werewolf

2015-11-06 Thread Berthier Lemieux


Hi!

 When I try to use django.contrib.gis.db.backends.spatialite as my db engine on 
Ubuntu Wily Werewolf (15.10), I am getting the following error:


*django.core.exceptions.ImproperlyConfigured: Unable to load the SpatiaLite 
library extension "libspatialite.so.7" because: 
/usr/local/lib/libspatialite.so.7: undefined symbol: sqlite3_spatialite_init*
I get that error every time I'm running one of the manage.py operations. The 
same code works fine on previous Ubuntu buils (14.04).

I can work around that problem by using mod_spatialite, defining in my 
settings.py:

*SPATIALITE_LIBRARY_PATH=*

*'/usr/local/lib/mod_spatialite.so'*  
The guys from the djangorestframework-gis seem to have decided to use the 
*mod_spatialite* https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=793526. 

I wonder if the same should be done for 
/django/contrib/gis/db/backends/spatialite/base.py?

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


Trouble with Intermediate Page for admin Interface

2015-11-06 Thread Jonny Mcgow


So I’ve been working for a couple days now on setting up a pretty basic 
bulk edit action for my server that consists of selecting all of the 
objects you want to change a designated field on, being redirected to an 
intermediate page, entering a new integer value for the designated field, 
and then clicking accept to make the changes to all of the objects. I tried 
to use the bulk delete that comes pre-installed with all models as a 
template to make my action, form, and template for the intermediate page, 
and I don’t get any errors, but when I submit my changes on the 
intermediate page, I’m redirected to the objects list page and my action is 
not run again.

I’m not sure how to get the redirect from the template to correctly call my 
action after it returns, I’ve tried a lot of things and nothing seems to 
work. I’ll post the code and screenshots below:
*my action definition:* 

def change_min_interval(self, request, queryset):
form = None
opts = self.model._meta
app_label = opts.app_label
if not self.has_change_permission(request):
raise PermissionDenied
using = router.db_for_write(self.model)
if 'apply' in request.POST:
form = self.ChangeMinIntervalForm()
if form.is_valid():
new_interval = form.cleaned_data['new_interval']
rows_updated = queryset.update(min_interval=new_interval)
plural = ''
if rows_updated != 1:
plural = 's'

self.message_user(request, "Successfully changed min_interval to %s 
on %d node%s." % (new_interval, rows_updated, plural))
return None
if len(queryset) == 1:
objects_name = force_text(opts.verbose_name)
else:
objects_name = force_text(opts.verbose_name_plural)

if not form:
form = self.ChangeMinIntervalForm()

context = dict(
self.admin_site.each_context(request),
app_label=app_label,
title="Change min_interval",
objects_name=objects_name,
nodes=queryset,
opts=opts,
new_interval_form=form,
)

request.current_app = self.admin_site.name
return TemplateResponse(request, 'admin/change_min_interval.html', context)
change_min_interval.short_description = "Change Minimum Interval"

*my form definition:* 

class ChangeMinIntervalForm(forms.Form):
new_interval = forms.IntegerField()

*my template definition:* 

{% extends "admin/base_site.html" %}
{% load i18n admin_urls %}

{% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ 
opts.model_name }} change-min-interval-confirmation{% endblock %}

{% block breadcrumbs %}{% trans 'Home' %}
 {{ 
opts.app_config.verbose_name }}
 {{ 
opts.verbose_name_plural|capfirst|escape }}

 {% trans 'Change min_interval' %}
{% endblock %}

{% block content %}
Enter new minimum interval to apply:
 {% csrf_token %}
{{ new_interval_form }}

The new minimum interval will be applied to:

{{ nodes|unordered_list }}



Cancel

{% endblock %}

*screenshots:* 

Selecting node to run the action on.



Selecting new min_interval for the node



Lack of results after submitting the form.



Shell outputs throughout this proccess.


​

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


what is best way to pass form from non editable view to a editable window then save it and send values back to previously non editor view

2015-11-06 Thread sushovan majumdar
I have a django view which has simple form with key value pair. 
I have made the fields non editable. I'm providing a edit button which will 
open a new window dialog and there i will load the same form in editable 
view and provide option to save or add new rows to form.
When user clicks on save on second window i want it to close and initial 
parent view to be refreshed with new values of the form.

I have never done this so I would appreciate if someone helps me understand 
on how to achieve this. 

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


Re: update_or_create() always creates (or recreates)

2015-11-06 Thread Yunti
Thanks - you've definitely given me some stuff to think about.  I'm doing 
XHR requests - returning JSON for the scraping (but probably later will 
have normal pages so I will definitely look at your Etag suggestion - I'm 
not familiar with that so will look into it). 

Given it's XHR and JSON I presume eTag isn't relevant, so I think your idea 
of setting a flag is a good one.  So for each row in each table (e.g. a 
Supplier) that I rescrape - get that from database based on the unique_id 
and then compare each attribute to the re-scraped JSON and alter 
flag/update instance if diff.  

The data will only change about a fraction of a percent of the time (most 
of the time constant) and it will be about 70k rows with 50 -100 fields. 
 DB is postgres (on Heroku for now). 

On Friday, 6 November 2015 17:12:05 UTC, Dan Tagg wrote:
>
> If you are web scraping you really need your code to be as efficient as 
> possible and to do as little as possible. Firstly, make sure you are using 
> everything the servers of the websites you are scraping are giving you to 
> decide whether to bother downloading the page. For example, check the etag 
> and only bother to scape if it is different from the last time you scraped 
> data.. If you don't trust the server's ETag, you can hash the page when you 
> download it and check that against your stored hash so you can check 
> whether it changed and whether it's worth processing. 
>
> Your approach of trying a 'get' with all the properties set and picking up 
> the exception has costs -- Assuming your tables have enough rows that 
> scanning the entire table won't be efficient for every "get" you will need 
> to have every column you are using in you "get" indexed in the database. 
> This obviously has a storage cost as well as an additional insert/update 
> cost and a larger cost to run the query than a simple select against a 
> single key. Whether that is more efficient than getting the result and 
> comparing the fields in python I don't know. I imagine it will be dependent 
> on what your RDBMS is and how it is hosted as well as how many rows and 
> columns will be in your database table.
>
> You could initialise a flag to False and as you process your scraped data 
> you could compare it to the attributes of your instance and set the flag to 
> True if they have changed and then not bother saving if you get to the end 
> of processing your scraped data and the modified flag has not been set to 
> True.
>
> Dan 
>
> On 6 November 2015 at 16:12, Yunti  wrote:
>
>> Hi Dan,
>>
>> Thanks for the suggestion, it's a web scraper (run as a django management 
>> command) which then saves the data to the database via the Django ORM.  
>> Given it's a scraper rather than a form (or view) is the above suggested 
>> function an ok way to proceed or would you suggest something else is more 
>> appropriate/best practice?
>>
>>
>>
>> On Friday, 6 November 2015 14:40:59 UTC, Dan Tagg wrote:
>>>
>>> Hi Yunti,
>>>
>>>
>>> You could go up a level in the structure of your application and apply 
>>> the logic there, where there is more support.
>>>
>>> Are you using Django forms? The ModelForm class pretty much does what 
>>> you want, it examines form data, validating it against its type and any 
>>> validation rules you have set in the form or your model, compares it to the 
>>> instance's data in the database and only saves if there has been some kind 
>>> of change. 
>>>
>>> Dan
>>>
>>> On 6 November 2015 at 13:47, Yunti  wrote:
>>>
 Jani,

 Thanks for your reply - you explained it much more concisely than I 
 did. :)

 Good to have it confirmed that update_or_create() doesn't quite do what 
 I needed - I was confused as to whether it would or not.

 Thanks for taking the time to do that function, that looks ideal. I'll 
 test it out.


 On Friday, 6 November 2015 12:52:11 UTC, Jani Tiainen wrote:

> Your problem lies on the way Django actually carries out create or 
> update.
>
> As name suggest, create or update does either one. But that's what you 
> don't want - you want conditional update.
>
> Only update if certain fields have been changed. Well this can be done 
> few ways.
>
> So you want to do 
> "update_only_if_at_least_one_of_default_fields_changed_or_create"
>
> Operation is simple, if object is not found, create new one using 
> defaults if found, pull values as a dict, compare against
> default values and if at least one differs do an update. Otherwise 
> don't do anything.
>
> So basically code would look something like this:
>
> update_if_changed_or_create(**kwargs):
> defaults = kwargs.pop('defaults', None)
>
> qs = MyModel.objects.filter(**kwargs)
>
>  if not qs:
> obj = MyModel(**kwargs).save()
> return obj, True  # Created object
> 

Re: django admin - You don't have permission to edit anything

2015-11-06 Thread Benjamin Smith
Yes, that was it. I changed the user manager function to create superuser
into this

def create_superuser(self, email, first_name, last_name, username,
date_of_birth, password, **kwargs):
user = self.create_user(
email,
first_name=first_name,
last_name=last_name,
username=username,
date_of_birth=date_of_birth,
password=password,
is_superuser=True,
**kwargs
)

All thanks to you! Now I understand much better.

Thank you.

On Fri, Nov 6, 2015 at 2:42 PM, Andreas Kuhne 
wrote:

> Hi,
>
> Check the PermissionsMixin. In that mixin you add the is_superuser field.
> It also adds the relations to the auth group for group permissions and so
> on. And the django admin site checks for permissions by calling the
> has_perm() method on your user model. The has_perm() method always returns
> True if the user is a superuser, so you always get ALL rights that way. If
> you want finegrained rights you need to add the permissions manually (can
> be done in django admin).
>
> Check the code for the PermissionsMixin here:
> https://github.com/django/django/blob/master/django/contrib/auth/models.py#L207
>
> The reason why it's working now is because you have explicitly set the
> is_superuser property to True.
>
> Regards,
>
> Andréas
>
> 2015-11-06 10:04 GMT+01:00 Benjamin Smith :
>
>> Hello,
>> Yes I thought so too, but in the example there is no *is_superuser *property
>> provided neither in the User models or in the User manager. Therefore, I
>> just copied the example from the django doc and tried running it. After
>> creating the superuser, I can edit the models. I have no Idea what I am
>> mission now.
>>
>>
>> On Fri, Nov 6, 2015 at 11:35 AM, Andreas Kuhne <
>> andreas.ku...@suitopia.com> wrote:
>>
>>> Hi,
>>>
>>> You don't have permissions to edit anything, because you haven't created
>>> a superuser.
>>>
>>> The superuser in django has a property that is called "is_superuser" and
>>> should be set to True. If you don't have that property (and your
>>> createsuperuser sets some other property), you will have the same rights as
>>> everyone else, which is nothing to begin with. You can add rights to the
>>> user be adding the permissions you want, or by setting the is_superuser
>>> property to True.
>>>
>>> Check the documentation for the django admin site here:
>>> https://docs.djangoproject.com/en/1.8/ref/contrib/admin/
>>>
>>> Regards,
>>>
>>> Andréas
>>>
>>> 2015-11-06 0:15 GMT+01:00 Benjamin Smith :
>>>
 I followed the django doc
 
 on creating a custom user model while extending the model itself with my
 own fields. So it became like this:

 class MyUser(AbstractBaseUser, PermissionsMixin):
 email = models.EmailField(max_length=255, unique=True)
 first_name = models.CharField(max_length=35)
 last_name = models.CharField(max_length=35)
 username = models.CharField(max_length=70, unique=True)
 date_of_birth = models.DateField()
 is_active = models.BooleanField(default=True)
 is_admin = models.BooleanField(default=False)

 @property
 def is_staff(self):
 return self.is_admin

 def get_full_name(self):
 return ('%s %s') % (self.first_name, self.last_name)

 def get_short_name(self):
 return self.username

 objects = MyUserManager()
 USERNAME_FIELD = 'email'
 REQUIRED_FIELDS = ['first_name', 'last_name', 'username',
 'date_of_birth']

 And its manager to be:

 class MyUserManager(BaseUserManager):
 def create_user(self, email, first_name, last_name, username,
 date_of_birth, password=None):
 if not email:
 raise ValueError('User must have an email address')

 user = self.model(
 email=self.normalize_email(email),
 first_name=first_name,
 last_name=last_name,
 username=username,
 date_of_birth=date_of_birth,
 )

 user.set_password(password)
 user.save(using=self._db)
 return user

 def create_superuser(self, email, first_name, last_name,
 username, date_of_birth, password):
 user = self.create_user(
 email,
 first_name=first_name,
 last_name=last_name,
 username=username,
 date_of_birth=date_of_birth,
 password=password
 )
 user.is_admin = True
  

Re: update_or_create() always creates (or recreates)

2015-11-06 Thread Dan Tagg
If you are web scraping you really need your code to be as efficient as
possible and to do as little as possible. Firstly, make sure you are using
everything the servers of the websites you are scraping are giving you to
decide whether to bother downloading the page. For example, check the etag
and only bother to scape if it is different from the last time you scraped
data.. If you don't trust the server's ETag, you can hash the page when you
download it and check that against your stored hash so you can check
whether it changed and whether it's worth processing.

Your approach of trying a 'get' with all the properties set and picking up
the exception has costs -- Assuming your tables have enough rows that
scanning the entire table won't be efficient for every "get" you will need
to have every column you are using in you "get" indexed in the database.
This obviously has a storage cost as well as an additional insert/update
cost and a larger cost to run the query than a simple select against a
single key. Whether that is more efficient than getting the result and
comparing the fields in python I don't know. I imagine it will be dependent
on what your RDBMS is and how it is hosted as well as how many rows and
columns will be in your database table.

You could initialise a flag to False and as you process your scraped data
you could compare it to the attributes of your instance and set the flag to
True if they have changed and then not bother saving if you get to the end
of processing your scraped data and the modified flag has not been set to
True.

Dan

On 6 November 2015 at 16:12, Yunti  wrote:

> Hi Dan,
>
> Thanks for the suggestion, it's a web scraper (run as a django management
> command) which then saves the data to the database via the Django ORM.
> Given it's a scraper rather than a form (or view) is the above suggested
> function an ok way to proceed or would you suggest something else is more
> appropriate/best practice?
>
>
>
> On Friday, 6 November 2015 14:40:59 UTC, Dan Tagg wrote:
>>
>> Hi Yunti,
>>
>>
>> You could go up a level in the structure of your application and apply
>> the logic there, where there is more support.
>>
>> Are you using Django forms? The ModelForm class pretty much does what you
>> want, it examines form data, validating it against its type and any
>> validation rules you have set in the form or your model, compares it to the
>> instance's data in the database and only saves if there has been some kind
>> of change.
>>
>> Dan
>>
>> On 6 November 2015 at 13:47, Yunti  wrote:
>>
>>> Jani,
>>>
>>> Thanks for your reply - you explained it much more concisely than I did.
>>> :)
>>>
>>> Good to have it confirmed that update_or_create() doesn't quite do what
>>> I needed - I was confused as to whether it would or not.
>>>
>>> Thanks for taking the time to do that function, that looks ideal. I'll
>>> test it out.
>>>
>>>
>>> On Friday, 6 November 2015 12:52:11 UTC, Jani Tiainen wrote:
>>>
 Your problem lies on the way Django actually carries out create or
 update.

 As name suggest, create or update does either one. But that's what you
 don't want - you want conditional update.

 Only update if certain fields have been changed. Well this can be done
 few ways.

 So you want to do
 "update_only_if_at_least_one_of_default_fields_changed_or_create"

 Operation is simple, if object is not found, create new one using
 defaults if found, pull values as a dict, compare against
 default values and if at least one differs do an update. Otherwise
 don't do anything.

 So basically code would look something like this:

 update_if_changed_or_create(**kwargs):
 defaults = kwargs.pop('defaults', None)

 qs = MyModel.objects.filter(**kwargs)

  if not qs:
 obj = MyModel(**kwargs).save()
 return obj, True  # Created object
 else if len(qs) == 1:
 obj = qs[0]
 changed = False
 for k, v in defaults:
  if getattr(obj, k) != v:
  changed = True
  setattr(obj, k, v)
 if changed:
 obj.save()
 return obj, False  # Updated object
 else:
 # Multiple objects...

 return obj, None  # No change.


 On 06.11.2015 14:08, Yunti wrote:

 Carsten ,

 Thanks for your reply,

 A note about the last statement: If a Supplier object has the same
 unique_id, and all
 other fields (in `defaults`) are the same as well, logically there is
 no difference
 between updating and not updating – the result is the same.

 The entry in the database is the same - apart from the last_updated
 flag if it's not rewritten over the top of it.  This means I can check for
 new data often and be alerted when there is an actual 

Re: update_or_create() always creates (or recreates)

2015-11-06 Thread Yunti
Hi Dan,

Thanks for the suggestion, it's a web scraper (run as a django management 
command) which then saves the data to the database via the Django ORM. 
 Given it's a scraper rather than a form (or view) is the above suggested 
function an ok way to proceed or would you suggest something else is more 
appropriate/best practice?



On Friday, 6 November 2015 14:40:59 UTC, Dan Tagg wrote:
>
> Hi Yunti,
>
>
> You could go up a level in the structure of your application and apply the 
> logic there, where there is more support.
>
> Are you using Django forms? The ModelForm class pretty much does what you 
> want, it examines form data, validating it against its type and any 
> validation rules you have set in the form or your model, compares it to the 
> instance's data in the database and only saves if there has been some kind 
> of change. 
>
> Dan
>
> On 6 November 2015 at 13:47, Yunti  wrote:
>
>> Jani,
>>
>> Thanks for your reply - you explained it much more concisely than I did. 
>> :)
>>
>> Good to have it confirmed that update_or_create() doesn't quite do what I 
>> needed - I was confused as to whether it would or not.
>>
>> Thanks for taking the time to do that function, that looks ideal. I'll 
>> test it out.
>>
>>
>> On Friday, 6 November 2015 12:52:11 UTC, Jani Tiainen wrote:
>>
>>> Your problem lies on the way Django actually carries out create or 
>>> update.
>>>
>>> As name suggest, create or update does either one. But that's what you 
>>> don't want - you want conditional update.
>>>
>>> Only update if certain fields have been changed. Well this can be done 
>>> few ways.
>>>
>>> So you want to do 
>>> "update_only_if_at_least_one_of_default_fields_changed_or_create"
>>>
>>> Operation is simple, if object is not found, create new one using 
>>> defaults if found, pull values as a dict, compare against
>>> default values and if at least one differs do an update. Otherwise don't 
>>> do anything.
>>>
>>> So basically code would look something like this:
>>>
>>> update_if_changed_or_create(**kwargs):
>>> defaults = kwargs.pop('defaults', None)
>>>
>>> qs = MyModel.objects.filter(**kwargs)
>>>
>>>  if not qs:
>>> obj = MyModel(**kwargs).save()
>>> return obj, True  # Created object
>>> else if len(qs) == 1:
>>> obj = qs[0]
>>> changed = False
>>> for k, v in defaults:
>>>  if getattr(obj, k) != v:
>>>  changed = True
>>>  setattr(obj, k, v)
>>> if changed:
>>> obj.save()
>>> return obj, False  # Updated object
>>> else:
>>> # Multiple objects...
>>>
>>> return obj, None  # No change.
>>>
>>>
>>> On 06.11.2015 14:08, Yunti wrote:
>>>
>>> Carsten , 
>>>
>>> Thanks for your reply,
>>>
>>> A note about the last statement: If a Supplier object has the same 
>>> unique_id, and all 
>>> other fields (in `defaults`) are the same as well, logically there is no 
>>> difference 
>>> between updating and not updating – the result is the same. 
>>>
>>> The entry in the database is the same - apart from the last_updated flag 
>>> if it's not rewritten over the top of it.  This means I can check for new 
>>> data often and be alerted when there is an actual update (i.e. a change to 
>>> the data).  If it rewrites the data everytime it checks then I have no idea 
>>> when data was actually updated.
>>>
>>> Have you checked? How? 
>>> In your create_or_update_if_diff() you seem to try to re-invent 
>>> update_or_create(), but 
>>> have you actually examined the results of the 
>>>
>>>  supplier, created = Supplier.objects.update_or_create(...) 
>>>
>>> call? 
>>>
>>> I checked by seeing that the last_updated field in the database was 
>>> updated everytime.  (I suppose the issue could be with how that field gets 
>>> reset to the next time it's run- I didn't eliminate that possibility.)
>>>
>>> Yes I was worried that I might be recreating (a poor version) of 
>>> update_or_create() but it didn't seem to have the option where it wouldn't 
>>> write to the database if there was no change to the data.   
>>> Can it do this? And how would I verify when an item has been updated or 
>>> created (or neither) - could I output to the console? 
>>>
>>> If it can how do I call it so it checks against all fields (unique_id 
>>> and defaults) and updates using the defaults if it finds a difference (and 
>>> creates if it doesn't find a unique_id)?
>>>
>>> I'm still not sure if this is possible and how to call the function, 
>>> particular how to pass in the remaining defaults to check against - 
>>> **kwargs = defaults isn't right but not sure what it should be.
>>>
>>> supplier, created = 
>>> Supplier.objects.update_or_create(unique_id=product_detail['supplierId'], 
>>> **kwargs=defaults, 
>>>defaults={
>>>'name': 
>>> 

Custom Templates in Django Sitemaps Index

2015-11-06 Thread Andreas Dickow
See my new tutorial on Custom Templates in Django Sitemaps:
https://biz-factory.de/django-sitemap-index-tutorial/

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


Re: update_or_create() always creates (or recreates)

2015-11-06 Thread Dan Tagg
Hi Yunti,


You could go up a level in the structure of your application and apply the
logic there, where there is more support.

Are you using Django forms? The ModelForm class pretty much does what you
want, it examines form data, validating it against its type and any
validation rules you have set in the form or your model, compares it to the
instance's data in the database and only saves if there has been some kind
of change.

Dan

On 6 November 2015 at 13:47, Yunti  wrote:

> Jani,
>
> Thanks for your reply - you explained it much more concisely than I did. :)
>
> Good to have it confirmed that update_or_create() doesn't quite do what I
> needed - I was confused as to whether it would or not.
>
> Thanks for taking the time to do that function, that looks ideal. I'll
> test it out.
>
>
> On Friday, 6 November 2015 12:52:11 UTC, Jani Tiainen wrote:
>
>> Your problem lies on the way Django actually carries out create or update.
>>
>> As name suggest, create or update does either one. But that's what you
>> don't want - you want conditional update.
>>
>> Only update if certain fields have been changed. Well this can be done
>> few ways.
>>
>> So you want to do
>> "update_only_if_at_least_one_of_default_fields_changed_or_create"
>>
>> Operation is simple, if object is not found, create new one using
>> defaults if found, pull values as a dict, compare against
>> default values and if at least one differs do an update. Otherwise don't
>> do anything.
>>
>> So basically code would look something like this:
>>
>> update_if_changed_or_create(**kwargs):
>> defaults = kwargs.pop('defaults', None)
>>
>> qs = MyModel.objects.filter(**kwargs)
>>
>>  if not qs:
>> obj = MyModel(**kwargs).save()
>> return obj, True  # Created object
>> else if len(qs) == 1:
>> obj = qs[0]
>> changed = False
>> for k, v in defaults:
>>  if getattr(obj, k) != v:
>>  changed = True
>>  setattr(obj, k, v)
>> if changed:
>> obj.save()
>> return obj, False  # Updated object
>> else:
>> # Multiple objects...
>>
>> return obj, None  # No change.
>>
>>
>> On 06.11.2015 14:08, Yunti wrote:
>>
>> Carsten ,
>>
>> Thanks for your reply,
>>
>> A note about the last statement: If a Supplier object has the same
>> unique_id, and all
>> other fields (in `defaults`) are the same as well, logically there is no
>> difference
>> between updating and not updating – the result is the same.
>>
>> The entry in the database is the same - apart from the last_updated flag
>> if it's not rewritten over the top of it.  This means I can check for new
>> data often and be alerted when there is an actual update (i.e. a change to
>> the data).  If it rewrites the data everytime it checks then I have no idea
>> when data was actually updated.
>>
>> Have you checked? How?
>> In your create_or_update_if_diff() you seem to try to re-invent
>> update_or_create(), but
>> have you actually examined the results of the
>>
>>  supplier, created = Supplier.objects.update_or_create(...)
>>
>> call?
>>
>> I checked by seeing that the last_updated field in the database was
>> updated everytime.  (I suppose the issue could be with how that field gets
>> reset to the next time it's run- I didn't eliminate that possibility.)
>>
>> Yes I was worried that I might be recreating (a poor version) of
>> update_or_create() but it didn't seem to have the option where it wouldn't
>> write to the database if there was no change to the data.
>> Can it do this? And how would I verify when an item has been updated or
>> created (or neither) - could I output to the console?
>>
>> If it can how do I call it so it checks against all fields (unique_id and
>> defaults) and updates using the defaults if it finds a difference (and
>> creates if it doesn't find a unique_id)?
>>
>> I'm still not sure if this is possible and how to call the function,
>> particular how to pass in the remaining defaults to check against -
>> **kwargs = defaults isn't right but not sure what it should be.
>>
>> supplier, created = 
>> Supplier.objects.update_or_create(unique_id=product_detail['supplierId'], 
>> **kwargs=defaults,
>>defaults={
>>'name': 
>> product_detail['supplierName'],
>>'entity_name_1': 
>> entity_name_1,
>>'entity_name_2': 
>> entity_name_1,
>>'rating': 
>> product_detail['supplierRating']})
>>
>> On Thursday, 5 November 2015 20:05:39 UTC, Carsten Fuchs wrote:
>>>
>>> Hi Yunti, Am 05.11.2015 um 18:19 schrieb Yunti: > I have tried to use
>>> the update_or_create() method assuming that it would either, create > a new
>>> entry in the db if it found 

Re: update_or_create() always creates (or recreates)

2015-11-06 Thread Yunti
Jani,

Thanks for your reply - you explained it much more concisely than I did. :)

Good to have it confirmed that update_or_create() doesn't quite do what I 
needed - I was confused as to whether it would or not.

Thanks for taking the time to do that function, that looks ideal. I'll test 
it out.


On Friday, 6 November 2015 12:52:11 UTC, Jani Tiainen wrote:
>
> Your problem lies on the way Django actually carries out create or update.
>
> As name suggest, create or update does either one. But that's what you 
> don't want - you want conditional update.
>
> Only update if certain fields have been changed. Well this can be done few 
> ways.
>
> So you want to do 
> "update_only_if_at_least_one_of_default_fields_changed_or_create"
>
> Operation is simple, if object is not found, create new one using defaults 
> if found, pull values as a dict, compare against
> default values and if at least one differs do an update. Otherwise don't 
> do anything.
>
> So basically code would look something like this:
>
> update_if_changed_or_create(**kwargs):
> defaults = kwargs.pop('defaults', None)
>
> qs = MyModel.objects.filter(**kwargs)
>
>  if not qs:
> obj = MyModel(**kwargs).save()
> return obj, True  # Created object
> else if len(qs) == 1:
> obj = qs[0]
> changed = False
> for k, v in defaults:
>  if getattr(obj, k) != v:
>  changed = True
>  setattr(obj, k, v)
> if changed:
> obj.save()
> return obj, False  # Updated object
> else:
> # Multiple objects...
>
> return obj, None  # No change.
>
>
> On 06.11.2015 14:08, Yunti wrote:
>
> Carsten , 
>
> Thanks for your reply,
>
> A note about the last statement: If a Supplier object has the same 
> unique_id, and all 
> other fields (in `defaults`) are the same as well, logically there is no 
> difference 
> between updating and not updating – the result is the same. 
>
> The entry in the database is the same - apart from the last_updated flag 
> if it's not rewritten over the top of it.  This means I can check for new 
> data often and be alerted when there is an actual update (i.e. a change to 
> the data).  If it rewrites the data everytime it checks then I have no idea 
> when data was actually updated.
>
> Have you checked? How? 
> In your create_or_update_if_diff() you seem to try to re-invent 
> update_or_create(), but 
> have you actually examined the results of the 
>
>  supplier, created = Supplier.objects.update_or_create(...) 
>
> call? 
>
> I checked by seeing that the last_updated field in the database was 
> updated everytime.  (I suppose the issue could be with how that field gets 
> reset to the next time it's run- I didn't eliminate that possibility.)
>
> Yes I was worried that I might be recreating (a poor version) of 
> update_or_create() but it didn't seem to have the option where it wouldn't 
> write to the database if there was no change to the data.   
> Can it do this? And how would I verify when an item has been updated or 
> created (or neither) - could I output to the console? 
>
> If it can how do I call it so it checks against all fields (unique_id and 
> defaults) and updates using the defaults if it finds a difference (and 
> creates if it doesn't find a unique_id)?
>
> I'm still not sure if this is possible and how to call the function, 
> particular how to pass in the remaining defaults to check against - 
> **kwargs = defaults isn't right but not sure what it should be.
>
> supplier, created = 
> Supplier.objects.update_or_create(unique_id=product_detail['supplierId'], 
> **kwargs=defaults, 
>defaults={
>'name': 
> product_detail['supplierName'],
>'entity_name_1': 
> entity_name_1,
>'entity_name_2': 
> entity_name_1,
>'rating': 
> product_detail['supplierRating']})
>
> On Thursday, 5 November 2015 20:05:39 UTC, Carsten Fuchs wrote:
>>
>> Hi Yunti, Am 05.11.2015 um 18:19 schrieb Yunti: > I have tried to use the 
>> update_or_create() method assuming that it would either, create > a new 
>> entry in the db if it found none or update an existing one if it found one 
>> and had > differences to the defaults passed in  - or wouldn't update if 
>> there was no difference. A note about the last statement: If a Supplier 
>> object has the same unique_id, and all other fields (in `defaults`) are the 
>> same as well, logically there is no difference between updating and not 
>> updating – the result is the same. >   However it just seemed to recreate 
>> entries each time even if there were no changes. Have you checked? How? In 
>> your create_or_update_if_diff() you seem to try to re-invent 
>> 

Re: update_or_create() always creates (or recreates)

2015-11-06 Thread Jani Tiainen

Your problem lies on the way Django actually carries out create or update.

As name suggest, create or update does either one. But that's what you 
don't want - you want conditional update.


Only update if certain fields have been changed. Well this can be done 
few ways.


So you want to do 
"update_only_if_at_least_one_of_default_fields_changed_or_create"


Operation is simple, if object is not found, create new one using 
defaults if found, pull values as a dict, compare against
default values and if at least one differs do an update. Otherwise don't 
do anything.


So basically code would look something like this:

update_if_changed_or_create(**kwargs):
defaults = kwargs.pop('defaults', None)

qs = MyModel.objects.filter(**kwargs)

 if not qs:
obj = MyModel(**kwargs).save()
return obj, True  # Created object
else if len(qs) == 1:
obj = qs[0]
changed = False
for k, v in defaults:
 if getattr(obj, k) != v:
 changed = True
 setattr(obj, k, v)
if changed:
obj.save()
return obj, False  # Updated object
else:
# Multiple objects...

return obj, None  # No change.


On 06.11.2015 14:08, Yunti wrote:

Carsten ,

Thanks for your reply,

A note about the last statement: If a Supplier object has the same 
unique_id, and all
other fields (in `defaults`) are the same as well, logically there is 
no difference

between updating and not updating – the result is the same.

The entry in the database is the same - apart from the last_updated 
flag if it's not rewritten over the top of it.  This means I can check 
for new data often and be alerted when there is an actual update (i.e. 
a change to the data).  If it rewrites the data everytime it checks 
then I have no idea when data was actually updated.


Have you checked? How?
In your create_or_update_if_diff() you seem to try to re-invent 
update_or_create(), but

have you actually examined the results of the

 supplier, created = Supplier.objects.update_or_create(...)

call?

I checked by seeing that the last_updated field in the database was 
updated everytime.  (I suppose the issue could be with how that field 
gets reset to the next time it's run- I didn't eliminate that 
possibility.)


Yes I was worried that I might be recreating (a poor version) of 
update_or_create() but it didn't seem to have the option where it 
wouldn't write to the database if there was no change to the data.
Can it do this? And how would I verify when an item has been updated 
or created (or neither) - could I output to the console?


If it can how do I call it so it checks against all fields (unique_id 
and defaults) and updates using the defaults if it finds a difference 
(and creates if it doesn't find a unique_id)?


I'm still not sure if this is possible and how to call the function, 
particular how to pass in the remaining defaults to check against - 
**kwargs = defaults isn't right but not sure what it should be.


supplier, created = 
Supplier.objects.update_or_create(unique_id=product_detail['supplierId'], 
**kwargs=defaults, defaults={ 'name': product_detail['supplierName'], 
'entity_name_1': entity_name_1, 'entity_name_2': entity_name_1, 
'rating': product_detail['supplierRating']})

On Thursday, 5 November 2015 20:05:39 UTC, Carsten Fuchs wrote:

Hi Yunti, Am 05.11.2015 um 18:19 schrieb Yunti: > I have tried to
use the update_or_create() method assuming that it would either,
create > a new entry in the db if it found none or update an
existing one if it found one and had > differences to the defaults
passed in  - or wouldn't update if there was no difference. A note
about the last statement: If a Supplier object has the same
unique_id, and all other fields (in `defaults`) are the same as
well, logically there is no difference between updating and not
updating – the result is the same. >   However it just seemed to
recreate entries each time even if there were no changes. Have you
checked? How? In your create_or_update_if_diff() you seem to try
to re-invent update_or_create(), but have you actually examined
the results of the  supplier, created =
Supplier.objects.update_or_create(...) call? > I think the issue
was that I wanted to: > 1)  get an entry if all fields were the
same, update_or_create() updates an object with the given kwargs,
the match is not made against *all* fields (i.e. for the match the
fields in `defaults` are not accounted for). > 2) or create a new
entry if it didn't find an existing entry with the unique_id > 3)
or if there was an entry with the same unique_id, update that
entry with remaining > fields. update_or_create() should achieve
this. It's hard to tell more without additional information, but
https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update-or-create


Re: update_or_create() always creates (or recreates)

2015-11-06 Thread Yunti
Carsten ,

Thanks for your reply,

A note about the last statement: If a Supplier object has the same 
unique_id, and all 
other fields (in `defaults`) are the same as well, logically there is no 
difference 
between updating and not updating – the result is the same. 

The entry in the database is the same - apart from the last_updated flag if 
it's not rewritten over the top of it.  This means I can check for new data 
often and be alerted when there is an actual update (i.e. a change to the 
data).  If it rewrites the data everytime it checks then I have no idea 
when data was actually updated.

Have you checked? How? 
In your create_or_update_if_diff() you seem to try to re-invent 
update_or_create(), but 
have you actually examined the results of the 

 supplier, created = Supplier.objects.update_or_create(...) 

call? 

I checked by seeing that the last_updated field in the database was updated 
everytime.  (I suppose the issue could be with how that field gets reset to 
the next time it's run- I didn't eliminate that possibility.)

Yes I was worried that I might be recreating (a poor version) of 
update_or_create() but it didn't seem to have the option where it wouldn't 
write to the database if there was no change to the data.   
Can it do this? And how would I verify when an item has been updated or 
created (or neither) - could I output to the console? 

If it can how do I call it so it checks against all fields (unique_id and 
defaults) and updates using the defaults if it finds a difference (and 
creates if it doesn't find a unique_id)?

I'm still not sure if this is possible and how to call the function, 
particular how to pass in the remaining defaults to check against - 
**kwargs = defaults isn't right but not sure what it should be.

supplier, created = 
Supplier.objects.update_or_create(unique_id=product_detail['supplierId'], 
**kwargs=defaults, 
   defaults={
   'name': 
product_detail['supplierName'],
   'entity_name_1': 
entity_name_1,
   'entity_name_2': 
entity_name_1,
   'rating': 
product_detail['supplierRating']})



On Thursday, 5 November 2015 20:05:39 UTC, Carsten Fuchs wrote:
>
> Hi Yunti, 
>
> Am 05.11.2015 um 18:19 schrieb Yunti: 
> > I have tried to use the update_or_create() method assuming that it would 
> either, create 
> > a new entry in the db if it found none or update an existing one if it 
> found one and had 
> > differences to the defaults passed in  - or wouldn't update if there was 
> no difference. 
>
> A note about the last statement: If a Supplier object has the same 
> unique_id, and all 
> other fields (in `defaults`) are the same as well, logically there is no 
> difference 
> between updating and not updating – the result is the same. 
>
> >   However it just seemed to recreate entries each time even if there 
> were no changes. 
>
> Have you checked? How? 
> In your create_or_update_if_diff() you seem to try to re-invent 
> update_or_create(), but 
> have you actually examined the results of the 
>
>  supplier, created = Supplier.objects.update_or_create(...) 
>
> call? 
>
> > I think the issue was that I wanted to: 
> > 1)  get an entry if all fields were the same, 
>
> update_or_create() updates an object with the given kwargs, the match is 
> not made 
> against *all* fields (i.e. for the match the fields in `defaults` are not 
> accounted for). 
>
> > 2) or create a new entry if it didn't find an existing entry with the 
> unique_id 
> > 3) or if there was an entry with the same unique_id, update that entry 
> with remaining 
> > fields. 
>
> update_or_create() should achieve this. It's hard to tell more without 
> additional 
> information, but 
>
> https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update-or-create 
> explains 
> the function well, including how it works. If you work through this in 
> small steps, 
> check examples and their (intermediate) results, you should be able to 
> find what the 
> original problem was. 
>
> Best regards, 
> Carsten 
>
>

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


Re: Safe tag is working differently for different view.

2015-11-06 Thread sonu kumar
Yeah , I am sure both are using same template. I  am using same template on 
many pages. On all pages it's working fine. Only on one page question 
answer it's not working as expected. I couldn't find any solution till now.

On Thursday, November 5, 2015 at 8:48:05 PM UTC+5:30, Collin Anderson wrote:
>
> Hello,
>
> Are you sure they're using the same template? (If you change something 
> does it actually affect both views?)
>
> Is one of the views using mark_safe?
>
> Collin
>
> On Tuesday, October 27, 2015 at 9:29:02 PM UTC+1, sonu kumar wrote:
>>
>> I am having two views both are extending from same base.html and both of 
>> them have loaded same template tags, but one is escaping string using safe 
>> and other is not what could be 
>> Code 
>>
>> view 1
>>
>> {% extends 'base.html' %}
>> {% load inplace_edit mezzanine_tags rating_tags keyword_tags comment_tags 
>> nano_tags staticfiles %}
>>
>> ...
>>
>> {% comments_for object %}
>>
>> ...
>>
>> view 2
>>
>> {% extends "base.html" %}
>>
>> {% load inplace_edit mezzanine_tags comment_tags keyword_tags nano_tags i18n 
>> future staticfiles %}
>>
>> ...
>>
>> {% comments_for blog_post %}
>>
>> ...
>>
>>
>> view3 (comment.html)
>>
>> {% load i18n mezzanine_tags comment_tags  nano_tags future %}
>>
>> ...
>>
>> {{ comment.comment|safe  }}
>>
>> ...
>>
>>
>> As we can see both view 1 and 2 are using same function so it would be using 
>> same template but in view2 safe is working and in view1 it's not working.
>>
>>
>> What could be the reason for this ?
>>
>>
>>

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


Re: update_or_create() always creates (or recreates)

2015-11-06 Thread Yunti
Carsten ,

Thanks for your reply,

A note about the last statement: If a Supplier object has the same 
unique_id, and all 
other fields (in `defaults`) are the same as well, logically there is no 
difference 
between updating and not updating – the result is the same. 

The entry in the database is the same - apart from the last_updated flag if 
it's not rewritten over the top of it.  This means I can check for new data 
often and be alerted when there is an actual update (i.e. a change to the 
data).  If it rewrites the data everytime it checks then I have no idea 
when data was actually updated.

Have you checked? How? 
In your create_or_update_if_diff() you seem to try to re-invent 
update_or_create(), but 
have you actually examined the results of the 

 supplier, created = Supplier.objects.update_or_create(...) 

call? 

I checked by seeing that the last_updated field in the database was updated 
everytime.  (I suppose the issue could be with how that field gets reset to 
the next time it's run- I didnt)



On Thursday, 5 November 2015 20:05:39 UTC, Carsten Fuchs wrote:
>
> Hi Yunti, 
>
> Am 05.11.2015 um 18:19 schrieb Yunti: 
> > I have tried to use the update_or_create() method assuming that it would 
> either, create 
> > a new entry in the db if it found none or update an existing one if it 
> found one and had 
> > differences to the defaults passed in  - or wouldn't update if there was 
> no difference. 
>
> A note about the last statement: If a Supplier object has the same 
> unique_id, and all 
> other fields (in `defaults`) are the same as well, logically there is no 
> difference 
> between updating and not updating – the result is the same. 
>
> >   However it just seemed to recreate entries each time even if there 
> were no changes. 
>
> Have you checked? How? 
> In your create_or_update_if_diff() you seem to try to re-invent 
> update_or_create(), but 
> have you actually examined the results of the 
>
>  supplier, created = Supplier.objects.update_or_create(...) 
>
> call? 
>
> > I think the issue was that I wanted to: 
> > 1)  get an entry if all fields were the same, 
>
> update_or_create() updates an object with the given kwargs, the match is 
> not made 
> against *all* fields (i.e. for the match the fields in `defaults` are not 
> accounted for). 
>
> > 2) or create a new entry if it didn't find an existing entry with the 
> unique_id 
> > 3) or if there was an entry with the same unique_id, update that entry 
> with remaining 
> > fields. 
>
> update_or_create() should achieve this. It's hard to tell more without 
> additional 
> information, but 
>
> https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update-or-create 
> explains 
> the function well, including how it works. If you work through this in 
> small steps, 
> check examples and their (intermediate) results, you should be able to 
> find what the 
> original problem was. 
>
> Best regards, 
> Carsten 
>
>

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


Re: Prefetch object with to_attr set to the same name as the field triggers rows deletions

2015-11-06 Thread Michele Ciccozzi
Thank you very much, Simon, for the detailed answer.
Now I'm digging through Django code, pull requests, and tickets, and it's
all very interesting.
Thank you also for the reminder of incoming deprecations: we'll definitely
be on the lookout for that!

All the best,
Michele

On Fri, Nov 6, 2015 at 12:00 AM, Simon Charette 
wrote:

> Bonsoir Michele,
>
> I'll try to explain what happens here with a simplified model definition
> assuming you are using Django 1.8. I used a GenericRelation like your
> provided example but this issue can be triggered for about any M2M
> relationship.
>
> Given the following models:
>
> from django.db import models
> from django.contrib.contenttypes.fields import (
> GenericForeignKey, GenericRelation
> )
> from django.contrib.contenttypes.models import ContentType
>
> class TaggedItem(models.Model):
> tag = models.SlugField()
> content_type = models.ForeignKey(ContentType)
> object_id = models.PositiveIntegerField()
> content_object = GenericForeignKey('content_type', 'object_id')
>
> class Bookmark(models.Model):
> url = models.URLField()
> tags = GenericRelation(TaggedItem)
>
> Assigning directly to a Bookmark instance tags attribute (a 
> ReverseGenericRelatedObjectsDescriptor
> instance) will result in a delete query followed by multiple insert or
> update queries
> 
> depending on whether they exist or not. For example:
>
> >>> b = Bookmark.objects.create(url='www.djangoproject.com')
> >>> # The following line will result in the following queries:
> >>> # 1) DELETE FROM bookmark WHERE id = b.id;
> >>> # 2) INSERT INTO taggeditem ...;
> >>> # 3) INSERT INTO taggeditem ...;
> >>> b.tags = [TaggedItem(tag='Python'), TaggedItem(tag='Web')]
>
> Note that the DELETE query is not run as of 1.9 since Django now performs
> updates in 'bulk' instead (that is comparing the existing relationship with
> this specified value and only perform the required insert/update).
>
> Now, as documented, when you specify a `to_attr` Django simply uses
> `setattr()` onder de motorkap and ends up triggering the code path
> described above if the specified attribute happens to be a reverse
> relationship descriptor. Note that is behavior will be deprecated in
> Django 1.10 and removed in Django 2.0.
> 
>
> I have to say I'm unsure how we should proceed here. I guess I would favor
> raising a ValueError if the model the list of prefetched objects will be
> attached to has a reverse descriptor for the specified `to_attr` at least
> until this behavior is deprecated since it looks like a major footgun to me.
>
> I guess we should move the discussion to the development mailing list
>  to gather
> feedback.
>
> Au plaisir,
> Simon
>
>
> Le jeudi 5 novembre 2015 17:17:04 UTC+1, mccc a écrit :
>
>> Hello Simon,
>>
>> I'm going to paste a trimmed-down version of the involved classes:
>>
>> class CeleryTask(models.Model):
>> celery_task_id = models.CharField(max_length=50, primary_key=True)
>> task_type = models.ForeignKey(ContentType)
>> task_id = models.PositiveIntegerField()
>> task = GenericForeignKey('task_type', 'task_id')
>>
>> class AccountManagementTask(models.Model):
>> account = models.ForeignKey(Account, null=True, editable=False)
>> task_content_type = models.ForeignKey(ContentType)
>> task_content_id = models.PositiveIntegerField()
>> task_content = GenericForeignKey('task_content_type',
>> 'task_content_id')
>> celery_task = GenericRelation(CeleryTask,
>> content_type_field='task_type', object_id_field='task_id',
>>
>> related_query_name='account_management_tasks')
>>
>> (the task_content thing is involved in a follow-up question that will be
>> asked in a short while)
>>
>> This is the code triggering the weirdness:
>>
>> previous_tasks =
>> AccountManagementTask.objects.filter(account=account)\
>> .prefetch_related(
>> Prefetch('celery_task',
>>  to_attr='celery_task'))\
>> .prefetch_related(
>> Prefetch('task_content',
>>  to_attr='task_content'))\
>> .annotate(created_on=F('celery_task__created_on'))\
>>
>> Immediately after that, the QuerySet is sent off to a simple DRF
>> serializer - which doesn't even touch the issue since the relevant piece of
>> information is annotated:
>>
>> class AccountManagementTaskSerializer(serializers.ModelSerializer):
>> def to_representation(self, instance):
>> return {'id': instance.pk,
>> 'created_on': instance.created_on,
>> 'date_from': instance.task_content.date_from,
>> 'date_to': instance.task_content.date_to}
>>
>> 

Django Cms 3.1.3 Search Using Haystack

2015-11-06 Thread nAncy sharma
Hi there,

I am working with django cms 3.1.3 to build a website.

I am trying to add functionality of "SEARCH" to the website .Tried using 
haystack with elasticsearch,whoosh,simple,xapian for which i followed the 
haysatck documentaion. Still unsuccessful in achieving the functionality.

Is the django cms version an issue ? Or the steps followed might be the 
problem?

Could someone share an useful link for the same?

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


Re: django admin - You don't have permission to edit anything

2015-11-06 Thread Andreas Kuhne
Hi,

Check the PermissionsMixin. In that mixin you add the is_superuser field.
It also adds the relations to the auth group for group permissions and so
on. And the django admin site checks for permissions by calling the
has_perm() method on your user model. The has_perm() method always returns
True if the user is a superuser, so you always get ALL rights that way. If
you want finegrained rights you need to add the permissions manually (can
be done in django admin).

Check the code for the PermissionsMixin here:
https://github.com/django/django/blob/master/django/contrib/auth/models.py#L207

The reason why it's working now is because you have explicitly set the
is_superuser property to True.

Regards,

Andréas

2015-11-06 10:04 GMT+01:00 Benjamin Smith :

> Hello,
> Yes I thought so too, but in the example there is no *is_superuser *property
> provided neither in the User models or in the User manager. Therefore, I
> just copied the example from the django doc and tried running it. After
> creating the superuser, I can edit the models. I have no Idea what I am
> mission now.
>
>
> On Fri, Nov 6, 2015 at 11:35 AM, Andreas Kuhne  > wrote:
>
>> Hi,
>>
>> You don't have permissions to edit anything, because you haven't created
>> a superuser.
>>
>> The superuser in django has a property that is called "is_superuser" and
>> should be set to True. If you don't have that property (and your
>> createsuperuser sets some other property), you will have the same rights as
>> everyone else, which is nothing to begin with. You can add rights to the
>> user be adding the permissions you want, or by setting the is_superuser
>> property to True.
>>
>> Check the documentation for the django admin site here:
>> https://docs.djangoproject.com/en/1.8/ref/contrib/admin/
>>
>> Regards,
>>
>> Andréas
>>
>> 2015-11-06 0:15 GMT+01:00 Benjamin Smith :
>>
>>> I followed the django doc
>>> 
>>> on creating a custom user model while extending the model itself with my
>>> own fields. So it became like this:
>>>
>>> class MyUser(AbstractBaseUser, PermissionsMixin):
>>> email = models.EmailField(max_length=255, unique=True)
>>> first_name = models.CharField(max_length=35)
>>> last_name = models.CharField(max_length=35)
>>> username = models.CharField(max_length=70, unique=True)
>>> date_of_birth = models.DateField()
>>> is_active = models.BooleanField(default=True)
>>> is_admin = models.BooleanField(default=False)
>>>
>>> @property
>>> def is_staff(self):
>>> return self.is_admin
>>>
>>> def get_full_name(self):
>>> return ('%s %s') % (self.first_name, self.last_name)
>>>
>>> def get_short_name(self):
>>> return self.username
>>>
>>> objects = MyUserManager()
>>> USERNAME_FIELD = 'email'
>>> REQUIRED_FIELDS = ['first_name', 'last_name', 'username',
>>> 'date_of_birth']
>>>
>>> And its manager to be:
>>>
>>> class MyUserManager(BaseUserManager):
>>> def create_user(self, email, first_name, last_name, username,
>>> date_of_birth, password=None):
>>> if not email:
>>> raise ValueError('User must have an email address')
>>>
>>> user = self.model(
>>> email=self.normalize_email(email),
>>> first_name=first_name,
>>> last_name=last_name,
>>> username=username,
>>> date_of_birth=date_of_birth,
>>> )
>>>
>>> user.set_password(password)
>>> user.save(using=self._db)
>>> return user
>>>
>>> def create_superuser(self, email, first_name, last_name,
>>> username, date_of_birth, password):
>>> user = self.create_user(
>>> email,
>>> first_name=first_name,
>>> last_name=last_name,
>>> username=username,
>>> date_of_birth=date_of_birth,
>>> password=password
>>> )
>>> user.is_admin = True
>>> user.save(using=self._db)
>>> return user
>>>
>>> However, after I created the superuser while syncdb, when I login to the
>>> admin panel, there is nothing to do. It displays:
>>>
>>> * You don't have permission to edit anything.*
>>>
>>> I saw some other post with the same problem and most of them suggested
>>> to add *admin.autodiscover()* in the urls.py. But even this didn't help
>>> me.
>>>
>>> This is the admin.py:
>>>
>>> class MyUserAdmin(UserAdmin):
>>> form = UserChangeForm
>>> add_form = UserCreationForm
>>>
>>> list_display = ('email', 'first_name', 'last_name', 'username',
>>> 'date_of_birth', 'is_admin')
>>> list_filter = ('is_admin',)
>>> fieldsets = (
>>>   

Re: django admin - You don't have permission to edit anything

2015-11-06 Thread Benjamin Smith
Hello,
Yes I thought so too, but in the example there is no *is_superuser *property
provided neither in the User models or in the User manager. Therefore, I
just copied the example from the django doc and tried running it. After
creating the superuser, I can edit the models. I have no Idea what I am
mission now.


On Fri, Nov 6, 2015 at 11:35 AM, Andreas Kuhne 
wrote:

> Hi,
>
> You don't have permissions to edit anything, because you haven't created a
> superuser.
>
> The superuser in django has a property that is called "is_superuser" and
> should be set to True. If you don't have that property (and your
> createsuperuser sets some other property), you will have the same rights as
> everyone else, which is nothing to begin with. You can add rights to the
> user be adding the permissions you want, or by setting the is_superuser
> property to True.
>
> Check the documentation for the django admin site here:
> https://docs.djangoproject.com/en/1.8/ref/contrib/admin/
>
> Regards,
>
> Andréas
>
> 2015-11-06 0:15 GMT+01:00 Benjamin Smith :
>
>> I followed the django doc
>> 
>> on creating a custom user model while extending the model itself with my
>> own fields. So it became like this:
>>
>> class MyUser(AbstractBaseUser, PermissionsMixin):
>> email = models.EmailField(max_length=255, unique=True)
>> first_name = models.CharField(max_length=35)
>> last_name = models.CharField(max_length=35)
>> username = models.CharField(max_length=70, unique=True)
>> date_of_birth = models.DateField()
>> is_active = models.BooleanField(default=True)
>> is_admin = models.BooleanField(default=False)
>>
>> @property
>> def is_staff(self):
>> return self.is_admin
>>
>> def get_full_name(self):
>> return ('%s %s') % (self.first_name, self.last_name)
>>
>> def get_short_name(self):
>> return self.username
>>
>> objects = MyUserManager()
>> USERNAME_FIELD = 'email'
>> REQUIRED_FIELDS = ['first_name', 'last_name', 'username',
>> 'date_of_birth']
>>
>> And its manager to be:
>>
>> class MyUserManager(BaseUserManager):
>> def create_user(self, email, first_name, last_name, username,
>> date_of_birth, password=None):
>> if not email:
>> raise ValueError('User must have an email address')
>>
>> user = self.model(
>> email=self.normalize_email(email),
>> first_name=first_name,
>> last_name=last_name,
>> username=username,
>> date_of_birth=date_of_birth,
>> )
>>
>> user.set_password(password)
>> user.save(using=self._db)
>> return user
>>
>> def create_superuser(self, email, first_name, last_name,
>> username, date_of_birth, password):
>> user = self.create_user(
>> email,
>> first_name=first_name,
>> last_name=last_name,
>> username=username,
>> date_of_birth=date_of_birth,
>> password=password
>> )
>> user.is_admin = True
>> user.save(using=self._db)
>> return user
>>
>> However, after I created the superuser while syncdb, when I login to the
>> admin panel, there is nothing to do. It displays:
>>
>> * You don't have permission to edit anything.*
>>
>> I saw some other post with the same problem and most of them suggested to
>> add *admin.autodiscover()* in the urls.py. But even this didn't help me.
>>
>> This is the admin.py:
>>
>> class MyUserAdmin(UserAdmin):
>> form = UserChangeForm
>> add_form = UserCreationForm
>>
>> list_display = ('email', 'first_name', 'last_name', 'username',
>> 'date_of_birth', 'is_admin')
>> list_filter = ('is_admin',)
>> fieldsets = (
>> (None, {'fields': ('email', 'password')}),
>> ('Personal info', {'fields': (('first_name', 'last_name'),
>> 'username', 'date_of_birth')}),
>> ('Permissions', {'fields': ('is_admin',)}),
>> )
>>
>> add_fieldsets = (
>> (None, {
>> 'classes': ('Wide',),
>> 'fields': ('email', 'first_name', 'last_name',
>> 'username', 'date_of_birth')
>> }),
>> )
>> search_fields = ('email',)
>> ordering = ('email',)
>> filter_horizontal = ()
>>
>>
>> admin.site.register(MyUser, MyUserAdmin)
>>
>> What am I doing wrong here? Please help me how to solve this problem.
>> 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 

Re: Controlling access at table row level

2015-11-06 Thread Steve West
Thanks for the suggestions. I'll give them a try.
Cheers
Steve

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