Sunday, February 28, 2021

How add raw query in a Model

this is query:
```
sub_query = PaymentDetails.objects.filter(order=OuterRef('pk')).order_by('-updated_at')[:1]
payment_summary = """select jsonb_build_object(
'total_paid_amount', coalesce(sum(amount), 0),
'total_due_amount', CASE WHEN (order_order.total_gross - coalesce(sum(amount), 0)) > 0.02 then (order_order.total_gross - coalesce(sum(amount), 0)) else 0 end,
'is_full_paid', coalesce(sum(amount), 0) > 0 and (order_order.total_gross - coalesce(sum(amount), 0)) <= 0.02 and order_order.is_payment_completed,
'total_customer_payable_amount', CASE WHEN (coalesce(sum(amount), 0) - order_order.total_gross) > 0.02 then coalesce(sum(amount), 0) - order_order.total_gross else 0 end
)
from payment_paymentdetails
where payment_paymentdetails.order_id = order_order.id
and payment_paymentdetails.status = %s"""

orders = Order.objects.prefetch_related(
'lines',
'lines__qc',
'lines__variant__product__vendor_user',
'lines__variant__product',
'lines__variant',
'lines__variant__product__vendor_user__vendor_details',
'lines__tickets', 'lines__lines', 'lines__lines__pickup_req'
).select_related('shipping_address').annotate(
payment_updated_at=Subquery(sub_query.values('transaction_date_time'))) \
.annotate(payment_summary=RawSQL(payment_summary, (PaymentStatus.CONFIRMED,))) \
.annotate(payment_method=Subquery(sub_query.values('method'))).order_by('-payment_updated_at').distinct()

if 'status' in request.GET or 'id' in request.GET:
status_list = request.GET.getlist('status')
order_list = request.GET.getlist('id')
if len(status_list) > 0 or len(order_list) > 0:
orders = orders.filter(
Q(status__in=status_list)
| Q(id__in=order_list),
Q(payment_details__status__in=[PaymentStatus.PAY_LATER, PaymentStatus.CONFIRMED])
)
else:
orders = orders.filter(
Q(status=OrderStatus.UNFULFILLED),
Q(payment_details__status__in=[PaymentStatus.PAY_LATER, PaymentStatus.CONFIRMED])
)
```
Now add I raw query with Order model like this 
```
AND
(lower("account_user"."email") similar to '%(sara|aa)%' OR lower("account_vendordetails"."company_name") similar to '%(sara|aa)%' OR
lower(order_orderline.data->>'host') similar to '%(sara|aa)%'
))
```

when I filter with vendor name, then added this query like this
```
if vendor_name:
vendor_name = "".join(vendor_name).replace(', ', ',').replace(',', '|')
print("vendor name============>", vendor_name)
vendor_sub_query = f""" and (lower("account_user"."email") similar to '%({vendor_name})%' OR lower("account_vendordetails"."company_name") similar to '%({vendor_name})%' OR
lower(order_orderline.data->>'host') similar to '%({vendor_name})%'
)"""
orders = orders.raw(vendor_sub_query)
```

but I found this error "'RawQuerySet' object has no attribute 'qs'
"

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/556111a0-117d-499c-b548-01e0459e0ffdn%40googlegroups.com.

Urgent

How to make delete request to API from the frontend, i typed the localhost URL for API but it is redirecting me to the browsable API but by the postman, the data is successfully deleted, please someone help me 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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b624e4d3-b0a1-4b90-91eb-552deaa50d28n%40googlegroups.com.

Re: Log out all sessions for current user logged in

New code for logging out all sessions of logged in users.

```
# Logout all devices in account security page.
def logoff_all(request):
try:
# Filtering all session objects.
session_query = Session.objects.all()

# Iterating session_query and fetching session key.
for s in session_query:
# Decoding session key and getting id from that.
var_id = s.get_decoded().get('id')
# Converting string to int data type.
var_id_user = int(var_id)
# Id from decode and logged in session id is same then
# delete that session key from Session table from database.
if var_id_user == request.session.get('id'):
s.flush()
messages.success(request, "All sessions are logged off successfully.")
return HttpResponseRedirect("/home")
except Exception as e:
logging.error(e)
print(e)
return HttpResponseRedirect("/home")
```
**Error**
```
'Session' object has no attribute 'flush'
```

On Sat, Feb 27, 2021 at 7:45 PM Ryan Nowakowski <tubaman@fattuba.com> wrote:
Please reply with your new code and copy and paste the exact error message with full traceback.

On February 26, 2021 6:40:28 PM CST, Salima Begum <salima.b@rohteksolutions.com> wrote:
Yes. I have tried that no it is not working and giving error like "Query object doesn't contain flush()"

On Sat, 27 Feb 2021, 12:35 am Ryan Nowakowski, <tubaman@fattuba.com> wrote:
Have your tried my suggestion below? Did it work?

On February 25, 2021 9:42:55 PM CST, Salima Begum <salima.b@rohteksolutions.com> wrote:
Logout all sessions belong to logged in user Can you please how can I achieve this?

Thanks
~salima

On Fri, Feb 26, 2021 at 4:56 AM Ryan Nowakowski <tubaman@fattuba.com> wrote:
On Wed, Feb 17, 2021 at 08:23:08AM +0530, Salima Begum wrote:
> Logout all sessions based on current user id and clear django sessions
> table based on user id. It is logging off all sessions.
>
> ```
> # Logout all devices in account security page.
> def logoff_all(request):
>     try:
>
>         # Filtering all session objects.
>         session_query = Session.objects.all()
>
>         # Iterating session_query and fetching session key.
>         for s in session_query:
>             # Decoding session key and getting id from that.
>             var_id = s.get_decoded().get('id')
>             # Converting string to int data type.
>             var_id_user = int(var_id)
>             # Id from decode and logged in session id is same then
>             # delete that session key from Session table from database.
>             if var_id_user == request.session.get('id'):
>                 s.delete()
>         messages.success(request, "All sessions are logged off
> successfully.")
>         return HttpResponseRedirect("/home")
>     except Exception as e:
>         logging.error(e)
>         print(e)
>     return HttpResponseRedirect("/home")
> ```

I would call s.flush() instead of s.delete().  That's what Django's
normal logout function does[1].

[1] https://github.com/django/django/blob/a948d9df394aafded78d72b1daa785a0abfeab48/django/contrib/auth/__init__.py#L149

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20210225232524.GG19963%40fattuba.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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/A440B5D5-3000-4004-9093-0F685D23BAD2%40fattuba.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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4EFB4A20-91CC-4CE0-B810-90C0694BF497%40fattuba.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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAMSz6bmaD7%3DxBKHHUY%2BJ_HfxrzEVAvg0Jeo%2BZxUscbkZmSgKvA%40mail.gmail.com.

save() in a loop. (Data Migrations example).


I'm wondering about this code snippet from the documentation

for person in Person.objects.all():
    person.name = '%s %s' % (person.first_name, person.last_name)
    person.save()

This looks like the N+1 Query problem but maybe I'm wrong. I usually avoid this kind of code in my projects.
How many times does this hit the database?
Does the fact that it's in a migration (therefore a transaction) change anything?

Perhaps, the better way would be to do

Person.objects.update(name=Concat(F('first_name'), Value(' '), F('last_name')))

What's the correct way?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ab38497b-be1d-42a7-bbcf-75055dd95856n%40googlegroups.com.

Re: Conseil et Guide

mr jean michel  selon moi django est pour le web devellopement en utilisant python pour rendre facile quelque task et d n est pas repeter les codes ecrit  beaucoup des fois
thank you

On Sun, Feb 28, 2021 at 6:33 PM Michel Mahomy <michelmahomy@gmail.com> wrote:
Bonjour M./M.., je suis Michel MAHOMY développeur débutant en Django.
Je voudrais savoir est-ce possible de faire de l'intelligence artificielle en Django ?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/cb021f3e-8c55-4e46-bcb6-9dbb8e0bc2c9n%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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAJCm56JSU1%3DBzNNdfWbOxfd%2BwyO_CCjzJEpK9ZS5xXih9RviHQ%40mail.gmail.com.

Re: template is not visible properliy

On 28/02/2021 12.53, Sky Lord wrote:
> Hello am new noob, anyone guide or take me as student?
>

Start by learning how to create a new post instead of just doing random
responses to unrelated threads.

Assuming you're using Google groups, this should be a start:

https://support.google.com/groups/answer/1046523?hl=en

Pay attention to the "Start a new conversation" part.

Learning basics like that will most likely improve that chances of
someone being willing to guide you or take you as a student, although
you should probably clarify what you mean by that.

Kind regards,

Kasper Laudrup

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f9eb3e8d-cbfd-a0fc-537f-b494878c5c62%40stacktrace.dk.

Conseil et Guide

Bonjour M./M.., je suis Michel MAHOMY développeur débutant en Django.
Je voudrais savoir est-ce possible de faire de l'intelligence artificielle en Django ?

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

Re: template is not visible properliy

Hello am new noob, anyone guide or take me as student?

On Sun, Feb 28, 2021, 6:02 AM Mr. X Offencer <mr.xoffencer@gmail.com> wrote:
Bro show me your file structure.

On Sun, 28 Feb 2021, 02:56 Kasper Laudrup, <laudrup@stacktrace.dk> wrote:
On 27/02/2021 12.19, Mayursinh Raulji wrote:
>    i have download template from google and try to load in Django with
> static file but in browser not show properly. show only  half template
> but  In my  friend PC this template working properly so what is problem
> please tell me.
>

A few options:

- Your computer is obviously broken while your friends computer works.
Try to take his computer while he's not looking and exchange it with
yours. Hopefully he won't notice.

- Download another template from google. If you're lucky, this time it
might work on your computer but not his. Spend some time laughing at his
inferior computer.

- Think about how you communicate with people who have no idea what
template you downloaded from google, what you mean when you say "load it
with static file" and what the difference might be between you and your
friends setup. Then write a question where someone might be able to give
you a proper answer.

Kind regards,

Kasper Laudrup

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4c295171-0c42-ddd4-83b7-82e8e4e5333a%40stacktrace.dk.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CABz7kDRSAgrFKTNassNU%3D-9TDkm0b7_X-a_%3DUi5bpKKv-EukYA%40mail.gmail.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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CADkdEzF45uvKm2ezqRYt55ZvkmW%2B%2BN8BgUjhxZuHynyHPE6r8Q%40mail.gmail.com.

Re: Class Base View Foreign key

What's that, am new please

On Sat, Feb 27, 2021, 4:47 PM Rob Wilkinson <wilkyconsultants@gmail.com> wrote:
This is what my code looks like and it now works :

see where it says "example of setting pk..." below:

def dyn_menu_new(request):

    from .models import menu as menuX

    from .models import buttons

    if request.method == 'POST':

        if request.user.is_superuser:

           super_user = "superuser"

        else:

           super_user = ""

        form = dyn_menuForm(request.POST,name=request.user.username,super_user=super_user)


        if form.is_valid():

            menu_id          = request.POST.get('menu_id', '')

            menu_id          = menu_id.replace(" ", "")

            menu_title       = request.POST.get('menu_title', '')

            menu_notes       = request.POST.get('menu_notes', '')

            menu_fb          = request.POST.get('menu_fb', '')

            menu_link        = request.POST.get('menu_link', '')

            menu_align       = request.POST.get('menu_align', '')

            menu_order       = request.POST.get('menu_order', '')

            menu_status      = request.POST.get('menu_status', '')

            menu_admin       = request.POST.get('menu_admin', '')

            menu_image       = request.POST.get('menu_image', '')

            #

            # example of setting pk : https://groups.google.com/g/django-users/c/PcSDKZhPVmc

            #

            buttons_pk = request.POST.get('menu_dropdown')

            menu_dropdown = buttons.objects.get(pk=buttons_pk)

            #

            menu_new_window  = request.POST.get('menu_new_window', '')

            menu_scope  = request.POST.get('menu_scope', '')

            current_user = request.user

            menu_user  = current_user


            p = menuX(menu_id=menu_id, menu_title=menu_title, menu_notes=menu_notes, menu_fb=menu_fb, menu_link=menu_link, menu_align=menu_align, menu_order=menu_order, menu_status=menu_status, menu_admin=menu_admin, menu_image=menu_image, menu_dropdown=menu_dropdown, menu_new_window=menu_new_window,menu_scope=menu_scope,menu_user=menu_user)

            try:

               p.save()

            except:


               messages.error(request, "Menu ID is not unique. Please specify a different Menu ID.")

               return render(request, 'dyn_menu.html', {'form': form})

            return redirect("/theme/dyn_menu_list")


On Sat, Feb 27, 2021 at 10:40 AM sebasti...@gmail.com <sebastian.jung2@gmail.com> wrote:
Hey,

thanks for you response. Before i save i want to make is_valid() and there came this exception.

Regards

wilkycon...@gmail.com schrieb am Samstag, 27. Februar 2021 um 16:36:35 UTC+1:
I had similar issues, I found this helpful:


On Sat, Feb 27, 2021 at 9:19 AM Ryan Nowakowski <tub...@fattuba.com> wrote:
I think choices is causing the problem. Try limit_choices_to instead:

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to

On February 27, 2021 8:06:26 AM CST, "sebasti...@gmail.com" <sebasti...@gmail.com> wrote:
Hello,

I have a CBV with Createview. Now i have a Foreign Key from Box to Tabs model. When i submit request then i get error: Cannot assign "1": "Box.tabs_link" must be a "Tabs" instance. This happens on form.is_valid

I understand this error but i don't know how can i fix this. 

Models.py:
class Box(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200, default="", blank=False, null=False) #Überschrift der Box
    tabs_link = models.ForeignKey(Tabs, on_delete=models.CASCADE, null=False,blank=False,choices=[
                                (c.id, c.name) for c in Tabs.objects.all()]
                                   )

    column = models.PositiveIntegerField(choices=column_choices,blank=False, null=False,default=0) #linke oder rechte Seite
    position = models.PositiveIntegerField(default=1,blank=False, null=False) #position auf der linken/rechten Seite
    modul = models.PositiveIntegerField(choices=Modul_Auswahl,
                                        default=0)  

    class Meta:
        ordering = ["position","column"]
    def __str__(self):
        return self.name

Views.py:
class BoxCreateView(CreateView):
    model = Box
    template_name = 'marketing/boxcreate.html'
    form_class = Boxform
    success_url = reverse_lazy('boxlist')

    def post(self, request, *args, **kwargs):
        formbox = Boxform(self.request.POST)
        if (formbox.is_valid()):
           pass

Forms.py
class Boxform(forms.ModelForm):
    class Meta:
        model = Box
        exclude = ('',)

        labels = {
            'tabs_link': 'Tabulator',
            'column': 'Spalte',
        }
        widgets = {
            'name': textinputfeld,
            'position': integerfeld,
            'column': integerfeld,
            'modul': selectfield,
            'tabs_link': selectfield,
        }

Regards


--
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/C48208D2-7C9F-4F99-B664-20269F331FD2%40fattuba.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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3a53be95-069b-434c-bdfa-b71c0d5fd9c5n%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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAAdSEeamDUxsGD3qmpBYq-kB34%3DaMTDUApe0WC3NM25Osoy4wQ%40mail.gmail.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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CADkdEzELut3N2nofznxrN%3D%2BAQ1ef-YtsWE5ynv7TJDrnAqX5ig%40mail.gmail.com.

Saturday, February 27, 2021

Re: template is not visible properliy

Bro show me your file structure.

On Sun, 28 Feb 2021, 02:56 Kasper Laudrup, <laudrup@stacktrace.dk> wrote:
On 27/02/2021 12.19, Mayursinh Raulji wrote:
>    i have download template from google and try to load in Django with
> static file but in browser not show properly. show only  half template
> but  In my  friend PC this template working properly so what is problem
> please tell me.
>

A few options:

- Your computer is obviously broken while your friends computer works.
Try to take his computer while he's not looking and exchange it with
yours. Hopefully he won't notice.

- Download another template from google. If you're lucky, this time it
might work on your computer but not his. Spend some time laughing at his
inferior computer.

- Think about how you communicate with people who have no idea what
template you downloaded from google, what you mean when you say "load it
with static file" and what the difference might be between you and your
friends setup. Then write a question where someone might be able to give
you a proper answer.

Kind regards,

Kasper Laudrup

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4c295171-0c42-ddd4-83b7-82e8e4e5333a%40stacktrace.dk.

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

Re: Query SET


https://docs.djangoproject.com/en/3.1/ref/models/instances/#django.db.models.Model
https://github.com/django/django/blob/64a0d1ef6e7a6739148996e9584bbb61fe3dcc60/django/db/models/base.py#L404

https://docs.djangoproject.com/en/3.1/ref/models/querysets/
https://github.com/django/django/blob/64a0d1ef6e7a6739148996e9584bbb61fe3dcc60/django/db/models/query.py#L175

On Sunday, February 28, 2021 at 2:59:56 AM UTC+6 aysha...@gmail.com wrote:
Hello everyone,
I was just learning Django and had a doubt.
while making django models classes,In CONSOLE, the objects of the models  were returning as query sets
The queryset is a class...."my question is whether query set is a parent class models.Model?".
I wanted to know how these 2 classes are related..

If I am wrong not making sense :) please do correct me, I am a beginner  in Django and still have n't yet completely worked out how django models work.

Thank you!!

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ef2968d0-39a1-4d91-90f2-96b1678f7a6bn%40googlegroups.com.

Re: template is not visible properliy

On 27/02/2021 12.19, Mayursinh Raulji wrote:
>   i have download template from google and try to load in Django with
> static file but in browser not show properly. show only  half template
> but  In my  friend PC this template working properly so what is problem
> please tell me.
>

A few options:

- Your computer is obviously broken while your friends computer works.
Try to take his computer while he's not looking and exchange it with
yours. Hopefully he won't notice.

- Download another template from google. If you're lucky, this time it
might work on your computer but not his. Spend some time laughing at his
inferior computer.

- Think about how you communicate with people who have no idea what
template you downloaded from google, what you mean when you say "load it
with static file" and what the difference might be between you and your
friends setup. Then write a question where someone might be able to give
you a proper answer.

Kind regards,

Kasper Laudrup

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4c295171-0c42-ddd4-83b7-82e8e4e5333a%40stacktrace.dk.

Re: Class Base View Foreign key

This is what my code looks like and it now works :

see where it says "example of setting pk..." below:

def dyn_menu_new(request):

    from .models import menu as menuX

    from .models import buttons

    if request.method == 'POST':

        if request.user.is_superuser:

           super_user = "superuser"

        else:

           super_user = ""

        form = dyn_menuForm(request.POST,name=request.user.username,super_user=super_user)


        if form.is_valid():

            menu_id          = request.POST.get('menu_id', '')

            menu_id          = menu_id.replace(" ", "")

            menu_title       = request.POST.get('menu_title', '')

            menu_notes       = request.POST.get('menu_notes', '')

            menu_fb          = request.POST.get('menu_fb', '')

            menu_link        = request.POST.get('menu_link', '')

            menu_align       = request.POST.get('menu_align', '')

            menu_order       = request.POST.get('menu_order', '')

            menu_status      = request.POST.get('menu_status', '')

            menu_admin       = request.POST.get('menu_admin', '')

            menu_image       = request.POST.get('menu_image', '')

            #

            # example of setting pk : https://groups.google.com/g/django-users/c/PcSDKZhPVmc

            #

            buttons_pk = request.POST.get('menu_dropdown')

            menu_dropdown = buttons.objects.get(pk=buttons_pk)

            #

            menu_new_window  = request.POST.get('menu_new_window', '')

            menu_scope  = request.POST.get('menu_scope', '')

            current_user = request.user

            menu_user  = current_user


            p = menuX(menu_id=menu_id, menu_title=menu_title, menu_notes=menu_notes, menu_fb=menu_fb, menu_link=menu_link, menu_align=menu_align, menu_order=menu_order, menu_status=menu_status, menu_admin=menu_admin, menu_image=menu_image, menu_dropdown=menu_dropdown, menu_new_window=menu_new_window,menu_scope=menu_scope,menu_user=menu_user)

            try:

               p.save()

            except:


               messages.error(request, "Menu ID is not unique. Please specify a different Menu ID.")

               return render(request, 'dyn_menu.html', {'form': form})

            return redirect("/theme/dyn_menu_list")


On Sat, Feb 27, 2021 at 10:40 AM sebasti...@gmail.com <sebastian.jung2@gmail.com> wrote:
Hey,

thanks for you response. Before i save i want to make is_valid() and there came this exception.

Regards

wilkycon...@gmail.com schrieb am Samstag, 27. Februar 2021 um 16:36:35 UTC+1:
I had similar issues, I found this helpful:


On Sat, Feb 27, 2021 at 9:19 AM Ryan Nowakowski <tub...@fattuba.com> wrote:
I think choices is causing the problem. Try limit_choices_to instead:

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to

On February 27, 2021 8:06:26 AM CST, "sebasti...@gmail.com" <sebasti...@gmail.com> wrote:
Hello,

I have a CBV with Createview. Now i have a Foreign Key from Box to Tabs model. When i submit request then i get error: Cannot assign "1": "Box.tabs_link" must be a "Tabs" instance. This happens on form.is_valid

I understand this error but i don't know how can i fix this. 

Models.py:
class Box(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200, default="", blank=False, null=False) #Überschrift der Box
    tabs_link = models.ForeignKey(Tabs, on_delete=models.CASCADE, null=False,blank=False,choices=[
                                (c.id, c.name) for c in Tabs.objects.all()]
                                   )

    column = models.PositiveIntegerField(choices=column_choices,blank=False, null=False,default=0) #linke oder rechte Seite
    position = models.PositiveIntegerField(default=1,blank=False, null=False) #position auf der linken/rechten Seite
    modul = models.PositiveIntegerField(choices=Modul_Auswahl,
                                        default=0)  

    class Meta:
        ordering = ["position","column"]
    def __str__(self):
        return self.name

Views.py:
class BoxCreateView(CreateView):
    model = Box
    template_name = 'marketing/boxcreate.html'
    form_class = Boxform
    success_url = reverse_lazy('boxlist')

    def post(self, request, *args, **kwargs):
        formbox = Boxform(self.request.POST)
        if (formbox.is_valid()):
           pass

Forms.py
class Boxform(forms.ModelForm):
    class Meta:
        model = Box
        exclude = ('',)

        labels = {
            'tabs_link': 'Tabulator',
            'column': 'Spalte',
        }
        widgets = {
            'name': textinputfeld,
            'position': integerfeld,
            'column': integerfeld,
            'modul': selectfield,
            'tabs_link': selectfield,
        }

Regards


--
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/C48208D2-7C9F-4F99-B664-20269F331FD2%40fattuba.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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3a53be95-069b-434c-bdfa-b71c0d5fd9c5n%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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAAdSEeamDUxsGD3qmpBYq-kB34%3DaMTDUApe0WC3NM25Osoy4wQ%40mail.gmail.com.

Re: Class Base View Foreign key

Hey,

thanks for you response. Before i save i want to make is_valid() and there came this exception.

Regards

wilkycon...@gmail.com schrieb am Samstag, 27. Februar 2021 um 16:36:35 UTC+1:
I had similar issues, I found this helpful:


On Sat, Feb 27, 2021 at 9:19 AM Ryan Nowakowski <tub...@fattuba.com> wrote:
I think choices is causing the problem. Try limit_choices_to instead:

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to

On February 27, 2021 8:06:26 AM CST, "sebasti...@gmail.com" <sebasti...@gmail.com> wrote:
Hello,

I have a CBV with Createview. Now i have a Foreign Key from Box to Tabs model. When i submit request then i get error: Cannot assign "1": "Box.tabs_link" must be a "Tabs" instance. This happens on form.is_valid

I understand this error but i don't know how can i fix this. 

Models.py:
class Box(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200, default="", blank=False, null=False) #Überschrift der Box
    tabs_link = models.ForeignKey(Tabs, on_delete=models.CASCADE, null=False,blank=False,choices=[
                                (c.id, c.name) for c in Tabs.objects.all()]
                                   )

    column = models.PositiveIntegerField(choices=column_choices,blank=False, null=False,default=0) #linke oder rechte Seite
    position = models.PositiveIntegerField(default=1,blank=False, null=False) #position auf der linken/rechten Seite
    modul = models.PositiveIntegerField(choices=Modul_Auswahl,
                                        default=0)  

    class Meta:
        ordering = ["position","column"]
    def __str__(self):
        return self.name

Views.py:
class BoxCreateView(CreateView):
    model = Box
    template_name = 'marketing/boxcreate.html'
    form_class = Boxform
    success_url = reverse_lazy('boxlist')

    def post(self, request, *args, **kwargs):
        formbox = Boxform(self.request.POST)
        if (formbox.is_valid()):
           pass

Forms.py
class Boxform(forms.ModelForm):
    class Meta:
        model = Box
        exclude = ('',)

        labels = {
            'tabs_link': 'Tabulator',
            'column': 'Spalte',
        }
        widgets = {
            'name': textinputfeld,
            'position': integerfeld,
            'column': integerfeld,
            'modul': selectfield,
            'tabs_link': selectfield,
        }

Regards


--
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/C48208D2-7C9F-4F99-B664-20269F331FD2%40fattuba.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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3a53be95-069b-434c-bdfa-b71c0d5fd9c5n%40googlegroups.com.