Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fetch details from a table Which creates cyclic redundancy
I want to write a code in models.py for fetching a row from a table by providing its id row = ABC.objects.get(id = id) But I cannot import ABC, since it causes a cyclic dependency. How can I execute the above code ? -
Django rest filter by deep/nested foreignkey name
I have an issue when I want to filter by source name( which is a related to a table that is a related to the main table I am serializing) For my filters im using django-filter module My serializers.py might provide insight on whats going on class FilterSerializer(serializers.ModelSerializer): owner_name = serializers.CharField(source='owner.name') source = serializers.CharField(source='source.trend_type.mnemonic') class Meta: model = TrendData fields = [obj.name for obj in TrendData._meta.fields if obj.name not in ['owner', 'id','source']] fields.insert(0, 'owner_name') fields.append('source') #code is still in dev mode, i will refactor all the inserts/append ofc :) and my views + filterset look like this class GlobalFilterSet(filters.FilterSet): class Meta: model = TrendData field_list = ['gte', 'lte', 'range','exact', 'icontains'] fields = { 'date_trend': field_list, 'views':field_list, 'views_u' : field_list, 'likes': field_list, 'shares': field_list, 'interaction_rate': field_list, 'mean_age': field_list, 'er_reach_day_1': field_list, 'er_reach_day_2': field_list, 'lr_4': field_list, 'sr_5': field_list, 'vur_1': field_list, 'views_pos': field_list, 'views_u_pos': field_list, 'likes_pos': field_list, 'shares_pos': field_list, 'interaction_rate_pos': field_list, 'mean_age_pos': field_list, 'er_reach_day_1_pos': field_list, 'er_reach_day_2_pos': field_list, 'lr_4_pos': field_list, 'sr_5_pos': field_list, 'vur_1_pos': field_list, 'source': ['exact'] ## < I want to filter by this name #TODO more fields to filter } ordering = ['-views'] class GlobalFilter(MixInTrendsAPIView): queryset = TrendData.objects.all() filter_backends = [DjangoFilterBackend] serializer_class = FilterSerializer filterset_class = GlobalFilterSet pagination_class = CustomPagination pagination_class.page_size = 10 ordering_fields= … -
Django validators TypeError int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute
I have this situation: When a modelf field is filled, it must not be greater than other model´s field. I wrote this validator. class Insumo(models.Model): nombre = models.CharField(max_length=100) cantidadexistencias = models.DecimalField(max_digits=50, decimal_places=3, validators=[MinValueValidator(0)]) def __str__(self): return self.nombre + " "+str(self.cantidadexistencias) class InsumoProduction(models.Model): idproduction = models.ForeignKey('Production', on_delete=models.CASCADE) idinsumo = models.ForeignKey('Insumo', on_delete=models.CASCADE) #Validar que la cantidad usada sea maximo el numero de existencias cantidadusada = models.DecimalField(max_digits=50, decimal_places=3,validators=[insumo_existencias]) def save(self,*args,**kwargs): insumo = Insumo.objects.get(id = self.idinsumo_id) insumo.cantidadexistencias -= self.cantidadusada insumo.save() super(InsumoProduction,self).save(*args,**kwargs) class Meta: constraints = [ models.UniqueConstraint(fields=["idproduction", "idinsumo"], name='unique_insumoproduction') ] def __str__(self): return self.idproduction.idfinalproduct.idproduct.nombre +" "+ self.idproduction.idfinalproduct.idtaste.nombre \ + " "+ self.idinsumo.nombre + " "+ str(self.cantidadusada) + " Fecha Produccion " + str( self.idproduction.fechaproduccion) Those are my models, and my validator is here: from django.core.exceptions import ValidationError from ubindustries.ubapi.models import models from django.utils.translation import gettext_lazy as _ def insumo_existencias(value): insumo = models.Insumo.objects.get(id=models.InsumoProduction.idinsumo_id) if (insumo.cantidadexistencias < value): raise ValidationError( _('Error no hay existencias suficientes'), ) I got this error message:TypeError at /ubapi/insumoproduction/add/ int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute -
Django ORM executes query with wrong time?
I am trying to fetch data based on DateTime Field! I wrote the following script for the same: import datetime as dt from dasboard.models import Visionsystem from django.utils.timezone import make_aware min_dt = dt.datetime.combine(dt.date.today(), dt.time(7, 15)) max_dt = dt.datetime.combine(dt.date.today(), dt.time(15, 44)) # Changing format for Django min_dt_aware = make_aware(min_dt) max_dt_aware = make_aware(max_dt) # Fetching all the data between 7:15:00 to 15:44:00 for current day l1 = Visionsystem.objects.filter(start_datetime__range=(min_dt_aware, max_dt_aware)) print(l1) yields empty list and Checking str(l1.query) gives: 'SELECT `visionsystem`.`id`, `visionsystem`.`Start_Datetime` ... FROM `visionsystem` WHERE `visionsystem`.`Start_Datetime` BETWEEN 2019-10-16 01:45:00 AND 2019-10-16 10:14:00' Desired query would be: 'SELECT `visionsystem`.`id`, `visionsystem`.`Start_Datetime` ... FROM `visionsystem` WHERE `visionsystem`.`Start_Datetime` BETWEEN 2019-10-16 07:15:00 AND 2019-10-16 15:44:00' I don't understand why Django-ORM is querying with a different time then what's specified ? My timezone settings ( in settings.py ): TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True How do I resolve this, to fetch the required data from 7:15:00 to 15:44:00, for current day ? -
What is the best way to structure my Django Models?
I am fairly new to Django and am working on a project that will do the following: Employee will fill out form to create a ticket That ticket will be assigned to the employee and other team members The ticket is associated with a specific person or persons within the organization (I'll call them customers) Once the ticket is complete, we will run reports to show how many tickets a specific person with the organization has created tickets as well as other stats related to the tickets themselves My question is as follows: What is the best way for me structure my Django models in this scenario? Should I have one app created for employees, one app created for the customer database and one app created for the tickets themselves? Thanks for your time! -
How to fix "File is not a zip file"
I am trying to upload some data representing information about products. The first row of my excel file represents the id of the product. The data in the column cells (begin from the 2nd row and then) represent serial numbers. I can not upload successfully my .xls file , taking back the error File is not a zip file. my view def excel_view(request): if "GET" == request.method: return render(request, 'excel/excel_form.html', {}) else: excel_file = request.FILES["excel_file"] # you may put validations here to check extension or file size wb = openpyxl.load_workbook(excel_file) sheet_obj = wb.active # getting a particular sheet by name out of many sheets worksheet = wb["Sheet1"] # print(worksheet) excel_data = list() # iterating over the rows and # getting value from each cell in row #flag=0 header_list=[] #list to store drug index input_dict={} #dict to store serial numbers per drug i = 0 #index of columns j = 0 #index of rows for row in worksheet.iter_rows(): .... my template <title> Excel file upload and processing </title> <body style="margin-top: 30px;margin-left: 30px;"> <h1>Excel file upload and processing</h1> <form action="{% url 'excel_functionality' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" title="Upload excel file" name="excel_file" style="border: 1px solid black; padding: 5px;" required="required"> <p> … -
How to get model instance form ModelForm to delete it
I'm trying this: if request.method == 'POST': form = RmEmplForm(request.POST) if form.is_valid(): employee = form.save(commit=False) employee.delete() but it returns an instance with None id field (but there is a correct instance in the table) Employee object can't be deleted because its id attribute is set to None. forms.py class RmEmplForm(forms.ModelForm): name = forms.ModelChoiceField(label="Сотрудник", queryset = Employee.objects.all()) class Meta: model = Employee fields = [] I would prefer to use save() method not to use primary keys or smth else if it's possible -
Cant install jinja in visual studios
how do i install jinja on to visual studio 2019? I click on exentions and search for jinja, but it is not there. i installed jinja on my visual studio code, but it seems to have no effect on visual studio 2019. -
forward reference to 'Form.pdfrw_3' not resolved upon final formatting Python 3
I tried to add pages from the existing pdf using pdfrw. It gave me this error. There is one link related to this problem https://github.com/pmaupin/pdfrw/issues/2. It did not solve my issue. Thanks in advance! for page in pages: pdf.setPageSize((page.BBox[2], page.BBox[3])) pdf.doForm(makerl(pdf, page)) pdf.showPage() -
what is the difference between application program interface and Uniform Resource Locator?
what is the difference between application program interface and Uniform Resource Locator? please explain in simple words as i am a beginner in web development -
Django: How to create a listview and query based on urlpatterns in urls.py
I have a question, if urls.py urlpatterns = [ path('index',views.index, name='index'**), path('resume',views.resume, name='resume'), ] I would like create a listview with urlpatterns, like that: <h2>Urls</h2> <ul> {% for urlpatternsList in object_list %} <li><a href={{ urlpatterns.name.url }} or {% url 'url:urlpatterns' name }}> {{ urlpatterns.name }}</a> </li> {% endfor %} </ul> and a query maybe that: views.py from myproject.urls import urlpatterns def UrlPatternsQuery(request): query = request.GET.get(search,none) if query: urlpatternsList = urlpatterns.objects.all() urlpatternsList = urlpatternsList.filter(name=query) # ex: name='resume' else: urlpatternsList = urlpatterns.objects.all() return render(request,'query.html', {'urlpatternsList':urlpatternsList}) Search Example <div class="search-container"> <form action=""> <input type="text" placeholder="Search.." name="search"> <button type="submit">Search/button> </form> </div> Can you help ? Tks -
Is it possible to insert string with variable inside include tag?
In admin panel I can choose which template will be use to display content. Instead of multiple lines with if/elif statement I came to the conclusion that I can use for loop. However the problem is I don't know how to put variable inside string. Is it even possible? I tried this ways: {% include 'templates/template_'+ key + '.html' %} {% include 'templates/template_{key}.html' %} {% include f'templates/template_{key}.html' %} but without success. models class Homepage(models.Model): choice_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} TEMPLATE_TYPE = [ (choice_dict['one'], 'template-one'), (choice_dict['two'], 'template-two'), (choice_dict['three'], 'template-three'), (choice_dict['four'], 'template-four'), (choice_dict['five'], 'template-five'), ] template = models.IntegerField('Optional', choices=TEMPLATE_TYPE, null=True, blank=True) views def index(request, *args, **kwargs): homepage = Homepage.objects.first() context = { 'homepage': homepage, } return render(request, 'home.html', context) home.html {% if homepage.template %} {% for key, value in homepage.choice_dict.items %} {% if homepage.template == value %} {% include 'templates/template_'+ key + '.html' %}{% endif %} {% endfor %} {% else %} -
how to implement consistent hashing in django using redis database?
I want to implement consistent hashing in django with redis as my cache DB. Firstly I tried utilising uhashing(https://pypi.org/project/uhashring/) package to implement consistent hashing with redis but I am unable to provide link between django and the package. The second thing I did is searching for Configuring Redis with consistent hashing in django itself but I am unable to find anything related. I can only find configuring redis with memcached. Is there any way to get solution for my problem. Any small hint will also be helpful, Thank you. -
Python Manage.Py
i am very New to Python web development ,so got confuse while learning ,when we create new Project with the command --"Django-admin startProject 'ProjectName'" create a project folder and it create application in it with the name of suppose "calculator", we start working in it ,but after some more requirement we have to create a new different Project with the Name of the "Hrms" so the question arise for this again we have to run the same command Django admin startProject 'ProjectName' and then we have to create application in it or we can create in it -
Interactive SSH terminal (shell) in Django template with Javascript, HTML
We have a provisioning tool in our entreprise that is used to create / modify / configure some devices with SSH (paramiko). It uses Django 2.1.0 and Python 3.5. Actually, we have an utility that allow us to send one command to the device by ssh and printing the output (ex : show running-config on a Cisco device). I'm trying to create an interactive shell (like http://web-console.org/ but embedded in the webpage), which would work like if you do an SSH connection on the device and that can be used in the webpage (HTML and Javascript). I can actually send one command, like the old method, and it displays correctly. The problem is that I can't re-use the SSH session to the device because every POST request made on the view create a new view, so a new SSH session is created and it doesn't use the old one. For example, on a Cisco device, I would like to send the commands "configure terminal" and "interface vlan 1". The first command will work, the second will be in the wrong context because a new SSH session was created. Question is : how can I store the SSH session to be … -
Get a distinct value from Django queryset USING MYSQL
Does Someone knows how to get a distinct value in Django querySet? I'm using Mysql db and I couldn't find a solution yet. The table is: ID WORK_YMD LINE_NM MODEL_CODE MAG_NO PRODC_MAGT_NO 118002 20191015 PBA-21F BN94-14806W A656MAF00001 BR10BN9414806WA656MAE4035 118003 20191015 PBA-21F BN94-14806W A656MAF00001 BR10BN9414806WA656MAE4027 118004 20191015 PBA-21F BN94-14806W A656MAF00001 BR10BN9414806WA656MAE4039 118005 20191015 PBA-21F BN94-14806W A656MAF00001 BR10BN9414806WA656MAE4037 118006 20191015 PBA-21F BN94-14806W A656MAF00001 BR10BN9414806WA656MAE4038 I want to get the model_code considering a Filter mag_no = "My Variable" Ex:A656MAF00001 I tried something like this, but didn't work. Magazine.objects.filter(mag_no='A656MAF00001').get('model_code').distinct().order_by() The error is: "Too many values to unpack" -
Django Redis connection error in heroku: Error 110 while writing to socket. Connection timed out
I'm using Redis for caching in my Django project which is hosted on Heroku. During Redis connection, on random times I got the below error message Error 110 while writing to socket. Connection timed out. I'm using the below packages with versions python-3.6.8 Django-2.2.2 redis-3.2.1 celery-4.3.0 Also, I'm access Redis using worker ( celery sometimes). Can someone please suggest me to get rid of this problem or any other countermeasure to handle this problem. Thanks in advance... -
exception __str__ returned non-string (type bytes) in django
Trying to execute following methods where i get exception like exception __str__ returned non-string (type bytes). def __unicode__(self): return u"{}{:02d}:{:02d}:{:05.2f}".format( '-' if self.sign == -1 else '', self._deghour, self.minute, self.second) def __str__(self): return unicode(self).encode('utf-8') def __repr__(self): return u"RADecBase('{0}')".format(self) -
Model seems overdone for single boolean value (switch on/off)
I would like admin to be able to switch a certain feature on/off on the website. It seems overdone to build an entire model for this. Any suggestions? -
How could upload to my google drive by PyDrive in digitalocean server
right now i'm using email for attaching a file every week automatically, but as google not accepting files greater then 25MB i'm going to replace email attachment with google drive store as much as more scalable. I found this lib called PyDrive and I already follow mentioned steps in the documentation for configuration either in code and google account , but the issue is still google every time asking me for permission, is there any way for passing this process by code without asking for permission or any visual stuff because i'm going to upload files to digitalocean and there is no way for select an account or press allow without any visual access ? in other hand is there any way to configure it for digitalocean server ? BTW, the I'm uploading files to my own google drive not for customers here is quickstart.py : from pydrive.auth import GoogleAuth gauth = GoogleAuth() gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication. this is code (for testing) from pydrive.drive import GoogleDrive from quickstart import gauth drive = GoogleDrive(gauth) file1 = drive.CreateFile({'title': 'Hello_me.txt'}) # Create GoogleDriveFile instance with title 'Hello.txt'. file1.SetContentString('Hello World! me again') # Set content of the file from … -
How create env on heroku and install requirements?
I want to create a virtual environment for adding a custom language.I have a project that without a virtual environment, how to add a virtual environment -
why field name getting 'none' in django templates
I created templates page and retrieving data from the model for one field I am getting none and displays Class name of the model, template code: {% for abc in events %} <div> <h2><a href="">{{ abc.event_title }}</a></h2> <p>published: {{ abc.event_release_date }}</p> <p>{{ abc.event_description|linebreaksbr }}</p> <p>{{ abc.event_author}}</p> </div> {% endfor %} View code: def index(request): return render(request, 'polls/home.html', {}) "model class name and function name should not be samm" def Event(request): events=Events.objects.all() return render(request, 'polls/events.html', {'events':events}) -
Filter foreign key date django_filters
Currently my filter works so I can filter on name. However I also want to filter on releases (So display game that has release.date between a certain range) How can I do that? filters.py class ReleaseFilter(django_filters.FilterSet): date = django_filters.DateFromToRangeFilter(field_name='date') class Meta: model = Release fields = ['date'] class GameFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') releases = ReleaseFilter() class Meta: model = Game fields = ['releases'] models.py class Game(models.Model): name = models.CharField(max_length=255) class Release(models.Model): game = models.ForeignKey(Game, related_name='releases', on_delete=models.CASCADE) date = models.DateField() -
Docker-compose on a django app postgresql connection refuse
i try to dockerize my django app, here my docker-compose.yml: version: '3' networks: mynetwork: driver: bridge services: postgres: restart: always image: postgres:11 ports: - "5432:5432" volumes: - ./data:/var/lib/postgresql/data web: build: . command: python /Code/core/manage.py runserver 0.0.0.0:8000 networks: - mynetwork ports: - "8000:8000" depends_on: - postgres inside my django app, in my settings.py i have this parameters for db connection: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydbname', 'USER': 'mydbuser', 'PASSWORD': 'mydbpassword', 'HOST': '127.0.0.1', 'PORT': '5432', 'OPTIONS': { 'client_encoding': 'UTF8', }, } } well at this point when i run docker-compose build al was done, but when i do: docker-compose up i get this error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | psycopg2.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "127.0.0.1" and accepting web_1 | TCP/IP connections on port 5432? how can i manage my django db connection parameters using my docker postgres image? So many thanks in advance -
not able to save data in django form
I am getting error Cannot assign "'1'": "dropdown.drp1" must be a "basedrop" instance. I am sharing my code. Kindly help. I got some solutions on stack but I did not understand how to implement that in my case. Django error. Cannot assign must be an instance models.py class basedrop(models.Model): name = models.CharField(max_length=50,blank=False,null=False) def __str__(self): return self.name class subdrop(models.Model): name = models.CharField(max_length=100,blank=False,null=False) bsdrop = models.ForeignKey(basedrop,null=False,blank=False,on_delete=models.CASCADE) def __str__(self): return self.name class lastdrop(models.Model): name = models.CharField(max_length=100,blank=False,null=False) sbdrop = models.ForeignKey(subdrop,null=False,blank=False,on_delete=models.CASCADE) def __str__(self): return self.name class dropdown(models.Model): name = models.CharField(max_length=50) drp1 = models.ForeignKey(basedrop,max_length=50,on_delete=models.CASCADE) drp2 = models.ForeignKey(subdrop,max_length=50,on_delete=models.CASCADE) drp3 = models.ForeignKey(lastdrop,max_length=50,on_delete=models.CASCADE) def __str__(self): return self.name views.py def create_drop(request): if request.method == 'POST': form = dropdownForm(request.POST or None) if form.is_valid(): form = dropdown(name=request.POST.get('name'),drp1_Id=int(request.POST.get('drp1')), drp2_Id=int(request.POST.get('drp1')),drp3_Id=int(request.POST.get('drp1'))) form.save() return HttpResponse('<p>this is working</p>') form = dropdownForm() return render(request,'drop.html',{'form':form})