Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In django,how get share the an object between the method of GET and POST
guys! I generate a requests.session() obeject in get method, and i want use it latter in the post method. How can i do it? # views.py import requests class Page(View): session = None def get(self,request): self.session = requests.session() # get an session object return def post(self,request): self.session # I want use the self.session which generate in get methon return # urls.py urlpatterns = [ path(r'page/',views.Page.as_view(),name='page'), ] -
How to skip validation for DRF serialiser FloatField
Problem I need to add the ability to save the minimum_commission as positive number, but None is also available. I have added the serialiser: class RentalTestSerializer(serializers.ModelSerializer): minimum_commission = serializers.FloatField(required=False, min_value=0) class Meta: model = Appartement fields = ( 'minimum_commission', ) But when I pass the empty string from the form(or shell), I see the A valid number is required validation error. In [21]: ser = RentalTestSerializer(data={'minimum_commission': ''}) In [22]: ser.is_valid() Out[22]: False In [23]: ser.errors Out[23]: ReturnDict([('minimum_commission', [ErrorDetail(string=u'A valid number is required.', code=u'invalid')])]) Possible solution At first I have added custom field: BlankableFloatField which convert empty string to the None: class BlankableFloatField(serializers.FloatField): """ We wanted to be able to receive an empty string ('') or 'null' for a float field and in that case turn it into a None number """ def to_internal_value(self, data): if data in ['', 'null']: return None return super(BlankableFloatField, self).to_internal_value(data) and added the custom validation: class RentalTestSerializer(serializers.ModelSerializer): minimum_commission = BlankableFloatField(required=False) class Meta: model = Appartement fields = ( 'minimum_commission', ) def validate_minimum_commission(self, value): if value and value < 0: raise serializers.ValidationError(_("Minimum commission should be greater than 0")) return value For now it works as expected: In [38]: ser = RentalTestSerializer(data={'minimum_commission': ''}) In [39]: ser.is_valid() Out[39]: True … -
Django user sign up doesn't work properly (Users are not registered to DB)
I made the django user registration form with profile picture uploading. By combining default user libraries with profile module. But when I register a user click on submit without registering the user i will be directed to the index.html. When i check in the data base also the user details entered in the sign up form doesn't appear. Im using pycharm for development and django version is 1.9 view.py def signup(request): if request.method == 'POST': form = Signup(request.POST,request.FILES) if form.is_valid(): user = form.save(commit=False) user.refresh_from_db() username = form.cleaned_data.get('username') password1 = form.cleaned_data.get('password1') user.set_password(password1) user.save() user = authenticate(username=username,password=password1) login(request,user) return HttpResponseRedirect('/') else: form = Signup() args = {'form':form} return render(request, 'register.html', args) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) business_reg = models.TextField(max_length=500, blank=True) avatar = models.ImageField(upload_to='avatars/') @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() forms.py class Signup(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) business_reg = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) avatar = forms.FileField(widget=forms.FileInput(attrs={'class': 'form-control'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = User fields = ('username','business_reg','avatar','password1', 'password2',) register.html <div class="panel-body"> <form method="post"> {% csrf_token %} <div class="form-group"><label for="formGroupExampleInput">Username</label>{{ form.username }} </div> <div class="form-group"><label for="formGroupExampleInput">Business Registration</label>{{ form.business_reg }} </div> <div class="form-group"><label for="formGroupExampleInput">Profile Picture</label>{{ form.avatar }} </div> <div class="form-group"><label for="formGroupExampleInput">Password</label>{{ form.password1 }} </div> <div class="form-group"><label … -
Correct way to apply gherkin features and scenarios to django views
I am trying to understand practical usage of gherkin features and scenarios using django generic views as an example, because I am familiar with django but not gherkin. In writing gherkin for django views, what would be an example of best practice for separating features and scenarios specific to django generic views, and an example of a terrible one, and why? For example - in a Reports app that has generic views for update, detail and list for a report model. Would there be separate features for update, list and detail or would the reports app be a feature with update, detail and list scenarios? I ask this specifically not only because I am writing a reporting app in django, but because django is a highly structured framework that would seem to easily fall into gherkin and examples of such would be very easy for me to learn to understand gherkin practically. -
redirect() between views in separate apps
I am following a Django tutorial where the blog app and users app are separate. Upon registering as a user I would like the user to be redirected to a view in the blog app. Here is the users app views.py: def register(request): if request.method == 'POST': # if form was submitted w data form = UserCreationForm(request.POST) #instantiate form w post data if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}') return redirect('blog-home') #not working else: form = UserCreationForm() return render(request, 'users/register.html', {'form':form}) and here is the blog app's views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Post # Create your views here. def home(request): posts = Post.objects.all() return render(request, 'blog/home.html', {'posts':posts}) and the url pattern tied to said view: path('', views.home, name = 'blog-home'), When a user submits the form, I get the following error: Reverse for 'home' not found. 'home' is not a valid view function or pattern name. I am not sure why this is, I believe I copied the code word for word and the example in the video is working. -
django model instance method not being called
I want to update my model upon login (to check the authorizations of a person from an external system). The code of my model looks as follow: import json from django.contrib.auth.models import AbstractUser from django.contrib.auth.signals import user_logged_in from django.db import models class Person(AbstractUser): is_dean = models.BooleanField(null=False, blank=False, default=False) is_institute_manager = models.BooleanField(null=False, blank=False, default=False) managed_institutes = models.TextField(blank=True, null=True, default=None) def get_managed_institutes(self): return json.loads(self.managed_institutes) def set_managed_institutes(self, value): self.managed_institutes = json.dumps(value) # Signals processing def check_authorizations(sender, user, request, **kwargs): ... # check if the user is dean is_dean = False # logic to check if the user is dean... user.is_dean = is_dean # Check if the user manages institutes is_institute_manager = False managed_institutes = list() # Logic to check if the user is managing institutes ... user.is_institute_manager = is_institute_manager user.set_managed_institutes = managed_institutes user.save() user_logged_in.connect(check_authorizations) Surprisingly, the boolean flags get set correctly, but the method set_managed_institute never gets called... I am quite convinced this a trivial mistake from my end, but I can't figure it out. -
Call View from another View after modifying request (Rest-Framework)
Book_ViewSet: I have a ViewSet that takes care of all the CRUD operations on a product. Consider Book API, where I can create a book based on title and author. ISBN_View: I have another View that accepts ISBN numbers, looks up the book, gets the title and author and creates the Book from Model. What I want: After parsing ISBN data and getting the book info, I want to create a fresh POST request to the Book_ViewSet with the book data as the body. I tried looking up best way to do this, but people suggested that modifying current request and sending it to different view is a bad practice. ============================================================= class Book_ViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = serializers.BookSerializer def create(self, request, *args, **kwargs): . . . return super().create(request, *args, **kwargs) def retrieve(self, request, *args, **kwargs): . . . return super().retrieve(request, *args, **kwargs) def destroy(self, request, *args, **kwargs): pass def update(self, request, *args, **kwargs): . . . return super().update(request, *args, **kwargs) class ISBN_view(generics.RetrieveAPIView): def get(self, request, isbn=None, *args, **kwargs): isbn, validation_error = self.validated_isbn(isbn) if not isbn: return Response(validation_error) # Here I use ISBN to search up books, and grab data # Here I want to call Book_ViewSet to create the … -
Django use calculated field for ordering_fields
I'm using Django and Django Rest Framework, with PostgreSQL. I need to create a calculated field on the model, and I need to also order by the field. I thought of using @property decorator for the calculated field, but as far as I know, I can't add this 'field' to the ordering_fields array. My question is - what would be the right way to do it? Should be something like (partial): The model- class MyModelViewSet(models.Model): due_date = models.DateField(null=True, blank=True) final_due_date = models.DateField(null=True, blank=True) @property def due_date_diff(self): if self.final_due_date: return self.final_due_date - due_date else: return due_date - date.today() In the View I would like to do something like: class MyModelViewSet(viewsets.ModelViewSet): serializer_class = MyModelSerializer ordering_fields = tuple(serializer_class.Meta.fields + due_date_diff) -
How to change the template of the added model in the admin panel of the django?
I added a model book and I want to set a template for the add method, but I can not find it( -
Customize Auto Generated Input button Django
I have a ModelForm to upload an image. My view handle it, upload works. But i want to crop the image with a javascript. The javascript needs to be called on the " input " like : <input type="file" id="fileInput" onchange="handleFileSelect()" /> I checked by inspecting the code generated by Django for the ' input' input and it looks like this : <input type="file" name="idPicture" accept="image/*" required="" id="id_idPicture"> so i'd like to add the onchange to the input. How can i do that ? Is this even possible ? Thank you. -
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 …