Django REST Swagger – Gera 2 metodos GET

Estou implementando uma API REST com Django REST Swagger 2.2.0.

Para um determinado endpoint defini que esteja disponível os seguintes métodos:

http_method_names = ['post', 'put', 'get'] 

Porém, no swagger, aparece 2 versões para o método GET:

1 - http://dominio/nome_metodo 2 - http://dominio/nome_metodo/{id} 

Como faço para que o Swagger oculte o método 2?

nginx gunicorn django 502 worker timeout just on some pages

I configured a django app with gunicorn and nginx all was working perfectly until the installation of SSL certifiate on the server. firstly all pages were served perfectly but after some time some pages were showing 502 Bad gateway while others are still working nicely.

I am not trying to upload a big file or to call a page that has a big loading time. the page should be served instantly. I tried everything but cant find the problem.maybe its a configuration error. Please if you can help me

The error was in error.log of gunicorn

[2019-04-20 14:38:24 +0200] [14828] [CRITICAL] WORKER TIMEOUT (pid:21460) [2019-04-20 12:38:24 +0000] [21460] [INFO] Worker exiting (pid: 21460) [2019-04-20 14:38:24 +0200] [21500] [INFO] Booting worker with pid: 21500 

this is my gunicorn configuration

import multiprocessing  timeout = 120 bind = 'unix:/tmp/gunicorn.sock' workers = multiprocessing.cpu_count() * 2 + 1 reload = True daemon = True accesslog = './access.log' errorlog = './error.log' 

nginx config

user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf;  events {         worker_connections 1024;         # multi_accept on; }  http {         fastcgi_buffers 8 16k;         fastcgi_buffer_size 32k;         fastcgi_connect_timeout 300;         fastcgi_send_timeout 300;         fastcgi_read_timeout 300;         ##     # Basic Settings     ##      sendfile on;     tcp_nopush on;     tcp_nodelay on;     keepalive_timeout 65;     types_hash_max_size 2048;     # server_tokens off;      # server_names_hash_bucket_size 64;     # server_name_in_redirect off;      include /etc/nginx/mime.types;     default_type application/octet-stream;      ##     # SSL Settings     ##      ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE     ssl_prefer_server_ciphers on;      ##     # Logging Settings     ##      access_log /var/log/nginx/access.log;     error_log /var/log/nginx/error.log;      ##     # Gzip Settings     ##      gzip on;      # gzip_vary on;     # gzip_proxied any;     # gzip_comp_level 6;     # gzip_buffers 16 8k;     # gzip_http_version 1.1;     # gzip_buffers 16 8k;     # gzip_http_version 1.1;     # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;      ##     # Virtual Host Configs     ##      include /etc/nginx/conf.d/*.conf;     include /etc/nginx/sites-enabled/*; }   #mail { #       # See sample authentication script at: #       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript # #       # auth_http localhost/auth.php; #       # pop3_capabilities "TOP" "USER"; #       # imap_capabilities "IMAP4rev1" "UIDPLUS"; # #       server { #               listen     localhost:110; #               protocol   pop3; #               proxy      on; #       } # #       server { #               listen     localhost:143; #               protocol   imap; #               proxy      on; #       } #} 

/etc/nginx/sites-available/example

upstream your-gunicorn {   server unix:/tmp/gunicorn.sock fail_timeout=0; }  # Catch all requests with an invalid HOST header  server {     server_name "";     listen      80;     return      444; }  server {   listen 80;   server_name example.com www.example.com;   return 301 https://www.example.com$  request_uri; }  server {   listen 443 default ssl;   server_name example.com www.example.com;    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;   ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;    client_max_body_size 4G;   keepalive_timeout 70;    access_log /var/log/nginx/example.access_log;   error_log /var/log/nginx/example.error_log warn;    root /var/www/django_projects/example;    location /static/ {     autoindex off;     alias /var/www/django_projects/example/static/;     expires 1M;     access_log off;     add_header Cache-Control "public";     proxy_ignore_headers "Set-Cookie";   }    location @proxy_to_app {     proxy_set_header Host $  host;      proxy_set_header X-Real-IP $  remote_addr;      proxy_set_header X-Forwarded-For $  proxy_add_x_forwarded_for;      proxy_set_header X-Forwarded-Proto $  scheme;      proxy_pass http://your-gunicorn;      proxy_read_timeout 90;      proxy_redirect http://your-gunicorn https://example.com;   }    location / {     try_files $  uri @proxy_to_app;   }    location /.well-known/acme-challenge/ {     root /var/www/django_projects/example/static/;   }  } 

Posso dar load de static files utilizado modulos do DJango

É possivel eu criar um modulo no django e utilizar a admin page para mudar imagens no meu webiste por exemplo: Eu tenho uma images no meu index.html mas gostaria de adicionar uma maneira mais facil de modificar essa imagem sem ter de abrir o ficheiro e eu queria implementar isso na admin paga fazendo com que se eu mudar a images na admin page ele tambem altera no index.html! Espero ter escalrecido a minha duvida!

¿Como obtener el campo en un modelo desde otro modelo, en Django?

Tengo dos modelos en una app, el primer modelo consiste en que yo creo un consejero, el consejero se crea con un user(y unos cuantos datos), es decir debo crear un usuario con privilegios bajos y lo registro como consejero.

El segundo modelo consiste en crear un aconsejado, con unos datos y le asigno un consejero(un aconsejado solo puede tener un consejero, el aconsejado no nesesita user).

Aquí los modelos:

class Adviser(models.Model):     user = models.ForeignKey(User, on_delete = models.CASCADE, verbose_name = 'Usuario')     first_name = models.CharField(max_length = 100, verbose_name = 'Nombre')     last_name = models.CharField(max_length = 100, verbose_name = 'Apellido')     created = models.DateTimeField(auto_now_add = True, verbose_name = 'Fecha de Creasion')     updated = models.DateTimeField(auto_now = True, verbose_name = 'Fecha de Edicion')      class Meta:         verbose_name = 'consejero'         verbose_name_plural = 'consejeros'      def __str__(self):         return self.first_name   class Advised(models.Model):     first_name = models.CharField(max_length = 100, verbose_name = 'Nombre')     last_name = models.CharField(max_length = 100, verbose_name = 'Apellido')     adviser = models.ForeignKey(Adviser, on_delete = models.CASCADE,verbose_name = 'Consejero')     created = models.DateTimeField(auto_now_add = True, verbose_name = 'Fecha de Creasion')     updated = models.DateTimeField(auto_now = True, verbose_name = 'Fecha de Edicion')      class Meta:         verbose_name = 'aconsejado'         verbose_name_plural = 'aconsejados'      def __str__(self):         return self.first_name 

En una app diferente tengo un modelo, consiste en que un consejero, le asigna calificaciones a sus aconsejados asignados(en su sesión activa) el problema surge que me aparecen aconsejados que no están asignados al consejero que esta loggeado, Entonces lo que intento hacer, es atraves de la ForeignKey del modelo del aconsejado(Advised) que se relaciona con el modelo consejero(Adviser) obtener su user y así poner en el advised = models.OneToOneField del modelo AdministrationOfCounseled los aconsejados correspondientes del consejero con la sesión activa.

Aqui el modelo AdministrationOfCounseled:

class AdministrationOfCounseled(models.Model):     adviser = models.OneToOneField(Adviser, on_delete = models.CASCADE, verbose_name = 'Consejero/a', default = Adviser)     advised = models.OneToOneField(Advised, on_delete = models.CASCADE, verbose_name = 'Aconsejado/a', unique = True)      # Campos de calificasiones.....      class Meta:         verbose_name = 'administracion de aconsejado'         verbose_name_plural = 'administracion de aconsejados'      def __str__(self):         return str('') 

Tan bien díganme si esta es la mejor o hay otra mejor forma o no, de hacer esto

Desde ya Gracias por sus Respuestas!

Listar todos los registros almacenados de mi clase python + django

He creado una view en python para mostrar especificamente un registro de mi base de datos y elcódigo me funciona excelente (con este bloque de código se me muestra en el navegador el articulo donde el id = 1) es el siguiente:

obj = Computer.objects.get(id=1)      context = {         'object': obj     }     return render(request, "Computers/computer_detail.html", context) 
{% block content %}          <h1>{{ object.name }}</h1>         <p>{{ object.serial }}</p>         <p>{{ object.user_name }}</p>         <p>{{ object.ip_address }}</p>   {% endblock content %} 

Sin embargo si cambio el código para ver todos los registros en el navegador no me sale nada:

obj = Computer.objects.all()      context = {         'object': obj     }     return render(request, "Computers/computer_detail.html", context)  
{% block content %}      {%for control_var in context%}         <h1>{{ object.name }}</h1>         <p>{{ object.serial }}</p>         <p>{{ object.user_name }}</p>         <p>{{ object.ip_address }}</p>      {% endfor %}   {% endblock content %} 

Que debería corregir para que me salgan todos los artículos?

How to show a field of the model to its inline method Django?


I have three models HomePage, Callout, FeatureContent like below:

class FeatureTip(models.Model):    feature_tip_title = models.CharField(max_length=120, null=True, blank=False)    feature_tip_description = models.TextField()    def __str__(self):       return self.feature_tip_title   class Citie(models.Model):    name = models.CharField(max_length=120, null=True, blank=False)    description = models.TextField()     def __str__(self):       return self.name   class HomePage(models.Model):    header = models.CharField(max_length=120, null=True, blank=False)    cities = models.ManyToManyField(Citie)    featured_tips = models.ManyToManyField(FeatureTip)     def __str__(self):       return 'Home Page'   class Callout(models.Model):    header = models.CharField(max_length=120, null=True, blank=False)    home_page = models.ForeignKey(HomePage,on_delete=models.CASCADE, null=True, blank=False)    def __str__(self):       return self.header     def get_city(self):       return self.cities.all()  class FeatureContent(models.Model):    title = models.CharField(max_length=120, null=True, blank=False)    home_page = models.ForeignKey(HomePage, on_delete=models.CASCADE, null=True)    def __str__(self):       return self.feature_article_title_en 

and it has been added to Admin.py like below:

class CalloutInline(admin.StackedInline):     model = Callout     fields = ['header']     extra = 4     max_num = 4     def get_queryset(self, request):         HomePage.objects.filter(name="Eminem")  class FeatureContentInline(admin.StackedInline):     model = FeatureContent     fields = ['title']     extra = 1     max_num = 1  class HomePageAdmin(admin.ModelAdmin):     filter_horizontal = ['cities', 'featured_tips']      inlines = [CalloutInline, FeatureContentInline] 

The problem is I want to show cities to show below the CalloutInline and featured_tips to show below FeatureContentInline. Currently, both are showing under Homepage. How can I do that?

Не отображаются формы Django на странице

Уже долго вожусь с данной проблемой, нигде не смог найти решение. чувствую, что ответ на поверхности, надеюсь тут помогут… Собственно проблема в том, что не могу передать form в html, он её просто не видет. Вот файл views.py:

from django.shortcuts import render, redirect from django.contrib import messages from .forms import ContactForm  def main_page_en(request):     return render(request, 'portfolio/main_page_en.html')  def main_page_rus(request):     return render(request, 'portfolio/main_page_rus.html')  def my_works(request):     return render(request, 'portfolio/works.html')  def contact_us(request):     return render(request, 'portfolio/contact_us.html')     def contact_form(request):     if request.method == 'POST':         form = ContactForm(request.POST)         if form.is_valid():             form.save()             username = contact_form.cleaned_data.get('name')             messages.success(request, f'Спасибо, {name}! Я свяжусь с Вами в ближайшее время')             return redirect('main-page-rus')     else:         form = ContactForm()     template_name = 'portfolio/contact_us.html'     context = {'form': form}     return render(request, template_name, context) 

Вот models.py:

from django.db import models from django.forms import ModelForm   class Contact(models.Model):     name = models.CharField(max_length=120)     email = models.EmailField()     content = models.CharField(max_length=255)     price = models.FloatField()     phonenumber = models.CharField(max_length=12)      def __str__(self):         return self.name  class ContactForm(ModelForm):     class Meta:         model = Contact         fields = ['name', 'email', 'content', 'price', 'phonenumber']  

Вот forms.py:

from django import forms from .models import Contact  class ContactForm(forms.ModelForm):     class Meta:         model = Contact         fields = ['name', 'email', 'content', 'phonenumber', 'price'] 

Сам HTML:

{% extends 'portfolio/base.html'%} {% load static %} {% load crispy_forms_tags %}   {% block content %} <form method="POST" action=".">     {{ form|crispy }} </form>  {% endblock %} 

Помогите новичку, скорее всего слона то и не вижу. Спасибо!

P.S. Если укажете и на другие ошибки, то буду очень признателен.

¿Cómo puedo correr comandos de Django sin entrar al contenedor Docker?

Realice el quickstart django-docker https://docs.docker.com/compose/django/ y estoy intentando correr los comandos de Django (makemigrations, migrate, startapp, etc…) sin tener que entrar al contenedor donde esta corriendo Django o corre docker-compose run web python manage.py ... . Alguna idea?

localhosted Chat Apps on Chrome doesn’t work properly DJANGO

localhosted Chat Apps on Chrome doesn’t work properly DJANGO

i am developing a project which is a chat room app which runs on localhost , chrome doesn’t show up messages on android but it does on desktop idk why ? i searched and found to change site permissions to send updates but the site isn’t found in the permissions section because its a localhost i guess

the project which i develop