Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting a property into request in Django test client
I have a middleware (tenant_schemas.BaseTenantMiddleware) that will inject tenant property into the request object. I can't use that middleware when unit testing. In a view I can then get the tenant object from the request. This view is mapped to the URL "myapp:member_info". class MemberView(TemplateView): template_name = 'myapp/member.html' def get_context_data(self, member_id=None, *args, **kwargs): ctx = super().get_context_data(*args, **kwargs) tenant = self.request.tenant ctx['tenant_name'] = tenant.name return ctx This view works when the project is run normally as the middleware will set request.tenant correctly. Now, if I want to test this view I try to write following test: class MemberViewTest(TestCase): def setUp(self): self.tenant = Tenant(name="test tenant") self.member = Member.objects.create( first_name='Test', last_name='Person') def test_saldo(self): self.client = Client(tenant=self.tenant) # Here I try to inject the tenant into the request print(self.client.defaults) # This will print {'tenant': <Tenant: test tenant>} response = self.client.get(reverse('myapp:member_info', kwargs={ 'tenant': self.tenant, 'member_id': self.member.token })) This test fails to error: File "myapp/views.py", line xxx, in get_context_data tenant = self.request.tenant AttributeError: 'WSGIRequest' object has no attribute 'tenant' So, the django.tests.Client class is not injecting the defaults to the request. One thing I tried is to override the RequestFactory (https://github.com/django/django/blob/ac6c4260074de43a978e5c6553ef89441e1d6748/django/test/client.py#L308) so that it would inject the tenant. class TenantRequestFactory(RequestFactory): def request(self, **request): req = super().request(**request) … -
Why firstname and lastname fields are stored after fail validation which password doesn't
I have a registration form there are have few fields including first name, last name, password and password confirm. I'm wondering why first name and last name value still in the form after the form fail in validation while password field doesn't. What makes those fields behave differently from each other. -
how to test a graphene mutation with **kwargs on mutate function?
I am testing a mutation that creates a user something like this: def test_create_user(self): user_mutation = """ mutation($id: ID!, $group: GroupInput!, $address: AddressInput!){ createUser(id: $id, group: $group, address: $address) { user { id } } } """ group = { 'name': 'GroupA', 'contact': '1231323131' } address = { 'street': '123', 'city': 'Test City' } resp = self.client.execute(user_mutation, variable_values={ 'id': str(uuid.uuid4()), 'group': group, 'address': address }) The Mutation Class: class CreateUser(graphene.Mutation): class Arguments: id = graphene.String(required=True) group = GroupInput(required=True) address = AddressInput(required=True) ...more input here user = graphene.Field(UserType) def mutate(self, info, **kwargs): user = create_user(**kwargs) return CreateUser(user=user) The problem is that when I try to run this test is it return an error: test_create_user {'errors': [{'message': "create_user() got an unexpected keyword argument 'group'", 'locations': [{'line': 4, 'co lumn': 25}], 'path': ['createUser']}], 'data': OrderedDict([('createUser', None)])} I'm not sure how should I go about this and I use kwargs because there is much more input to be added here. Any ideas and suggestions is greatly appreciated! -
The submitted data was not a file. Check the encoding type on the form. This error showing up while submitting image through react hook forms
Hi guys I am getting this error while submitting this form with an image through react hook form. This is the error I am getting from the backend. {image: ["The submitted data was not a file. Check the encoding type on the form."],…} image: ["The submitted data was not a file. Check the encoding type on the form."] 0: "The submitted data was not a file. Check the encoding type on the form." But I am able to make it work without any problems through postman. I am new to react, can anyone help to solve this. I am using django in the backend and django rest framework for api endpoints. form. import React, { useState } from 'react'; import axiosInstance from '../../axios'; import { useForm } from 'react-hook-form'; //MaterialUI import Button from '@material-ui/core/Button'; import CssBaseline from '@material-ui/core/CssBaseline'; import TextField from '@material-ui/core/TextField'; import Grid from '@material-ui/core/Grid'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/core/styles'; import Container from '@material-ui/core/Container'; const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(9), display: 'flex', flexDirection: 'column', alignItems: 'center', }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { margin: theme.spacing(3, 0, 2), }, input: { display: "none", … -
only one slug provided but URL is taking two parameters
I am trying to test my application and found out the I provided only one parameter as a slug but the URL is using two. I have added slug in the urls.py and in the HTML form as well. Here is the code example: URLs: urlpatterns = [ ... path('edit/<slug:loanid>/', views.edit, name="edit"), path('edituser/<int:userid>/', views.edituser, name="edituser"), ] Views: def edit(requests, loanid): if (requests.user.is_authenticated and requests.user.userrank.userstatus == 'Agent'): loan = Loan.objects.get(loanid=loanid) history = loan.history.all() # print(history) loanstatus = Loan.objects.filter(loanid=loanid).values('loanstatus') if loanstatus[0]['loanstatus'] == 'Approved' or loanstatus[0]['loanstatus'] == 'Rejected': return JsonResponse({"message": "Loan is approved Cannot Edit"}) else: return render(requests, 'edit.html', {'loan': loan, 'history': history}) else: return HttpResponseForbidden() def edituser(requests, userid): if (requests.user.is_authenticated and requests.user.userrank.userstatus == 'Agent' or requests.user.userrank.userstatus == 'Admin'): user = User.objects.get(pk=userid) return render(requests, 'edituser.html', {'user': user}) else: return HttpResponseForbidden() Here are the templates and form used to render: <form action="/edituser/{{eachuser.id}}/" method="GET" class="status"> <input type="hidden" value="{{eachuser.id}}" name="loanid"/> <input type="submit" value="Edit" class="btn btn-primary"/> </form> <form action="/edit/{{eachloan.loanid}}/" method="GET" class="status"> <input type="hidden" value="{{eachloan.loanid}}" name="loanid"/> <input type="submit" value="Edit" class="btn btn-primary"/> </form> URLs that are showing in the browser: http://127.0.0.1:8000/edituser/19/?loanid=19 http://127.0.0.1:8000/edit/a38aa1b6-9158-4d71-a725-dc5406184aec/?loanid=a38aa1b6-9158-4d71-a725-dc5406184aec -
How to Keep Django Project Running after Closing terminal?
I have Very Comman issue might looks easy.I have Pushed my Django project on Live Digital Ocean server.I have done all the Configuration using Putty terminal.My project is Working Fine but when i close my Terminal,Project stopped working.I am using Digital Ocean Server.my Question is How to Keep Project Running after closing terminal? i will be Thankful if anyone can Help me with this issue. -
search results are not displayed on the search page in django
I have a search form on the index page and I want to display the result inside the search page when it does a search. I hope help me. urls.py path('search/', views.search, name='results'), veiw.py def get_queryset(self): booksearchlist=Book.objects.all() query = self.request.GET.get('q') object_list = Book.objects.filter( Q(Titel__icontains=query) ) return render(request,'search.html',{'object_list':object_list,'booksearchlist':booksearchlist}) model.py class Book (models.Model): BookID= models.AutoField(primary_key=True) Titel=models.CharField(max_length=150 ) Author=models.ForeignKey('Author',on_delete=models.CASCADE,verbose_name="نام نویسنده") Price= models.IntegerField(null='true',blank='true') Image=models.ImageField(upload_to ='upload/bookimage' ) result.html {% if object_list %} {% for Book in object_list %} <section id="card" class="col-md-6 col-lg-3 col-sm-6 col-xs-12"> <a href=""><img src= {{Book.Image.url}}></a> <h1 id="bookname">{{Book.Titel}}</h1> <p id="price">{{Book.Price}}</p> <p>{{Book.Author}}</p> </section> {% endfor %} {% else %} <p>No search results for this query</p> {% endif %} index.html <form class="searchform "method="GET" action="{% url 'results' %}" value="{{request.GET.q}}" > <input type="search" name="q" class="search-box" value="{{request.GET.q}}" formnovalidate autocomplete="off" placeholder="جست و جوی کتاب، نویسنده، ناشر"> <button type="submit" class="searchbtn" value="search"> <i class="fas fa-2x fa-search"></i> </button> </form> -
Custom sorting on model property django-table2
I use django-table2. Now I want to create custom sorting on property of my model. My models are: class Department(models.Model): Department_TYPE_CHOICES = ( (1, 'branch'), (2, 'unit'), (3, 'center'), ) title = models.CharField(max_length=128) identity = models.IntegerField(choices=global_vars.Department_TYPE_CHOICES) reference = models.ForeignKey('self', on_delete=models.PROTECT,null=True) class Enrollment(models.Model): title = models.CharField(max_length=128) department = models.ForeignKey('department', on_delete=models.PROTECT,null=True) @property def unit(self): department = self.department if department.identity == 2: return department.title elif department.identity == 3: return department.reference.title My table is: class MyTable(tables.Table): unit = tables.Column(order_by=("department")) class Meta: model = Enrollment fields = ("title") sequence = ('unit', "title") All things are good except that I want to sort on unit property. I used order_by on unit property, but sorting didn't done on unit and done on department field. So, How can I define sorting for my property? -
Django & Vuejs Issue while downloading excel file
I tired to download Excel file from Django REST API I created and the Excel file downloaded after opening it gives me the <xlsxwriter.workbook.Workbook object at 0x000001D627EF7A90> object in the first cell. Here's the code for django for generating Excel file: @csrf_exempt def export_to_excel(request): response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=Report.xlsx' xlsx_data = WriteToExcel() response.write(xlsx_data) return response Here's the function of creating Excel file: def WriteToExcel(repo_data): workbook = xlsxwriter.Workbook('Expenses01.xlsx') worksheet = workbook.add_worksheet() # Some data we want to write to the worksheet. expenses = ( ['Rent', 1000], ['Gas', 100], ['Food', 300], ['Gym', 50], ) # Start from the first cell. Rows and columns are zero indexed. row = 0 col = 0 for header in headers: worksheet.write(0,col,header) col += 1 workbook.close() return workbook in Vuejs file, here's the axios request I do to download the file: export_to_excel: function () { axios .post(this.$apiServer + "/export_to_excel", { headers: { "Content-Type": "application/vnd.ms-excel", "Access-Control-Allow-Origin": "*", }, }) .then((response) => { var fileURL = window.URL.createObjectURL(new Blob([response.data])); var fileLink = document.createElement('a'); fileLink.href = fileURL; fileLink.setAttribute('download', 'Expenses01.xlsx'); document.body.appendChild(fileLink); console.log(response.data); fileLink.click(); }).catch(error => { console.log(error); }) }, What's wrong with this code? -
Apache Process Memory Leaking
I have a Apache server running with Django API and this API is serving only images . There are opencv and dlib libraries are using to crop the image . But when there is a spike in traffic Apache process the requests but memory somehow not released here is graph of memory showing how server memory act during spike and after spike when there is not process running memory utilization is very high enter image description here My distribution is Ubuntu 18 hosted on and ec2 with 2vcpu and 4GB Ram . using below command its says 204 mb but in time of spike it increase to 450MB or more ps -ylC apache2 --sort:rss | awk '{sum+=$8; ++n} END {print "Tot="sum"("n")";print "Avg="sum"/"n"="sum/n/1024"MB"}' Tot=2514524(12) Avg=2514524/12=204.632MB Here are my Apache configurations for keepalive and timeout /etc/apaache2/apach2.conf Timeout 65 # # KeepAlive: Whether or not to allow persistent connections (more than # one request per connection). Set to "Off" to deactivate. # KeepAlive On # # MaxKeepAliveRequests: The maximum number of requests to allow # during a persistent connection. Set to 0 to allow an unlimited amount. # We recommend you leave this number high, for maximum performance. # MaxKeepAliveRequests 0 # # … -
Generation checks
У меня есть модели: class Printer(models.Model): name = models.CharField(max_length=250) api_key = models.CharField(max_length=250, unique=True) check_type = models.CharField(max_length=20, choices=STATUS_CHOICES, default='kitchen') point_id = models.PositiveIntegerField() def __str__(self): return self.name class Check(models.Model): printer_id = models.ForeignKey(Printer,related_name='printer', on_delete=models.CASCADE) type = models.CharField(max_length=10,choices=STATUS_CHOICES) order = models.JSONField() status = models.CharField(max_length=10,choices=STATUS) pdf_file = models.FileField() def __str__(self): return self.printer_id I need: 1.The service receives information about a new order, creates receipts in the database for all printers of the point specified in the order, and sets asynchronous tasks to generate PDF files for these receipts. If the point has no printers, it returns an error. If receipts for this order have already been created, it returns an error. 2.Asynchronous worker using wkhtmltopdf generate PDF from HTML template. The file name should look like _ .pdf (123456_client.pdf). The files should be stored in the media / pdf folder at the root of the project. 3.The application polls the service for new receipts. The poll takes place in the following way: first, a list of receipts that have already been generated for a specific printer is requested, then a PDF file for each receipt is downloaded and sent to print. Please, tell me the steps on how to do this work, and what api … -
Django- How do I select particular columns from a model?
I have an array of columns. Like, fields = ['first_name', 'last_name', 'email'] # this values can be dynamic I want the values of those columns from the User model. I tried this. User.objects.values(fields) But it doesn't work. It provides a traceback. AttributeError: 'list' object has no attribute 'split' Any solution? -
is there a way to use the querries developed within python into django
I have developped many SQLite querries using python (see an example here below) and i'd like to publish the results of the querry via Django web page . I have installed Django and created the ORM linked to the SQLITEDB . My question is the following : Is there a way to call these querries (created with python) or their results directly from Django ? . Or i have to recode these quesrries into "Django" language . I have already started recoding these querries in a compatible 'Django language" under views.py and a html page. I'm afraid that i'm losing my time in recoding . any recommendations or advice that can help are welcome . Example of Querry in pyhthon : cursor.execute(""" SELECT "AgentName", count (*) FROM "CSQ Agent Report" WHERE "AgentName" != "None" AND "OriginatorDNHANDELED" = '1' or "OriginatorDNNOTHANDELED" = '1' Group by "AgentName" """) liste8= cursor.fetchall() for i in range (len(liste8)): print (liste8[i][0],liste8[i][1]) ///////////////////////////////////////////////////// Here below what i started coding in django views and html page in Django views def home(request): queryset = CsqAgentReport.objects.values('agentname').filter(csqnames__exact = 'CSQ_HDF*').filter(contactdisposition__contains='2').annotate(total=Count('nodeid_sessionid_sequenceno',distinct=True)).order_by('csqnames') context = { 'object_list' : queryset, } In the html file : {% block content %} <h1> Stats Call Center </h1> <p> … -
How can I connect to MySQL in Python 3.7 on Windows?
After changing database to mysql in Django I cannot migrate. I use Django 3.0.8, Python 3.7, I have tried: pip install PyMySQL pip install mysql-connector-python==8.0.21 pip install mysqlclient and I received an error: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Do you have any idea guys? -
About PostgreSQL with Django and CPanel
Quick question I have Django (version 3.1.1) on the server with Centos 7 with CPanel and database based on PostgreSQL (version 9.2.24). I was pretty happy with this setup, till recently I tried to do changes in my databse tables through the python models.py. I ran the following command: python manage.py inspectdb... So I understand which changes I have to make in models.py... This command gave me the following fault: # Unable to inspect table 'auth_group' # The error was: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... For every table in my database. In the meantime I never had any problems with makemigrations or migrate commands... So I tried to look up this fault, the only thing I found is that PostgreSQL version 9 is not supported by Django anymore... I looked up into manage.py in my project folder and discovered that somehow it is empty, despite I have my tables in my PostgreSQL it contacts to Django and behaves normally on the site... So I would definitely need to post my tables into the file.(?) I would like to install PostgreSQL which is supported by Django, but I have response from my … -
Convert image to PDF with Django?
Receive multiple images as input from the user and convert them into PDF. I don't understand how to implement it with Django. -
cant convert response to json
i try to use an api that return something like this: {"responseCode": "-1002","responseMessage":"Invalid UserName oR Password"} now I want to access responseCode.I have to functions: def A in API module: def A(UserName,Password,RoleID): obj=models.Api.objects.all().last() url = "{}/GetPatNo?UserName={}&Password={}&RoleID={}".format(obj.Api,str(UserName),str(Password),int(RoleID)) payload = {} headers= {} response = requests.request("GET", url, headers=headers, data = payload) return (response) and def B in views.py: import json from . import API as API def B(request): if request.method == 'POST' user=request.POST['username'] password=request.POST['password'] user_type=request.POST['user_type'] result = API.A(user,password,user_type) return HttpResponse(result.json()['responseCode']) the error is here: Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) and here traceback: -
The view posts.views.register didn't return an HttpResponse object. It returned None instead
I'm unable to add serverside validations for username it was working fine for password -
How can i get the raw SQL of changes in models.py including table creation
I want to get the SQL query of the changes i have made in my application model -
Do malicious files uploaded via forms pose any threat before saving to disk?
I currently have a form that allows users to upload photos with Python/Django. I want to bypass all the issues of dealing with malicious files though and just upload them straight into an S3 bucket. My question now is, is it safe for me to Accept the POST Instead of saving to disk, just upload the photo straight into an S3 bucket in the backend Or would I still be putting my server at risk just by accepting the POST request? -
Can I set up my Django REST API to only allow a specific sub domain from a domain?
I am trying to have my API be accessible from a specific subdomain. Currently my Settings.py file is structured as: ALLOWED_HOSTS = [ 'localhost', 'http://localhost:7999' ] ... ... ... CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ 'http://localhost:8001' ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT' ] Let's say I wanted the api to be accessible from only localhost:7999, but specifying localhost in the ALLOWED_HOSTS variable makes all the subdomains able to access the API. Is there a way around this without having to use CORs. -
i am getting inconsistent migration history when running my first migrate on django-oscar
this is my installed app list when i run migrations,it just displaye django.db.migrations.exceptions.InconsistentMigrationHistory: Migration order.0001_initial is applied before its dependency basket.0002_auto_20140827_1705 on database 'default'. 'oscar.apps.address.apps.AddressConfig', 'oscar.apps.shipping.apps.ShippingConfig', 'oscar.apps.catalogue.apps.CatalogueConfig', 'oscar.apps.catalogue.reviews.apps.CatalogueReviewsConfig', -
DJANGO - REDIRECT USER TO ITS VIEW AFTER LOGIN
I'm working on a django project. My project manages tasks and it is devided in 3: there's a part for the designers, a part for web developers, and a part for accounting. After the user logs in I've redirected them to the view that show the designers's tasks,through: LOGIN_REDIRECT_URL. I'd like to know how can i redirect the webdeveloper users to the view that show their task and not the designers' ones. and the same thing for the accountants, that like the webdevelopers when the login in they now see the designers' tasks view. I mean there's a way to specify different login redirect urls based on the user that is logging in? -
Truncated or oversized response headers received from daemon process error and WSGIApplicationGroup %{GLOBAL} does not fix it
My app crashes when it is been called from certain route (/shop/all) which extract every product and display on the page but does not crash on other route. I've tried WSGIApplicationGroup %{GLOBAL} which does not seem to fix. I'm running multiple django on one server instance which could be potential problem too. I've tried disabling the rest of django project except only one which does not seem to work as the problem still occurs. requirements.txt beautifulsoup4==4.9.1 bleach==3.2.1 Django==3.1 django-bootstrap4==2.2.0 django-crispy-forms==1.9.2 gunicorn==20.0.4 lxml==4.5.2 packaging==20.4 Pillow==7.2.0 psycopg2==2.8.6 pyparsing==2.4.7 pytz==2020.1 six==1.15.0 soupsieve==2.0.1 sqlparse==0.3.1 webencodings==0.5.1 whitenoise==5.2.0 So i came to conclusion of my own that my problem might come from saving binary data(images) in the database (PostgreSQL) and when web request has been made to certain api(/shop/all) that extract 80% of data from the database (such as all products) the process became some sort of timeout which simply out of my knowledge. Considering the site used to work fine when there were not much of data as it compare to now which only reinforce my doubt. I'm asking is there's anything I can try that I've been missing before I try implementing pagination on the app. I'll update if pagination fixes my problem and … -
Django Rest Framework using Extra Actions to make foreign key data routable
I have two models which are each in a different app. Stock model references Financials model through a foreignkey relationship as shown below. with the current Stock Viewset, also displayed below, I am able to access the individual stock through localhost:8000/stocks/aapl, but I would like to extend that url to include the financials foreign key data such as localhost:8000/stocks/aapl/financials/balance-sheet/. I was told to use Extra Actions, which I've attmpted and posted below but no luck. Any clue how to do this ? class Stock(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) ticker = models.CharField(max_length=10, unique=True, primary_key=True) slug = models.SlugField(default="", editable=False) financials = models.OneToOneField( Financials, on_delete=models.CASCADE, default=None ) def get_financials(self): return self.financials financial model class Financials(models.Model): # ticker = models.ForeignKey( # Stock, on_delete=models.CASCADE, related_name="balance_sheets" # ) balance_sheet = models.ForeignKey( BalanceSheet, on_delete=models.CASCADE, related_name="balance_sheets" ) income_statement = models.ForeignKey( IncomeStatement, on_delete=models.CASCADE, related_name="income_statements" ) cashflows_statement = models.ForeignKey( CashflowsStatement, on_delete=models.CASCADE, related_name="cashflows_statements", default=None, ) stocks.views.py class StockViewSet(viewsets.ModelViewSet): queryset = Stock.objects.all() serializer_class = StockSerializer lookup_url_kwarg = "ticker" lookup_field = "ticker__iexact" @action(detail=True, methods=['post', 'get']) def financials(self, request, ticker=None): stock = self.get_object() financials = stock.get_financials() return Response({financials})