Friday, May 1, 2020

Trying to send mails from website

Hi guys,

 

I am using Celery and Eventlet to facilitate a task which sends emails.  I am using the following code:

 

@task

def order_created(order_id):

    """

    Task to send an e-mail notification when an order is

    successfully created.

    """

    order = Order.objects.get(id=order_id)

    subject = 'Order nr. {}'.format(order.id)

    message = 'Dear {},\n\nYou have successfully placed an order.\

                    Your order id is {}.'.format(order.first_name,

                                                 order.id)

    mail_sent = send_mail(subject,message,settings.EMAIL_HOST_USER,[order.email],fail_silently=False)

   

 

    return mail_sent

 

I get the following error

 

TypeError: wrap_socket() got an unexpected keyword argument '_context'

 

Can anyone assist?

I am using Python 3.8

Celery 4.4.2

Eventlet 0.25.2

Django 2.2.12

 

 

Sent from Mail for Windows 10

 

Re: sphinx inside

Make a view that returns a template only , and give it a url

On Fri, 1 May 2020, 10:09 am Kai Kobschätzki, <kai.kobschaetzki@gmail.com> wrote:

Hi Amit,

thanks for your response. But in this way, I can't use the sphinx templates, the links are not correct and after every new make html (or using sphinx-autobuild) I have to copy the changed or new files. Are there no more likable way?

Greetings

bengoshi

On 5/1/20 1:53 AM, Amit Gupta wrote:
Hii 
If u want to just add your file in your django project u can probably copy and paste the file in your project file and after that you can successfully use your file in the project by just writing the name of  your file with correct extension

On Fri, 1 May, 2020, 1:29 AM Kai Kobschätzki, <kai.kobschaetzki@gmail.com> wrote:
Hi,

I installed sphinx and I get an documentation in
project_main/docs/_build/html, starting with html/index.html. In so far
- fine.

Now I want to present this documents inside my project so I can see in
the nav-bar a "doc" where I can see them. But I have no idea how to
start it. I tried it with a simple function in a view inside an app, but
then I need a symbolic-link for getting the index.html, but then I can't
get the rest of the documentation.

I tried to google it but I only find tutorials for using sphinx to make
a documentation for the django-project but I didn't find a tip how I can
realize it.

Could anyone give a kick-off for it or a link for a tutorial? Perhaps I
have only the wrong keywords..

Greetings

bengoshi



--
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/17689333-b06c-1dfc-1f18-341689914c42%40gmail.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/CAGCPjY-tNBKxj%3Dk-e9ew_6DtySK%2BDPE1QJyyMsXi%2Bjt4f-qA4g%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/6e32e790-46bd-bb1b-24a2-3e765f0a273a%40gmail.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/CAHV4E-c741j1swLvKEmjtrmJeC5RfDzxV5XEBvpvsZLZ8W9FPg%40mail.gmail.com.

Djando with ubuntu core

can i bilud a django app on ubuntu core ?

--
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/14cdcf6f-603b-4f3e-92a9-abc6857d9055%40googlegroups.com.

Re: Django framework with machine learning

Hi Lansana,

On 01/05/2020 01.21, Lansana Sangare wrote:
>
> Good evening here is the output on the developpement server and the code
> in django, for smaller scripts I get the output, but for larger ones I
> get strange output or sometimes not. In the attachment I have the large
> file run.py that I run in my django app. I ask for help if someone
> already has experience with it.
>

Some thoughts.

You are collecting all the output from stdout into the out object
returned from the the subprocess run() function.

That means the run function is buffering stdout before returning from
the call. I haven't been able to find a limit on the buffer size (which
could explain why it never returns), but even if there is no limit, you
most likely want to return the output in chunks to improve user
experience and limit memory usage.

Try to look at popen and use that instead:

https://docs.python.org/3/library/subprocess.html

The strange output is caused by combining the output from stdout and
stderr. You almost certainly don't want to return output from stderr to
the user, but consider that an error/exception and handle that
internally. The popen object should help you with that. If the script
you are calling is well written, it will return a non-successful return
code (ie. not 0) on errors which should cause an exception you can handle.

Finally, you are passing user input directly from the user (the "param"
POST value) to the script. As long as you don't execute it through the
shell, it is probably not much of a security issue, but be careful and
assume that the inp variable could contain anything and is not under
your control.

Hope that can help you in the right direction. I don't have any complete
solution, but that's what I would look into.

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/b457529a-4b16-3c78-e8ee-535fe9d1c0d7%40stacktrace.dk.

Re: sphinx inside

Hi Amit,

thanks for your response. But in this way, I can't use the sphinx templates, the links are not correct and after every new make html (or using sphinx-autobuild) I have to copy the changed or new files. Are there no more likable way?

Greetings

bengoshi

On 5/1/20 1:53 AM, Amit Gupta wrote:
Hii 
If u want to just add your file in your django project u can probably copy and paste the file in your project file and after that you can successfully use your file in the project by just writing the name of  your file with correct extension

On Fri, 1 May, 2020, 1:29 AM Kai Kobschätzki, <kai.kobschaetzki@gmail.com> wrote:
Hi,

I installed sphinx and I get an documentation in
project_main/docs/_build/html, starting with html/index.html. In so far
- fine.

Now I want to present this documents inside my project so I can see in
the nav-bar a "doc" where I can see them. But I have no idea how to
start it. I tried it with a simple function in a view inside an app, but
then I need a symbolic-link for getting the index.html, but then I can't
get the rest of the documentation.

I tried to google it but I only find tutorials for using sphinx to make
a documentation for the django-project but I didn't find a tip how I can
realize it.

Could anyone give a kick-off for it or a link for a tutorial? Perhaps I
have only the wrong keywords..

Greetings

bengoshi



--
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/17689333-b06c-1dfc-1f18-341689914c42%40gmail.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/CAGCPjY-tNBKxj%3Dk-e9ew_6DtySK%2BDPE1QJyyMsXi%2Bjt4f-qA4g%40mail.gmail.com.

Watch "What is RSS feed How to create RSS feed in Django | part 2" on YouTube

https://youtu.be/2fB4PN-WRcQ

If you are facing issue in creating RSS feed in django ..
Here is tutorial they are coming up with.

And they help Developers like us to solve many problems. Follow there telegram channel where usefull and updated problems solution updates come always.
@errormania

--
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/CAF_9Cit9Zz6h2p%2B%3DubRzBRrfndL6N5fu6xY6ySL0n365-kBnEg%40mail.gmail.com.

Re: How to use ModelChoiceField? I whould like to filter the output from a field form.

А не могли бы вы подсказать как вызвать две разные формы, от двух разных классов в models.py, на одной странице?
Нужно передать в контекст views.py две формы, и эти две формы по разному назвать.

class SkladCreateView(LoginRequiredMixin, CustomSuccessMessageMixin, CreateView):
    model = Sklad
    template_name = 'sklad.html'
    form_class = SkladForm
    success_url = reverse_lazy('sklad')
    success_msg = 'Материал сохранён'
    def get_context_data(self, **kwargs):
        kwargs['list_sklad'] = Sklad.objects.all().order_by('material')
        return super().get_context_data(**kwargs)
    # это функция для назначения автора
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.author = self.request.user
        self.object.save()
        return super().form_valid(form)




четверг, 30 апреля 2020 г., 19:51:54 UTC+2 пользователь hend hend написал:
Кажется я понял, вы влепили два init в класс? А зачем...
    def __init__(self, *args, **kwargs):
        # get 'user' param from kwargs
        user = kwargs.pop('user', None)
        
super().__init__(*args, **kwargs)
        # set class attrs  
        for field in self.fields.values():
             field.widget.attrs['class'] = 'form-control'
        # set 'name_job' queryset
        self.fields['name_job'].queryset = TypJob.objects.filter(author__id=user.id)

четверг, 30 апреля 2020 г., 20:00:57 UTC+3 пользователь Sergei Sokov написал:
Так перестает работать первоначальная задача

четверг, 30 апреля 2020 г., 18:14:38 UTC+2 пользователь hend hend написал:
Не совсем понимаю, это init какого класса...Но можно попробовать так:
    def __init__(self, *args, **kwargs):
        # delete 'user' from kwargs before calling perent init
        user = kwargs.pop('user', None)
        
super().__init__(*args, **kwargs)
        
#количество строк в поле комментариев
        
self.fields['comment'].widget = Textarea(attrs={'rows': 3})
        
for field in self.fields:
            
self.fields[field].widget.attrs['class'] = 'form-control'


четверг, 30 апреля 2020 г., 15:46:43 UTC+3 пользователь Sergei Sokov написал:
так работает, но если я добавляю вот это для редактирования отображения полей в форме
    def __init__(self, *args, **kwargs):
       
super().__init__(*args, **kwargs)
       
#количество строк в поле комментариев
       
self.fields['comment'].widget = Textarea(attrs={'rows': 3})
       
for field in self.fields:
           
self.fields[field].widget.attrs['class'] = 'form-control'
тогда у меня вот такая ошибка

TypeError at /new-big-print-order

__init__() got an unexpected keyword argument 'user'

Я так понимаю потому что во views.py вот это
def get_form_kwargs(self):
    kwargs
= super(OrderNewBigPrintView, self).get_form_kwargs()
    kwargs
['user'] = self.request.user
   
return kwargs



четверг, 30 апреля 2020 г., 12:19:35 UTC+2 пользователь hend hend написал:
Уже приводил вариант без self, хотя и с self должно бы работать нормально, но раз ругается попробуйте без self.
    def __init__(self, *args, **kwargs):
        # get 'user' param from kwargs
        # user without self
        user = kwargs.pop('user', None)
        
super().__init__(*args, **kwargs)
        # set 'name_job' queryset
        # user.id without self
        self.fields['name_job'].queryset = TypJob.objects.filter(author__id=user.id)


четверг, 30 апреля 2020 г., 11:34:28 UTC+3 пользователь Sergei Sokov написал:
А как тогда?
self.fields['name_job'].queryset = TypJob.objects.filter(author__id=self.user.id)
как тогда фильтр будет работать?

среда, 29 апреля 2020 г., 20:36:00 UTC+2 пользователь hend hend написал:
Не нужно нигде  в классе формы обращаться к  'self.user'.  

среда, 29 апреля 2020 г., 19:49:45 UTC+3 пользователь Sergei Sokov написал:
без self такая ошибка

'OrderForm' object has no attribute 'user'

среда, 29 апреля 2020 г., 17:56:10 UTC+2 пользователь hend hend написал:
Если 'user'  в классе не нужен, можно не вешать его на self. просто вместо 'self.user' используем 'user': в этом случае 'user' просто локальная переменная метода init.
    def __init__(self, *args, **kwargs):
        # get 'user' param from kwargs
        user = kwargs.pop('user', None)
        
super().__init__(*args, **kwargs)
        # set 'name_job' queryset
        self.fields['name_job'].queryset = TypJob.objects.filter(author__id=user.id)

среда, 29 апреля 2020 г., 17:19:41 UTC+3 пользователь Sergei Sokov написал:
hend hend спасибо большое!
Работает!
Но!
Теперь у меня не получается управлять внешним видом полей

Я хочу переопределить класс в форме, но "user" из представления попадает в этот __init__  тоже

     def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
         #количество строк в поле комментариев
         self.fields['comment'].widget = Textarea(attrs={'rows': 3})
         for field in self.fields:
             self.fields[field].widget.attrs['class'] = 'form-control'


среда, 29 апреля 2020 г., 13:54:23 UTC+2 пользователь hend hend написал:


вторник, 28 апреля 2020 г., 19:56:37 UTC+3 пользователь Sergei Sokov написал:
forms.py
class OrderForm(forms.ModelForm):
   
class Meta:
        model
= Order
    name_job
= forms.ModelMultipleChoiceField(queryset=None)
   
def __init__(self, *args, **kwargs):
       
super().__init__(*args, **kwargs)
        qs
= TypJob.objects.filter(author__id=request.user.id)

views.py
class OrderNewBigPrintView(LoginRequiredMixin, CustomSuccessMessageMixin, CreateView):
    model
= Order
    template_name
= 'new_order_bp.html'
    form_class
= OrderForm
    success_url
= reverse_lazy('orders')
    success_msg
= 'Ok'
 

models.py
class TypJob(models.Model):
 author
= models.ForeignKey(User, on_delete = models.CASCADE, verbose_name='author', null=True)
 name_job
= models.CharField('name job', max_length=200)


class Order(models.Model):
 author
= models.ForeignKey(User, on_delete = models.CASCADE, verbose_name='author', blank=True, null=True)
 number_order
= models.CharField('number of order', max_length=100)
 date_create
= models.DateTimeField(auto_now=True)
 name
= models.ForeignKey(Customer, on_delete = models.CASCADE, verbose_name='customer', null=True)
 name_order
= models.CharField('name of order', max_length=200)

# Так должно работать вроде.. 
# view
 class OrderNewBigPrintView(LoginRequiredMixin, CustomSuccessMessageMixin, CreateView):
    model = Order
    template_name 
= 'new_order_bp.html'
    form_class 
= OrderForm
    success_url 
= reverse_lazy('orders')
    success_msg 
= 'Ok'

    # this method will pass 'user' as param in kwargs to form __init__()
    def get_form_kwargs(self):
        kwargs = super(OrderNewBigPrintView, self).get_form_kwargs()
        kwargs['user'] =  self.request.user
        return kwargs

# form
class OrderForm(forms.ModelForm):
    
class Meta:
        model 
= Order
    name_job 
= forms.ModelMultipleChoiceField(queryset=None)

    
def __init__(self, *args, **kwargs):
        # get 'user' param from kwargs
        self.user = kwargs.pop('user', None)
        
super().__init__(*args, **kwargs)
        # set 'name_job' queryset
        self.fields['name_job'].queryset = TypJob.objects.filter(author__id=self.user.id)

--
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/4a21d932-1acd-490f-a45f-0fd476a99678%40googlegroups.com.