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(,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     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     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/',,    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)

Problema al subir post django

Estoy con una app creada en React, pasando con la parte del CRUD al momento de editar un post que esta guardado en la base a traves de una peticion todo bien. el problema surge al momento de crear un nuevo post. Al crear un post a traves del front con su respectivo metodo POST me aparece el siguiente error dentro de la respuesta 500.

IntegrityError at /api/ NOT NULL constraint failed: posts_article.author_id

Aun no logro establecer que podria estar pasando dentro de la api o quizas estoy enviando mal los datos a traves del fetch. Adjunto mi modelo de la bd:

class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) title = models.CharField(max_length=100) description = models.CharField(max_length=200, blank=True) content = models.TextField(blank=True) category = models.ForeignKey('Category', on_delete=models.CASCADE,  default='', blank=True, null=True) url = models.CharField(max_length=200, blank=True) photo = models.ImageField(upload_to='images/', blank=True) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now=True, blank=True)  def __str__(self):     return self.title   class Category(models.Model): category_name = models.CharField(max_length=100, blank=True)  def __str__(self):     return self.category_name 

desde el front envio la data desde la pagina create.js de la siguiente manera una vez capturados los datos en el formulario:

export class CreatePost extends React.Component {  state = {     newPost: [] }  handleChange = (e) => {     const { name, value } =;     let newObj = { [name]: value };     const newData = {...this.state.newPost, ...newObj};     this.setState({         newPost: newData     }) }  handleSubmit = (e) => {     e.preventDefault();     console.log('posted ', this.state.newPost);     const secretKey = localStorage.getItem('key');     let url = '';     fetch(url, {         method: 'POST',         body: JSON.stringify(this.state.newPost),         headers: {             'Content-Type': 'application/json',             'Accept': 'application/json',             Authorization: `token $  {secretKey}`         }     })     .then(resp => {         console.log('respuesta de la subida ', resp.status);         return resp.text();     }) }    render() {     return(         <Fragment>             <h1>Create page</h1>             <form>                 <input name='title' placeholder='title' onChange={e => this.handleChange(e)}></input>                 <input name='description' placeholder='description' onChange={e => this.handleChange(e)}></input>                 <input name='content' placeholder='content' onChange={e => this.handleChange(e)}></input>                 <input name='category' placeholder='category' onChange={e => this.handleChange(e)}></input>                 <button onClick={e => this.handleSubmit(e)}>Crea</button>             </form>         </Fragment>     ) } }