Re: DJNAGO Many to Many field MultiSelect Into DropdownList

2021-10-23 Thread danielp...@gmail.com


you can use django-ajax-selects library

https://github.com/crucialfelix/django-ajax-selects/

Define a lookup channel:
yourapp/lookups.py

from ajax_select import register, LookupChannel 
from .models import Tag 

@register('tags') 
class TagsLookup(LookupChannel): 
model = Tag 

def get_query(self, q, request): 
  return 
self.model.objects.filter(name__icontains=q).order_by('name')[:50] 
  def format_item_display(self, item): 
  return u"%s" % item.name 

Add field to a form:
yourapp/forms.py
from ajax_select.fields import AutoCompleteSelectMultipleField 

class DocumentForm(ModelForm): 
   class Meta: 
   model = Document 
   tags = AutoCompleteSelectMultipleField('tags')
On Wednesday, October 20, 2021 at 1:58:27 AM UTC-4 sebasti...@gmail.com 
wrote:

> This is Admin Frontend this has nothing to do with normal Frontend. In 
> Admin Frontend i have no experience...
>
> Am Di., 19. Okt. 2021 um 09:55 Uhr schrieb 'Maryam Yousaf' via Django 
> users :
>
>> It is not working with SelectMultiple. I can select multiple values but 
>> it is not showing any drop down.
>>
>> On Mon, 18 Oct 2021 at 16:07, Sebastian Jung  
>> wrote:
>>
>>> Hello,
>>>
>>> then change in widgets Select() to SelectMultiple().
>>>
>>> https://docs.djangoproject.com/en/3.2/ref/forms/widgets/#selectmultiple
>>>
>>> Regards
>>>
>>> Am Mo., 18. Okt. 2021 um 15:51 Uhr schrieb 'Maryam Yousaf' via Django 
>>> users :
>>>
 Hi,  

 I have one manytomany field in one of my model which is currently 
 coming as Multiselect but I need a dropdown where user can select multiple 
 values as I have huge data to show.

 I am trying this in forms.py but it is not showing dropdown field.

 Kindly help me out.

 *Model.py:*

 class Chain(models.Model):
 chain_id = models.AutoField(primary_key=True)
 chain_name = models.CharField(max_length=255, unique=True)
 chain_type = models.ForeignKey(ChainType, on_delete=models.CASCADE)
 history = HistoricalRecords()

 def __str__(self):
 return self.chain_name

 class Meta:
 ordering = ('chain_name',)


 class Brg(models.Model):
 brg_campaign_id = models.AutoField(primary_key=True)
 campaign_tracking = models.ForeignKey(CampaignTracking, 
 on_delete=models.CASCADE)
 brg_name = models.ForeignKey(Chain, on_delete=models.CASCADE, 
 related_name="primary_brg",
 help_text='Add Brgs/chain names for these above campaign has run')
 brg_benchmark = models.ManyToManyField(Chain, 
 related_name="competitor_brg", null=True,
 blank=True, help_text='Add max.5 other benchmarks brgs to check overall 
 impact')
 history = HistoricalRecords()

 def __str__(self):
 return "Brg names list"

 class Meta:
 verbose_name = 'Brg Campaign Tracking'

 *forms.py:*
 class ChainForm(forms.ModelForm):
 class Meta:
 model: Chain
 # fields = ('campaign_tracking', 'brg_name', 'brg_benchmark',)
 widgets = {
 'chain_name': Select(),
 }

 Regards,
 maryam


 --
 This email and any files transmitted with it contain confidential 
 information and/or privileged or personal advice. This email is intended 
 for the addressee(s) stated above only. If you are not the addressee of 
 the 
 email please do not copy or forward it or otherwise use it or any part of 
 it in any form whatsoever. If you have received this email in error please 
 notify the sender and remove the e-mail from your system. Thank you.

 This is an email from the company Just Eat Takeaway.com N.V., a public 
 limited liability company with corporate seat in Amsterdam, the 
 Netherlands, and address at Oosterdoksstraat 80, 1011 DK Amsterdam, 
 registered with the Dutch Chamber of Commerce with number 08142836 and 
 where the context requires, includes its subsidiaries and associated 
 undertakings.

 -- 
 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 view this discussion on the web visit 
 https://groups.google.com/d/msgid/django-users/ac59ba2a-5baa-4302-88c9-0dd17606fdaen%40googlegroups.com
  
 
 .

>>> -- 
>>> You received this message because you are subscribed to the Google 
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send 
>>> an email to django-users...@googlegroups.com.
>>> To view this discussion on the web visit 
>>> https://groups.google.com/d/msgid/django-users/CAKGT9mwXNTc2638qv-vScbHZW2uRq3utmu%2BbfM5Mz06WER

Re: DJNAGO Many to Many field MultiSelect Into DropdownList

2021-10-19 Thread Sebastian Jung
This is Admin Frontend this has nothing to do with normal Frontend. In
Admin Frontend i have no experience...

Am Di., 19. Okt. 2021 um 09:55 Uhr schrieb 'Maryam Yousaf' via Django users
:

> It is not working with SelectMultiple. I can select multiple values but it
> is not showing any drop down.
>
> On Mon, 18 Oct 2021 at 16:07, Sebastian Jung 
> wrote:
>
>> Hello,
>>
>> then change in widgets Select() to SelectMultiple().
>>
>> https://docs.djangoproject.com/en/3.2/ref/forms/widgets/#selectmultiple
>>
>> Regards
>>
>> Am Mo., 18. Okt. 2021 um 15:51 Uhr schrieb 'Maryam Yousaf' via Django
>> users :
>>
>>> Hi,
>>>
>>> I have one manytomany field in one of my model which is currently coming
>>> as Multiselect but I need a dropdown where user can select multiple values
>>> as I have huge data to show.
>>>
>>> I am trying this in forms.py but it is not showing dropdown field.
>>>
>>> Kindly help me out.
>>>
>>> *Model.py:*
>>>
>>> class Chain(models.Model):
>>> chain_id = models.AutoField(primary_key=True)
>>> chain_name = models.CharField(max_length=255, unique=True)
>>> chain_type = models.ForeignKey(ChainType, on_delete=models.CASCADE)
>>> history = HistoricalRecords()
>>>
>>> def __str__(self):
>>> return self.chain_name
>>>
>>> class Meta:
>>> ordering = ('chain_name',)
>>>
>>>
>>> class Brg(models.Model):
>>> brg_campaign_id = models.AutoField(primary_key=True)
>>> campaign_tracking = models.ForeignKey(CampaignTracking,
>>> on_delete=models.CASCADE)
>>> brg_name = models.ForeignKey(Chain, on_delete=models.CASCADE,
>>> related_name="primary_brg",
>>> help_text='Add Brgs/chain names for these above campaign has run')
>>> brg_benchmark = models.ManyToManyField(Chain,
>>> related_name="competitor_brg", null=True,
>>> blank=True, help_text='Add max.5 other benchmarks brgs to check overall
>>> impact')
>>> history = HistoricalRecords()
>>>
>>> def __str__(self):
>>> return "Brg names list"
>>>
>>> class Meta:
>>> verbose_name = 'Brg Campaign Tracking'
>>>
>>> *forms.py:*
>>> class ChainForm(forms.ModelForm):
>>> class Meta:
>>> model: Chain
>>> # fields = ('campaign_tracking', 'brg_name', 'brg_benchmark',)
>>> widgets = {
>>> 'chain_name': Select(),
>>> }
>>>
>>> Regards,
>>> maryam
>>>
>>>
>>> --
>>> This email and any files transmitted with it contain confidential
>>> information and/or privileged or personal advice. This email is intended
>>> for the addressee(s) stated above only. If you are not the addressee of the
>>> email please do not copy or forward it or otherwise use it or any part of
>>> it in any form whatsoever. If you have received this email in error please
>>> notify the sender and remove the e-mail from your system. Thank you.
>>>
>>> This is an email from the company Just Eat Takeaway.com N.V., a public
>>> limited liability company with corporate seat in Amsterdam, the
>>> Netherlands, and address at Oosterdoksstraat 80, 1011 DK Amsterdam,
>>> registered with the Dutch Chamber of Commerce with number 08142836 and
>>> where the context requires, includes its subsidiaries and associated
>>> undertakings.
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-users+unsubscr...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/ac59ba2a-5baa-4302-88c9-0dd17606fdaen%40googlegroups.com
>>> 
>>> .
>>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/CAKGT9mwXNTc2638qv-vScbHZW2uRq3utmu%2BbfM5Mz06WERmt2g%40mail.gmail.com
>> 
>> .
>>
>
>
> --
> This email and any files transmitted with it contain confidential
> information and/or privileged or personal advice. This email is intended
> for the addressee(s) stated above only. If you are not the addressee of the
> email please do not copy or forward it or otherwise use it or any part of
> it in any form whatsoever. If you have received this email in error please
> notify the sender and remove the e-mail from your system. Thank you.
>
> This is an email from the company Just Eat Takeaway.com N.V., a public
> limited liability company with corporate seat in Amsterdam, the
> Netherlands, and address at Oosterdoksstraat 80, 1011 DK Amsterdam,
> registered with the Dutch Chamber of Commerce with number 08142836 and

Re: DJNAGO Many to Many field MultiSelect Into DropdownList

2021-10-18 Thread Shaheed Haque
On Mon, 18 Oct 2021 at 15:41, Sebastian Jung 
wrote:

> When u use SelectMultiple then you get a select widget where you can
> select many options Your code are wrong in forms.py in widgets=
>
> Am Mo., 18. Okt. 2021 um 16:22 Uhr schrieb 'Maryam Yousaf' via Django
> users :
>
>> It is already selectmultiple . I need dropdown where I can select
>> multiple values .
>> currently, it is coming like this:
>>
>
Apologies if this is stating the obvious, but to select more than one item,
are you using "shift+click" or "ctrl+click" or just "click"?

You need to use the modifier key with "click", not just "click".


>
>> On Mon, 18 Oct 2021 at 16:07, Sebastian Jung 
>> wrote:
>>
>>> Hello,
>>>
>>> then change in widgets Select() to SelectMultiple().
>>>
>>> https://docs.djangoproject.com/en/3.2/ref/forms/widgets/#selectmultiple
>>>
>>> Regards
>>>
>>> Am Mo., 18. Okt. 2021 um 15:51 Uhr schrieb 'Maryam Yousaf' via Django
>>> users :
>>>
 Hi,

 I have one manytomany field in one of my model which is currently
 coming as Multiselect but I need a dropdown where user can select multiple
 values as I have huge data to show.

 I am trying this in forms.py but it is not showing dropdown field.

 Kindly help me out.

 *Model.py:*

 class Chain(models.Model):
 chain_id = models.AutoField(primary_key=True)
 chain_name = models.CharField(max_length=255, unique=True)
 chain_type = models.ForeignKey(ChainType, on_delete=models.CASCADE)
 history = HistoricalRecords()

 def __str__(self):
 return self.chain_name

 class Meta:
 ordering = ('chain_name',)


 class Brg(models.Model):
 brg_campaign_id = models.AutoField(primary_key=True)
 campaign_tracking = models.ForeignKey(CampaignTracking,
 on_delete=models.CASCADE)
 brg_name = models.ForeignKey(Chain, on_delete=models.CASCADE,
 related_name="primary_brg",
 help_text='Add Brgs/chain names for these above campaign has run')
 brg_benchmark = models.ManyToManyField(Chain,
 related_name="competitor_brg", null=True,
 blank=True, help_text='Add max.5 other benchmarks brgs to check overall
 impact')
 history = HistoricalRecords()

 def __str__(self):
 return "Brg names list"

 class Meta:
 verbose_name = 'Brg Campaign Tracking'

 *forms.py:*
 class ChainForm(forms.ModelForm):
 class Meta:
 model: Chain
 # fields = ('campaign_tracking', 'brg_name', 'brg_benchmark',)
 widgets = {
 'chain_name': Select(),
 }

 Regards,
 maryam


 --
 This email and any files transmitted with it contain confidential
 information and/or privileged or personal advice. This email is intended
 for the addressee(s) stated above only. If you are not the addressee of the
 email please do not copy or forward it or otherwise use it or any part of
 it in any form whatsoever. If you have received this email in error please
 notify the sender and remove the e-mail from your system. Thank you.

 This is an email from the company Just Eat Takeaway.com N.V., a public
 limited liability company with corporate seat in Amsterdam, the
 Netherlands, and address at Oosterdoksstraat 80, 1011 DK Amsterdam,
 registered with the Dutch Chamber of Commerce with number 08142836 and
 where the context requires, includes its subsidiaries and associated
 undertakings.

 --
 You received this message because you are subscribed to the Google
 Groups "Django users" group.
 To unsubscribe from this group and stop receiving emails from it, send
 an email to django-users+unsubscr...@googlegroups.com.
 To view this discussion on the web visit
 https://groups.google.com/d/msgid/django-users/ac59ba2a-5baa-4302-88c9-0dd17606fdaen%40googlegroups.com
 
 .

>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-users+unsubscr...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/CAKGT9mwXNTc2638qv-vScbHZW2uRq3utmu%2BbfM5Mz06WERmt2g%40mail.gmail.com
>>> 
>>> .
>>>
>>
>>
>> --
>> This email and any files transmitted with it contain confidential
>> information and/or privileged or personal advice. This email is intended
>> for the addressee(s) stated above only. If you are not the addressee of the
>> email please do not copy or forward it or otherwise use it or any par

Re: DJNAGO Many to Many field MultiSelect Into DropdownList

2021-10-18 Thread Sebastian Jung
When u use SelectMultiple then you get a select widget where you can select
many options Your code are wrong in forms.py in widgets=

Am Mo., 18. Okt. 2021 um 16:22 Uhr schrieb 'Maryam Yousaf' via Django users
:

> It is already selectmultiple . I need dropdown where I can select multiple
> values .
> currently, it is coming like this:
>
> On Mon, 18 Oct 2021 at 16:07, Sebastian Jung 
> wrote:
>
>> Hello,
>>
>> then change in widgets Select() to SelectMultiple().
>>
>> https://docs.djangoproject.com/en/3.2/ref/forms/widgets/#selectmultiple
>>
>> Regards
>>
>> Am Mo., 18. Okt. 2021 um 15:51 Uhr schrieb 'Maryam Yousaf' via Django
>> users :
>>
>>> Hi,
>>>
>>> I have one manytomany field in one of my model which is currently coming
>>> as Multiselect but I need a dropdown where user can select multiple values
>>> as I have huge data to show.
>>>
>>> I am trying this in forms.py but it is not showing dropdown field.
>>>
>>> Kindly help me out.
>>>
>>> *Model.py:*
>>>
>>> class Chain(models.Model):
>>> chain_id = models.AutoField(primary_key=True)
>>> chain_name = models.CharField(max_length=255, unique=True)
>>> chain_type = models.ForeignKey(ChainType, on_delete=models.CASCADE)
>>> history = HistoricalRecords()
>>>
>>> def __str__(self):
>>> return self.chain_name
>>>
>>> class Meta:
>>> ordering = ('chain_name',)
>>>
>>>
>>> class Brg(models.Model):
>>> brg_campaign_id = models.AutoField(primary_key=True)
>>> campaign_tracking = models.ForeignKey(CampaignTracking,
>>> on_delete=models.CASCADE)
>>> brg_name = models.ForeignKey(Chain, on_delete=models.CASCADE,
>>> related_name="primary_brg",
>>> help_text='Add Brgs/chain names for these above campaign has run')
>>> brg_benchmark = models.ManyToManyField(Chain,
>>> related_name="competitor_brg", null=True,
>>> blank=True, help_text='Add max.5 other benchmarks brgs to check overall
>>> impact')
>>> history = HistoricalRecords()
>>>
>>> def __str__(self):
>>> return "Brg names list"
>>>
>>> class Meta:
>>> verbose_name = 'Brg Campaign Tracking'
>>>
>>> *forms.py:*
>>> class ChainForm(forms.ModelForm):
>>> class Meta:
>>> model: Chain
>>> # fields = ('campaign_tracking', 'brg_name', 'brg_benchmark',)
>>> widgets = {
>>> 'chain_name': Select(),
>>> }
>>>
>>> Regards,
>>> maryam
>>>
>>>
>>> --
>>> This email and any files transmitted with it contain confidential
>>> information and/or privileged or personal advice. This email is intended
>>> for the addressee(s) stated above only. If you are not the addressee of the
>>> email please do not copy or forward it or otherwise use it or any part of
>>> it in any form whatsoever. If you have received this email in error please
>>> notify the sender and remove the e-mail from your system. Thank you.
>>>
>>> This is an email from the company Just Eat Takeaway.com N.V., a public
>>> limited liability company with corporate seat in Amsterdam, the
>>> Netherlands, and address at Oosterdoksstraat 80, 1011 DK Amsterdam,
>>> registered with the Dutch Chamber of Commerce with number 08142836 and
>>> where the context requires, includes its subsidiaries and associated
>>> undertakings.
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-users+unsubscr...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/ac59ba2a-5baa-4302-88c9-0dd17606fdaen%40googlegroups.com
>>> 
>>> .
>>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/CAKGT9mwXNTc2638qv-vScbHZW2uRq3utmu%2BbfM5Mz06WERmt2g%40mail.gmail.com
>> 
>> .
>>
>
>
> --
> This email and any files transmitted with it contain confidential
> information and/or privileged or personal advice. This email is intended
> for the addressee(s) stated above only. If you are not the addressee of the
> email please do not copy or forward it or otherwise use it or any part of
> it in any form whatsoever. If you have received this email in error please
> notify the sender and remove the e-mail from your system. Thank you.
>
> This is an email from the company Just Eat Takeaway.com N.V., a public
> limited liability company with corporate seat in Amsterdam, the
> Netherlands, and address at Oosterdoksstraat 80, 1011 DK Amsterdam,
> registered with the Dutc

Re: DJNAGO Many to Many field MultiSelect Into DropdownList

2021-10-18 Thread Sebastian Jung
Hello,

then change in widgets Select() to SelectMultiple().

https://docs.djangoproject.com/en/3.2/ref/forms/widgets/#selectmultiple

Regards

Am Mo., 18. Okt. 2021 um 15:51 Uhr schrieb 'Maryam Yousaf' via Django users
:

> Hi,
>
> I have one manytomany field in one of my model which is currently coming
> as Multiselect but I need a dropdown where user can select multiple values
> as I have huge data to show.
>
> I am trying this in forms.py but it is not showing dropdown field.
>
> Kindly help me out.
>
> *Model.py:*
>
> class Chain(models.Model):
> chain_id = models.AutoField(primary_key=True)
> chain_name = models.CharField(max_length=255, unique=True)
> chain_type = models.ForeignKey(ChainType, on_delete=models.CASCADE)
> history = HistoricalRecords()
>
> def __str__(self):
> return self.chain_name
>
> class Meta:
> ordering = ('chain_name',)
>
>
> class Brg(models.Model):
> brg_campaign_id = models.AutoField(primary_key=True)
> campaign_tracking = models.ForeignKey(CampaignTracking,
> on_delete=models.CASCADE)
> brg_name = models.ForeignKey(Chain, on_delete=models.CASCADE,
> related_name="primary_brg",
> help_text='Add Brgs/chain names for these above campaign has run')
> brg_benchmark = models.ManyToManyField(Chain,
> related_name="competitor_brg", null=True,
> blank=True, help_text='Add max.5 other benchmarks brgs to check overall
> impact')
> history = HistoricalRecords()
>
> def __str__(self):
> return "Brg names list"
>
> class Meta:
> verbose_name = 'Brg Campaign Tracking'
>
> *forms.py:*
> class ChainForm(forms.ModelForm):
> class Meta:
> model: Chain
> # fields = ('campaign_tracking', 'brg_name', 'brg_benchmark',)
> widgets = {
> 'chain_name': Select(),
> }
>
> Regards,
> maryam
>
>
> --
> This email and any files transmitted with it contain confidential
> information and/or privileged or personal advice. This email is intended
> for the addressee(s) stated above only. If you are not the addressee of the
> email please do not copy or forward it or otherwise use it or any part of
> it in any form whatsoever. If you have received this email in error please
> notify the sender and remove the e-mail from your system. Thank you.
>
> This is an email from the company Just Eat Takeaway.com N.V., a public
> limited liability company with corporate seat in Amsterdam, the
> Netherlands, and address at Oosterdoksstraat 80, 1011 DK Amsterdam,
> registered with the Dutch Chamber of Commerce with number 08142836 and
> where the context requires, includes its subsidiaries and associated
> undertakings.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/ac59ba2a-5baa-4302-88c9-0dd17606fdaen%40googlegroups.com
> 
> .
>

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


DJNAGO Many to Many field MultiSelect Into DropdownList

2021-10-18 Thread 'Maryam Yousaf' via Django users
Hi,  

I have one manytomany field in one of my model which is currently coming as 
Multiselect but I need a dropdown where user can select multiple values as 
I have huge data to show.

I am trying this in forms.py but it is not showing dropdown field.

Kindly help me out.

*Model.py:*

class Chain(models.Model):
chain_id = models.AutoField(primary_key=True)
chain_name = models.CharField(max_length=255, unique=True)
chain_type = models.ForeignKey(ChainType, on_delete=models.CASCADE)
history = HistoricalRecords()

def __str__(self):
return self.chain_name

class Meta:
ordering = ('chain_name',)


class Brg(models.Model):
brg_campaign_id = models.AutoField(primary_key=True)
campaign_tracking = models.ForeignKey(CampaignTracking, 
on_delete=models.CASCADE)
brg_name = models.ForeignKey(Chain, on_delete=models.CASCADE, 
related_name="primary_brg",
help_text='Add Brgs/chain names for these above campaign has run')
brg_benchmark = models.ManyToManyField(Chain, 
related_name="competitor_brg", null=True,
blank=True, help_text='Add max.5 other benchmarks brgs to check overall 
impact')
history = HistoricalRecords()

def __str__(self):
return "Brg names list"

class Meta:
verbose_name = 'Brg Campaign Tracking'

*forms.py:*
class ChainForm(forms.ModelForm):
class Meta:
model: Chain
# fields = ('campaign_tracking', 'brg_name', 'brg_benchmark',)
widgets = {
'chain_name': Select(),
}

Regards,
maryam

-- 



This email and any files transmitted with it contain confidential 
information and/or privileged or personal advice. This email is intended 
for the addressee(s) stated above only. If you are not the addressee of the 
email please do not copy or forward it or otherwise use it or any part of 
it in any form whatsoever. If you have received this email in error please 
notify the sender and remove the e-mail from your system. Thank you.


This 
is an email from the company Just Eat Takeaway.com N.V., a public limited 
liability company with corporate seat in Amsterdam, the Netherlands, and 
address at Oosterdoksstraat 80, 1011 DK Amsterdam, registered with the 
Dutch Chamber of Commerce with number 08142836 and where the context 
requires, includes its subsidiaries and associated undertakings.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/ac59ba2a-5baa-4302-88c9-0dd17606fdaen%40googlegroups.com.


Re: Many to many field does not save in the main object

2020-08-28 Thread Annick Sakoua
 I found the mistake, I removed the 'for item in instance'  in my 
addcustomer function and Elesire suggestion about iterating in the 
{{customer.gp}} object  in my template helped me a lof. Thank you soo much.

Le mardi 25 août 2020 à 14:57:48 UTC+1, Annick Sakoua a écrit :

> Hi all,
> Please Help.
> I have been on this problem for 2 weeks now :(
> I have an object: customer  that has 1 manytomany relationship with 
> another object: gp.
> I created some gp instances in the admin page. When I select one gp in the 
> select dropdown list of existing gp  in my addcustomer form and submit my 
> form, the form is saved with all the information except the gp selected. I 
> only get the this: app.GeneralPractitioner.None  
> Here are bellow my different classes. 
>
> Thank you for your help :)
>
> *model.py*
>
> class Customer(models.Model):
> first_name = models.CharField(max_length=100)
> last_name = models.CharField(max_length=100)
> gp = models.ManyToManyField(GeneralPractitioner, help_text="Select your 
> general practitioner", related_name="customer")
>
>
> class GeneralPractitioner(models.Model):
> name = models.CharField(
> max_length=40,
> help_text="Enter the gp name)"
> )
> contact= models.CharField(max_length=11)
>
> def __str__(self):
> return self.name
>
> *in view.py*
>
> @login_required
> def add_customer(request):
> if request.method == 'POST':
>
> form = AddCustomerForm(request.POST)
> if form.is_valid():
> instance = form.save(commit=False)
> for item in instance:
> item.save()
> form.save_m2m()
> instance.author = request.user
>
> messages.success(request, f'Your form has been created!')
> return redirect('addcustomer')
> else:
> form = AddCustomerForm()
> return render(request, 'app/addcustomer.html', {'form': form})
>
> *customer_details.html*
>
> {% extends "app/base.html" %}
> {% load crispy_forms_tags %}
> {% block content %}
>
> 
> Firstname: {{customer.first_name}}
> Lastname: {{customer.last_name}}
> General practitioner: {{customer.gp}}
> 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/6426a74f-6096-473e-87bf-3a1c4914392en%40googlegroups.com.


Many to many field does not save in the main object

2020-08-25 Thread Annick Sakoua
Hi all,
Please Help.
I have been on this problem for 2 weeks now :(
I have an object: customer  that has 1 manytomany relationship with another 
object: gp.
I created some gp instances in the admin page. When I select one gp in the 
select dropdown list of existing gp  in my addcustomer form and submit my 
form, the form is saved with all the information except the gp selected. I 
only get the this: app.GeneralPractitioner.None  
Here are bellow my different classes. 

Thank you for your help :)

*model.py*

class Customer(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
gp = models.ManyToManyField(GeneralPractitioner, help_text="Select your 
general practitioner", related_name="customer")


class GeneralPractitioner(models.Model):
name = models.CharField(
max_length=40,
help_text="Enter the gp name)"
)
contact= models.CharField(max_length=11)

def __str__(self):
return self.name

*in view.py*

@login_required
def add_customer(request):
if request.method == 'POST':

form = AddCustomerForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
for item in instance:
item.save()
form.save_m2m()
instance.author = request.user

messages.success(request, f'Your form has been created!')
return redirect('addcustomer')
else:
form = AddCustomerForm()
return render(request, 'app/addcustomer.html', {'form': form})

*customer_details.html*

{% extends "app/base.html" %}
{% load crispy_forms_tags %}
{% block content %}


Firstname: {{customer.first_name}}
Lastname: {{customer.last_name}}
General practitioner: {{customer.gp}}


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a40a8a68-b774-4b13-9306-a4939778329cn%40googlegroups.com.


Please help I want to list down all the users with the sharewith from the frontend in backend I used Many to Many field and also my data is not getting into database

2020-07-16 Thread mick
views.py
def notesadd(request):
form = NoteForm(request.POST or None)
if form.is_valid():
form.save()
form=NoteForm()
context = {
'form': form
}
print('submitted')
   
return render(request, 'notes.html', context)



models.py
class Notes(models.Model):
sharewith = models.ManyToManyField(User, blank=True, null=True)
subject = models.CharField(max_length=10, null=True)
uploadingdate = models.DateTimeField(null=True)
notesfile = models.FileField(null=True)
description = models.TextField(max_length=50,null=True)
   
def __str__(self):
  return self.sharewith.user.username

forms.py

class NoteForm(forms.ModelForm):
class Meta:
model=Notes
fields = [
'sharewith' ,
'subject',
'uploadingdate',
   'notesfile',
'description' ]

notes.html

 {% extends 'navigation.html' %}

 {% block body %}


  {% csrf_token %}

 
  
 

  
Subject:

{{note.subject}}
  

  


  
Description:

  
  

  
Choose Notes:

  

  





Share With

  {{form.username}}
 

  
  Submit

 

 
 {% endblock  %}



admin.py
from django.contrib import admin

from .models import Notes

admin.site.register(Notes)


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c669fa9c-a4ec-45ed-8409-abe85ce5982do%40googlegroups.com.


how to retrieve maximum value in many to many field

2020-07-13 Thread Rajshree Some


Table1

id

1

Item1

Good

2

Item2

bad


  

Table2


Id 
table1_id   
 
 marks  

1.

1

23

2.

1

54

3.

2

66

4.

2

55

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a95d04e7-969e-4737-bc48-e0b4dd148995o%40googlegroups.com.


How can I delete the parent object related through a many to many field?

2020-03-24 Thread Mark Phillips
I have three related models - Document, Collection, and CollectionDocument.
A Collection object is made up of a group of documents.

class Document(Model):
document_id = models.AutoField(primary_key=True)
class Collection(Model):
collection_id = models.AutoField(primary_key=True)
document = models.ManyToManyField(Document,
through='CollectionDocument', related_name='collections',)
class CollectionDocument(Model):
collection_id = models.ForeignKey(Collection, on_delete=models.CASCADE, )
document = models.ForeignKey(Document, on_delete=models.CASCADE, )

In the Djangop Admin, I have a DocumentAdmin and a CollectionAdmin with the
CollectionDocument as inlines in the CollectionAdmin.

When I delete all the documents associated with a Collection, I also want
the Collection to be deleted. Right now, when I delete the documents in a
Collection, the CollectioDocument is empty, but the Collection still exists
without any documents associated with it.

I have tried several ways to do it using pre- and post-delete signals for
the CollectionDocument model, but nothing seems to work. Have I structured
my models incorrectly? How do I get the Collection to be deleted when all
the associated Documents are deleted?

Thanks!

Mark

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAEqej2MBD3gH5h7m2YAp8zW%2Bi1cPC%2B-jFbnFmDUiTnVZZwYgBg%40mail.gmail.com.


help on how to pass a many to many field to form template

2020-03-05 Thread Tosin Ayoola
good day,
I have to models, using a many to many relationship, I want to access the
fields in they model in my form template, how do i achieve this?
i attached my view, model and template code screenshot, hopping anyone can
help

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAHLKn73RQSEYi%3D2C_9VpQ9YoKq11PXYHaHGoMuh5OJDk1nOXDg%40mail.gmail.com.


Re: Issue with unique key error on Many to Many field

2019-11-10 Thread Malibu
Hi, thanks for the answer.  Of course, the moment I posted the question I 
figured out what it was.

I ended up checking my primary keys, and found that they didn't have unique 
constraints.  I added them and all was fine.

Must have fallen off during an import.

On Sunday, 10 November 2019 13:55:06 UTC-4, Integr@te System wrote:
>
> Hi Issuer, 
>
> Check your tracker_passenger.
>
> https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.ManyToManyField
>
>
> On Sun, Nov 10, 2019, 21:40 Malibu > 
> wrote:
>
>> Hi there.  I've been doing Django for awhile but I am stumped on this 
>> one..  I have a many to many relationship with a 'through' definition
>>
>> main.models: 
>>
>> class Client(models.Model):
>> uid = models.CharField(max_length=128, unique=True)
>> key = models.CharField(max_length=128)
>> img = models.TextField()
>> version = models.CharField(max_length=20)
>> lastConnection = models.DateTimeField()
>> role = models.CharField(max_length=128,default="")
>>
>>
>>
>> tracker.models:
>>
>> from main.models import Client
>>
>> class PassengerAccess(models.Model):
>> passenger = models.ForeignKey('Passenger',on_delete=models.CASCADE)
>> client = models.ForeignKey(Client,on_delete=models.CASCADE)
>> created = models.DateTimeField(auto_now_add=True,blank=True)
>> selected = models.BooleanField(default=False)
>>
>> class Passenger(models.Model):
>> first_name = models.CharField(max_length=50)
>> last_name = models.CharField(max_length=50)
>> access_code = models.CharField(max_length=32)
>> school_division = models.ForeignKey(SchoolDivision)
>> open_clients = models.ManyToManyField(Client, through='PassengerAccess')
>>
>>
>> The error I get when I try to migrate is: django.db.utils.ProgrammingError: 
>> there is no unique constraint matching given keys for referenced table 
>> "tracker_passenger"
>>
>> Any solution to this error appears to be related to a foreign key that is 
>> referencing a field that is not unique, but in this case passenger and 
>> client should both be accessing the primary key should they not?  I always 
>> use plain integer primary keys.
>>
>> Any suggestions on how to troubleshoot this would be appreciated.
>>
>> -- 
>> 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...@googlegroups.com .
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/db29f623-eecd-4b58-8b70-d2fcd063aaaf%40googlegroups.com
>>  
>> 
>> .
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/76dfb80d-6310-4a4e-a47b-244f00e04ac0%40googlegroups.com.


Re: Issue with unique key error on Many to Many field

2019-11-10 Thread Integr@te System
Hi Issuer,

Check your tracker_passenger.
https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.ManyToManyField


On Sun, Nov 10, 2019, 21:40 Malibu  wrote:

> Hi there.  I've been doing Django for awhile but I am stumped on this
> one..  I have a many to many relationship with a 'through' definition
>
> main.models:
>
> class Client(models.Model):
> uid = models.CharField(max_length=128, unique=True)
> key = models.CharField(max_length=128)
> img = models.TextField()
> version = models.CharField(max_length=20)
> lastConnection = models.DateTimeField()
> role = models.CharField(max_length=128,default="")
>
>
>
> tracker.models:
>
> from main.models import Client
>
> class PassengerAccess(models.Model):
> passenger = models.ForeignKey('Passenger',on_delete=models.CASCADE)
> client = models.ForeignKey(Client,on_delete=models.CASCADE)
> created = models.DateTimeField(auto_now_add=True,blank=True)
> selected = models.BooleanField(default=False)
>
> class Passenger(models.Model):
> first_name = models.CharField(max_length=50)
> last_name = models.CharField(max_length=50)
> access_code = models.CharField(max_length=32)
> school_division = models.ForeignKey(SchoolDivision)
> open_clients = models.ManyToManyField(Client, through='PassengerAccess')
>
>
> The error I get when I try to migrate is: django.db.utils.ProgrammingError: 
> there is no unique constraint matching given keys for referenced table 
> "tracker_passenger"
>
> Any solution to this error appears to be related to a foreign key that is 
> referencing a field that is not unique, but in this case passenger and client 
> should both be accessing the primary key should they not?  I always use plain 
> integer primary keys.
>
> Any suggestions on how to troubleshoot this would be appreciated.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/db29f623-eecd-4b58-8b70-d2fcd063aaaf%40googlegroups.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAP5HUWr3kVimTG1NE80iBFr4kNPyhEyfcTN39fGo%2BAAmv7O%3DnQ%40mail.gmail.com.


Issue with unique key error on Many to Many field

2019-11-10 Thread Malibu
Hi there.  I've been doing Django for awhile but I am stumped on this 
one..  I have a many to many relationship with a 'through' definition

main.models: 

class Client(models.Model):
uid = models.CharField(max_length=128, unique=True)
key = models.CharField(max_length=128)
img = models.TextField()
version = models.CharField(max_length=20)
lastConnection = models.DateTimeField()
role = models.CharField(max_length=128,default="")



tracker.models:

from main.models import Client

class PassengerAccess(models.Model):
passenger = models.ForeignKey('Passenger',on_delete=models.CASCADE)
client = models.ForeignKey(Client,on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True,blank=True)
selected = models.BooleanField(default=False)

class Passenger(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
access_code = models.CharField(max_length=32)
school_division = models.ForeignKey(SchoolDivision)
open_clients = models.ManyToManyField(Client, through='PassengerAccess')


The error I get when I try to migrate is: django.db.utils.ProgrammingError: 
there is no unique constraint matching given keys for referenced table 
"tracker_passenger"

Any solution to this error appears to be related to a foreign key that is 
referencing a field that is not unique, but in this case passenger and client 
should both be accessing the primary key should they not?  I always use plain 
integer primary keys.

Any suggestions on how to troubleshoot this would be appreciated.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/db29f623-eecd-4b58-8b70-d2fcd063aaaf%40googlegroups.com.


select quantity for each items selected in many to many field

2019-07-20 Thread namo
hi there, i'm working on an restaurant ordering system , when someone order 
more than one product with different quantities for each product , be able 
to select its quantities 
it may order 3 Pizza with 2 sandwich , how to let the customer to define 
the quantities of each product , and then calculate with its prices  
 class Restaurant(models.Model):

name = models.CharField(max_length=50)
price = models.PositiveIntegerField(default=1)


def __str__(self):
return self.name
class Topping(models.Model):
name = models.CharField(max_length=50)
product_names = models.ManyToManyField(Restaurant, blank=True)
quantity = models.PositiveIntegerField(default=1)


total price of orders , for one product for example : one pizza with one 
sandwich however they order more than one pizza and sandwich

@property
def total(self):  
return self.product_names.aggregate(Sum('price'))['price__sum'] 

I expected to provide a quantity field for each selected items : pizza : 3 
, sandwich:2 , then calculate them (3*pizza price , 2*sandwich price)

thanks for advice 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/227bb8d8-f393-43d0-a9a8-79557f0e32df%40googlegroups.com.


Re: Many to Many field in ModelForm - with tens of thousands of records

2018-10-29 Thread Web Architect
Hi Sanjay,

Thanks for the prompt response and the approach. 

That seems to be an efficient approach - would look into auto-complete.

Thanks.

On Monday, October 29, 2018 at 5:09:50 PM UTC+5:30, Sanjay Bhangar wrote:
>
> My recommendation would be to use a bit of Javascript to implement an 
> "autocomplete" to fetch records via AJAX as the user types (with 
> perhaps a minimum of 3 characters or so), so you only ever fetch a 
> subset of records and don't overload your template. 
>
> You can find quite a few 3rd party libraries that should be able to 
> aid in setting up this behaviour, see: 
> https://djangopackages.org/grids/g/auto-complete/ - unfortunately, I 
> can't recommend a particular one right now - but most should have 
> integrations for the django admin / django forms with Many2Many or 
> ForeignKey fields. 
>
> Hope that helps, 
> Sanjay 
> On Mon, Oct 29, 2018 at 5:01 PM Web Architect  > wrote: 
> > 
> > Would also add that the server CPU usage was hitting 100% due to the 
> template loading issue. 
> > 
> > On Monday, October 29, 2018 at 4:48:54 PM UTC+5:30, Web Architect wrote: 
> >> 
> >> Hi, 
> >> 
> >> We are using django 1.11 for our ecommerce site. 
> >> 
> >> We are facing an issue with modelform and many to many field in it as 
> follows: 
> >> 
> >> Lets say there are two models: 
> >> 
> >> class A(models.Model): 
> >>c = models.CharField() 
> >> 
> >> class B(models.Model): 
> >>   a = models.ManyToManyField('A') 
> >> 
> >> Now if I define a modelform: 
> >> 
> >> class MF(models.ModelForm): 
> >>   class Meta: 
> >>   model = B 
> >>   fields = [a,] 
> >> 
> >> We are using django widget tweaks to render the fields in MF. Now if 
> there are tens of thousands of records in A, the MF form rendering causes 
> the page to hang as the widget will try to show the whole set of tens of 
> thousands of records option for field a. 
> >> 
> >> Hence, would appreciate if anyone could suggest a smart solution 
> wherein the above issue is taken care of. 
> >> 
> >> Thanks. 
> >> 
> >> 
> > -- 
> > You received this message because you are subscribed to the Google 
> Groups "Django users" group. 
> > To unsubscribe from this group and stop receiving emails from it, send 
> an email to django-users...@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/36ebab2d-7440-40bc-b5e9-a4a2897dcd3a%40googlegroups.com.
>  
>
> > For more options, visit https://groups.google.com/d/optout. 
>

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


Re: Many to Many field in ModelForm - with tens of thousands of records

2018-10-29 Thread Sanjay Bhangar
My recommendation would be to use a bit of Javascript to implement an
"autocomplete" to fetch records via AJAX as the user types (with
perhaps a minimum of 3 characters or so), so you only ever fetch a
subset of records and don't overload your template.

You can find quite a few 3rd party libraries that should be able to
aid in setting up this behaviour, see:
https://djangopackages.org/grids/g/auto-complete/ - unfortunately, I
can't recommend a particular one right now - but most should have
integrations for the django admin / django forms with Many2Many or
ForeignKey fields.

Hope that helps,
Sanjay
On Mon, Oct 29, 2018 at 5:01 PM Web Architect  wrote:
>
> Would also add that the server CPU usage was hitting 100% due to the template 
> loading issue.
>
> On Monday, October 29, 2018 at 4:48:54 PM UTC+5:30, Web Architect wrote:
>>
>> Hi,
>>
>> We are using django 1.11 for our ecommerce site.
>>
>> We are facing an issue with modelform and many to many field in it as 
>> follows:
>>
>> Lets say there are two models:
>>
>> class A(models.Model):
>>c = models.CharField()
>>
>> class B(models.Model):
>>   a = models.ManyToManyField('A')
>>
>> Now if I define a modelform:
>>
>> class MF(models.ModelForm):
>>   class Meta:
>>   model = B
>>   fields = [a,]
>>
>> We are using django widget tweaks to render the fields in MF. Now if there 
>> are tens of thousands of records in A, the MF form rendering causes the page 
>> to hang as the widget will try to show the whole set of tens of thousands of 
>> records option for field a.
>>
>> Hence, would appreciate if anyone could suggest a smart solution wherein the 
>> above issue is taken care of.
>>
>> Thanks.
>>
>>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users+unsubscr...@googlegroups.com.
> To 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/36ebab2d-7440-40bc-b5e9-a4a2897dcd3a%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

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


Re: Many to Many field in ModelForm - with tens of thousands of records

2018-10-29 Thread Web Architect
Would also add that the server CPU usage was hitting 100% due to the 
template loading issue. 

On Monday, October 29, 2018 at 4:48:54 PM UTC+5:30, Web Architect wrote:
>
> Hi,
>
> We are using django 1.11 for our ecommerce site. 
>
> We are facing an issue with modelform and many to many field in it as 
> follows:
>
> Lets say there are two models:
>
> class A(models.Model):
>c = models.CharField()
>
> class B(models.Model):
>   a = models.ManyToManyField('A')
>
> Now if I define a modelform:
>
> class MF(models.ModelForm):
>   class Meta:
>   model = B
>   fields = [a,]
>
> We are using django widget tweaks to render the fields in MF. Now if there 
> are tens of thousands of records in A, the MF form rendering causes the 
> page to hang as the widget will try to show the whole set of tens of 
> thousands of records option for field a. 
>
> Hence, would appreciate if anyone could suggest a smart solution wherein 
> the above issue is taken care of. 
>
> Thanks.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To 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/36ebab2d-7440-40bc-b5e9-a4a2897dcd3a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Many to Many field in ModelForm - with tens of thousands of records

2018-10-29 Thread Web Architect
Hi,

We are using django 1.11 for our ecommerce site. 

We are facing an issue with modelform and many to many field in it as 
follows:

Lets say there are two models:

class A(models.Model):
   c = models.CharField()

class B(models.Model):
  a = models.ManyToManyField('A')

Now if I define a modelform:

class MF(models.ModelForm):
  class Meta:
  model = B
  fields = [a,]

We are using django widget tweaks to render the fields in MF. Now if there 
are tens of thousands of records in A, the MF form rendering causes the 
page to hang as the widget will try to show the whole set of tens of 
thousands of records option for field a. 

Hence, would appreciate if anyone could suggest a smart solution wherein 
the above issue is taken care of. 

Thanks.


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To 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/2b3be3a1-e0a6-4c73-8c69-d7a314885ab3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Display Many to Many Field in Django admin site

2018-04-03 Thread carlos
[i.fields for i in self.ingredients.objects.all()]
fields is you method __str__ back, try comments __str__ method in model
Ingredients

or this function get_ingredient create in admin files and used obj parameter

cheers

On Tue, Apr 3, 2018 at 10:34 AM, Muhammad bin-haneef 
wrote:

> kindly share the code where you registered your product for admin site and
> you are calling "get_ ingredients()" method.
>
> As the error shows your method needs 2 arguments to pass when you call
> "get_ingredients()".
>
> On Tue, Apr 3, 2018 at 12:05 PM, mansi thakkar 
> wrote:
>
>> It is there in ProductIngredient.png.
>>
>> On Tuesday, April 3, 2018 at 11:57:38 AM UTC-4, squal poreover wrote:
>>>
>>> I need to see get_ingredients() . To guess what's happening?
>>>
>>> On Tue, 3 Apr 2018, 21:22 mansi thakkar,  wrote:
>>>
>>>> Hello ,
>>>>
>>>> In my database, there is one table named Product and the other table is
>>>> Ingredient. Both are related with ManyToMany Relationship using bridge
>>>> entity (table) named ProductIngredient.
>>>>
>>>> I am trying to display Many To Many field named ingredient in my Django
>>>> admin site.
>>>>
>>>> Here is the attached code and screen shot of the error.
>>>>
>>>> I would like to know the solution of this error and also any other way
>>>> to display  the list of ingredients for each product.
>>>>
>>>> Thank you.
>>>>
>>>> --
>>>> You received this message because you are subscribed to the Google
>>>> Groups "Django users" group.
>>>> To unsubscribe from this group and stop receiving emails from it, send
>>>> an email to django-users...@googlegroups.com.
>>>> To post to this group, send email to django...@googlegroups.com.
>>>> Visit this group at https://groups.google.com/group/django-users.
>>>> To view this discussion on the web visit https://groups.google.com/d/ms
>>>> gid/django-users/63c89597-39c0-4765-ab43-4df41e729f4b%40goog
>>>> legroups.com
>>>> <https://groups.google.com/d/msgid/django-users/63c89597-39c0-4765-ab43-4df41e729f4b%40googlegroups.com?utm_medium=email&utm_source=footer>
>>>> .
>>>> For more options, visit https://groups.google.com/d/optout.
>>>>
>>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit https://groups.google.com/d/ms
>> gid/django-users/2de0db4a-e455-464b-8a46-dae694ed52e4%40googlegroups.com
>> <https://groups.google.com/d/msgid/django-users/2de0db4a-e455-464b-8a46-dae694ed52e4%40googlegroups.com?utm_medium=email&utm_source=footer>
>> .
>>
>> For more options, visit https://groups.google.com/d/optout.
>>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/
> msgid/django-users/CABFB2NVuBTs_GiJyVFOwC4VbpwyvmCBpGZBYJ0kDHn
> aqwPp_OQ%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-users/CABFB2NVuBTs_GiJyVFOwC4VbpwyvmCBpGZBYJ0kDHnaqwPp_OQ%40mail.gmail.com?utm_medium=email&utm_source=footer>
> .
>
> For more options, visit https://groups.google.com/d/optout.
>



-- 
att.
Carlos Rocha

-- 
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/CAM-7rO1prTG37fPSDeYpvH0TVNtg41dm-Y20e%3DvNSQZU4jd8RQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Display Many to Many Field in Django admin site

2018-04-03 Thread Muhammad bin-haneef
kindly share the code where you registered your product for admin site and
you are calling "get_ ingredients()" method.

As the error shows your method needs 2 arguments to pass when you call "get_
ingredients()".

On Tue, Apr 3, 2018 at 12:05 PM, mansi thakkar 
wrote:

> It is there in ProductIngredient.png.
>
> On Tuesday, April 3, 2018 at 11:57:38 AM UTC-4, squal poreover wrote:
>>
>> I need to see get_ingredients() . To guess what's happening?
>>
>> On Tue, 3 Apr 2018, 21:22 mansi thakkar,  wrote:
>>
>>> Hello ,
>>>
>>> In my database, there is one table named Product and the other table is
>>> Ingredient. Both are related with ManyToMany Relationship using bridge
>>> entity (table) named ProductIngredient.
>>>
>>> I am trying to display Many To Many field named ingredient in my Django
>>> admin site.
>>>
>>> Here is the attached code and screen shot of the error.
>>>
>>> I would like to know the solution of this error and also any other way
>>> to display  the list of ingredients for each product.
>>>
>>> Thank you.
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-users...@googlegroups.com.
>>> To post to this group, send email to django...@googlegroups.com.
>>> Visit this group at https://groups.google.com/group/django-users.
>>> To view this discussion on the web visit https://groups.google.com/d/ms
>>> gid/django-users/63c89597-39c0-4765-ab43-4df41e729f4b%40googlegroups.com
>>> <https://groups.google.com/d/msgid/django-users/63c89597-39c0-4765-ab43-4df41e729f4b%40googlegroups.com?utm_medium=email&utm_source=footer>
>>> .
>>> For more options, visit https://groups.google.com/d/optout.
>>>
>> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/
> msgid/django-users/2de0db4a-e455-464b-8a46-dae694ed52e4%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/2de0db4a-e455-464b-8a46-dae694ed52e4%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>
> For more options, visit https://groups.google.com/d/optout.
>

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


Re: Display Many to Many Field in Django admin site

2018-04-03 Thread mansi thakkar
Yes I have. But it didn't work. Basically my product has many ingredients 
and on ingredient is contained in many products so all I need is just 
display product with all the ingredients it contains on admin site.

On Tuesday, April 3, 2018 at 12:48:34 PM UTC-4, Julio Biason wrote:
>
> It seems your `get_ingredients()` is expecting the Product itself and 
> another object (for some reason).
>
> Have you tried to remove `obj` from the parameters and use `self` in that 
> function?
>
> On Tue, Apr 3, 2018 at 12:22 PM, mansi thakkar  > wrote:
>
>> Hello ,
>>
>> In my database, there is one table named Product and the other table is 
>> Ingredient. Both are related with ManyToMany Relationship using bridge 
>> entity (table) named ProductIngredient. 
>>
>> I am trying to display Many To Many field named ingredient in my Django 
>> admin site. 
>>
>> Here is the attached code and screen shot of the error.
>>
>> I would like to know the solution of this error and also any other way to 
>> display  the list of ingredients for each product. 
>>
>> Thank you.
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/63c89597-39c0-4765-ab43-4df41e729f4b%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/63c89597-39c0-4765-ab43-4df41e729f4b%40googlegroups.com?utm_medium=email&utm_source=footer>
>> .
>> 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/fd1fc0fe-a997-46f2-b9bf-96c7041e7108%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Display Many to Many Field in Django admin site

2018-04-03 Thread Julio Biason
It seems your `get_ingredients()` is expecting the Product itself and
another object (for some reason).

Have you tried to remove `obj` from the parameters and use `self` in that
function?

On Tue, Apr 3, 2018 at 12:22 PM, mansi thakkar 
wrote:

> Hello ,
>
> In my database, there is one table named Product and the other table is
> Ingredient. Both are related with ManyToMany Relationship using bridge
> entity (table) named ProductIngredient.
>
> I am trying to display Many To Many field named ingredient in my Django
> admin site.
>
> Here is the attached code and screen shot of the error.
>
> I would like to know the solution of this error and also any other way to
> display  the list of ingredients for each product.
>
> Thank you.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+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/63c89597-39c0-4765-ab43-4df41e729f4b%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/63c89597-39c0-4765-ab43-4df41e729f4b%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
> 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/CAEM7gE2ufSQNgKq-jrY3WBPM9N8Jd4b%3DZL%2B%3DxvLPgC-fepCXEQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Display Many to Many Field in Django admin site

2018-04-03 Thread mansi thakkar
It is there in ProductIngredient.png.

On Tuesday, April 3, 2018 at 11:57:38 AM UTC-4, squal poreover wrote:
>
> I need to see get_ingredients() . To guess what's happening?
>
> On Tue, 3 Apr 2018, 21:22 mansi thakkar,  > wrote:
>
>> Hello ,
>>
>> In my database, there is one table named Product and the other table is 
>> Ingredient. Both are related with ManyToMany Relationship using bridge 
>> entity (table) named ProductIngredient. 
>>
>> I am trying to display Many To Many field named ingredient in my Django 
>> admin site. 
>>
>> Here is the attached code and screen shot of the error.
>>
>> I would like to know the solution of this error and also any other way to 
>> display  the list of ingredients for each product. 
>>
>> Thank you.
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/63c89597-39c0-4765-ab43-4df41e729f4b%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/63c89597-39c0-4765-ab43-4df41e729f4b%40googlegroups.com?utm_medium=email&utm_source=footer>
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>

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


Re: Display Many to Many Field in Django admin site

2018-04-03 Thread squal poreover
I need to see get_ingredients() . To guess what's happening?

On Tue, 3 Apr 2018, 21:22 mansi thakkar,  wrote:

> Hello ,
>
> In my database, there is one table named Product and the other table is
> Ingredient. Both are related with ManyToMany Relationship using bridge
> entity (table) named ProductIngredient.
>
> I am trying to display Many To Many field named ingredient in my Django
> admin site.
>
> Here is the attached code and screen shot of the error.
>
> I would like to know the solution of this error and also any other way to
> display  the list of ingredients for each product.
>
> Thank you.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+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/63c89597-39c0-4765-ab43-4df41e729f4b%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/63c89597-39c0-4765-ab43-4df41e729f4b%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
> For more options, visit https://groups.google.com/d/optout.
>

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


Can I test for count of a many to many field, in a Q query, along with other filters?

2018-01-16 Thread Mark London
If I'm creating a query using Q, can I make one of Q tests, be a count of a 
manytomany field?I.e., one of the Q filters, should test to see if a 
specific manytomany field, has a count greater than 5,   I know that I can 
use annotate to test for count.   But can annotate be specified within a Q 
query?   

If not, can I make 2 separate queries, and combine them, and eliminate 
duplicates?

Thanks! - Mark 

-- 
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/198c6f85-ba4c-4f38-844f-cb8cc4d67772%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Clarification on __in when attribute on left is a many to many field

2018-01-15 Thread Jeff Tchang

In the documentation on this page:
https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_many/

you have the following example:

>>> Article.objects.filter(publications__in=[1,2]).distinct()>> [, >> Python>]>


Does the __in for many to many fields mean for ANY publication in [1,2]. So 
does Django go through every publication in every article and if any of them 
are in the list on the right that Article is included in the result?



-Jeff

-- 
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/331d1f73-ce56-4296-a9e3-bcbd033a1530%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Override save method to add list in the many to many field

2017-01-04 Thread Robin Lery
I have this model to save post from the users:

class Tag(models.Model):
name = models.CharField(max_length=255, unique=True)

def add_tags(obj_id, body):
object = Post.objects.get(id=obj_id)
tag_list = [Tag.objects.create(name=word) for word in body.split()]
for tag in tag_list:
object.tags.add(tag)

class Post(models.Model):
user = models.ForeignKey(User)
body = models.TextField()
tags = models.ManyToManyField(Tag, blank=True)
pub_date = models.DateTimeField(default=timezone.now)
activity = GenericRelation(Activity, related_query_name="posts")

def save(self, *args, **kwargs):
super(Post, self).save(*args, **kwargs)
if self.body:
body = self.body
obj_id = self.id
add_tags(obj_id, body)

So whenever a user post something, I would like to check if there's any
hash-tag used inside the body. If there are tags, then fetch the tags
inside the list.

But when I am posting, the tag objects are created, but they are not adding
for the Post.tags fields.

post.body example = Check #from the http://somesitedotcom/page#idtop #hell
yeah!

What am I doing wrong here?

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


Re: Migrate a many-to-many field to an explicit intermediate ("through") model?

2015-07-24 Thread Carsten Fuchs

Hi all,

just wanted to let you know that I was successful!

I followed Gergely's final recipe, using RunPython for the data migrations and separate 
migration files for each of the steps.


For step 3 (the deletion of the ManyToManyField) I temporarily had to remove the 
django.contrib.admin from the INSTALLED_APPS, because I was referring to the old 
ManyToManyField in my app's admin.py setup, which in turn was processed while running 
`./manage.py makemigrations`.


Overall, this worked very well.

Many thanks to you both for your help!
:-)

Am 23.07.2015 um 22:37 schrieb Carl Meyer:

Meanwhile it might worth a question to the devs (or a more thorough
search on the topic) to understand why you can't switch from a simple
m2m field to one with a through option.


Just because it's a bit complex to implement, and nobody has implemented
it yet.


Well, if I understand this correctly, https://code.djangoproject.com/ticket/23034 has a 
reviewed PR that implements this, but unfortunately the original author has not updated 
the PR for several months...


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/55B2814E.1090604%40cafu.de.
For more options, visit https://groups.google.com/d/optout.


Re: Migrate a many-to-many field to an explicit intermediate ("through") model?

2015-07-23 Thread Carl Meyer
Hi Gergely,

On 07/23/2015 02:27 PM, Gergely Polonkai wrote:
> Yes, you are right, my attempt is not the solution to your problem; it
> seems that this m2m field really cannot be modified like this. With some
> slight modifications, though, it may be.
> 
> 1) create the through table
> 2) migrate data with RunPython — if you want to be portable, stay with
> RunPython instead of RunSQL

Yes, this is true. Don't use RunSQL if you want your code to be portable
between database backends. (For most of my non-reusable-apps code, I
take great advantage of Postgres-specific features and don't care at all
about cross-database portability.)

> 3) delete the ManyToManyField
> 4) recreate the ManyToManyField with the through option
> 
> All this can (and I think, should) go into the same migration file.

Hmm. I'm almost sure I've had problems in the past with trying to do
schema alterations and data migration in the same migration file (thus
same transaction), but with a simple test just now it seems to work OK
on Postgres. I'll have to start trying to combine migrations like this
more often and see how it goes.

> Meanwhile it might worth a question to the devs (or a more thorough
> search on the topic) to understand why you can't switch from a simple
> m2m field to one with a through option.

Just because it's a bit complex to implement, and nobody has implemented
it yet.

Carl

-- 
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/55B15070.8000707%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: OpenPGP digital signature


Re: Migrate a many-to-many field to an explicit intermediate ("through") model?

2015-07-23 Thread Gergely Polonkai
Hello,

I'm sorry, I was not around my mailbox lately.

Yes, you are right, my attempt is not the solution to your problem; it
seems that this m2m field really cannot be modified like this. With some
slight modifications, though, it may be.

1) create the through table
2) migrate data with RunPython — if you want to be portable, stay with
RunPython instead of RunSQL
3) delete the ManyToManyField
4) recreate the ManyToManyField with the through option

All this can (and I think, should) go into the same migration file.
Meanwhile it might worth a question to the devs (or a more thorough search
on the topic) to understand why you can't switch from a simple m2m field to
one with a through option.

Best,
Gergely
On 23 Jul 2015 19:08, "Carsten Fuchs"  wrote:

> Hi Carl,
>
> Am 23.07.2015 um 18:28 schrieb Carl Meyer:
>
>> Overall I think it might be simpler to go with your initial approach. I'd
>> first rename
>> the old field to some other temporary name (you don't have to update any
>> other code to
>> use this name, as you'll commit all of these migrations in one commit, so
>> nothing but
>> the following data migration ever needs to know anything about this
>> temporary name),
>>
>
> Thanks for clarifying the details regarding renaming! With this, this is
> the approach that I feel the most comfortable with and will try now.
>
> Overall, many thanks for your thoughts and your detailed reply, it's very
> much appreciated and helps a lot!
>
> 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/55B11F7B.1010805%40cafu.de.
> For more options, visit https://groups.google.com/d/optout.
>

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


Re: Migrate a many-to-many field to an explicit intermediate ("through") model?

2015-07-23 Thread Carsten Fuchs

Hi Carl,

Am 23.07.2015 um 18:28 schrieb Carl Meyer:

Overall I think it might be simpler to go with your initial approach. I'd first 
rename
the old field to some other temporary name (you don't have to update any other 
code to
use this name, as you'll commit all of these migrations in one commit, so 
nothing but
the following data migration ever needs to know anything about this temporary 
name),


Thanks for clarifying the details regarding renaming! With this, this is the approach 
that I feel the most comfortable with and will try now.


Overall, many thanks for your thoughts and your detailed reply, it's very much 
appreciated and helps a lot!


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/55B11F7B.1010805%40cafu.de.
For more options, visit https://groups.google.com/d/optout.


Re: Migrate a many-to-many field to an explicit intermediate ("through") model?

2015-07-23 Thread Carl Meyer
Hi Carsten,

On Thursday, July 16, 2015 at 12:44:55 PM UTC-6, Carsten Fuchs wrote:
>
> Am 2015-07-16 um 18:15 schrieb Gergely Polonkai: 
> > 1) create the "through" model, add it to the migration file 
> > 2) migrate all m2m instances (e.g. iterate over all Bereich objects then 
> > iterate through its users, creating a UserBereichAssignment object for 
> > each (all this done in a migrations.RunPython call) 
>
> Ok. I've never used migrations.RunPython before, but I'm quite confident 
> that I can manage it. 
>

You could also use RunSQL instead of RunPython for this data migration step 
- personally I often find that easier (and almost always more efficient) 
for a simple data migration, since all you need is a SQL query to copy some 
data from one table to another, you don't need any Python conveniences or 
model instances along the way.

But either can work, it really just depends how comfortable you are with 
raw SQL.
 

> Would the migration for step 2) be a separate migration file from step 
> 1), or is the migration file of step 1) edited to cover step 2) as well? 
>

Separate migration. In general you can't put schema alterations and data 
migrations in the same migration file, because then they'll try to run in 
the same transaction, and PostgreSQL at least doesn't like that.

In general, for complex changes, this three-step dance (one migration to 
add the new field/table, a second migration to copy the data, and a third 
migration to remove the old field/table) is very common and the right way 
to do things.
 

> > 3) change the m2m field by adding the through option, and add this 
> > change to the migrations file. 
>
> Same question: Is this supposed to go into a separate migration file or 
> into the common migrations file from above? 
>
> And won't this last step trigger the same error as before? ("... you 
> cannot alter to or from M2M fields, or add or remove through= on M2M 
> fields") ? 
>

This part I'm not sure about without trying it. I'm honestly not sure what 
exactly Gergely was recommending. Based on my reading of the code, the 
error is raised by the schema-editor backend, meaning if you try an 
`AlterField` with this change, you'd hit the error.

Another possibility might be to use the `SeparateDatabaseAndState` 
operation to create a migration that has no effect on the schema, but just 
updates the Python state for the field. Since you've already made the 
necessary db schema changes simply by adding the through model itself, this 
should work fine.

You could also go back and edit the field definition in whichever migration 
initially created it. This would probably work, but it would cause problems 
for any `RunPython` migrations since then that used that field (because now 
they'd try to use the through table instead), including your own data 
migration that you just created prior to this. So probably not a good 
option.
 

> (Not so important, but out of curiosity: This won't get us rid of the 
> old, implicit intermediate table, will it?) 
>

No. You could add another RunSQL migration to remove this table using raw 
SQL.

Overall I think it might be simpler to go with your initial approach. I'd 
first rename the old field to some other temporary name (you don't have to 
update any other code to use this name, as you'll commit all of these 
migrations in one commit, so nothing but the following data migration ever 
needs to know anything about this temporary name), then add the new field 
with through table (using the original field name), then migrate data 
(using either RunPython or RunSQL), then remove the old field. I think this 
will work fine, and it should also remove the old auto-created through 
table.

Good luck! I think this is definitely an area where the migrations system 
could help a bit more.

Carl

-- 
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/e987cf79-358d-4fdc-bac5-5131a19a25c1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Migrate a many-to-many field to an explicit intermediate ("through") model?

2015-07-23 Thread Carsten Fuchs

Am 16.07.2015 um 16:05 schrieb Carsten Fuchs:

Alas... are there any viable alternatives to this?
I'd be very grateful for any hint!   :-)



Anyone please?

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/55B10E2A.7060809%40cafu.de.
For more options, visit https://groups.google.com/d/optout.


Re: Migrate a many-to-many field to an explicit intermediate ("through") model?

2015-07-20 Thread Carsten Fuchs

Hi Gergely,

Am 16.07.2015 um 20:44 schrieb Carsten Fuchs:

3) change the m2m field by adding the through option, and add this
change to the migrations file.


[...]
And won't this last step trigger the same error as before? ("... you cannot 
alter to or
from M2M fields, or add or remove through= on M2M fields") ?


Would you mind clarifying and elaborating on your reply please?

Most importantly, why would step 3) not result in the same error as I originally 
experienced?


Many thanks and 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/55ACE8C2.7000508%40cafu.de.
For more options, visit https://groups.google.com/d/optout.


Re: Migrate a many-to-many field to an explicit intermediate ("through") model?

2015-07-16 Thread BHAGYARAJ POLA

>
> hey hi,

I want to create web based visualization by using django framework in 
python.

 i need to have a front end interface which will communicate with the 
database.

The front end should look like similar to this.

http://specobs.ee.washington.edu/


For Map you can use Google Maps API, See how to use that and you know most 
of the information.

>From my view:

Google Maps should take the location data from your input
Input will be latitude, longitude and channel number

Output will be the heat map with the PSD value from the database.


Can u help me in this task?

thanx,

-- 
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/c3a8c6c8-f704-46b0-8d74-c555f1e0ca63%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Migrate a many-to-many field to an explicit intermediate ("through") model?

2015-07-16 Thread Carsten Fuchs

Hi Gergely,

many thanks for your quick reply!

Am 2015-07-16 um 18:15 schrieb Gergely Polonkai:

1) create the "through" model, add it to the migration file
2) migrate all m2m instances (e.g. iterate over all Bereich objects then
iterate through its users, creating a UserBereichAssignment object for
each (all this done in a migrations.RunPython call)


Ok. I've never used migrations.RunPython before, but I'm quite confident 
that I can manage it.


Would the migration for step 2) be a separate migration file from step 
1), or is the migration file of step 1) edited to cover step 2) as well?



3) change the m2m field by adding the through option, and add this
change to the migrations file.


Same question: Is this supposed to go into a separate migration file or 
into the common migrations file from above?


And won't this last step trigger the same error as before? ("... you 
cannot alter to or from M2M fields, or add or remove through= on M2M 
fields") ?


(Not so important, but out of curiosity: This won't get us rid of the 
old, implicit intermediate table, will it?)



However, you may want to go with django-guardian and thus, with
object-level permissions instead ;)


Thanks for mentioning this!

I've started looking into it, but the only user-code example that I've 
been able to find so far is in the middle of 
https://github.com/djangoadvent/djangoadvent-articles/blob/master/1.2/06_object-permissions.rst
Are there any other examples that demonstrate the purpose and usage of 
this package?



Many thanks and 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/55A7FB88.1040108%40cafu.de.
For more options, visit https://groups.google.com/d/optout.


Re: Migrate a many-to-many field to an explicit intermediate ("through") model?

2015-07-16 Thread Gergely Polonkai
You don't need the temporary field.

1) create the "through" model, add it to the migration file
2) migrate all m2m instances (e.g. iterate over all Bereich objects then
iterate through its users, creating a UserBereichAssignment object for each
(all this done in a migrations.RunPython call)
3) change the m2m field by adding the through option, and add this change
to the migrations file.

However, you may want to go with django-guardian and thus, with
object-level permissions instead ;)
On 16 Jul 2015 16:05, "Carsten Fuchs"  wrote:

> Dear Django fellows,
>
> using Django 1.8.3, in a fully migrated app I have a model with a
> many-to-many relationship like this:
>
> from django.db import models
> from django.contrib.auth.models import User
>
> class Bereich(models.Model):
> benutzer = models.ManyToManyField(User)
>
> Now I would like to store some extra information with the relationship
> (e.g. some Booleans that describe what the user is permitted to do with the
> related Bereich object).
> That is, the intended result is planned to look like this:
>
> class Bereich(models.Model):
> benutzer = models.ManyToManyField(User,
> through='UserBereichAssignment')
>
> class UserBereichAssignment(models.Model):
> bereich  = models.ForeignKey(Bereich)
> user = models.ForeignKey(User)
> can_edit = models.BooleanField(verbose_name="can edit?",
> default=True)
>
> However:
>
> $ ./manage.py makemigration # ok, creates a new migrations file
> $ ./manage.py migrate
>
> # ...
> ValueError: Cannot alter field Lori.Bereich.benutzer into
> Lori.Bereich.benutzer - they are not compatible types (you cannot alter to
> or from M2M fields, or add or remove through= on M2M fields)
>
>
> Well, I understand that and also seem to see some of the involved
> problems: For example, how would it make sure that the same database table
> is used for the previous implicit intermediate model and the new
> UserBereichAssignment?
>
> I'm also aware of https://code.djangoproject.com/ticket/23034, but I'm
> not sure what to make of it, or if it is even applicable here.
>
>
> Thus, what would be a good way to proceed?
>
> To the best of my understanding, I could do this manually, that is: create
> an entirely new many-to-many field, e.g.
>
> class Bereich(models.Model):
> benutzer  = models.ManyToManyField(User)# old,
> unchanged
> benutzer_ = models.ManyToManyField(User,
> through='UserBereichAssignment')
>
> then manually migrate the data from "benutzer" to "benutzer_" (possibly
> using a data migration?), and finally remove the old field "benutzer". The
> only downside seems that all dependent code had to be updated from using
> the old name "benutzer" to the new name "benutzer_". (I'm not sure if
> making a migration for renaming the new field name to the old field name is
> possible?)
>
> Alas... are there any viable alternatives to this?
> I'd be very grateful for any hint!   :-)
>
> 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/55A7BA3E.5030105%40cafu.de.
> For more options, visit https://groups.google.com/d/optout.
>

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


Migrate a many-to-many field to an explicit intermediate ("through") model?

2015-07-16 Thread Carsten Fuchs

Dear Django fellows,

using Django 1.8.3, in a fully migrated app I have a model with a many-to-many 
relationship like this:


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

class Bereich(models.Model):
benutzer = models.ManyToManyField(User)

Now I would like to store some extra information with the relationship (e.g. some 
Booleans that describe what the user is permitted to do with the related Bereich object).

That is, the intended result is planned to look like this:

class Bereich(models.Model):
benutzer = models.ManyToManyField(User, through='UserBereichAssignment')

class UserBereichAssignment(models.Model):
bereich  = models.ForeignKey(Bereich)
user = models.ForeignKey(User)
can_edit = models.BooleanField(verbose_name="can edit?", default=True)

However:

$ ./manage.py makemigration # ok, creates a new migrations file
$ ./manage.py migrate

# ...
ValueError: Cannot alter field Lori.Bereich.benutzer into Lori.Bereich.benutzer - 
they are not compatible types (you cannot alter to or from M2M fields, or add or remove 
through= on M2M fields)



Well, I understand that and also seem to see some of the involved problems: For example, 
how would it make sure that the same database table is used for the previous implicit 
intermediate model and the new UserBereichAssignment?


I'm also aware of https://code.djangoproject.com/ticket/23034, but I'm not sure what to 
make of it, or if it is even applicable here.



Thus, what would be a good way to proceed?

To the best of my understanding, I could do this manually, that is: create an entirely 
new many-to-many field, e.g.


class Bereich(models.Model):
benutzer  = models.ManyToManyField(User)# old, unchanged
benutzer_ = models.ManyToManyField(User, 
through='UserBereichAssignment')

then manually migrate the data from "benutzer" to "benutzer_" (possibly using a data 
migration?), and finally remove the old field "benutzer". The only downside seems that 
all dependent code had to be updated from using the old name "benutzer" to the new name 
"benutzer_". (I'm not sure if making a migration for renaming the new field name to the 
old field name is possible?)


Alas... are there any viable alternatives to this?
I'd be very grateful for any hint!   :-)

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/55A7BA3E.5030105%40cafu.de.
For more options, visit https://groups.google.com/d/optout.


Re: How to read part of many-to-many field in the template

2014-06-15 Thread alghafli

Thank you for the fast reply. I did what you suggested and it worked fine :)

على الأحد 15 حزيران 2014 16:39, كتب Elliot Bradbury:

Hi Mohammad,

Check out slice 
.


It's a builtin template filter that can be used like this:

{% for author in book.authors.all|slice:"3" %}
  {# HTML up in here #}
{% endfor %}

Good luck,
Elliot


On Sun, Jun 15, 2014 at 9:31 AM, alghafli > wrote:


Hello django users. I am working on my first django project and I
faced a little problem.
I have a library database with books. A book element may have
several authors.
In the view function I query the database for books. I want to
show the *first three* authors. I was thinking to do something
similar to the following python code but using the template language:

authors_to_show = book.authors.get_queryset() [0:3]
for author in authors_to_show:
#html code here

However, it appears that I cannot define variables in the template
unless I extend the language a bit. Note that I have several books
to process and I can do that using the for loop in the template
language. But I want to ignore some authors in each book.
Any idea of a proper way to do this.

Thank you in advance,
Mohammad
-- 
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/539DA033.4060100%40gmail.com

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


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

Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAAErR_z4JoZu0Xe7M7LiJq-3M4pR%2BYwTxaEnJk56AqZnX-nZHg%40mail.gmail.com 
.

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


--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+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/539DA777.2030404%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to read part of many-to-many field in the template

2014-06-15 Thread Elliot Bradbury
Hi Mohammad,

Check out slice
.

It's a builtin template filter that can be used like this:

{% for author in book.authors.all|slice:"3" %}
  {# HTML up in here #}
{% endfor %}

Good luck,
Elliot


On Sun, Jun 15, 2014 at 9:31 AM, alghafli  wrote:

>  Hello django users. I am working on my first django project and I faced a
> little problem.
> I have a library database with books. A book element may have several
> authors.
> In the view function I query the database for books. I want to show the *first
> three* authors. I was thinking to do something similar to the following
> python code but using the template language:
>
> authors_to_show = book.authors.get_queryset() [0:3]
> for author in authors_to_show:
> #html code here
>
> However, it appears that I cannot define variables in the template unless
> I extend the language a bit. Note that I have several books to process and
> I can do that using the for loop in the template language. But I want to
> ignore some authors in each book.
> Any idea of a proper way to do this.
>
> Thank you in advance,
> Mohammad
>
> --
> 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/539DA033.4060100%40gmail.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

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


How to read part of many-to-many field in the template

2014-06-15 Thread alghafli
Hello django users. I am working on my first django project and I faced 
a little problem.
I have a library database with books. A book element may have several 
authors.
In the view function I query the database for books. I want to show the 
*first three* authors. I was thinking to do something similar to the 
following python code but using the template language:


authors_to_show = book.authors.get_queryset() [0:3]
for author in authors_to_show:
#html code here

However, it appears that I cannot define variables in the template 
unless I extend the language a bit. Note that I have several books to 
process and I can do that using the for loop in the template language. 
But I want to ignore some authors in each book.

Any idea of a proper way to do this.

Thank you in advance,
Mohammad

--
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/539DA033.4060100%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to query multiple described objects exist in a many to many field

2013-12-05 Thread Aamu Padi
Thank you so much! That was a very helpful explanation. And it worked
perfectly!!!

Just, one more question please. Suppose, the user wants to send a message
to a group of users, how do I find the thread in this situation?

Eg: user1 wants to send a message to both the user2 and user3. How to find
the thread, in this case '*t3*'?

>>> t1 = Thread.objects.get(id=1)
>>> t1
[,]
>>> t2 = Thread.objects.get(id=2)
>>> t2
[,]
>>> t3 = Thread.objects.get(id=3)
>>> t3
[,,]


On Wed, Dec 4, 2013 at 5:41 PM, Tom Evans  wrote:

> On Wed, Dec 4, 2013 at 10:24 AM, Aamu Padi  wrote:
> > How do I check whether there is a thread containing only the sender
> (user 1)
> > and the recipient (user 2), and no other users.
> >
> > models.py
> >
> > class Thread(models.Model):
> > user = models.ManyToManyField(User)
> > is_hidden = models.ManyToManyField(User,
> > related_name='hidden_thread', blank=True)
> >
> > class Message(models.Model):
> > thread = models.ForeignKey(Thread)
> > sent_date = models.DateTimeField(default=datetime.now)
> > sender = models.ForeignKey(User)
> > body = models.TextField()
> > is_hidden = models.ManyToManyField(User,
> > related_name='hidden_message', blank=True)
> >
> > I tried
> >
> > >>> Thread.objects.filter(user=user1&user2)
> > >>> Thread.objects.filter(user=user1|user2)
> > # Both gave me an error:  Unsupported operand.
> >
> > # Then this
> > >>> Thread.objects.filter(Q(user=user1) & Q(user=user2))
> > # Which gave me no threads at all.
> >
> > # Then this
> > >>> Thread.objects.filter(Q(user=user1) | Q(user=user2)).distinct()
> > # Gave me threads of both the users.
> >
> > What I want is to check the thread, with the specified users only.
> Suppose,
> > User 1 wants to send a message to User 2. What I want is, first check
> > whether there is a thread between both the users. If there is, get that
> > thread, or else create a new one. How is it possible? What is the best
> way
> > to do it. Please help me. Thank you.
>
> I hope you understand SQL a little, as it will be required to follow
> this explanation.
>
> The condition "Thread.objects.filter(user=..)" goes across a join to
> the users<->threads "through" table, which has columns (id, thread_id,
> user_id).
>
> When you specify conditions in a "filter()" call, each of the
> conditions specified in that call is AND'ed together (the equivalent
> of what you were doing in the "Q(user=user1) & Q(user=user2)", django
> would do that for you). However, what does that mean, in terms of SQL?
>
> Well, it means "find me rows from the users<->threads through table
> that have user_id=user1.pk and user_id=user2.pk". Obviously, this will
> never find results unless user1==user2.
>
> So, you need to specify that you want to join twice to that table. You
> do this by specifying the conditions for each join in a separate
> "filter()" call, and so to find threads that have a row with user1 in
> the through table, and also have user2 in the through table:
>
> Thread.objects.filter(user=user1).filter(user=user2)
>
> You started by asking how to find threads which had user1 and user2,
> but no other users. This is more complex, you need to count the number
> of users in the thread without filtering the users first! This means
> two queries, or a sub query:
>
> threads_with_both = Thread.objects.filter(user=user1).filter(user=user2)
> threads_with_only_both = Thread.objects.filter(
>  pk__in=threads_with_both).annotate(
>  num_users=Count('user')).filter(
>  num_users=2)
>
> >
> > And please tell me what's the difference between | and &? Because I had
> very
> > different results with these two.
>
> | is OR
> & is AND
>
> So to find threads with either user1 or user2 (or both):
>
> Thread.objects.filter(Q(user=user1) | Q(user=user2))
>
> To find hidden threads with user1
>
> Thread.objects.filter(Q(user=user1) & Q(is_hidden=True))
>
> which is the same as
>
> Thread.objects.filter(user=user1, is_hidden=True)
>
>
> Cheers
>
> Tom
>
> --
> 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/CAFHbX1J%3DWX9p12B2X%2B1b_afDF0yEr80t0cfBsGbggzrKEBqqTg%40mail.gmail.com
> .
> For more options, visit https://groups.google.com/groups/opt_out.
>

-- 
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

Re: How to query multiple described objects exist in a many to many field

2013-12-04 Thread Tom Evans
On Wed, Dec 4, 2013 at 10:24 AM, Aamu Padi  wrote:
> How do I check whether there is a thread containing only the sender (user 1)
> and the recipient (user 2), and no other users.
>
> models.py
>
> class Thread(models.Model):
> user = models.ManyToManyField(User)
> is_hidden = models.ManyToManyField(User,
> related_name='hidden_thread', blank=True)
>
> class Message(models.Model):
> thread = models.ForeignKey(Thread)
> sent_date = models.DateTimeField(default=datetime.now)
> sender = models.ForeignKey(User)
> body = models.TextField()
> is_hidden = models.ManyToManyField(User,
> related_name='hidden_message', blank=True)
>
> I tried
>
> >>> Thread.objects.filter(user=user1&user2)
> >>> Thread.objects.filter(user=user1|user2)
> # Both gave me an error:  Unsupported operand.
>
> # Then this
> >>> Thread.objects.filter(Q(user=user1) & Q(user=user2))
> # Which gave me no threads at all.
>
> # Then this
> >>> Thread.objects.filter(Q(user=user1) | Q(user=user2)).distinct()
> # Gave me threads of both the users.
>
> What I want is to check the thread, with the specified users only. Suppose,
> User 1 wants to send a message to User 2. What I want is, first check
> whether there is a thread between both the users. If there is, get that
> thread, or else create a new one. How is it possible? What is the best way
> to do it. Please help me. Thank you.

I hope you understand SQL a little, as it will be required to follow
this explanation.

The condition "Thread.objects.filter(user=..)" goes across a join to
the users<->threads "through" table, which has columns (id, thread_id,
user_id).

When you specify conditions in a "filter()" call, each of the
conditions specified in that call is AND'ed together (the equivalent
of what you were doing in the "Q(user=user1) & Q(user=user2)", django
would do that for you). However, what does that mean, in terms of SQL?

Well, it means "find me rows from the users<->threads through table
that have user_id=user1.pk and user_id=user2.pk". Obviously, this will
never find results unless user1==user2.

So, you need to specify that you want to join twice to that table. You
do this by specifying the conditions for each join in a separate
"filter()" call, and so to find threads that have a row with user1 in
the through table, and also have user2 in the through table:

Thread.objects.filter(user=user1).filter(user=user2)

You started by asking how to find threads which had user1 and user2,
but no other users. This is more complex, you need to count the number
of users in the thread without filtering the users first! This means
two queries, or a sub query:

threads_with_both = Thread.objects.filter(user=user1).filter(user=user2)
threads_with_only_both = Thread.objects.filter(
 pk__in=threads_with_both).annotate(
 num_users=Count('user')).filter(
 num_users=2)

>
> And please tell me what's the difference between | and &? Because I had very
> different results with these two.

| is OR
& is AND

So to find threads with either user1 or user2 (or both):

Thread.objects.filter(Q(user=user1) | Q(user=user2))

To find hidden threads with user1

Thread.objects.filter(Q(user=user1) & Q(is_hidden=True))

which is the same as

Thread.objects.filter(user=user1, is_hidden=True)


Cheers

Tom

-- 
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/CAFHbX1J%3DWX9p12B2X%2B1b_afDF0yEr80t0cfBsGbggzrKEBqqTg%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


How to query multiple described objects exist in a many to many field

2013-12-04 Thread Aamu Padi
How do I check whether there is a thread containing only the sender (user
1) and the recipient (user 2), and no other users.

models.py

class Thread(models.Model):
user = models.ManyToManyField(User)
is_hidden = models.ManyToManyField(User,
related_name='hidden_thread', blank=True)

class Message(models.Model):
thread = models.ForeignKey(Thread)
sent_date = models.DateTimeField(default=datetime.now)
sender = models.ForeignKey(User)
body = models.TextField()
is_hidden = models.ManyToManyField(User,
related_name='hidden_message', blank=True)

I tried

>>> Thread.objects.filter(user=user1&user2)
>>> Thread.objects.filter(user=user1|user2)
# Both gave me an error:  Unsupported operand.

# Then this
>>> Thread.objects.filter(Q(user=user1) & Q(user=user2))
# Which gave me no threads at all.

# Then this
>>> Thread.objects.filter(Q(user=user1) | Q(user=user2)).distinct()
# Gave me threads of both the users.

What I want is to check the thread, with the specified users only. Suppose,
User 1 wants to send a message to User 2. What I want is, first check
whether there is a thread between both the users. If there is, get that
thread, or else create a new one. How is it possible? What is the best way
to do it. Please help me. Thank you.

And please tell me what's the difference between | and &? Because I had
very different results with these two.

-- 
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/CAHSNPWtFESu7WGZcHDOeNCVc1FqOqxqw2kkiRY0jaJctXy6XHQ%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


showing many-to-many field in admin interface

2012-08-09 Thread Mo Mughrabi
hello everyone,

am trying to build a single model that will be used for uploaded
images/files. Am trying to use it in the best way in the admin pages, so
when i associate it with a specific model as a many-to-many field it would
appear in a friendly way for users to upload images.

My attachment model is as following

class Attachment(models.Model):
_attachment_types = (
('I', ('Image')),
('P', ('PDF'))  ,
)

attachment_type = models.CharField(max_length=2, default='I')
description = models.TextField(null=True, blank=True)
file= models.FileField(upload_to='%Y/%m/%d')


my other model is

class LawCaseImage(models.Model):
bonanza = models.ForeignKey('LawCase')
image   = models.ForeignKey(Attachment)
primary_photo   = models.BooleanField(default=False)




class LawCase(models.Model):
"""  """
user_profile= models.ForeignKey(UserProfile,
limit_choices_to={'profile_type' : 'C'}, help_text=_('Only corporate
accounts will appear in the drop down.'))
name= models.CharField(max_length=20, )
description = models.TextField()
created_at  = models.DateTimeField(auto_now_add=True)
created_by  = models.ForeignKey(User, editable=False)
image   = models.ManyToManyField(Attachment, through=LawCaseImage)


I tried to use inline associate in my admin.py as following

class LawCaseImageForm(admin.TabularInline):
model = LawCaseImage


class LawCaseForm(admin.ModelAdmin):
inlines = [LawCaseImageForm, ]


but all i got was a grid with the many-to-many table. I would like to be
able to upload images right away when creating a new record and they will
be uploaded to attachment model and relation will be created on that base..

Is there a way to configure admin to work on that behavior? and if not, is
there a plugin out there i could use for that purpose?

regards,

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: sql for Many To Many Field in existing django model

2012-03-24 Thread Nikhil Verma
Hi

I am able to create the field through in postgres.
When i execute that sql statement :-

CREATE TABLE "visit_visit_research" (
"id" serial NOT NULL PRIMARY KEY,
"visit_id" integer NOT NULL REFERENCES "visit_visit" ("id") DEFERRABLE
INITIALLY DEFERRED,
"research_id" integer NOT NULL REFERENCES "www_researchprotocol" ("id")
DEFERRABLE INITIALLY DEFERRED,
UNIQUE ("visit_id", "research_id")
)
;

I get this :-

psql:db/2012-03-24_research_protocol.sql:7: NOTICE:  CREATE TABLE will
create implicit sequence "visit_visit_research_id_seq" for serial column "
visit_visit_research.id"
psql:db/2012-03-24_research_protocol.sql:7: NOTICE:  CREATE TABLE / PRIMARY
KEY will create implicit index "visit_visit_research_pkey" for table
"visit_visit_research"
psql:db/2012-03-24_research_protocol.sql:7: NOTICE:  CREATE TABLE / UNIQUE
will create implicit index "visit_visit_research_visit_id_key" for table
"visit_visit_research"
CREATE TABLE

So the field gets created but when i am going in django-admin in table
visit i am getting an error.It is not showing up two boxes i mean the many
to many widget which django displays.

This is the error

Exception Type: DatabaseError at /admin/visit/visit/20/
Exception Value: column visit_visit_research.researchprotocol_id does not
exist
LINE 1: ...visit_research" ON ("www_researchprotocol"."id" = "visit_vis...
 ^

Any help will be appreciated.

Thanks in advance.


On Thu, Mar 22, 2012 at 6:26 PM, Joel Goldstick wrote:

> On Thu, Mar 22, 2012 at 6:55 AM, Nikhil Verma 
> wrote:
> > Hi All
> >
> > I want to add a ManyToManyField  to an existing django model.
> >
> > I can use sql app_name and see the statement.
> >
> > My models
> >
> > Class Visit(modes.Model):
> >   x = something
> >   . ..
> >   .. and so on
> >  # finally Here i want to add that field research protol
> >  research_protocol  =
> > models.ManyToManyField(ResearchProtocol,blank=True)
> >
> >
> >
> > class ResearchProtocol(models.Model):
> > title = models.CharField(max_length=30)
> > description = models.TextField()
> > start_date = models.DateField(_("Date Started"))
> > end_date = models.DateField(_("Date Completed"))
> >
> > def __unicode__(self):
> > return '%s' % self.title
> >
> >
> >
> > So i made an sql statement like this:-
> >
> > CREATE TABLE "visit_visit_research_protocols"
> > (
> > "id" integer NOT NULL PRIMARY KEY,
> >
> > "visit_id" integer NOT NULL REFERENCES "visit_visit" ("id")
> DEFERRABLE
> > INITIALLY DEFERRED,
> > "research_protocols_id" varchar(80) NOT NULL REFERENCES
> > "www_researchprotocol" ("title") DEFERRABLE INITIALLY DEFERRED,
> > UNIQUE ("visit_id","research_protocols_id")
> > );
> >
> > The dbshell says:-
> > psql:db/2012-03-22_research_id.sql:8: NOTICE:  CREATE TABLE / PRIMARY KEY
> > will create implicit index "visit_visit_research_protocols_pkey" for
> table
> > "visit_visit_research_protocols"
> > psql:db/2012-03-22_research_id.sql:8: NOTICE:  CREATE TABLE / UNIQUE will
> > create implicit index
> > "visit_visit_research_protocol_visit_id_research_protocols_i_key" for
> table
> > "visit_visit_research_protocols"
> > psql:db/2012-03-22_research_id.sql:8: ERROR:  there is no unique
> constraint
> > matching given keys for referenced table "www_researchprotocol"
> >
> >
> >
> > What mistake i am doing  ?
> >
> > Thanks in advance.
> >
> >
> > --
> > Regards
> > Nikhil Verma
> > +91-958-273-3156
> >
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To post to this group, send email to django-users@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> > http://groups.google.com/group/django-users?hl=en.
>
> You can't add the many to many relationship after you already have the
> model with django.  See this:
>
> http://stackoverflow.com/questions/830130/adding-a-field-to-an-existing-django-model
> That answer points to South, which I have played with but am not
> proficient yet.  Another thought is to create a new model, identical
> to your present one, but include the many2many and dbsync that.  If it
> works, copy your data from your old model into your new model.
>
>
> --
> Joel Goldstick
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>


-- 
Regards
Nikhil Verma
+91-958-273-3156

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group

Re: sql for Many To Many Field in existing django model

2012-03-22 Thread Joel Goldstick
On Thu, Mar 22, 2012 at 6:55 AM, Nikhil Verma  wrote:
> Hi All
>
> I want to add a ManyToManyField  to an existing django model.
>
> I can use sql app_name and see the statement.
>
> My models
>
> Class Visit(modes.Model):
>   x = something
>   . ..
>   .. and so on
>  # finally Here i want to add that field research protol
>  research_protocol  =
> models.ManyToManyField(ResearchProtocol,blank=True)
>
>
>
> class ResearchProtocol(models.Model):
>     title = models.CharField(max_length=30)
>     description = models.TextField()
>     start_date = models.DateField(_("Date Started"))
>     end_date = models.DateField(_("Date Completed"))
>
>     def __unicode__(self):
>     return '%s' % self.title
>
>
>
> So i made an sql statement like this:-
>
> CREATE TABLE "visit_visit_research_protocols"
> (
>     "id" integer NOT NULL PRIMARY KEY,
>
>     "visit_id" integer NOT NULL REFERENCES "visit_visit" ("id") DEFERRABLE
> INITIALLY DEFERRED,
>     "research_protocols_id" varchar(80) NOT NULL REFERENCES
> "www_researchprotocol" ("title") DEFERRABLE INITIALLY DEFERRED,
>     UNIQUE ("visit_id","research_protocols_id")
> );
>
> The dbshell says:-
> psql:db/2012-03-22_research_id.sql:8: NOTICE:  CREATE TABLE / PRIMARY KEY
> will create implicit index "visit_visit_research_protocols_pkey" for table
> "visit_visit_research_protocols"
> psql:db/2012-03-22_research_id.sql:8: NOTICE:  CREATE TABLE / UNIQUE will
> create implicit index
> "visit_visit_research_protocol_visit_id_research_protocols_i_key" for table
> "visit_visit_research_protocols"
> psql:db/2012-03-22_research_id.sql:8: ERROR:  there is no unique constraint
> matching given keys for referenced table "www_researchprotocol"
>
>
>
> What mistake i am doing  ?
>
> Thanks in advance.
>
>
> --
> Regards
> Nikhil Verma
> +91-958-273-3156
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.

You can't add the many to many relationship after you already have the
model with django.  See this:
http://stackoverflow.com/questions/830130/adding-a-field-to-an-existing-django-model
That answer points to South, which I have played with but am not
proficient yet.  Another thought is to create a new model, identical
to your present one, but include the many2many and dbsync that.  If it
works, copy your data from your old model into your new model.


-- 
Joel Goldstick

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



sql for Many To Many Field in existing django model

2012-03-22 Thread Nikhil Verma
Hi All

I want to add a ManyToManyField  to an existing django model.

I can use sql app_name and see the statement.

My models

Class Visit(modes.Model):
  x = something
  . ..
  .. and so on
 # finally Here i want to add that field research protol
 research_protocol  =
models.ManyToManyField(ResearchProtocol,blank=True)



class ResearchProtocol(models.Model):
title = models.CharField(max_length=30)
description = models.TextField()
start_date = models.DateField(_("Date Started"))
end_date = models.DateField(_("Date Completed"))

def __unicode__(self):
return '%s' % self.title



So i made an sql statement like this:-

CREATE TABLE "visit_visit_research_protocols"
(
"id" integer NOT NULL PRIMARY KEY,

"visit_id" integer NOT NULL REFERENCES "visit_visit" ("id") DEFERRABLE
INITIALLY DEFERRED,
"research_protocols_id" varchar(80) NOT NULL REFERENCES
"www_researchprotocol" ("title") DEFERRABLE INITIALLY DEFERRED,
UNIQUE ("visit_id","research_protocols_id")
);

The dbshell says:-
psql:db/2012-03-22_research_id.sql:8: NOTICE:  CREATE TABLE / PRIMARY KEY
will create implicit index "visit_visit_research_protocols_pkey" for table
"visit_visit_research_protocols"
psql:db/2012-03-22_research_id.sql:8: NOTICE:  CREATE TABLE / UNIQUE will
create implicit index
"visit_visit_research_protocol_visit_id_research_protocols_i_key" for table
"visit_visit_research_protocols"
psql:db/2012-03-22_research_id.sql:8: ERROR:  there is no unique constraint
matching given keys for referenced table "www_researchprotocol"



What mistake i am doing  ?

Thanks in advance.


-- 
Regards
Nikhil Verma
+91-958-273-3156

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Delete a many to many field who is in another table

2011-11-30 Thread jose osuna perez
I try to make this using delete, remove.. Also I using too
 if request.POST.get('experimentosDelete','')!='':
 for i in
request.POST.getlist('experimentosDelete'):
 
exp=Experimentos.objects.get(proyecto=datos,id=i)
 
exp.experimentos=[]

...
I don't know how to make this..
Anyone who say me ??? Thanks a lot

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Delete a many to many field who is in another table

2011-11-30 Thread Tom Evans
On Wed, Nov 30, 2011 at 11:42 AM, jose osuna perez
 wrote:
> Hi, I am finally going to finish the project started and where I end
> up liking this xD Django that the problem I have is the clearing of a
> field.
> ...
> I try like this:
>
> if request.POST.get('experimentosDelete','')!='':
>                                                 for i in 
> request.POST.getlist('experimentosDelete'):
>                                                        
> exp=Experimentos.objects.get(proyecto=datos,id=i)
>                                                        
> exp.experimentos.remove(request.POST.get('experimentosDelete'))
>

The remove() method takes objects, not ids.

https://docs.djangoproject.com/en/1.3/ref/models/relations/#django.db.models.fields.related.RelatedManager.remove

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Delete a many to many field who is in another table

2011-11-30 Thread Salvatore Iovene
Hi,
after:

exp.experimentos.remove(request.POST.get('experimentosDelete'))

You should do:

exp.save()

I hope this helps.
Salvatore.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/qDb9Yfp_mCgJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Delete a many to many field who is in another table

2011-11-30 Thread jose osuna perez
Hi, I am finally going to finish the project started and where I end
up liking this xD Django that the problem I have is the clearing of a
field.
I have the following tables.

class Proyectos(models.Model):
titulo=models.CharField(max_length=100)
creacion=models.DateField(default=datetime.datetime.now)
estado=models.CharField(max_length=30)
objetivo=models.TextField(null=True)
conclusion=models.TextField(null=True)
porcentaje=models.IntegerField()
modificado=models.DateTimeField(default=datetime.datetime.now)
autor=models.IntegerField()
usuarios=models.ManyToManyField(User)
proyectos_rel=models.ManyToManyField("self")
documentos=models.ManyToManyField(Documentos)
class Meta:
db_table='Proyectos'
def __unicode__(self):
return self.titulo

class Experimentos(models.Model):
titulo=models.CharField(max_length=100)
creacion=models.DateField(default=datetime.datetime.now)
estado=models.CharField(max_length=30)
objetivo=models.TextField(null=True)
conclusion=models.TextField(null=True)
porcentaje=models.IntegerField()
modificado=models.DateTimeField(default=datetime.datetime.now)
autor=models.IntegerField()
proyecto=models.ForeignKey(Proyectos)
usuarios=models.ManyToManyField(User)
experimentos=models.ManyToManyField("self")
documentos=models.ManyToManyField(Documentos)
class Meta:
db_table='Experimentos'
.
I want to eliminate only one of the experiments which may contain a
Project
I try like this:

if request.POST.get('experimentosDelete','')!='':
 for i in 
request.POST.getlist('experimentosDelete'):

exp=Experimentos.objects.get(proyecto=datos,id=i)

exp.experimentos.remove(request.POST.get('experimentosDelete'))

The result is that it does nothing ... and otherwise remove whole
objects, not the relationship.I don't  know .
I greatly appreciate your help in all questions.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Help with many-to-many field update

2011-11-24 Thread Leslie Maclachlan
Hi Mario,
Thanks so much - I updated my view as below and it is now working as
expected!
Regards,
Leslie

if form.is_valid():
new_item = form.save(commit=False)
new_item.client = orderClient
new_item.orderdate = datetime.now()
new_item.orderIP = remote_ip
new_item.status = "Not_Paid"
new_item.save()
form.save_m2m()
ordernumber = new_item.pk

for opt in request.POST.getlist('srvoptions'):
theopt = srvoptions.objects.get(pk=opt)
new_item.srvopts.add(theopt.id)

On Fri, Nov 25, 2011 at 1:40 AM, Mario Gudelj wrote:

> Hey Leslie,
>
> Try add() method like in this answer on SO
> http://stackoverflow.com/questions/1226290/django-manytomany-relation-add-error
>
> Cheers,
>
> On 25 November 2011 00:43, Nichehosters  wrote:
>
>> Hi,
>> I am relatively new to Django, and am trying to update a many-to-many
>> related table using a ModelForm.
>> I see fro the documentation that if I use save(commit=False) - which I
>> do - I need to use save_m2m() after saving the initial form.  I am
>> using the save_m2m(), but my related table does not get updated.
>> Any help appreciated.
>> I am using django V1.3.1 on linux using Postgresql as the db.
>>
>> Details:
>>
>> The Model:
>> class srvorders(models.Model):
>>client = models.CharField('Client', max_length=200)
>>server = models.CharField('Server Type', max_length=200)
>>os = models.CharField('Operating System', max_length=200)
>>osopts = models.CharField('Operating System Options',
>> max_length=200, blank=True, null=True)
>>ordertotal = models.IntegerField()
>>notes = models.TextField('Notes', blank=True, null=True)
>>orderdate = models.DateTimeField()
>>orderIP = models.IPAddressField()
>>status = models.CharField('Order Status', max_length="20")
>>srvopts = models.ManyToManyField(srvoptions, blank=True,
>> null=True)
>>
>> class Meta:
>>ordering = ["id"]
>>verbose_name_plural = "Server Orders"
>>
>> def __unicode__(self):
>>return str(self.id)
>>
>> class Admin:
>>pass
>>
>> The ModelForm:
>> class NewOrderForm(forms.ModelForm):
>>Server_CHOICES = [('', '-- choose a Server --'), ] + [(s.id,
>> s.name) for s in products.objects.all()]
>>OS_CHOICES = [('', '-- choose a Server --'), ] +[(o.id, o.name)
>> for o in OS.objects.all()]
>>OPTION_CHOICES = [('', '-- choose a Server --'), ] +[(opt.id,
>> opt.name) for opt in osoptions.objects.all()]
>>
>> server=forms.ChoiceField(choices=Server_CHOICES)
>> os = forms.ChoiceField(choices=OS_CHOICES)
>> osopts=forms.ChoiceField(choices=OPTION_CHOICES, required=False)
>> ordertotal=forms.CharField(required=False)
>> notes=forms.CharField(required=False)
>>
>> class Meta:
>>model= srvorders
>>exclude = ('client', 'orderdate', 'orderIP', 'status')
>>
>> The View snippet:
>> if request.method == 'POST':
>>form = NewOrderForm(request.POST)
>>if form.is_valid():
>>new_item = form.save(commit=False)
>>new_item.client = orderClient
>>new_item.orderdate = datetime.now()
>>new_item.orderIP = remote_ip
>>new_item.status = "Not_Paid"
>>new_item.save()
>>form.save_m2m()
>>
>> Regards,
>> Leslie
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To post to this group, send email to django-users@googlegroups.com.
>> To unsubscribe from this group, send email to
>> django-users+unsubscr...@googlegroups.com.
>> For more options, visit this group at
>> http://groups.google.com/group/django-users?hl=en.
>>
>>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>



-- 
Regards,
MyGolf
http://www.mygolf.za.net

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Help with many-to-many field update

2011-11-24 Thread Mario Gudelj
Hey Leslie,

Try add() method like in this answer on SO
http://stackoverflow.com/questions/1226290/django-manytomany-relation-add-error

Cheers,

On 25 November 2011 00:43, Nichehosters  wrote:

> Hi,
> I am relatively new to Django, and am trying to update a many-to-many
> related table using a ModelForm.
> I see fro the documentation that if I use save(commit=False) - which I
> do - I need to use save_m2m() after saving the initial form.  I am
> using the save_m2m(), but my related table does not get updated.
> Any help appreciated.
> I am using django V1.3.1 on linux using Postgresql as the db.
>
> Details:
>
> The Model:
> class srvorders(models.Model):
>client = models.CharField('Client', max_length=200)
>server = models.CharField('Server Type', max_length=200)
>os = models.CharField('Operating System', max_length=200)
>osopts = models.CharField('Operating System Options',
> max_length=200, blank=True, null=True)
>ordertotal = models.IntegerField()
>notes = models.TextField('Notes', blank=True, null=True)
>orderdate = models.DateTimeField()
>orderIP = models.IPAddressField()
>status = models.CharField('Order Status', max_length="20")
>srvopts = models.ManyToManyField(srvoptions, blank=True,
> null=True)
>
> class Meta:
>ordering = ["id"]
>verbose_name_plural = "Server Orders"
>
> def __unicode__(self):
>return str(self.id)
>
> class Admin:
>pass
>
> The ModelForm:
> class NewOrderForm(forms.ModelForm):
>Server_CHOICES = [('', '-- choose a Server --'), ] + [(s.id,
> s.name) for s in products.objects.all()]
>OS_CHOICES = [('', '-- choose a Server --'), ] +[(o.id, o.name)
> for o in OS.objects.all()]
>OPTION_CHOICES = [('', '-- choose a Server --'), ] +[(opt.id,
> opt.name) for opt in osoptions.objects.all()]
>
> server=forms.ChoiceField(choices=Server_CHOICES)
> os = forms.ChoiceField(choices=OS_CHOICES)
> osopts=forms.ChoiceField(choices=OPTION_CHOICES, required=False)
> ordertotal=forms.CharField(required=False)
> notes=forms.CharField(required=False)
>
> class Meta:
>model= srvorders
>exclude = ('client', 'orderdate', 'orderIP', 'status')
>
> The View snippet:
> if request.method == 'POST':
>form = NewOrderForm(request.POST)
>if form.is_valid():
>new_item = form.save(commit=False)
>new_item.client = orderClient
>new_item.orderdate = datetime.now()
>new_item.orderIP = remote_ip
>new_item.status = "Not_Paid"
>new_item.save()
>form.save_m2m()
>
> Regards,
> Leslie
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Help with many-to-many field update

2011-11-24 Thread Nichehosters
Hi,
I am relatively new to Django, and am trying to update a many-to-many
related table using a ModelForm.
I see fro the documentation that if I use save(commit=False) - which I
do - I need to use save_m2m() after saving the initial form.  I am
using the save_m2m(), but my related table does not get updated.
Any help appreciated.
I am using django V1.3.1 on linux using Postgresql as the db.

Details:

The Model:
class srvorders(models.Model):
client = models.CharField('Client', max_length=200)
server = models.CharField('Server Type', max_length=200)
os = models.CharField('Operating System', max_length=200)
osopts = models.CharField('Operating System Options',
max_length=200, blank=True, null=True)
ordertotal = models.IntegerField()
notes = models.TextField('Notes', blank=True, null=True)
orderdate = models.DateTimeField()
orderIP = models.IPAddressField()
status = models.CharField('Order Status', max_length="20")
srvopts = models.ManyToManyField(srvoptions, blank=True,
null=True)

class Meta:
ordering = ["id"]
verbose_name_plural = "Server Orders"

def __unicode__(self):
return str(self.id)

class Admin:
pass

The ModelForm:
class NewOrderForm(forms.ModelForm):
Server_CHOICES = [('', '-- choose a Server --'), ] + [(s.id,
s.name) for s in products.objects.all()]
OS_CHOICES = [('', '-- choose a Server --'), ] +[(o.id, o.name)
for o in OS.objects.all()]
OPTION_CHOICES = [('', '-- choose a Server --'), ] +[(opt.id,
opt.name) for opt in osoptions.objects.all()]

server=forms.ChoiceField(choices=Server_CHOICES)
os = forms.ChoiceField(choices=OS_CHOICES)
osopts=forms.ChoiceField(choices=OPTION_CHOICES, required=False)
ordertotal=forms.CharField(required=False)
notes=forms.CharField(required=False)

class Meta:
model= srvorders
exclude = ('client', 'orderdate', 'orderIP', 'status')

The View snippet:
if request.method == 'POST':
form = NewOrderForm(request.POST)
if form.is_valid():
new_item = form.save(commit=False)
new_item.client = orderClient
new_item.orderdate = datetime.now()
new_item.orderIP = remote_ip
new_item.status = "Not_Paid"
new_item.save()
form.save_m2m()

Regards,
Leslie

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: object appears twice after filtering by many to many field

2010-12-22 Thread Dan Fairs
> Thanks for the quick replay.
> The problem is the clip duplication, when relaying on clip_set.count()
> and also in the admin site when you see raw duplication after
> filtering , it is not very reasonable :)
> 

Ah, I didn't realise it was in the admin.

It'll still be the same underlying problem - the intermediate JOIN table 
producing too many rows. If you want to 'fix' that, I suspect you'll need to 
write a custom manager for your Clip model, give it a get_query_set() method 
that calls the superclass method with .distinct() on the end.

> 1. in order to change this behavior in the admin site I need to
> manipulate main.py and add distinct() somewhere?

Read up on custom managers and the default manager.

> 2. I read everywhere that distinct() works really slow and you better
> avoid using it.
> 
> what do you say?

Things are not 'slow' or 'fast' in isolation. They are either 'too slow', or 
'fast enough'. Try it, it may be fast enough for you. If it's not, you'll need 
to find a faster solution. In particular, if the resultant filtered set is 
relatively small, then I doubt you'll notice the difference. 

Cheers,
Dan

--
Dan Fairs | dan.fa...@gmail.com | www.fezconsulting.com


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: object appears twice after filtering by many to many field

2010-12-22 Thread tom
Thanks for the quick replay.
The problem is the clip duplication, when relaying on clip_set.count()
and also in the admin site when you see raw duplication after
filtering , it is not very reasonable :)

1. in order to change this behavior in the admin site I need to
manipulate main.py and add distinct() somewhere?
2. I read everywhere that distinct() works really slow and you better
avoid using it.

what do you say?

Thanks again,

On Dec 22, 11:42 am, Dan Fairs  wrote:
> > Hi all!
> > I have 2 models: Clip, Tag.
> > class Clip(models.Model):
> >          name = models.CharField(max_length=80)
> >          tags = models.ManyToManyField(Tag, through = 'TagsToClips')
>
> > class Tag(models.Model):
> >          tagName = models.CharField(max_length=80, unique=True)
>
> > class TagsToClips(models.Model)
> >          clip = models.ForeignKey(Clip)
> >          tag = models.ForeignKey(Tag)
> >          start_frame = models.IntegerField()
> >    duration = models.IntegerField()
>
> Great! Do you actually have a problem then? ;)
>
> Joking aside, and taking a wild stab at what your problem is without any 
> actual code, I'd say the underlying JOIN is producing multiple rows, and you 
> probably need a distinct() call somewhere on your queryset.
>
> Then again, that might not be the problem at all, because you haven't said :)
>
> Cheers,
> Dan
>
> --
> Dan Fairs | dan.fa...@gmail.com |www.fezconsulting.com

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: object appears twice after filtering by many to many field

2010-12-22 Thread Dan Fairs
> Hi all!
> I have 2 models: Clip, Tag.
> class Clip(models.Model):
>  name = models.CharField(max_length=80)
>  tags = models.ManyToManyField(Tag, through = 'TagsToClips')
> 
> class Tag(models.Model):
>  tagName = models.CharField(max_length=80, unique=True)
> 
> class TagsToClips(models.Model)
>  clip = models.ForeignKey(Clip)
>  tag = models.ForeignKey(Tag)
>  start_frame = models.IntegerField()
>duration = models.IntegerField()

Great! Do you actually have a problem then? ;)

Joking aside, and taking a wild stab at what your problem is without any actual 
code, I'd say the underlying JOIN is producing multiple rows, and you probably 
need a distinct() call somewhere on your queryset.

Then again, that might not be the problem at all, because you haven't said :)

Cheers,
Dan

--
Dan Fairs | dan.fa...@gmail.com | www.fezconsulting.com


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



object appears twice after filtering by many to many field

2010-12-22 Thread tom
Hi all!
I have 2 models: Clip, Tag.
class Clip(models.Model):
  name = models.CharField(max_length=80)
  tags = models.ManyToManyField(Tag, through = 'TagsToClips')

class Tag(models.Model):
  tagName = models.CharField(max_length=80, unique=True)

class TagsToClips(models.Model)
  clip = models.ForeignKey(Clip)
  tag = models.ForeignKey(Tag)
  start_frame = models.IntegerField()
  end_frame = models.IntegerField()
  class meta:
  unique_together = ("clip", "tag",
"start_frame","end_frame")

now, assume I have clip named "clip_1", and tag "adult_scene" with
tag.id = 1
if I tag the the same clip twice with the same tag but different
frames (clip has an adult scene from frame 1 to 10 and also from frame
50 to 70 )
now I wnat all clips with adult scenes - I filter:
clip_set = Clip.objects.filter(tags__id__exact = 1)

I get the clip "clip_1" twice! (clip_set.all() =
[,])
I tried to filter in different ways, but didn't succeed.
What am I doing wrong?
Thanks,

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



object appears twice after filtering by many to many field

2010-12-22 Thread tom
Hi all!
I have 2 models: Clip, Tag.
class Clip(models.Model):
  name = models.CharField(max_length=80)
  tags = models.ManyToManyField(Tag, through = 'TagsToClips')

class Tag(models.Model):
  tagName = models.CharField(max_length=80, unique=True)

class TagsToClips(models.Model)
  clip = models.ForeignKey(Clip)
  tag = models.ForeignKey(Tag)
  start_frame = models.IntegerField()
duration = models.IntegerField()

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Editing a many to many field in a save method

2010-11-30 Thread When ideas fail
Hi, I've got the following model and I want it so that each delivery
has a default category of undefined

class Delivery(models.Model):
.
categories = models.ManyToManyField(Category, blank = True, null =
True)
.

Then if other categories are selected undefined is automatically
removed from the delivery's categories.
I thought I would be able to do this using the save method below, but
it doesn't work. If categories are none it doesn't add undefined and
if serveral are selected it doesn't remove undefined.

def save(self):
super(Delivery, self).save()
if self.categories.count() == 0:
undefined = Category.objects.get(name='undefined')
self.categories.add(undefined)
if self.categories.count() > 1:
undefined = Category.objects.get(name='undefined')
for category in self.categories.all():
if category == undefined:
self.categories.remove(undefined)
super(Delivery, self).save()

if i select/deselect them using the admin interface they work fine,
just not the changes i try to make in save. I'd appreciate any help, I
don't know if i've misunderstood something or if its something else.

thanks

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: How to display many-to-many field as a list of text input fields?

2010-09-02 Thread Steve Holden
On 9/2/2010 4:27 PM, adelein wrote:
> When I display the ToolBoxEditForm it uses a multiple select field.
> But what I want is a form that lets the user edit each tool he has in
> the toolbox as a text field. I cant figure out how to do this with the
> many-to-many field.
> 
A many-to-many relationship represents a constraint on the database,
which is therefore reflected by Django as a constraint in the user input.

What would you expect Django to do if the user enters the name of a
tool in your form that doesn't exist?

regards
 Steve

> class Tool(models.Model):
> tool_name = models.CharField(unique=True, max_length=200)
> ..
> 
> class ToolBox(models.Model):
> tools = models.ManyToManyField(Tool,max_length=300)
> 
> class ToolBoxEditForm (ModelForm):
> tools = ???
> class Meta:
>   model = ToolBox
>   exclude  = ('user', 'popularity',)
> 
> I would appreciate any pointers!
> 


-- 
DjangoCon US 2010 September 7-9 http://djangocon.us/

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



How to display many-to-many field as a list of text input fields?

2010-09-02 Thread adelein
When I display the ToolBoxEditForm it uses a multiple select field.
But what I want is a form that lets the user edit each tool he has in
the toolbox as a text field. I cant figure out how to do this with the
many-to-many field.

class Tool(models.Model):
tool_name = models.CharField(unique=True, max_length=200)
..

class ToolBox(models.Model):
tools = models.ManyToManyField(Tool,max_length=300)

class ToolBoxEditForm (ModelForm):
tools = ???
class Meta:
  model = ToolBox
  exclude  = ('user', 'popularity',)

I would appreciate any pointers!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Querying a many-to-many field based on entries' number in the relationship

2010-09-01 Thread Jordon Wii
Hi,
I have a model named 'Period' and a model named 'Schedule'.  They have
a many-to-many relationship.  I need to get all Period's whose
position in the relationship is a certain number (All second periods
in each schedule, for example).

I could use raw SQL to query the m2m database, but is this possible
without raw SQL?


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Initial data in a many to many field

2010-03-25 Thread mjlissner
I wasn't using ProfileForm(instance = userProfile) because I didn't
realize I could. Wow, that makes things easier and neater.

Thanks so much.

On Mar 25, 11:57 am, Nuno Maltez  wrote:
> >On Thu, Mar 25, 2010 at 2:00 AM, mjlissner  wrote:
> > I'll make things more concrete. I have the following in my model
> > (which is made into a ModelForm):
> > class UserProfile(models.Model):
> >    barmembership = models.ManyToManyField(BarMembership,
> >        verbose_name="the bar memberships held by the user",
> >        blank=True,
> >        null=True)
>
> > In my view, I have some code that looks like this:
> >        userProfile = request.user.get_profile()
> >        bar_memberships = userProfile.barmembership.all()
>
> >        profileForm = ProfileForm(
> >        initial = {'barmembership' : [bar_memberships]})
>
> I don't know why you're not using the "instance" argument to populate the form
>
> profileForm = ProfileForm(instance=userProfile)
>
> but you need to give the ModelForm a list of PKs for the many-to-many-field:
>
> bar_memberships = [obj.pk for obj in ob.barmembership.all()]
> profileForm = ProfileForm( initial = {'barmembership' : bar_memberships})
>
> (see the model_to_dict code in django/forms/models.py )
>
> And force the refresh on the browser if it looks like it's not working
> :) (at least FF has a strange
> habit of keeping selections when reloading a form, ignoring the
> initial selected items on the HTML).
>
> hth,
> Nuno

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Initial data in a many to many field

2010-03-25 Thread Nuno Maltez
>On Thu, Mar 25, 2010 at 2:00 AM, mjlissner  wrote:
> I'll make things more concrete. I have the following in my model
> (which is made into a ModelForm):
> class UserProfile(models.Model):
>    barmembership = models.ManyToManyField(BarMembership,
>        verbose_name="the bar memberships held by the user",
>        blank=True,
>        null=True)
>
> In my view, I have some code that looks like this:
>        userProfile = request.user.get_profile()
>        bar_memberships = userProfile.barmembership.all()
>
>        profileForm = ProfileForm(
>        initial = {'barmembership' : [bar_memberships]})


I don't know why you're not using the "instance" argument to populate the form

profileForm = ProfileForm(instance=userProfile)


but you need to give the ModelForm a list of PKs for the many-to-many-field:

bar_memberships = [obj.pk for obj in ob.barmembership.all()]
profileForm = ProfileForm( initial = {'barmembership' : bar_memberships})

(see the model_to_dict code in django/forms/models.py )

And force the refresh on the browser if it looks like it's not working
:) (at least FF has a strange
habit of keeping selections when reloading a form, ignoring the
initial selected items on the HTML).

hth,
Nuno

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Initial data in a many to many field

2010-03-24 Thread mjlissner
I've been struggling with this literally for hours.

I'm trying to use a ModelForm with initial values being set as those
that are already in the DB for a user. This works marvelously for
every field that I have EXCEPT for the one manytomany field I have in
my model. For that one, I can submit the form just fine, but it NEVER
prepopulates with initial data.

I'll make things more concrete. I have the following in my model
(which is made into a ModelForm):
class UserProfile(models.Model):
barmembership = models.ManyToManyField(BarMembership,
verbose_name="the bar memberships held by the user",
blank=True,
null=True)

In my view, I have some code that looks like this:
userProfile = request.user.get_profile()
bar_memberships = userProfile.barmembership.all()

profileForm = ProfileForm(
initial = {'barmembership' : [bar_memberships]})

But I just can't get it to work. Is there something I'm missing here,
or does anybody have any pointers as to what I need to do to make this
work? All my other fields populate properly in this form...but this
one is causing me major headaches.

Thanks.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: sitemap how to publish many to many field?

2009-12-11 Thread Michael
Alright, so I have taken it one step further. In the code below all
the items appear in the sitemap (shops from category prepaid and shops
from the category tv). Next step is to add the productgroup in the
custom sitemap url (see location code). When I try to do this, only
the first item of the slug_list appears in the sitemap. So all shops
get '/tv/' at the end of the url (also the prepaid shops). Somehow the
iteration doesn't work here

Suggestions are welcome.

class ShopsInProductGroup(Sitemap):
changefreq = "daily"
priority = 0.7

slug_list = ['tv', 'prepaid']

def items(self):
list = []
slug_list = self.slug_list
for slug in slug_list:
productgroup = ProductGroup.objects.get(slug=slug)
shops = productgroup.shop_set.all().order_by('shopname')
for shop in shops:
list.append(shop)
return list

def location(self, obj):
slug_list = ['tv', 'prepaid', 'prepaid', 'prepaid', 'prepaid',
'prepaid', 'prepaid', 'prepaid', 'prepaid', 'prepaid']
for pg in slug_list:
return '/aanbiedingen/%s/%s/' % (obj.slug, pg)

On Dec 10, 11:26 pm, Michael  wrote:
> Hi there,
>
> I am playing around with Django's sitemap app and I have a question.
> When I pass a normal query in a sitemap class like Shop.objects.all()
> everything works fine. My problem begins when I try to publish a model
> with a many to many field in it.
>
> When I test this code below in the Python shell everything works as I
> expected. The query returns two lists. The first is a list of shops
> with productgroup 'prepaid' and the second is a list of shops with
> productgroup 'tv'. However, when I save the query in my sitemap.py
> file and run it only the first group appears in my /sitemap.xml page.
>
> class ShopsInProductGroup(Sitemap):
>         changefreq = "daily"
>         priority = 0.7
>
>         slug = ['prepaid', 'tv']
>
>         def items(self):
>                 for item in self.slug:
>                         navigation = ProductGroup.objects.get(slug=item)
>                         shops = navigation.shop_set.all().order_by('shopname')
>                         return shops
>
> I guess I am doing something wrong but I can't figure out what

--

You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




sitemap how to publish many to many field?

2009-12-10 Thread Michael
Hi there,

I am playing around with Django's sitemap app and I have a question.
When I pass a normal query in a sitemap class like Shop.objects.all()
everything works fine. My problem begins when I try to publish a model
with a many to many field in it.

When I test this code below in the Python shell everything works as I
expected. The query returns two lists. The first is a list of shops
with productgroup 'prepaid' and the second is a list of shops with
productgroup 'tv'. However, when I save the query in my sitemap.py
file and run it only the first group appears in my /sitemap.xml page.

class ShopsInProductGroup(Sitemap):
changefreq = "daily"
priority = 0.7

slug = ['prepaid', 'tv']

def items(self):
for item in self.slug:
navigation = ProductGroup.objects.get(slug=item)
shops = navigation.shop_set.all().order_by('shopname')
return shops

I guess I am doing something wrong but I can't figure out what

--

You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Using raw_id_fields with a many-to-many field

2008-10-29 Thread Brian Rosner

On Wed, Oct 29, 2008 at 4:35 PM, AndrewD <[EMAIL PROTECTED]> wrote:
>
> # models.py
> class Membership(models.Model):
> person = models.ForeignKey(Person)
> group = models.ForeignKey(Group)
>
> # admin.py
> class MembershipInline(admin.TabularInline):
> model = Membership
> raw_id_fields = ('person',)
> extra = 1
>
> class PersonAdmin(admin.ModelAdmin):
> # ... add other features
> inlines = (MembershipInline,)
> admin.site.register(Person, PersonAdmin)

The MembershipInline doesn't make much sense. You have put the foreign
key used for the relationship between Membership and Person in a
raw_id_field. In this case it would normally be implied by the
relationship you have setup. Is explicitly putting 'person' in
raw_id_fields intentional, it should rather be 'group' if anything.

> The resulting admin tool generates a separate Membership ID field
> (table row) with a spyglass next to it. Each spyglass sets or replaces
> the single ID in that row.

I presume you are asking a question here? That extra row is
technically a bug in the fact that it should always render it hidden.

-- 
Brian Rosner
http://oebfare.com

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Using raw_id_fields with a many-to-many field

2008-10-29 Thread AndrewD

I have a ManyToMany field that works as a raw_id_fields item. It is an
intermediary ManyToMany model class using the through='ClassName'
feature.

The admin.py shows that ManyToMany model using an Inline admin class.
The Inline class has the raw_id_fields and extras attributes. Here is
an example based on the Admin tool docs...

# models.py
class Membership(models.Model):
 person = models.ForeignKey(Person)
 group = models.ForeignKey(Group)

# admin.py
class MembershipInline(admin.TabularInline):
 model = Membership
 raw_id_fields = ('person',)
 extra = 1

class PersonAdmin(admin.ModelAdmin):
 # ... add other features
 inlines = (MembershipInline,)
admin.site.register(Person, PersonAdmin)

The resulting admin tool generates a separate Membership ID field
(table row) with a spyglass next to it. Each spyglass sets or replaces
the single ID in that row.

The "extra" makes a new open field. Use that to add more entrties,
without deleted the others.

DISCLOSURE
This applies to an intermediary model, with a ForeignKey field, and
the "through" declaration. You may see the bug as described with an
implied "many-to-many table", which is the normal way to do this.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Using raw_id_fields with a many-to-many field

2008-10-10 Thread Karen Tracey
On Thu, Oct 9, 2008 at 5:59 PM, Hancock, David (dhancock) <
[EMAIL PROTECTED]> wrote:

>  I've found that using raw_id_fields saves a lot of time for our users
> over loading an entire many-to-many select. (But for shorter lists, the
> many-to-many widget is by far the best interface I've seen for multiple
> selections.)
>
> There's an aspect of the raw_id_fields (this is in the admin interface)
> that is unsettling to the users, though. On a normal foreign-key
> relationship, it works great. But here's a scenario where it's not so good
> for the many-to-many relationship. A trip leg can have several travelers. If
> you open that leg to add a traveler, you see the list of IDs and a little
> magnifying glass. Click the glass to add another traveler, click the one one
> you, and it's added to the list. If you click the magnifying glass,
> determine that you need to add a NEW traveler from that index list, and then
> save the traveler, it's populated back on the original leg page as the sole
> ID in the travelers field. (That is, all the IDs previously in that field
> are overwritten.)
>
> This seems like a bug to me, but if someone can set me straight on how it
> should work, I'd be grateful.
>

It sounds like a bug to me and worth a ticket so it's not forgotten,
assuming a search of the tracker doesn't reveal any similar reports.  Sample
(simple) models with a detailed recreation recipe are always appreciated in
tickets.

Karen

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Using raw_id_fields with a many-to-many field

2008-10-09 Thread Hancock, David (dhancock)
I've found that using raw_id_fields saves a lot of time for our users over
loading an entire many-to-many select. (But for shorter lists, the
many-to-many widget is by far the best interface I've seen for multiple
selections.)

There's an aspect of the raw_id_fields (this is in the admin interface) that
is unsettling to the users, though. On a normal foreign-key relationship, it
works great. But here's a scenario where it's not so good for the
many-to-many relationship. A trip leg can have several travelers. If you
open that leg to add a traveler, you see the list of IDs and a little
magnifying glass. Click the glass to add another traveler, click the one one
you, and it's added to the list. If you click the magnifying glass,
determine that you need to add a NEW traveler from that index list, and then
save the traveler, it's populated back on the original leg page as the sole
ID in the travelers field. (That is, all the IDs previously in that field
are overwritten.)

This seems like a bug to me, but if someone can set me straight on how it
should work, I'd be grateful.

Thanks, and
Cheers!
-- 
David Hancock | [EMAIL PROTECTED]


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: how to add more information in a model with a many-to-many field to itself, and 'symmetrical=True'

2008-10-06 Thread Karen Tracey
Answered on the other thread started with the same question.

Karen

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



how to add more information in a model with a many-to-many field to itself, and 'symmetrical=True'

2008-10-06 Thread Matrixer

in django, it's not allowed to create an intermediary model, when
'symmetrical' is set to True in this kind of many-to-many
relationship, then how to add more information for the relationship,
is there any good solutions for this, or do I have to use the
unsymemtrical one instead and do some extra work for it.

any replies will be appreciated
Matrixer
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Getting specific data from a many to many field.

2008-09-16 Thread Daniel Roseman

On Sep 16, 4:16 pm, "Lance F. Squire" <[EMAIL PROTECTED]> wrote:
> On Sep 16, 2:30 am, Daniel Roseman <[EMAIL PROTECTED]>
> wrote:
> > try:
> >     return
> > self.system_pictures.filter(image_category__name='Header_Pic')[0]
> > except IndexError:
> >     pass
>
> > which will always get the first related image in that category, and
> > silently swallows the error that's thrown if there's no such picture.
>
> Can't seem to get the 'except IndexError:' line to pass syntax.
>
> However, it works fine without. Just have to be sure images are
> there. :)

As R Gorman says, indentation is probably the problem. Try this:

try:
return self.system_pictures.filter(
image_category__name='Header_Pic'
)[0]
except IndexError:
pass

--
DR.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Getting specific data from a many to many field.

2008-09-16 Thread R. Gorman


>
> > try:
> >     return
> > self.system_pictures.filter(image_category__name='Header_Pic')[0]
> > except IndexError:
> >     pass
>

Make sure you have the indentation set correctly.  The second and
third line of the posted code should actually be one line.  I think
the formatting was changed when Daniel posted the code.

R.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Getting specific data from a many to many field.

2008-09-16 Thread R. Gorman

> > try:
> >     return
> > self.system_pictures.filter(image_category__name='Header_Pic')[0]
> > except IndexError:
> >     pass
>
> > which will always get the first related image in that category, and
> > silently swallows the error that's thrown if there's no such picture.
>
> Can't seem to get the 'except IndexError:' line to pass syntax.
>
> However, it works fine without. Just have to be sure images are
> there. :)
>

It might be an indentation issue:

try:
  return
self.system_pictures.filter(image_category__name='Header_Pic')[0]
except IndexError:
  pass

R.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Getting specific data from a many to many field.

2008-09-16 Thread Lance F. Squire



On Sep 16, 2:30 am, Daniel Roseman <[EMAIL PROTECTED]>
wrote:
>
> Sorry, my mistake. filter() always gives you a queryset - because
> there might be more than one instance of the related model that fits
> the criteria - so you can't jut reference the location/width directly.
> The best way is to do something like this:
>
> try:
> return
> self.system_pictures.filter(image_category__name='Header_Pic')[0]
> except IndexError:
> pass
>
> which will always get the first related image in that category, and
> silently swallows the error that's thrown if there's no such picture.
>

Can't seem to get the 'except IndexError:' line to pass syntax.

However, it works fine without. Just have to be sure images are
there. :)

> By the way, I would recommend playing around in the shell (./manage.py
> shell) with this - you'll get a much better feel for how it all fits
> together.

Had done some of that, but just couldn't figure this one out!

Again Much Thanks!

Lance

P.S.
I am really enjoying Django much more than Rails.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Getting specific data from a many to many field.

2008-09-15 Thread Daniel Roseman

On Sep 16, 2:30 am, "Lance F. Squire" <[EMAIL PROTECTED]> wrote:
> On Sep 15, 5:21 pm, Daniel Roseman <[EMAIL PROTECTED]>
> wrote:
>
> > Probably the easiest solution, if you know you're
> > always going to be requesting a certain lookup, is to define a custom
> > method on the model:
>
> > class System(models.Model):
> >     ... field declarations ...
>
> >     def get_header_pic(self):
> >         return
> > self.system_pictures.filter(image_category__name='Header_Pic')
>
> > and then in the template you can just do {{ info.get_header_pic }}
>
> As there can be 20 or more images associated with a system, This is
> more what I was looking for. Thanks!!!
>
> However, I can't seem to get this to work.
>
> Here are the new lines in System:
>
>         def get_header_pic(self):
>             return
> self.system_pictures.filter(image_category__name='Header_Pic')
>
>         def get_header_logo(self):
>             return
> self.system_pictures.filter(image_category__name='Header_Logo')
>
> I put them just above the Class Admin: line.
>
> Here is the new lines in the template:
>
>      width="{{ info.get_header_pic.width }}"
> height="{{ info.get_header_pic.height }}" border="0"
> name="{{ info.get_header_pic.name }}">
>
>      width="{{ info.get_header_logo.width }}"
> height="{{ info.get_header_logo.height }}" border="0"
> name="{{ info.get_header_logo.name }}">
>
> Lance

Sorry, my mistake. filter() always gives you a queryset - because
there might be more than one instance of the related model that fits
the criteria - so you can't jut reference the location/width directly.
The best way is to do something like this:

try:
return
self.system_pictures.filter(image_category__name='Header_Pic')[0]
except IndexError:
pass

which will always get the first related image in that category, and
silently swallows the error that's thrown if there's no such picture.

By the way, I would recommend playing around in the shell (./manage.py
shell) with this - you'll get a much better feel for how it all fits
together.
-
DR.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Getting specific data from a many to many field.

2008-09-15 Thread Lance F. Squire



On Sep 15, 5:21 pm, Daniel Roseman <[EMAIL PROTECTED]>
wrote:

> Probably the easiest solution, if you know you're
> always going to be requesting a certain lookup, is to define a custom
> method on the model:
>
> class System(models.Model):
> ... field declarations ...
>
> def get_header_pic(self):
> return
> self.system_pictures.filter(image_category__name='Header_Pic')
>
> and then in the template you can just do {{ info.get_header_pic }}


As there can be 20 or more images associated with a system, This is
more what I was looking for. Thanks!!!

However, I can't seem to get this to work.

Here are the new lines in System:

def get_header_pic(self):
return
self.system_pictures.filter(image_category__name='Header_Pic')

def get_header_logo(self):
return
self.system_pictures.filter(image_category__name='Header_Logo')

I put them just above the Class Admin: line.

Here is the new lines in the template:





Lance
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Getting specific data from a many to many field.

2008-09-15 Thread Daniel Roseman

On Sep 15, 9:25 pm, "Lance F. Squire" <[EMAIL PROTECTED]> wrote:
> On Sep 15, 4:13 pm, Daniel Roseman <[EMAIL PROTECTED]>
> wrote:
>
> > So, putting that all together:
>
> > {% for pic in info.system_pictures.all %}
> >     {% ifequal pic.image_category.name 'Header_Pic' %}
> >         
> >     {% endifequal %}
> > {% endfor %}
>
> Sweet! That works.
> Thanks!
>
> I'll try to remember that.
>
> However, Is there a way I can pull just the specific pictures, rather
> than iterating through all possible images?
>
> Lance

That's what this does: gives you all images that are related to the
instance of System (ie 'info') that you passed. It doesn't give you
all images in the database.

If you need to filter it further, you can do it in the view by using
eg info.system_pictures.filter(height__gte=50) to give you all related
images that have a height greater than 50. Or, probably more useful,
info.system_pictures.filter(image_category__name='Header_Pic') to give
you only the related images with category Header_Pic (note the double
underscores in these lookups).

However, you can't do this directly in the template, as it requires
passing arguments to a function call, and Django's template language
doesn't allow that. Probably the easiest solution, if you know you're
always going to be requesting a certain lookup, is to define a custom
method on the model:

class System(models.Model):
... field declarations ...

def get_header_pic(self):
return
self.system_pictures.filter(image_category__name='Header_Pic')

and then in the template you can just do {{ info.get_header_pic }}

--
DR.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Getting specific data from a many to many field.

2008-09-15 Thread Lance F. Squire



On Sep 15, 4:13 pm, Daniel Roseman <[EMAIL PROTECTED]>
wrote:
> So, putting that all together:
>
> {% for pic in info.system_pictures.all %}
> {% ifequal pic.image_category.name 'Header_Pic' %}
> 
> {% endifequal %}
> {% endfor %}
>

Sweet! That works.
Thanks!

I'll try to remember that.

However, Is there a way I can pull just the specific pictures, rather
than iterating through all possible images?

Lance
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Getting specific data from a many to many field.

2008-09-15 Thread Daniel Roseman

On Sep 15, 8:50 pm, "Lance F. Squire" <[EMAIL PROTECTED]> wrote:
> Using Fedora 8, Django  version 0.96.3
>
> I'm currently trying to pull two specific images from a list of images
> associated with a model.
>
> Currently the Models are like this:
>
> class ImageCat(models.Model):
>     name = models.CharField(maxlength=80)
>
> class Image(models.Model):
>         name = models.CharField(maxlength=80)
>         location = models.URLField()
>         height = models.IntegerField()
>         width = models.IntegerField()
>         image_category = models.ForeignKey('ImageCat')
>
> class System(models.Model):
>         manufacturer = models.ForeignKey('Manufacturer')
>         name = models.CharField(maxlength=80)
>         slug = models.SlugField(prepopulate_from=['name'])
> ... other stuff...
>         system_pictures = models.ManyToManyField('Image')
>
> ImageCat is just a name list, as I may need to add categories in the
> future.
>
> Image doesn't use ImageField as I'm manually uploading the images to
> another server and didn't want to deal with the extra stuff (uploading
> etc)
>
> I'm currently trying to pull 2 images of specific category types in
> the template. Unfortunately, I can't quite grasp how to do this...
> Or weather it would be better to pull them in the View before hand
>
> I'm currently passing the System fields to the template as 'info'.
>
> I've been trying things like 'info.Image.location' but can't figure
> how to specify the category.
>
> Also tried:
>
> {% for pic in info.Image %}
>     {% ifequal pic.image_category 'Header_Pic' %}
>         
>     {% endifequal %}
> {% endfor %}
>
> But that gets me nothing.
>
> Where am I going wrong?
>
> Lance

The model field that relates System to Image is called
system_pictures, so you need to use that rather than the name of the
Image model. system_pictures gives you a Manager, so you need to call
all() on it (although you omit the brackets since you're in a
template). Finally, image_category will give you a model, not a
string, so you need to refer directly to the name field if you want to
compare it with a string.

So, putting that all together:

{% for pic in info.system_pictures.all %}
{% ifequal pic.image_category.name 'Header_Pic' %}

{% endifequal %}
{% endfor %}

--
DR.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Getting specific data from a many to many field.

2008-09-15 Thread Lance F. Squire

Using Fedora 8, Django  version 0.96.3

I'm currently trying to pull two specific images from a list of images
associated with a model.

Currently the Models are like this:

class ImageCat(models.Model):
name = models.CharField(maxlength=80)

class Image(models.Model):
name = models.CharField(maxlength=80)
location = models.URLField()
height = models.IntegerField()
width = models.IntegerField()
image_category = models.ForeignKey('ImageCat')

class System(models.Model):
manufacturer = models.ForeignKey('Manufacturer')
name = models.CharField(maxlength=80)
slug = models.SlugField(prepopulate_from=['name'])
... other stuff...
system_pictures = models.ManyToManyField('Image')

ImageCat is just a name list, as I may need to add categories in the
future.

Image doesn't use ImageField as I'm manually uploading the images to
another server and didn't want to deal with the extra stuff (uploading
etc)

I'm currently trying to pull 2 images of specific category types in
the template. Unfortunately, I can't quite grasp how to do this...
Or weather it would be better to pull them in the View before hand

I'm currently passing the System fields to the template as 'info'.

I've been trying things like 'info.Image.location' but can't figure
how to specify the category.

Also tried:

{% for pic in info.Image %}
{% ifequal pic.image_category 'Header_Pic' %}

{% endifequal %}
{% endfor %}

But that gets me nothing.

Where am I going wrong?

Lance
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Many to Many field Assignment

2008-08-31 Thread Vadivel Kumar
i see that there exists a handy way -- *icontains* does exactly what iam
looking at

On Sun, Aug 31, 2008 at 9:35 PM, Vadivel Kumar <[EMAIL PROTECTED]> wrote:

>  Thanks Michael,
>
> I solved the problem - i had a silly mistake in the way how i handled  to
> check the existing tag. But, now the problem is when i check the given tag
> text against the database, i do it as like below,
>
>newTag = request.POST['tag']
>existingTag = Tags.objects.filter(TagName__exact=newTag)
>
> Now, I wanted to check it more perfectly, I want to check with
> case-insensitve etc., I am not seeing any appropriate django method to do
> this, may be i should check the documentation.
>
> Thanks for your quick help.
>

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Many to Many field Assignment

2008-08-31 Thread Vadivel Kumar
Thanks Michael,

I solved the problem - i had a silly mistake in the way how i handled  to
check the existing tag. But, now the problem is when i check the given tag
text against the database, i do it as like below,

   newTag = request.POST['tag']
   existingTag = Tags.objects.filter(TagName__exact=newTag)

Now, I wanted to check it more perfectly, I want to check with
case-insensitve etc., I am not seeing any appropriate django method to do
this, may be i should check the documentation.

Thanks for your quick help.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Many to Many field Assignment

2008-08-31 Thread Michael Newman

On Aug 31, 11:14 am, "Vadivel Kumar" <[EMAIL PROTECTED]> wrote:
> I know this might sound very newbie .. its true
>
> How can i assign an exising record of the child table to an parent record.
> For example I have two models,
>
>     class User (models.Model):
>          ... all other fields ...
>         Tags  = models.ManyToManyField(Tag)
>
>      class Tag (models.Mode):
>          .. all fields ..
>
> The problem i am facing is whenever i create a new user and add an existing
> tag object to User.Tags.add() method it creates a new record in Tag table
> instead i need to just map the record with the new user.
>
> I know am missing a paramount thing .. what is that ?

The methods you are using, if I understand you correctly, should work.
I would need to take a look at the exact code that is creating a new
object to help you out. But one thing you can look at is
http://www.djangoproject.com/documentation/models/many_to_many/  . It
is very helpful at showing how the manytomanyfields work. If you are
still having an issue, post the offending code to dpaste.com and we
can take a look.

Thanks,
Michael
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Many to Many field Assignment

2008-08-31 Thread Vadivel Kumar
I know this might sound very newbie .. its true

How can i assign an exising record of the child table to an parent record.
For example I have two models,

class User (models.Model):
 ... all other fields ...
Tags  = models.ManyToManyField(Tag)

 class Tag (models.Mode):
 .. all fields ..

The problem i am facing is whenever i create a new user and add an existing
tag object to User.Tags.add() method it creates a new record in Tag table
instead i need to just map the record with the new user.

I know am missing a paramount thing .. what is that ?

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: list_display a Many to Many field

2008-07-10 Thread [EMAIL PROTECTED]

No, authors is the related manager, so it's all method returns a
QuerySet with all the relevant items.

On Jul 10, 8:25 am, Fernando Rodríguez <[EMAIL PROTECTED]> wrote:
> El mié, 09-07-2008 a las 06:40 -0700, urukay escribió:
>
>
>
> > this should work:
>
> > def get_authors(self):
> >     return self.authors.all()
>
> Thanks Radovan. Shouldn't it be self.authors.objects.all()?
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: list_display a Many to Many field

2008-07-10 Thread Fernando Rodríguez

El mié, 09-07-2008 a las 06:40 -0700, urukay escribió:
> 
> this should work:
> 
> def get_authors(self):
> return self.authors.all()


Thanks Radovan. Shouldn't it be self.authors.objects.all()?



--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: list_display a Many to Many field

2008-07-09 Thread urukay


this should work:

def get_authors(self):
return self.authors.all()

list_display = ('title', 'Publisher', 'publicationDate',
'get_authors' )

Radovan


Fernando Rodríguez wrote:
> 
> 
> Hi,
> 
> I'm trying to display a many to many field in the admin interface.
> 
> This is my model:
> 
> class Book(models.Model):
> title = models.CharField(maxlength = 100, db_index = True)
> authors = models.ManyToManyField(Author)
> Publisher = models.ForeignKey(Publisher)
> publicationDate = models.DateField()
> 
> class Admin: 
> list_display = ('title', 'Publisher', 'publicationDate',
> 'authors' )
> list_filter = ('Publisher', 'publicationDate') 
> search_fields = ('title')
> 
> def __str__(self):
> return self.title
> 
> In the authors column, instead of the author's name(s), I get what seems
> to be the __str__ of an object:
> 
> 
> How can I get this ManyRelatedManager to display what I want? O:-)
> 
> Thanks!
> 
> 
> 
> > 
> 
> 

-- 
View this message in context: 
http://www.nabble.com/list_display-a-Many-to-Many-field-tp18361728p18361891.html
Sent from the django-users mailing list archive at Nabble.com.


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



list_display a Many to Many field

2008-07-09 Thread Fernando Rodríguez

Hi,

I'm trying to display a many to many field in the admin interface.

This is my model:

class Book(models.Model):
title = models.CharField(maxlength = 100, db_index = True)
authors = models.ManyToManyField(Author)
Publisher = models.ForeignKey(Publisher)
publicationDate = models.DateField()

class Admin: 
list_display = ('title', 'Publisher', 'publicationDate',
'authors' )
list_filter = ('Publisher', 'publicationDate') 
search_fields = ('title')

def __str__(self):
return self.title

In the authors column, instead of the author's name(s), I get what seems
to be the __str__ of an object:


How can I get this ManyRelatedManager to display what I want? O:-)

Thanks!



--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: many to many field

2008-06-25 Thread Stephan Jäkel

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

'cause the current patch in the ticket doesnt seem to work perfect until
now, i created a small hack

http://steph.rdev.info/devel/m2m_custom_columnnames-r7732.patch

example:

class Article(models.Model):
categories = models.ManyToManyField(
'Category',
db_table='articles_has_categories',
db_n_field='articles_idarticles',
db_m_field='categories_id',
filter_interface=models.HORIZONTAL
)

db_n_field is the column name for the Article Model in the db_table,
db_m_field is the column name for the Category Model in the db_table.

Have fun..

Best regards,

Stephan Jäkel wrote:
| thanks for the advice. great stuff. i'll follow the ticket.
|
| best regards,
|
| Ramiro Morales wrote:
| | On Tue, Jun 24, 2008 at 3:40 PM, Stephan Jäkel <[EMAIL PROTECTED]> wrote:
| |> -BEGIN PGP SIGNED MESSAGE-
| |> Hash: SHA1
| |>
| |> OK. I hoped, there is a possibility to use ManyToManyField. Well, the
| |> Model-way is already implemented but i would like to use
| |> ManyToManyField. Anyway, it works.
| |>
| |
| | If you are using Django from SVN trunk and willing to patch and test
| | code, you might
| | be interested in taking a look at ticket [1]6095 and helping with the
| | testing of the
| | most recent patch attached to it.
| |
| | Regards,
| |
|

- 


- --
Stephan Jäkel

e-Mail  : [EMAIL PROTECTED]
Website : http://rdev.info
Mobile  : +49 163 458 9 173

What do you mean that could take down the whole network?
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFIYgJH4B/i3Mb6qe4RAhtdAJ9BZNOi1NJ27T5jsNtPZUiVpwatdQCgmlnn
g29bRDOr/X4pG1CG0bWsq5w=
=urku
-END PGP SIGNATURE-

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: many to many field

2008-06-24 Thread Stephan Jäkel

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

thanks for the advice. great stuff. i'll follow the ticket.

best regards,

Ramiro Morales wrote:
| On Tue, Jun 24, 2008 at 3:40 PM, Stephan Jäkel <[EMAIL PROTECTED]> wrote:
|> -BEGIN PGP SIGNED MESSAGE-
|> Hash: SHA1
|>
|> OK. I hoped, there is a possibility to use ManyToManyField. Well, the
|> Model-way is already implemented but i would like to use
|> ManyToManyField. Anyway, it works.
|>
|
| If you are using Django from SVN trunk and willing to patch and test
| code, you might
| be interested in taking a look at ticket [1]6095 and helping with the
| testing of the
| most recent patch attached to it.
|
| Regards,
|

- --
Stephan Jäkel

e-Mail  : [EMAIL PROTECTED]
Website : http://rdev.info
Mobile  : +49 163 458 9 173

What do you mean that could take down the whole network?
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFIYcYb4B/i3Mb6qe4RAhVtAJ4izg7WxoHBpXKB2LgCCWJbkZMAAQCg41qj
iU8/cUkgI5+JLSilFd3sOGI=
=PuED
-END PGP SIGNATURE-

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: many to many field

2008-06-24 Thread Ramiro Morales

On Tue, Jun 24, 2008 at 3:40 PM, Stephan Jäkel <[EMAIL PROTECTED]> wrote:
>
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> OK. I hoped, there is a possibility to use ManyToManyField. Well, the
> Model-way is already implemented but i would like to use
> ManyToManyField. Anyway, it works.
>

If you are using Django from SVN trunk and willing to patch and test
code, you might
be interested in taking a look at ticket [1]6095 and helping with the
testing of the
most recent patch attached to it.

Regards,

-- 
 Ramiro Morales

1. http://code.djangoproject.com/ticket/6095

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: many to many field

2008-06-24 Thread Stephan Jäkel

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

OK. I hoped, there is a possibility to use ManyToManyField. Well, the
Model-way is already implemented but i would like to use
ManyToManyField. Anyway, it works.

joshuajonah wrote:
| You need to define your many-to-many table in the model, and then use
| the "db_column" option to name the fields in that table.
|
| http://www.djangoproject.com/documentation/models/custom_columns/
|
| On Jun 24, 1:43 pm, Stephan Jäkel <[EMAIL PROTECTED]> wrote:
| hi,
|
| joshuajonah wrote:
|
| | You should use the 'db_table' option for any given model. This will
| | allow you to use a specific table name and it also works on many-to-
| | many relational tables if you define them specifically in your
| | models.py.
|
| yes, db_table helps do define the many-to-many table. but i also need to
| define the field-names in the many-to-many table, because they dont
| match the names generated by the many-to-many related manager (and i
| cant rename them).
|
| |
| | You can get the info on them (scattered everywhere) in this doc:
| |http://www.djangoproject.com/documentation/model-api/
| |
| | Does that help?
|
| a bit, but thanks anyway :-)
|
| |
| | On Jun 24, 12:41 pm, Stephan Jäkel <[EMAIL PROTECTED]> wrote:
| | Hi list,
| |
| | i'm currently implementing django as management interface for an
| | existing project. until now, nearly everything worked as expected,
| | but i've got a problem.
| |
| | is there a way to override the join_table, source_col_name and
| | target_col_name in many-to-many relations. as i read django's source i
| | think these properties define the names used in the database.
| | and i cant change the database schema without getting many problems.
| |
| | is there another way to solve this problem excluding the possibility to
| | create a database view to map the tablename and columns?
| |
| | best regards,
|
| 
- --
Stephan Jäkel

e-Mail  : [EMAIL PROTECTED]
Website : http://rdev.info
Mobile  : +49 163 458 9 173

What do you mean that could take down the whole network?
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFIYT+y4B/i3Mb6qe4RAgjqAJ93PoRas8LKnG5Fyg1TD0/BhVaLTACfSSi/
q6awo8ahMK2xNU/2Ig5jf6Q=
=mjII
-END PGP SIGNATURE-

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: many to many field

2008-06-24 Thread joshuajonah

You need to define your many-to-many table in the model, and then use
the "db_column" option to name the fields in that table.

http://www.djangoproject.com/documentation/models/custom_columns/

On Jun 24, 1:43 pm, Stephan Jäkel <[EMAIL PROTECTED]> wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> hi,
>
> joshuajonah wrote:
>
> | You should use the 'db_table' option for any given model. This will
> | allow you to use a specific table name and it also works on many-to-
> | many relational tables if you define them specifically in your
> | models.py.
>
> yes, db_table helps do define the many-to-many table. but i also need to
> define the field-names in the many-to-many table, because they dont
> match the names generated by the many-to-many related manager (and i
> cant rename them).
>
> |
> | You can get the info on them (scattered everywhere) in this doc:
> |http://www.djangoproject.com/documentation/model-api/
> |
> | Does that help?
>
> a bit, but thanks anyway :-)
>
> |
> | On Jun 24, 12:41 pm, Stephan Jäkel <[EMAIL PROTECTED]> wrote:
> | Hi list,
> |
> | i'm currently implementing django as management interface for an
> | existing project. until now, nearly everything worked as expected,
> | but i've got a problem.
> |
> | is there a way to override the join_table, source_col_name and
> | target_col_name in many-to-many relations. as i read django's source i
> | think these properties define the names used in the database.
> | and i cant change the database schema without getting many problems.
> |
> | is there another way to solve this problem excluding the possibility to
> | create a database view to map the tablename and columns?
> |
> | best regards,
>
> - --
> Stephan Jäkel
>
> e-Mail  : [EMAIL PROTECTED]
> Website :http://rdev.info
> Mobile  : +49 163 458 9 173
>
> What do you mean that could take down the whole network?
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v1.4.6 (GNU/Linux)
> Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org
>
> iD8DBQFIYTI14B/i3Mb6qe4RAgFKAJ94ElQ5fKeeRdIz2c8ug1q+hup4EACfXlfz
> cGh5ZOVLhxUb4e3Fy0KSSGc=
> =Rj1H
> -END PGP SIGNATURE-
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



  1   2   >