Cascading ondelete of session.

2018-03-22 Thread Eliot Simcoe
Hello world,

I'm very new to Django and I come from a web2py background, so if this 
should be obvious please forgive me. My webapp allows anonymous users to 
upload files to my server for processing. I would like to track these files 
by the session, and when the session expires I would like these files to be 
deleted. I understand that I can run the manage.py clearsessions command to 
remove expired sessions, but I'm a little fuzzy on how to make this 
connection. I have added the django-cleanup application to my webapp and I 
believe that it is installed correctly - though I'm not sure how to test 
this. I currently have a table similar to the following:

class Raster(models.Model):
image = models.ImageField(
upload_to='rasters', width_field='width', height_field='height')
width = models.IntegerField(validators=[MinValueValidator(0)])
height = models.IntegerField(validators=[MinValueValidator(0)])

# when the session is deleted, this raster should be deleted as well
session = models.ForeignKey(Session, on_delete=models.CASCADE)

I'm able to populate the table with the an image file and session relation 
using the following class method of Raster:

@classmethod
def Create_With_File(cls, name, file, session=None):
# build the raster
raster = cls(
session_id = session.session_key
)

# store the image file
raster.image.save(path.basename(name), ImageFile(file))

return raster


This is all well and good - my file is created in the filesystem and the 
record is added in the database AFAIK. However, when I run manage.py 
clearsessions my files persist. I guess I have a couple of related 
questions:

1. I don't see a Session table in the admin interface, so it is difficult 
for me to tell what is working and what is not... Should I be able to 
inspect a Session table through admin?? For that matter I don't see a 
Raster table to inspect either...

2. Assuming that sessions are being stored and removed from the database 
correctly am I incorrect to assume that the manage.py clearsessions command 
would trigger the ondelete cascade as defined in my model?

Thanks for any help you can give. I'm a little lost.

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


Using Django Sessions

2018-03-22 Thread Manu Febie
Hello,

I am practicing for my college exams. I am building a Restaurant Order 
System with Django and I am using Django sessions for the first. I borrowed 
some ideas from the "Django by example".

Below you can find the MenuItem model and Order Model.

class MenuItem(models.Model):
   category = models.ForeignKey(Category, related_name='menu_items')
   # table ???
   name = models.CharField(max_length=255, db_index=True)
   slug = models.SlugField(max_length=255, db_index=True, default='')
   description = models.TextField(blank=True)
   image = models.ImageField(upload_to='menu_items/%Y/%m/%d', blank=True)
   price = models.DecimalField(max_digits=10, decimal_places=2)
   available = models.BooleanField(default=True)
   added_on = models.DateTimeField(auto_now_add=True)
   updated = models.DateTimeField(auto_now=True)


class Order(models.Model):
STATUS_CHOICES = (
('in behandeling', 'In behandeling'),
('klaar', 'Klaar')
)
# random_id = models.CharField(max_length=255)
table = models.ForeignKey(settings.AUTH_USER_MODEL)
item = models.ForeignKey(MenuItem, related_name='order_items')
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField(default=1)
status = models.CharField(max_length=50, choices=STATUS_CHOICES, default='in 
behandeling')
paid = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)


Below you can find a Cart class which handles adding, removing, iterating 
etc. over the Menu Items using Django sessions. What I need is a function 
in this class that only clears the items I have in the cart, but I still 
need the total price. Right now I have the "clear" function which removes 
the entire cart from the session. But since I am kinda confused on how to 
do this I need some help. 

from decimal import Decimal
from django.conf import settings

from menu.models import MenuItem


class Cart:
   
   def __init__(self, request):
   self.session = request.session
   cart = self.session.get(settings.CART_SESSION_ID)
   if not cart:
   cart = self.session[settings.CART_SESSION_ID] = {}
   self.cart = cart

def add(self, menu_item, quantity=1, update_quantity=False):
   # Add a menu item to the cart or update its quantity
   menu_item_id = str(menu_item.id)

if menu_item_id not in self.cart:
   self.cart[menu_item_id] = {'quantity': 0,
  'price': str(menu_item.price)}
   
   if update_quantity:
   self.cart[menu_item_id]['quantity'] = quantity
   else:
   self.cart[menu_item_id]['quantity'] += quantity
   self.save()

def save(self):
   # Update the session cart
   self.session[settings.CART_SESSION_ID] = self.cart
   # Mark the session as "modified" to make sure its saved
   self.session.modified = True

def remove(self, menu_item):
   # Remove a product from the cart
   menu_item_id = str(menu_item.id)
   if menu_item_id in self.cart:
   del self.cart[menu_item_id]
   self.save()

def __iter__(self):
   # Iterate over the item in the cart and get the products from the DB
   menu_item_ids = self.cart.keys()
   # get thte product objects and add them to the cart
   menu_items = MenuItem.objects.filter(id__in=menu_item_ids)
   
   for menu_item in menu_items:
   self.cart[str(menu_item.id)]['menu_item'] = menu_item

for item in self.cart.values():
   item['price'] = Decimal(item['price'])
   item['total_price'] = item['price'] * item['quantity']
   yield item

def __len__(self):
   # Count all the items in the cart
   return sum(item['quantity'] for item in self.cart.values())

def get_total_price(self):
   return sum(Decimal(item['price']) * item['quantity'] for item in self
.cart.values())

def clear(self):
   # Remove cart from the session
   del self.session[settings.CART_SESSION_ID]
   self.session.modified = True

And below here you'll find the view that handles saving the items in the 
request cart in to the Order model. Instead of calling the cart.clear() 
function I need to call a function that removes the ordered items from the 
cart while still having the total price in this session.

@login_required
def create_order(request):
   cart = Cart(request)
   
   if request.method == 'POST':
   for item in cart:
   Order.objects.create(table=request.user,
item=item['menu_item'],
price=item['price'],
quantity=item['quantity'])
   cart.clear()
   return render(request, 'orders/order_success.html', {'cart': cart})
   
   return render(request, 'cart/cart_detail.html', {'cart': cart})

I hope my question is clear and someone can help me with this. 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users

Re: Finding a decent ordering widget ...

2018-03-22 Thread Bernd Wechner
Julio,

Funnily stumbled on the same notion myself last night. I've worked up a 
niceish sample here:

https://jsfiddle.net/34Lv6try/68/

So it's possible without too much hassle using JQuery Think I'll build be a 
widget out that fiddle ;-). 

Regards,

Bernd.

On Wednesday, 21 March 2018 23:14:54 UTC+11, Julio Biason wrote:
>
> Hi Bernd,
>
> A bit of this "k anbd drag lines up and down to reposition them" is done 
> by jQuery UI, in its "Draggable" functionality: 
> https://jqueryui.com/draggable/#sortable
>
> Not sure if that helps, though, 'cause you could provide functionality to 
> reorder using plain JS, just reordering divs around moving the DOM around.
>
> On Wed, Mar 21, 2018 at 6:54 AM, Bernd Wechner  > wrote:
>
>> Hmmm, my next problem. 
>>
>> I envisage a widget which is kind of like a HTML textarea, but basically 
>> each line would hold the name of a field say, and I'd like a user to be 
>> able to order the lines, not change the text. Basically click anbd drag 
>> lines up and down to reposition them.
>>
>> I've poked around for HTML widgets for a bit now and find my main 
>> handicap is I'm not even sure how to describe this in terse search terms. 
>>
>> I know I've seen such widgets in practice - I didn't invent the idea ;-) 
>> - but have till now never needed one and suddenly I'm left wondering if 
>> there is one out there somewhere, and/or how I'd go about finding one. No 
>> real desire to try and build one with javascript right now, not least given 
>> I'm confident it exists already and I just don't know what it's called, how 
>> to describe it well or find it and well, DRY, I don't like spending my time 
>> recreating widgets that exist already. Not a priority.
>>
>> Does anyone here have any experience? Places tom look, terms to use in 
>> searching for one?
>>
>> Regards,
>>
>> Bernd.
>>
>> -- 
>> 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 https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/5ce7a37d-c5c1-4460-84a9-cb8974a86a6a%40googlegroups.com
>>  
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>
>
> -- 
> *Julio Biason*, Sofware Engineer
> *AZION*  |  Deliver. Accelerate. Protect.
> Office: +55 51 3083 8101  |  Mobile: +55 51 *99907 0554*
>

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


Django and graphs

2018-03-22 Thread Mohsen
Hi all:

I am quite new to Django, and I am looking for Django extensions that 
support graphs and networks. Would anybody guide me with a tutorial or some 
hints how we may use Django together with Networkx or SNAP graph library 
packages.

Many thanks

Mohsen

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


Re: IntegrityError: FOREIGN KEY constraint failed: Django 2.0.3

2018-03-22 Thread Seven Reeds
Uh, am I not using the ORM?  If I am not then what must I do to get back on 
track?

I just realized that i didn't include the "Delete" CBV in my original 
post.  I do not have easy access to the code at the moment so what follows 
is a rough approximation of what that code is about and is prolly full of 
errors:

class Delete(DeleteView):
def get:
profile = Profile.objects.get(account_number=self.request.account_number)
user = user.objects.get(pk=profile.user.pk)
user.delete()

In a debugger I can stop on the "user.delete()" line and see that the 
profile and user objects are what I expect them to be.



On Wednesday, March 21, 2018 at 10:34:47 AM UTC-5, Simon Charette wrote:
>
> Hello Anon,
>
> Django doesn't use database level ON DELETE constraints and emulates them 
> in Python
> to dispatch pre_delete/post_delete signals. As long as you're using the 
> ORM to perform
> the deletion you shouldn't encounter constraint violations.
>
> There's a ticket to add support for database level on_delete 
> constraints[0].
>
> Cheers,
> Simon
>
> [0] https://code.djangoproject.com/ticket/21961
>
> Le mercredi 21 mars 2018 10:50:25 UTC-4, Anon Ymous a écrit :
>>
>> Hi,
>>
>> I am learning python by trying to create a small Django app.  I may have 
>> found a bug related to Django and/or sqlite3.  If you are stackoverflow 
>> folks then my initial post is there:  
>> https://stackoverflow.com/questions/49361834/integrityerror-exception-in-deleteview-cbv
>>
>> My app really is just creating a small web site to add users and figure 
>> out how to do CRUD operations in building user profiles.  I am using the 
>> following setup:
>>
>> Django Version: 2.0.3
>> Python Version: 3.6.3
>> Installed Applications:
>> ['django.contrib.admin',
>> 'django.contrib.auth',
>> 'django.contrib.contenttypes',
>> 'django.contrib.sessions',
>> 'django.contrib.messages',
>> 'django.contrib.staticfiles',
>> 'django_extensions',
>> 'django.contrib.sites',
>> 'allauth',
>> 'allauth.account',
>> 'allauth.socialaccount',
>> 'auditlog',
>> 'widget_tweaks',
>> 'Members.apps.MembersConfig']
>> Installed Middleware:
>> ['django.middleware.security.SecurityMiddleware',
>> 'django.contrib.sessions.middleware.SessionMiddleware',
>> 'django.middleware.common.CommonMiddleware',
>> 'django.middleware.csrf.CsrfViewMiddleware',
>> 'django.contrib.auth.middleware.AuthenticationMiddleware',
>> 'django.contrib.messages.middleware.MessageMiddleware',
>> 'django.middleware.clickjacking.XFrameOptionsMiddleware',
>> 'auditlog.middleware.AuditlogMiddleware']
>>
>> I am using sqlite3 as the DB backend..
>>
>> I can create the virgin project, tweak the settings file and do the 
>> initial "makemigrations" and "migrate".  This, of course, creates the 
>> Django "user" table(s).  I went about creating my own "profile" model that 
>> "extends" the User model by creating a "oneToOne" field that points back to 
>> User and specifies an "on_delete=models.CASCADE" clause:
>>
>> class Profile(models.Model):
>> ...
>> user = models.OneToOneField(
>> User,
>> on_delete=models.CASCADE,
>> blank=False,
>> null=False,
>> )
>> ...
>>
>> The thing is the table that is created is given the constraint:
>>
>> FOREIGN KEY(`user_id`) REFERENCES `auth_user`(`id`) DEFERRABLE INITIALLY 
>> DEFERRED,
>>
>> but the "on delete cascade" clause is missing.  
>>
>> I first noticed this when testing a profile delete operation.  I get a 
>> foreign key constraint violation.  Looking into that led me here to you 
>> guys.
>>
>> I have added that clause to the table:
>>
>> FOREIGN KEY(`user_id`) REFERENCES `auth_user`(`id`) on delete cascade 
>> DEFERRABLE INITIALLY DEFERRED,
>>
>> but I still get the constraint violation.  I did more digging last night 
>> and see that at least one of the Django generated "user_*" tables also has 
>> a foreign key relationship back to the "user" table and that is also 
>> missing the cascade clause.
>>
>> My guesses at this instant include:
>>
>>- I have no idea what I am doing
>>- Django or the sqlite3 backend *should* be handling the cascade ops 
>>internally -- but isn't
>>
>> What am I missing?
>>
>

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


Re: Django 1,11 upgrade, render template with context in template.Node

2018-03-22 Thread Christian Ledermann
For the record,
I ended up with:

def get_context_dict_request(context):
"""Decompose a Context or a RequestContext to a request and dict."""
ctx = context.flatten()
try:
request = context.request
except AttributeError:
request = None
return ctx, request

class EpilogueNode(template.Node):

def __init__(self):  # noqa: D102
self.epilogue_template =
template.loader.get_template('themes/presenter_epilogue.html')

def render(self, context):  # noqa: D102
context, request = get_context_dict_request(context)
rendered = self.epilogue_template.render(context=context,
request=request)

On 5 March 2018 at 08:49, Christian Ledermann
 wrote:
> cool thanks I try that :-)
>  Django 1.11 vs 2.x => we are still on python 2.7 so the first step is
> Django 1.11 with python 2.7, that 1.11 upgrade to python 3.x and
> afterwards (well you get the timeline)
> Our codebase is 11 years old so there are some stumble blocks upgrading.
>
> On 5 March 2018 at 05:50, Bernd Wechner  wrote:
>> Can't say I'm experienced with template.Node, but you piqued my curiosity so
>> I found this:
>>
>> https://stackoverflow.com/questions/14434624/how-to-get-dictionary-of-requestcontext-imported-from-django-template
>>
>> which may help, but am left wondering why upgrade to 1.11 when 2.0 is out
>> already and the way to go? I'm on 1.11 and about to move to 2.0.
>>
>> Regards,
>>
>> Bernd.
>>
>>
>> On Saturday, 3 March 2018 06:26:46 UTC+11, Christian Ledermann wrote:
>>>
>>> In Django 1,8 it  worked but in Django 1.11 it throws:
>>>
>>> TypeError: context must be a dict rather than RequestContext.
>>>
>>> The code is:
>>>
>>> class EpilogueNode(template.Node):
>>>
>>> def __init__(self):  # noqa: D102
>>> self.epilogue_template =
>>> template.loader.get_template('themes/presenter_epilogue.html')
>>>
>>> def render(self, context):  # noqa: D102
>>> rendered = self.epilogue_template.render(context)
>>>
>>> In https://docs.djangoproject.com/en/1.11/ref/templates/upgrading/ it
>>> is documeted that I need to pass a dict as context, but the context
>>> passed to Node,render is a
>>> RequestContext.
>>>
>>> How can I upgrade this to 1.11?
>>>
>>>
>>>
>>> --
>>> Best Regards,
>>>
>>> Christian Ledermann
>>>
>>> Newark-on-Trent - UK
>>> Mobile : +44 7474997517
>>>
>>> https://uk.linkedin.com/in/christianledermann
>>> https://github.com/cleder/
>>>
>>>
>>> <*)))>{
>>>
>>> If you save the living environment, the biodiversity that we have left,
>>> you will also automatically save the physical environment, too. But If
>>> you only save the physical environment, you will ultimately lose both.
>>>
>>> 1) Don’t drive species to extinction
>>>
>>> 2) Don’t destroy a habitat that species rely on.
>>>
>>> 3) Don’t change the climate in ways that will result in the above.
>>>
>>> }<(((*>
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/0d289efe-614b-4fa8-ad87-87d559b6aaa3%40googlegroups.com.
>> For more options, visit https://groups.google.com/d/optout.
>
>
>
> --
> Best Regards,
>
> Christian Ledermann
>
> Newark-on-Trent - UK
> Mobile : +44 7474997517
>
> https://uk.linkedin.com/in/christianledermann
> https://github.com/cleder/
>
>
> <*)))>{
>
> If you save the living environment, the biodiversity that we have left,
> you will also automatically save the physical environment, too. But If
> you only save the physical environment, you will ultimately lose both.
>
> 1) Don’t drive species to extinction
>
> 2) Don’t destroy a habitat that species rely on.
>
> 3) Don’t change the climate in ways that will result in the above.
>
> }<(((*>



-- 
Best Regards,

Christian Ledermann

Newark-on-Trent - UK
Mobile : +44 7474997517

https://uk.linkedin.com/in/christianledermann
https://github.com/cleder/


<*)))>{

If you save the living environment, the biodiversity that we have left,
you will also automatically save the physical environment, too. But If
you only save the physical environment, you will ultimately lose both.

1) Don’t drive species to extinction

2) Don’t destroy a habitat that species rely on.

3) Don’t change the climate in ways that will result in the above.

}<(((*>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion

Re: I NEED HELP PLEASE

2018-03-22 Thread Sadialiou Diallo


hello. first you need to be with the documentation. It is your best freind

clic here to go there
https://docs.djangoproject.com/fr/2.0/intro/
 https://docs.djangoproject.com/en/2.0/

 

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


[no subject]

2018-03-22 Thread Muwanguzi Derrick
Hello

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