Understanding the importance of Gunicorn and Nginx for Django web development

I’m entirely uninitiated to the world of web development, and only have a tentative grasp on Django and web development through the test server it works through.

From the guide I’m reading, the author turns to using Nginx once he starts working on site deployment, because Django is "not designed for real-life workloads." What does that mean, and why doesn’t it? In terms of justification for using Gunicorn, the author remarks:

Do you know why the Django mascot is a pony? The story is that Django comes with so many things you want: an ORM, all sorts of middleware, the admin site…​ "What else do you want, a pony?" Well, Gunicorn stands for "Green Unicorn", which I guess is what you’d want next if you already had a pony…​

Well and good, but I don’t really know what the two are doing for the server. I know for web developers this is like asking what multiplication is to a maths professor, so please excuse the naivety. In your please keep in mind I have almost no knowledge of web development other than what I’ve thus far learned from this guide, doing my best to understand as much as I can for the previously entirely uninitiated (I’m from a computational programming background).

How to hide or secure django admin page?

I am working on an E-commerce website which is mainly in Django.

I have this admin page. I want to hide, protect, secure it from other users/visitors means that only a set of IP address can view that and login with their credentials. is it possible? I have heard about IP whitelisting but IP’s can be faked and also someone suggested that just don’t publish it. if I choose not to publish make the desktop app for admin then how this work. Please explain.

how to Reduce number of queries generated by Django ORM [closed]

I have below models

class Order(models.Model):    ....  class Component(models.Model):      line = models.ForeignKey(         Line,         on_delete=models.CASCADE,         blank=True,         null=True,         related_name="components",     )   ...  class Detail(models.Model):     line = models.ForeignKey(         "Line",         on_delete=models.CASCADE,         blank=True,         null=True,         related_name="details",     )   order= models.ForeignKey(Order, on_delete=models.CASCADE, related_name="details")    .....  class Line(models.Model):  ....  **Serializer** class ComponentSerializer(serializers.ModelSerializer):     qty = serializers.SerializerMethodField(read_only=True)      def get_qty(self,component):         return (component.qty)-sum(                map(                    some_calculation,                    Detail.objects.filter(                        line__components=component,order__active=True)                )            ) 

I have a list view using model viewsets

def list(self, request):  queryset = Order.objects.filter(order__user=request.user.id,active=True)   serilizer = OrderSerializer(queryset,many=true) 

The component serializer is used inside the order serializer. My question is the query inside the ComponentSerializer hits DB fpr every order record. If my understanding is correct, is there any way to reduce this?

Django admin site add html link


@admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecord(admin.ModelAdmin):     list_display = ('Student_Users', 'School_Year', '<a href="#">Report</a>')     ordering = ('Education_Levels',)     list_filter = ('Student_Users',) 

enter image description here I just want that to add the html link in the adminsite then if the admin click the “report” it will filter what studentenrollmentrecord selected to html file

Filtrar field en el administrador Django

Hola estoy trabajando con el framewor Django y se me presenta la siguiente situación.

Quisiera poder filtrar las opciones que se despliegan en el field factura del administrador de AbonoFactura, solo con las facturas marcadas con credito=True. Ya que por defecto Django me despliega todos los objetos relacionados.

Modelo AbonoFactura

class AbonoFactura(Auditoria):     factura = models.ForeignKey(Factura, null=False, blank=False, verbose_name=_('factura'), on_delete=models.PROTECT,                                 related_name='abono_factura_factura')     fecha_abono = models.DateTimeField(null=False, blank=False, verbose_name=_('fecha del abono'))     valor_abono = models.IntegerField(null=True, blank=True, verbose_name=_('valor del abono')) 

Modelo Factura

class Factura(Auditoria):     fecha_compra = models.DateTimeField(null=False, blank=False, verbose_name=_('fecha de compra'))     cliente = models.ForeignKey(Cliente, null=False, blank=False, verbose_name=_('cliente'), on_delete=models.PROTECT)     contado = models.BooleanField(default=False, verbose_name=_('contado'))     credito = models.BooleanField(default=False, verbose_name=_('credito'))     fecha_pago = models.DateField(null=True, blank=True, verbose_name=_('fecha de pago'),                                   help_text=_('Uselo solo si selecciono crédito como método de pago.')) 

Agradezco la ayuda que me puedan brindar.

Error ImproperlyConfigured Could not resolve URL for hyperlinked relationship using view name, Django

Estoy haciendo una aplicación en django-REST, en la que una empresa puede tener varios talleres, el problema es que cuando creo una empresa y luego intento entrar al viewset de los talleres, me sale el siguiente error:

django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name “enterprise-detail”. You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.

Alguien sabe como solucionar esto?, solo pasa cuando hay empresas creadas, si no hay empresas me deja entrar entrar al viewset de los talleres, aqui el codigo:


#modelo para empresas class Enterprise(models.Model):    nit = models.CharField(db_column='NIT', primary_key=True, max_length=12)      name = models.CharField(max_length=50)    type = models.CharField(max_length=8)     def __str__(self):       return self.name     class Meta:       db_table = 'enterprise'  #modelo para talleres class Workship(models.Model):    idworkship = models.AutoField(primary_key=True)    name = models.CharField(max_length=128)    description = models.TextField()    type_service = models.CharField(db_column='type_Service', max_length=45)      stars = models.PositiveIntegerField(default=0)    votes = models.PositiveIntegerField(default=0)    email = models.CharField(max_length=254)    field_bahias_quant = models.PositiveIntegerField(db_column='_bahias_quant')    #clave foránea a Enterprise    enterprise_nit = models.ForeignKey(Enterprise, models.DO_NOTHING, db_column='enterprise_NIT')      def __str__(self):     return self.name     class Meta:       db_table = 'workship'       unique_together = (('idworkship', 'enterprise_nit'),) 


class EnterpriseSerializer(serializers.HyperlinkedModelSerializer):      class Meta:        model = models.Enterprise        fields = ('nit', 'name', 'type',)  class WorkshipSerializer(serializers.HyperlinkedModelSerializer):      class Meta:        model = models.Workship        fields = ('name','ubication', 'description', 'type_service', 'stars', 'votes', 'email' , 'field_bahias_quant', 'enterprise_nit',) 


class EnterpriseViewSet(viewsets.ModelViewSet):    queryset = models.Enterprise.objects.all()    serializer_class= serializers.EnterpriseSerializer  class WorkshipViewSet(viewsets.ModelViewSet):    queryset = models.Workship.objects.all()    serializer_class = serializers.WorkshipSerializer 


router = routers.DefaultRouter() router.register('Enterprise', views.EnterpriseViewSet, base_name = 'Enterprise') router.register('Workship', views.WorkshipViewSet, base_name = 'Workship') urlpatterns = [    path('admin/', admin.site.urls),    path('', include(router.urls)),    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] 

Queryset Entres fechas Django

estoy tratando de realizar una consulta entre dos fecha es decir:

where fecha_creacion >= fecha_iniciar and fecha_creacion <= fecha_final. 

Este es mi código Django:

if request.method == 'POST':         fecha_inicio=str(request.POST.get('fecha_inicio', False))         fecha_final=str(request.POST.get('fecha_final', False))         fecha_inicio = datetime.datetime.strptime(fecha_inicio,          '%d/%m/%Y').strftime('%Y-%m-%d')         fecha_final = datetime.datetime.strptime(fecha_final,          '%d/%m/%Y').strftime('%Y-%m-%d')           Encuesta.objects.filter(fecha_creacion__gt=fecha_inicio,         fecha_creacion__lt=fecha_final, jefe_unidad_id__isnull=False).         order_by('id'):   

Tambien he probado esto:

    Encuesta.objects.filter(fecha_creacion__range(fecha_inicio,fecha_final),      jefe_unidad_id__isnull=False).order_by('id'):   

Me obtiene los datos no incluyendo el día inicial y final de la consulta, es decir esta haciendo esto:

where fecha_creacion > fecha_iniciar and fecha_creacion < fecha_final. 

Como puedo hacer para que me tome el día inicial y final de la consulta?

Django 1.8 Python 2.7

Django / Python – Implement a server-side countdown timer

Im developing a typical Question/Answer game where multiple players can answer the same Question at the same time. They have 10 seconds to choose the right answer.

I need to implement a countdown in the server and when the time is up, all players must know if they choose right or wrong. Then, the game continue with the next Question, restarting the countdown again to 10 seconds. The game finishes when no other Question remains.

The Backend is developed with Django and Django-Rest-Framework exposing a REST API. The Frontend is developed with React consuming the REST API.

I think there probably will be an endpoint where the Frontend (all the Players) ask the Backend the time remaining, but im really lost in how the Backend update that remaining time every second.

Any ideas on how can i aproach this? Thank you!

Explanation needed with Django and AMP logic using 1 url

I’m using AMP at one of my parts of the website with Django template and python, my question is what will happen to a page (*SEO wise) if I take and break an AMPed page (only on desktop) and leave the page AMPed on mobile?!

To be more specific, I have made a full AMP page for both mobile and desktop which use the url (/example-amp-url) and now I need to add a widget to the page which is rendered with js and not AMPed at all but render it only on desktop.

Any one knows how it would impact on my SEO? Because for now in my site-map this page is AMPed both on mobile search and on desktop page (if Im losing the AMP on desktop it is fine but if I lose both its a huge problem thats why Im afraid to test it)