Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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}) -
Django call_command and read from stdin
I've a django management command (MG1) which reads from stdin this way: sys.stdin.read() . I've another django management command (MG2) from which I'd like to call the MG1 command in a way that it can read from stdin. This case stdin can be a file as well, so something like: MG1 < /tmp/file.txt . How can I call the management command (from MG2) this way so it can read the /tmp/file.txt file as stdin? Django: 1.11.16 Python: 2.7.12 . Thanks. -
How can I implement the video recording feature on Agora in a Vuejs project?
I am building a project using Vuejs (frontend) and Django (backend) in which I have integrated Agora-Web-SDK-NG for video calls. Now, I want to add a feature of video recording and recordings will be stored in the cloud. I have researched a lot but couldn't found that Agora-Web-SDK-NG provides this feature and that too in Vuejs. I have read its official documentation too but couldn't found an understanding way to implement. Has anyone ever been implemented this feature in Vuejs? -
django testing 'Object has no meta error' and User has not attribute 'get'
I am trying to Test my views. I have created this Base test class and working with it. I have tried using User like this: user = User.objects.filter(id=1).first(). It shows me the same error. Also, these tests works fine if I remove the self.client part. Can anyone please help me identify the problem? class BaseTest(TestCase): def setUp(self): self.home = reverse('home') self.login = reverse('login') self.signup = reverse('signup') self.admin = User.objects.create_user(pk='1', username='random', password='secret', first_name= 'admin', last_name='user', email='admin@gmail.com') self.adminrank = UserRank.objects.create(user = self.admin, userstatus='Admin') self.agent = User.objects.create_user(pk='2', username='agent', password='secret', first_name= 'agent', last_name='user', email='agent@gmail.com') self.agentrank = UserRank.objects.create(user = self.agent, userstatus='Agent') self.client = User.objects.create_user(pk='3', username='client', password='secret', first_name= 'client', last_name='user', email='client@gmail.com') self.clientrank = UserRank.objects.create(user = self.client, userstatus='Client') self.logincred = { 'username': 'random', 'password': 'secret' } self.agentcred = { 'username': 'agent', 'password': 'secret' } self.clientcred = { 'username': 'client', 'password': 'secret' } self.wrongcred = { 'username': 'client', 'password': 'wrong' } Here are is my view that I am testing: def login(requests): if requests.method == 'POST': username = requests.POST['username'] password = requests.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(requests, user) return redirect('/profile/') else: return JsonResponse({"message": "login failed"}) def profile(requests): userstatus = UserRank.objects.filter(user= requests.user).values('userstatus') # print(userstatus) # ADMIN View if userstatus[0]['userstatus'] == 'Admin': allchecks = requests.POST.get('filter') … -
How to create anagram solver using python? [closed]
I don't understand how to write anagram solver program using python , From where i can get the dictionary of all words? can you provide me some good article on it.basically i am new to python. -
How to implement video calling feature using Django?
I have developed a website but now I want to add video calling feature in my website. Can I use Zoom Api? What will be the best option for me? -
HTTP 405 Method Not Allowed in Django rest framework
I am using Django Rest Framework to create update, delete and create view for blog, but I am getting this error while heading to a specific URL like creating - GET /api/create HTTP 405 Method Not Allowed Allow: OPTIONS, POST Content-Type: application/json Vary: Accept { "detail": "Method \"GET\" not allowed." } this is the view I used @api_view(['POST', ]) def api_create_blog_view(request): user = User.objects.get(id=1) blog = BlogPost.objects.get(author=user) if request.method == 'POST': serializer = BlogPostSerializer(blog, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['PUT', ]) def api_update_blog_view(request, blog_slug): try: blog = BlogPost.objects.get(slug=blog_slug) except blog.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'PUT': serializer = BlogPostSerializer(blog, data=request.data) data = {} if serializer.is_valid(): serializer.save() data['success'] = 'Updated Successfully!' return Response(data=data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py app_name = 'blog' urlpatterns = [ path('create', api_create_blog_view, name='create'), path('<slug:blog_slug>/', api_detail_blog_view, name='detail'), path('<slug:blog_slug>/delete', api_delete_blog_view, name='delete'), path('<slug:blog_slug>/update', api_update_blog_view, name='update'), ] I am using model serializer. class BlogPostSerializer(serializers.ModelSerializer): username = serializers.CharField(read_only=True, source="user.username") class Meta: model = BlogPost fields = ['pk', 'title', 'slug', 'body', 'image', 'date_updated', 'username'] Thank you for reading -
Is it possible to use React in Django project "partially"?
This may be a weird question, and not exactly about programming itself, but let me elaborate anyway. I hope you understand. So I myself am not a professional programmer, only learned Django this year to build the prototype of a web service I'm thinking. Now I'm able to create a basic CRUD application using Django for both front and back end. Then I recently started co-working with a full-stack programmer, who uses React for front-end and Django for back-end. In our project, there are several independent applications, with separate templates/views/models of course, and I decided to take one of them and work on it since we were running out of time. The problem is that I know nothing about React, so I thought I would work on the application purely with Django, and he could work on the rest of the project with React+Django. In this case, is it possible to "work on some parts of the project purely with Django and the rest with React+Django combination"? Or would it cause any problem or error in the entire project? Thank you very much in advance. Please let me know if you need further information. -
Django+Apache | ImportError: No Module named django
I am hosting my django app on Linode with Ubuntu OS and i have configured apache webserver. When I try to access the site i get 500 Internal Server error Apache logs show the following error Traceback (most recent call last): File "/home/mosajan/artistry/artistry/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application<br> ImportError: No module named 'django' Target WSGI script '/home/mosajan/artistry/artistry/wsgi.py' cannot be loaded as Python module. Exception occurred processing WSGI script '/home/mosajan/artistry/artistry/wsgi.py'. wsgi.py import os import sys from django.core.wsgi import get_wsgi_application sys.path.append('home/mosajan/artistry/') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'artistry.settings') application = get_wsgi_application() apache2 conf file artistry.conf Alias /static /home/mosajan/artistry/static <Directory /home/mosajan/artistry/static> Require all granted </Directory> <Directory /home/mosajan/artistry/artistry> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/mosajan/artistry/artistry/wsgi.py WSGIDaemonProcess artistry python-path=/home/mosajan/artistry python-home=/home/mosajan/artistry/venv WSGIProcessGroup artistry WSGIPythonHome /home/mosajan/artistry/venv WSGIPythonPath /hom/mosajan/artistry File structure -
code snippets in styling django template bootstrap
I have to include variables while styling django templates using Bootstrap. <div class="card mb-2 text-white bg-info"> The info part will be changed for each card accordingly. Is there any way similair to this ? <div class="card mb-2 text-white bg-{card.category}"> Please Help -
Django can't recognize view when add transaction.atomic on view function
My django project works fine. But when I add @transaction.atomic on a view function in test_view.py,e.g. @transaction.atomic @csrf_exempt @required_http_methods def test_view(request): Django server can't run correctly with Error: AttributeError: modyle 'xxx.test_view.test_view has not attribute 'test_view Without @transaction.atomic, url can find my view module. What's the problem? -
get data from primary key table in django
i have 2 table a and b class A(models.Model) abc = models.CharField(max_length = 10) class B(models.Model) xyz = models.CharField(max_length = 10) a = models.ForeignKey(A, on_delete = models.CASCADE, related_name = "get_a") not i want to implemnt query on A class and want to print data from A class and B class i try this but did not get result a = A.objects.select_related('get_a') a = A.objects.select_related('a')