Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Foreign Keys and the Admin Page
Preface: I've been scouring stackoverflow but have found a solution - please point me in the correct direction if one does exist. I am trying to display the foreign key relations on the admin change page (i.e. the www.some.url/admin/<app>/<model>/<id>/change/ page): I have two models linked together via a foreign key relationship like so: # models.py class Bank(models.Model): name = models.CharField(max_length=100) class Branch(models.Model): bank = models.ForeignKey('Bank', on_delete=models.CASCADE, related_name='branches') name = models.CharField(max_length=100) And I have a model-admin like so: # admin.py class BankAdmin(admin.ModelAdmin): list_display = ('id', 'name',) How can I add the list of branches associated to a given bank on the django-admin-change page? Can I add something to my BankAdmin class that will achieve this? i.e. If I were to visit the admin page and click on a bank instance (i.e. www.some.url/admin/<app>/bank/2/change/) I would like to see the name of the bank and all of its foreign-key related branches. -
Stripe Checkout Client-only integration with Django
My goal is to integrate a Stripe Checkout Client-only integration with a Django app using these instructions. I copied the code provided by stripe into a html template. When I run the template, the checkout button appears but the stripe script is not executed when the button is clicked (no errors). I expected to be redirected to the stripe checkout page. I have tried moving the javascript to separate files in the static folder with the same result. Is the issue linking the button click to the javascript? Here is the html template with the stripe code inserted: {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <title></title> <!-- Load Stripe.js on your website. --> <script src="https://js.stripe.com/v3"></script> </head> <body> <!-- Create a button that your customers click to complete their purchase. Customize the styling to suit your branding. --> <button style="background-color:#6772E5;color:#FFF;padding:8px 12px;border:0;border-radius:4px;font-size:1em" id="checkout-button-sku_GyczP1qEmsj6eZ" role="link" > Checkout </button> <div id="error-message"></div> <script> (function() { var stripe = Stripe('pk_test_yWdjuG9EAuGjwpVenyzR6Ykn00AsFHsmGC'); var checkoutButton = document.getElementById('checkout-button-sku_GyczP1qEmsj6eZ'); checkoutButton.addEventListener('click', function () { // When the customer clicks on the button, redirect // them to Checkout. stripe.redirectToCheckout({ items: [{sku: 'sku_GyczP1qEmsj6eZ', quantity: 1}], // Do not rely on the redirect to the successUrl for fulfilling // purchases, customers may … -
adding a new column to postgres db django
I am trying to add a new column to an existing table with django in my postgres db. I did python3 makemigrations and python3 migrate but the new column does not appear. I also cleared migrations. It would still say the column does not exist on the db. The only workaround is to manually enter it in commandline or clear the whole database and start from scratch. Is there another alternative? -
Querying BigQuery Dataset from Django App Engine
I have data stored in BigQuery - it is a small dataset - roughly 500 rows. I want to be able to query this data and load it in to the front end of Django Application. What is the best practice for this type of data flow? I want to be able to make calls to the BigQuery API using Javascript. I will then parse the result of the query and serve it in the webpage. The alternative seems to be to find a way of making a regular copy of the BigQuery data which I could store in a Cloud Storage Bucket but this adds a potentially unnecessary level of complexity which I could hopefully avoid if there is a way to query the live dataset. -
updating values in django template in html input?
i am making a shopping cart , i want to update the value as the user updates the input field.. here is my code.. `<tr> <th scope="row">1</th> <td>${object['name']}</td> <td><input type="number" value=1 id=${object['id']}></td> <td>${object['price']*this.value}</td> </tr>`; the input field has a default value of 1. In the last tag i am multiplying value by the price. i am using "this" keyword because i want to apply the multiplied amount to the same row. It doesn't give me any error but it just prints "NaN" in the table not the figure. -
Is there any security issue while giving only "select" and "insert" permissions on all tables with psycopg2?
I think that writing a python script that includes admin credentials for postgresql database is not secure way. So I am trying to add another side: Django web server. But I have concerns yet again. I wanted to increase security by giving only "select" and "insert" permissions to a user and giving all other jobs (creating table, updating, again inserting) to a Django server. But I've started to think it's a bad idea. However I don't have another idea to do it securely. What do you think about that? -
Cannot set Django migrations in the right order
I added a new app 'portfolio' in my project, but since then migrations won't work anymore because Django seems to be trying to do them in the wrong order. Running migrations: Applying core.0001_initial... OK Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying user.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying data.0001_initial... OK Applying data.0002_auto_20200306_1522...Traceback (most recent call last): File "/opt/miniconda3/envs/cert_tool/lib/python3.7/site-packages/django/apps/registry.py", line 155, in get_app_config return self.app_configs[app_label] KeyError: 'portfolio' During handling of the above exception, another exception occurred: [...] LookupError: No installed app with label 'portfolio'. portfolio is listed in my INSTALLED_APPS : LOCAL_APPS = ( 'core', 'portfolio', 'user', 'data', 'editor', ) INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS + THIRD_PARTY_APPS If I add a dependency in the problematic data.0002_auto_20200306_1522 migration : class Migration(migrations.Migration): dependencies = [ ('data', '0001_initial'), ('portfolio', '0001_initial'), ] Other errors occur : django.db.migrations.exceptions.NodeNotFoundError: Migration data.0002_auto_20200306_1522 dependencies reference nonexistent parent node ('portfolio', '0001_initial') Traceback (most recent call last): File "/opt/miniconda3/envs/cert_tool/lib/python3.7/site-packages/django/db/migrations/loader.py", line 166, in check_key return self.graph.root_nodes(key[0])[0] IndexError: list index out of range During handling … -
What is the replacement for AWS infrastructure for Celery and Redis?
My application is written in django f/w which uses celery and redis for asynchronous tasks. I would like to autoscale workers according load/no.of messages in queue. For this, I would like to make use of different options provided by AWS. What is the replacement for AWS infrastructure for Celery and Redis? -
Where to save file that gets updated nightly?
I have a cron job that runs nightly and updates a json file, the json file is used by the site to build a map. Right now I am saving it to the MEDIA_ROOT is this a good practice, if not where should this file be saved to? -
Why PDF is not showing in angular
How can I show a pdf file while using a url? Frontend is in angular and backend is in django. PDF files can have dynamic links but those PDF are hosted on my own server. I know about X-Frame and X-Frame is DENY but I have tried all other options and still unable to fix it. I have tried almost every possible solution available online!! This is how I am trying to show my PDF in html file <div [innerHTML]="innerHtml"> </div> Here my code which inititalize innerHtml constructor( public sanitizer: DomSanitizer ) { } public setInnerHtml(pdfurl: string) { this.innerHtml = this.sanitizer.bypassSecurityTrustHtml( "<object data='" + pdfurl + "' type='application/pdf' class='embed-responsive-item' style='width: 100%; height: 90vh'>" + "Object " + pdfurl + " failed" + "</object>"); } but its showing this error on console and not showing any pdf Refused to display 'FULL_URL_OF_MY_PDF_FILE' in a frame because it set 'X-Frame-Options' to 'deny'. -
OpenCV videocapture returns False when calling isOpened(), although, another code example works well
So, I have a Django app, that manages some USB webcameras(all Logitech C525) This app takes frame from a VideoCapture object, when the GET request comes on specified API-endpoint and sends this frame to a server, to do some classification of object on image (usually fruits/vegetables) App receiving requests from clients, each client's IP address(app and clients are in the same local network) is binded to unique webcam ID Here's a snippet, that shows, how I'm searching binding between camera ID and logical device in /dev/video* to create a VideoCapture object: import re import subprocess class CameraBinder(object): def __init__(self): self.cam = 'C525' self.cam_id_list_in_dev_video = [] self.binding_between_udev_dev = None def find_cam_in_dev_video(self): cmd = ['/usr/bin/v4l2-ctl', '--list-devices'] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate() out, err = out.strip(), err.strip() for line in [i.split("\n\t".encode()) for i in out.split("\n\n".encode())]: if self.cam.encode() in line[0]: cam_id_from_dev = re.search(r'(?<=/dev/video).*', line[1].decode('utf-8')) self.cam_id_list_in_dev_video.append(cam_id_from_dev.group(0)) process.kill() return self.cam_id_list_in_dev_video def bind_cam_between_dev_udev(self, cam_id): cmd = ['/bin/udevadm', 'info', '--attribute-walk', f'--name=/dev/video{cam_id}'] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate() out, err = out.strip(), err.strip() kernel_for_udev_rules = re.search(r'(?<=KERNELS==\")[^\"]*', out.decode('utf-8')).group(0) serial = re.search(r'(?<=ATTRS{serial}==\")[^\"]*', out.decode('utf-8')).group(0) self.binding_between_udev_dev = f'{kernel_for_udev_rules} {serial}' process.kill() return self.binding_between_udev_dev Than, I have some Django management commands, that are configurating my system (collecting camera … -
Connecting to Aurora Serverless from Lambda Django?
I want to connect to my Aurora Serverless mysql database inside of my django Lambda function. Currently, I have: a Lambda function inside of the default VPC Uses the default security group Uses two public subnets I created Allows inbound requests from TCP ports 1024 - 65535 Allows outbound requests to Aurora/Mysql on Aurora security group an Aurora cluster inside of the default VPC Uses the same (default) VPC as the Lambda Uses two private subnets I created Allows inbound requests on port 3306 from Lambda security group an internet gateway for the default VPC a NAT gateway which pipes communications to the internet gateway a public routing table with the target ID of the internet gateway a private routing table with the target ID of the NAT gateway When I try to deploy my Lambda function to API gateway, the request times out: START RequestId: [request id] Version: $LATEST Instancing.. END RequestId: [request id] REPORT RequestId: [request id] Duration: 30030.15 ms Billed Duration: 30000 ms Memory Size: 512 MB Max Memory Used: 49 MB [time] [request id] Task timed out after 30.03 seconds When I remove the Lambda function from the VPC (setting the VPC to none in the … -
Django manage.py
after creating a new django project I wrote in powershell(run as administrator):PS C:\Users\User\Desktop\new> python manage.py runserver Then it shows something like this python : Python was not found but can be installed from the Microsoft Store: https://go.microsoft.com/fwlink?linkID=2082640 At line:1 char:1 + python manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (Python was not ...?linkID=2082640:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError -
**SERIOUS ISSUE** django multiple search issue
my problem is when I'm adding simple functionality to individual search fields, it's working fine as I expected, like after adding functionality for location field it's working fine as i wanted but when I add same functionality for another field it's not showing results, even though 1st field was showing the results but now none of them showing anything. I'm not sure where's the problem I'm hanging around last 2 days. please help HTML search form <form action="{% url 'search-page' %}" method=""> <div class="row"> <div class="col-12 col-lg-10"> <div class="row"> <div class="col-12 col-md-6 col-lg-3"> <select name="location" id="" class="form-control"> <option value="">Location</option> {% for key,value in location_choices.items %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="col-12 col-md-6 col-lg-3"> <select name="types" id="" class="form-control"> <option value="all-types">All Types</option> {% for key,value in property_choices.items %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="col-12 col-md-6 col-lg-3"> <select name="city" id="" class="form-control"> <option value="01">All City</option> {% for key,value in city_choices.items %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="col-12 col-md-6 col-lg-3"> <select name="status" id="all" class="form-control"> <option value="01">Status</option> {% for key,value in status_choices.items %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div … -
failed Manage.py runserver command
i am a biginer in web developing, i am using pycharm and django 2.1 framework i installed django using ('py -m pip install django==2.1') and it is done. i started myweb project using ('py -m django-admin startproject myweb .') and it also done but when i try ('manage.py runserver') command, this is the result: enter code here (venv) C:\Users\مرحبا\PycharmProjects\Myweb>manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 27, 2020 - 20:08:58 Django version 3.0.4, using settings 'myweb.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread <bound method Thread.name of <Thread(django-main-thread, started daemon 5152)>>: Traceback (most recent call last): File "C:\Users\مرحبا\AppData\Local\Programs\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\مرحبا\AppData\Local\Programs\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\django\core\management\commands\runserver.py", line 139, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\django\core\servers\basehttp.py", line 206, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\django\core\servers\basehttp.py", line 67, in __init__ super().__init__(*args, **kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\socketserver.py", line 449, in __init__ self.server_bind() File "C:\Users\مرحبا\AppData\Local\Programs\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\مرحبا\AppData\Local\Programs\lib\http\server.py", line 139, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\مرحبا\AppData\Local\Programs\lib\socket.py", line 680, in getfqdn aliases.insert(0, hostname) AttributeError: … -
Getting Following ! ACCESS to my shope/models
Traceback (most recent call last): File "h:/Django Framwork/WebCard/Shope/views.py", line 3, in from .models import product ImportError: attempted relative import with no known parent package I cant Import or use product.objects and get access to product.objects.aLL() funcs i want to see my models of product shope/views.py from django.shortcuts import render from django.http import HttpResponse from .models import product product.objects.all() def Index(request): return render(request,'Shope/index.html') def about(request): return render(request,'Shope/about.html') def contant(request): return HttpResponse('This page is working') def tracker(request): return HttpResponse('This page is working') def search(request): return HttpResponse('This page is working') def productview(request): return HttpResponse('This page is working') def checkout(request): return HttpResponse('This page is working') # print(product.objects.all()) # m = django.apps.apps.get_models() # print(m)** Shope\Model.py from django.db import models import django.db # Create your models here. class product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=50) product_catagory = models.CharField(max_length=50) product_subcatagory = models.CharField(max_length=50) product_desc = models.CharField(max_length=300) product_pricse = models.IntegerField(max_length=50,default=0) product_pub_date = models.DateField() product_imag = models.ImageField(upload_to='shope/images') def __str__(self): return self.product_name # print(product.objects.all()) enter image description here -
local variable 'routingForm' referenced before assignment
Am trying to do a form submit,but getting the error"local variable 'routingForm' referenced before assignment".please help me to solve this. *****forms.py***** from django import forms class routingForm(forms.Form): areaDigit = forms.CharField(label='areaDigit', max_length=100) product = forms.CharField(label='product', max_length=100) *****views.py***** from django.shortcuts import render from .forms import routingForm # Create your views here. from django.http import HttpResponse,HttpResponseRedirect from .models import Product,Routing_Dest_Area def get_route_list(request): #areaDigit= request.POST.get('areaDigit', False) #data=Routing_Dest_Area.objects.filter(areaDigit_pk=request.POST['areaDigit']) if request.method == "POST": #Get the posted form routingForm = routingForm(request.POST) if routingForm.is_valid(): areaDigit = routingForm.cleaned_data['areaDigit'] else: MyLoginForm = routingForm() return render(request, 'routing/test.html',{'areaDigit':areaDigit}) *****home.html***** <form method="POST" action="{% url 'get_route_list'%}" id="routingForm" name="routingForm"> {% csrf_token %} <div class="form-content"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <input type="text" class="form-control" placeholder="Area String *" name"areaDigit" id="areaDigit" value="{{areaDigit}}"/> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="sel1">Select list (select one):</label> <select class="form-control" id="Product" name="product"> <option> 1</option> <option> 21</option> </select> </div> </div> </div> <button type="submit" class="btnSubmit">Submit</button> -
Django - "warning" messages in class-based views not existing?
Im in Django and I'm trying to flash a "warning" message in a class-based view. But it seems like it's only possible to create "success" messages. The module django.contrib.messages.views only have the function SuccessMessageMixin, so there doesn't seem to be any equivalent to other types of messages. Been looking through the documentations but can't find any relevant info. -
Testing PUT method in Django Rest Framework
I'm trying to test a PUT method in django rest framework. I get HttpResponsePermanentRedirect instead of response object. My views for a put method are set to send status 200 after successful update. Error: self.assertEqual(response.data, serializer.data) AttributeError: 'HttpResponsePermanentRedirect' object has no attribute 'data' tests.py class PostTestGetAndPutMethod(APITestCase): def setup(self): Post.objects.create(title="POST CREATED", content="POST WAS CREATED") Post.objects.create(title="POST CREATED 2", content="POST WAS CREATED 2") Post.objects.create(title="POST CREATED 3", content="POST WAS CREATED 3") def test_get_posts(self): ''' Ensure we can get list of posts ''' # get API response response = self.client.get(reverse('posts')) # get data from DB posts = Post.objects.all() # convert it to JSON serializer = PostSerializer(posts, many=True) # check the status self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serializer.data) def test_update_put_post(self): ''' Check if we can update post ''' data = {'title': 'POST MODIFIED', 'content': 'CONTENT MODIFIED'} response = self.client.put('/posts/1', data) serializer = PostSerializer(data) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK) views.py @api_view(['GET', 'PUT', 'DELETE']) def post_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: post = Post.objects.get(pk=pk) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = PostSerializer(post) return Response(data=serializer.data, status=status.HTTP_200_OK) elif request.method == 'PUT': serializer = PostSerializer(post, data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': post.delete() return Response(status=status.HTTP_204_NO_CONTENT) -
Django 'author' is not defined
from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length = 100) content = models.TextField() date_posted = models.DateTimeField(default = timezone.now) author - models.ForeignKey(User, on_delete = models.CASCADE) >>>NameError: name 'author' is not defined Why python does not recognize User paramether that is imported from django? GHOw can I fix that? -
is there any way can i use the Django for existing database? if yes how to used models?
I am working on already existing data on relational database. Now question is that how to build models and how to update the tables with new data coming from user (technically django forms)? -
Django getting session variables from a dictonary?
I don't know if this is even possible but can I get session objects from a dictonary in Django? e.g. somthing like this: def initial_view: ... else: request.session['send_something'] = {'sender', 'abc', '123', 'xyz'} return redirect('send_something_summary') def send_something_summary(request): send_something = request.session['send_something'] doing it like so always results in the following error: Object of type set is not JSON serializable Is there a way to do it somehow like that or do I have to set a new session object for each variable I want to pass to the next view like so: else: request.session['sender'] = 'sender' request.session['abc'] = 'abc' request.session['123'] = '123' request.session['xyz'] = 'xyz' Thanks for reading and kind regards -
WinError 10060 A connection attempt failed because the connected party did not properly respond after a period of time
1) add in settings.py ''' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', 'app.apps.AppConfig', ] ''' ''' ACCOUNT_ACTIVATION_DAYS=3 EMAIL_HOST='smtp.gmail.com' EMAIL_HOST_USER='xxxx@gmail.com' EMAIL_HOST_PASSWORD='xxxx' EMAIL_PORT=587 EMAIL_USE_TLS=True ''' 2) add url ''' urlpatterns=[ path('admin/',admin.site.urls), path('accounts/',include('registration.backends.default.urls')), ] ''' 3)migrate 4)update view.py add methos decorator for view where you want login required ''' from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required @method_decorator(login_required,name='dispatch') class StudentDetailView(DetailView): model = Student ''' [the singup page][1] [the error page][2] [1]: https://i.stack.imgur.com/yqizU.png [2]: https://i.stack.imgur. com/wROmM.png } -
Django Import error: cannot import "name"
I got an error i dont understand: cannot import name "UserUpdateForm" from "users.forms". Im doing the django tutorial from corey schafer, and we are creating a form as a class to update the users profiles of a blog page, then importing it to views.py and calling it in a function and when i try to run the server it pops up that error. I already looked for other questions but in general they say that the problem is a circular import, but i cant figure if it is my case and where it is. Im relatively new to programming so i dont really understand how this works, any help will be aprecciated: (Already tried to import the UserUpdateForm inside my profile function and didnt work) Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] class UserUptadeForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email"] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ["image"] views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib.auth.decorators … -
Why models.EmbeddedModelField is not working with djongo/django?
I have class Dimension and Feature. ( Want to create an Embedded Model from Feature to Dimension) Documentation: bottom of page I keep getting the error: dimension = models.EmbeddedModel AttributeError: module 'djongo.models' has no attribute 'EmbeddedModel' class Dimension(models.Model): dimensionName = models.CharField(max_length=20) def __str__(self): return self.dimensionName class Feature(models.Model): featureName = models.CharField(max_length=20) dimension = models.EmbeddedModel( model_container=Dimension, ) def __str__(self): return self.featureName Any leads would be appreciated!