Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to store uploaded files for a web application while using AWS ECS FARGATE
I am very new to the concept of AWS EFS. As i am currently building a web application using Django with ECS - AWS Fargate backend and javascript with react front end, which is deployed to s3. About the backend, I am wondering what would be the best way for a user to: 1/ store/upload the images related to their profile? 2/ assuming the user also own a product in the app and each product has images, how to store these images as well... Would AWS S3 or AWS EFS be the most appropriate way to store 1 and 2 above? Thanks for the feedback -
django Type error 'Bank' model object is not iterbale
i am trying to create list and detail api view. I have database with over 100K object model.py from django.db import models # Create your models here. class Banks(models.Model): name = models.CharField(max_length=49, blank=True, null=True) id = models.BigIntegerField(primary_key=True) class Meta: managed = False db_table = 'banks' class Branches(models.Model): ifsc = models.CharField(primary_key=True, max_length=11) bank = models.ForeignKey(Banks, models.DO_NOTHING, blank=True, null=True) branch = models.CharField(max_length=250, blank=True, null=True) address = models.CharField(max_length=250, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) district = models.CharField(max_length=50, blank=True, null=True) state = models.CharField(max_length=26, blank=True, null=True) class Meta: managed = False db_table = 'branches' serializers.py from rest_framework import serializers from .models import Branches, Banks class BankSerializer(serializers.ModelSerializer): class Meta: model = Banks fields= ['name', 'id'] class BranchSerializer(serializers.ModelSerializer): bank = BankSerializer(many=True,read_only=True) class Meta: model = Branches fields= ['ifsc','bank','branch','address','city','district','state'] views.py from rest_framework import viewsets from .serializers import BranchSerializer from rest_framework import viewsets class BankViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed. """ queryset = Branches.objects.all() serializer_class = BranchSerializer I tried using .get_queryset(), .filter() in place of .all() but its still throwing error error datail Request Method: GET Request URL: http://127.0.0.1:8000/bankdetailapi/ Django Version: 3.2.3 Python Version: 3.9.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'rest_framework', 'corsheaders', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', … -
Python Django: Django won't render images from a folder outside static
Been working on a Django project for a personal portfolio. Inside the project I have different apps: a blog app and a projects app. When I try to render a images it wont display unless a use a specific path from the templates folder to the static folder. For example, based on my project directory, if I use "../static/img/example.jpg" it renders the image with out problem, but as soon as I use another path like "../../media/img/example.jpg" the image wont render and a blank space will appear. I would like to know id this is normal behavior with Django and if its then what is the best practice to display images, because nothing comes to mind right now.enter image description here -
Cannot close a running event loop
What is the way to close the discord.py bot loop once tasks are done? Added: nest_asyncio.apply() Tried: bot.logout(), bot.close(), bot.cancel() Code: async def helper(bot, discord_user_feed): nest_asyncio.apply() await bot.wait_until_ready() # await asyncio.sleep(10) for each_id, events_list in discord_user_feed.items(): discord_user = await bot.fetch_user(int(each_id)) for each_one in events_list: msg_sent = True while msg_sent: await discord_user.send(each_one) msg_sent = False await bot.close() return 'discord messages sent' async def discord_headlines(request): nest_asyncio.apply() discord_user_feed = await get_details() bot = commands.Bot(command_prefix='!') bot.loop.create_task(helper(bot, discord_user_feed)) message = bot.run('my_token') return HttpResponse(message) I can be able to send messages to discord users using id and discord bot. But, even after, django view api is continuously running and getting the error. It needs to return a response message - discord messages sent. Error: Exception in callback <TaskWakeupMethWrapper object at 0x000001C852D2DA38>(<Future finis...SWdZVtXT7E']}>) handle: <Handle <TaskWakeupMethWrapper object at 0x000001C852D2DA38>(<Future finis...SWdZVtXT7E']}>)> Traceback (most recent call last): File "E:\sd\envs\port\lib\asyncio\events.py", line 145, in _run self._callback(*self._args) KeyError: <_WindowsSelectorEventLoop running=True closed=False debug=False> Internal Server Error: /api/v0/discord_headlines/ Traceback (most recent call last): File "E:\sd\envs\port\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\sd\envs\port\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\sd\envs\port\lib\site-packages\asgiref\sync.py", line 139, in __call__ return call_result.result() File "E:\sd\envs\port\lib\concurrent\futures\_base.py", line 425, in result return self.__get_result() File "E:\sd\envs\port\lib\concurrent\futures\_base.py", line 384, in … -
DRF: Is two sided object creation and relation assignment possible?
For example, I have two models, Questionnaire Model Profile Model These two models are linked by a one-to-one relation, where the one-to-one-field is declared on the questionnaire model. I want to be able to: Create a new questionnaire instance, and assign an existing profile instance to it Create a new profile instance, and assign an existing questionnaire instance to it Currently, because my one-to-one relation is defined on the questionnaire model, I can do 1) However, I am not able to achieve 2) How do i get both 1) and 2) working? Serializer class ProfileCreateSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = "__all__" Models class Questionnaire(models.Model): distance = models.FloatField(null=True) profile = models.OneToOneField("Profile", on_delete=models.SET_NULL, null=True, related_name="questionnaire", blank=True) class Profile(models.Model): bio = models.CharField(max_length=300, blank=True) Views class ProfileCreate(generics.CreateAPIView): queryset = Profile.objects.all() serializer_class = ProfileCreateSerializer permission_classes = [IsAuthenticated] POST Request { "bio": "I like to eat pizza", "questionnaire": 2 } -
django how to merge selling product row if product id and price is same
hi I'm new in Django please anyone help me how to merge the selling product row if the product id and price is the same my deman is bellow seconod image. here is my code: my view method code is: def invoiceTest(request): SaleData = Sales.objects.get(pk=322) SalesDetailsData = SalesDetails.objects.filter(SalesID_id=322) TotalPrice = totalPriceCalculate(request,322) NetAmonut = Decimal(TotalPrice)+Decimal(SaleData.BillVatAmount)-Decimal(SaleData.BillDiscountAmount) ExtraCharge = 0.00 context = { 'SaleData': SaleData, 'SalesDetailsData':SalesDetailsData, 'TotalPrice':TotalPrice, 'NetAmonut':NetAmonut, 'ExtraCharge':ExtraCharge } return render(request, 'Admin UI/Bill Invoice Challan/Bill Invoice.html',context) def totalPriceCalculate(request,SaleID): SalesDetailsData = SalesDetails.objects.filter(SalesID_id=SaleID) TotalAmount = 0.00 for SingleSale in SalesDetailsData: TotalAmount = Decimal(TotalAmount)+Decimal(SingleSale.Qty)*Decimal(SingleSale.UnitPrice) return TotalAmount class SalesDetails(models.Model): SalesID = models.ForeignKey(Sales, null=False, on_delete=models.RESTRICT) Purchase = models.ForeignKey(Purchase, null=False, on_delete=models.RESTRICT) ProductID = models.ForeignKey(Product_Master.ProductList, related_name='ProductID', null=False, on_delete=models.RESTRICT) StoreID = models.ForeignKey(Setup_Master.StoreList, null=False, on_delete=models.RESTRICT) EnterdBy = models.CharField(max_length=250, null=True) EntryTime = models.DateTimeField(auto_now_add=True) EntryDate = models.DateTimeField(auto_now_add=True) EntryDate = models.DateTimeField(auto_now_add=True) Serial = models.CharField(max_length=250, null=True) Qty = models.FloatField(default=1) Warranty = models.CharField(max_length=250, null=True) Cost = models.DecimalField(max_digits=50, decimal_places=2, default=0) AverageCost = models.DecimalField(max_digits=50, decimal_places=2, default=0) UnitPrice = models.DecimalField(max_digits=50, decimal_places=2, default=0) ItemDiscountPercent = models.DecimalField(max_digits=50, decimal_places=2, default=0) ItemDiscountAmount = models.DecimalField(max_digits=50, decimal_places=2, default=0) ItemVatPercent = models.DecimalField(max_digits=50, decimal_places=2, default=0) ItemVatAmount = models.DecimalField(max_digits=50, decimal_places=2, default=0) Approved = models.CharField(max_length=250, null=True,default='NO') Inventory = models.CharField(max_length=250, null=True, default='YES') <div class="row"> <table class="table table-sm table-bordered"> <thead> <tr style="background-color: #e2f0ff"> <th style="width: 40px" scope="col">SL</th> <th scope="col">Description</th> <th style="width: … -
Django how to pass an argument into a form made with Model_FormFactory?
I have an abstract form, that is used as a template form when calling modelform_factory. However this abstract form requires some initialising data, foo. How do I pass the initialising data foo from the concrete class to AbstractForm.__init__? class AbstractForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) foo = kwargs.pop('foo') # Need to get this initialising value self.fields['some_field'] = forms.ModelChoiceField(required=True, queryset=SomeModel.objects.filter(baz=foo).all()) class AbstractAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, change=False, **kwargs): # How to pass self.foo into AbstractForm? form = forms.modelform_factory(self.model, form=AbstractForm, exclude=[]) return form class ConcreteAdmin(AbstractAdmin): foo = 123 -
How to deploy django web App on windows iis server?
i am trying to host django web app on windows iis server and i am having problem with web.config file .the auto generated web.config file doesnot have complete setup ,is there any way to complete this config file manually . django version 3.2.4 -
Django file upload in REST-framework : TypeError: a bytes-like object is required, not 'TemporaryUploadedFile'
I want to make a post create view. There are various functions to write an article, and there is a file upload function in particular. So, I use Multipartparser and override create function in serializer. like below: create instance first. save the file on the created instance. but when I save, the error occur: TypeError: a bytes-like object is required, not 'TemporaryUploadedFile' but don't know how to convert 'TemporaryUploadedFile' to 'a bytes-like object'. <api_view> class PostCreate(generics.CreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer # parser_classes = (FileUploadParser,) # parser_classes = (FormParser, MultiPartParser) parser_classes = (MultiPartParser,) # def put(self, request, format = None): # post_files = request.data['post_files'] def post(self, request, *args, **kwargs): serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class PostSerializer(serializers.ModelSerializer): post_files = serializers.FileField(required=False) def create(self, request): print("@@@@@request") print(request) post_files = request.pop("post_files") print("@@@ post_files.path : " + post_files.temporary_file_path()) print("@@@ post_files.name : " + str(post_files)) instance = Post.objects.create(**request) # files = open(post_files.temporary_file_path(), "wb+") # for chunk in post_files.chunks(): # files.write(chunk) # files.close() instance.post_files.save(str(post_files), ContentFile(files), save=True) return instance -
Custom 500 error page for only one template
Hi i cant figure out how i can create a custom 500 page but only for a single view, i basically want to redirect to another template when i get an 404 error by not passing a positional argument. i currently made an .html custom page, but its works for any page. im triying to do something like this: def handler_no_board(request,exception): board= request.GET["board_id"] if board == null return render(request,'board-not-found.html') -
Django Channels error appears in separate Django project (broken pipe error)
I'm relatively new to ASGI and Django Channels, so this is probably a very basic question. I got ASGI running thanks to Django Channels in one of my Django projects and it works fine. I then want to work on my old project, which doesn't yet use ASGI. I kill the debug server running locally on 127.0.0.1, switch environments (in an entirely new shell window) and start the debug server running for the old project: (server) me@laptop server % ./manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 12, 2021 - 11:23:40 Django version 3.2, using settings 'oldproj.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Not Found: /ws/chats/1056/ [12/Jun/2021 11:23:46] "GET /ws/chats/1056/ HTTP/1.1" 404 6103 [12/Jun/2021 11:23:46,327] - Broken pipe from ('127.0.0.1', 58901) Not Found: /ws/chats/1056/ [12/Jun/2021 11:37:43] "GET /ws/chats/1056/ HTTP/1.1" 404 6103 [12/Jun/2021 11:37:43,293] - Broken pipe from ('127.0.0.1', 59096) Not Found: /ws/chats/1056/ [12/Jun/2021 11:37:43] "GET /ws/chats/1056/ HTTP/1.1" 404 6103 [12/Jun/2021 11:37:43,293] - Broken pipe from ('127.0.0.1', 59096) These error messages repeat every 30 seconds or so. I suspect there's a process still running in support of the new, ASGI-equipped project but I don't know what … -
Can I add any kinda condition to the model.py file in django?
Can I add any kinda condition to this model? If it's possible, how can I do that? class Book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) rating = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)]) is_bestseller = models.BooleanField(default=False) slug = models.SlugField(default="", null=False, db_index=True) def __str__(self): return f"{self.title} ({self.rating})" -
Django: How to read an image sent using Dio from flutter
I'm a newbie to Flutter and trying to build a Flutter App. I want to upload an image from android device to django, process it and send the results back to flutter in a json format without saving the image anywhere. But I'm facing difficulty in reading image in django. However, the image is sent successfully from flutter. Here is my flutter code for sending an image using Dio : Future<void> _clearImage() async { try { String filename = imageFile!.path.split('/').last; FormData formData = FormData.fromMap({ "image": await MultipartFile.fromFile(imageFile!.path, filename: filename, contentType: MediaType('image', 'jpg')), "type": "image/png" }); Response response = await dio.post('http://192.168.43.63:8000/scan/', data: formData, options: Options( followRedirects: false, // will not throw errors validateStatus: (status) => true, headers: { "accept": "*/*", "Content-Type": "multipart/form-data", })); print(response); } catch (e) { print(e); } setState(() {}); } } Here is my code for django: file = request.FILES['image'] print(file) img = cv2.imread(file.read()) print(img) I'm getting the following error: img = cv2.imread(file.read()) TypeError: Can't convert object of type 'bytes' to 'str' for 'filename' Your help will really be appreciated. Thank you in advance! -
Filter django QuerySet on subclassed type (multi-table inheritance)?
I'm looking for an efficient model manager method that uses the following class structure to generate the QuerySet described by code in views.py: #models.py from django.db import models class Super(models.Model): date_of_interest = models.DateField(...) # <other model_fields> class SubA(Super): # <other model_fields> class SubB(Super): # <other model_fields> class SubC(Super): # <other model_fields> #somewhere else (eg. views.py) ... query_set = Super.objects.filter(date_of_interest=today) qs_to_list = [e for e in query_set if hasattr(e, 'subb') or hasattr(e, 'subc')] I would like to keep qs_to_list a QuerySet, so I'm searching for a way to filter with a model manager, based on the type of subclass. As noted, I'm using multitable inheritance with abstract=False and implicitly using the OneToOneField created with this type of inheritance. Thanks! -
TypeError show_poll() got an unexpected keyword argument 's'
i'm trying to redirect the user after submitting a form to the polls list.. the form is saved in the admin after submitting but the redirection is failing anyone can help me with this? my views.py def show_poll(request, id): p = Poll.objects.get(id=id) pops = p.option_set.all() context = { 'poll': p, 'options': pops, } return render(request, "show_poll.html", context) def create_poll(request): c_form = PollForm(request.POST or None) data = {} data["create_form"] = c_form if c_form.is_valid(): poll = c_form.save(commit=False) poll.slug = slugify(poll.title) poll.save() return redirect("show_poll", s=poll.slug) return render(request, "create_poll.html", context=data) my urls.py from django.urls import path from . import views urlpatterns = [ path('show/poll/<int:id>/', views.show_poll, name="show_polls"), path('c_poll/<slug:s>/',views.show_poll, name="show_poll"), path('create/poll/',views.create_poll) ] -
I want to Upload a file and then I want to parse that file to get the phone number and email id to fill the the columns email and mobile
I have created this model files to store a file two fields more fields. class Profile(models.Model): email = models.EmailField(max_length=254, blank=False) mobile = PhoneField(blank=False) resume = models.FileField(upload_to='resume/') and here is the view file. @api_view(['POST']) @parser_classes([MultiPartParser]) def upload_file(request, format=None): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) and with the help of this all i can do is that i have to provide all the three field which are there in the the model.py but i want just to upload the file and parse that file to get those two fields. Suggest a way through which it can be achieved, I know it is something really basic but i cant figure it out. here is the seriliazers.py file class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['email', 'mobile', 'resume'] -
Not able to navigate between two templates in a Django application
I have a ran into a difficulty when navigating between different templates in a Django (v3.2) application. The app is called 'manage_remittance'. The default landing page (which uses template manage_remittance/templates/manage_remittance/view_remittance.html) for the app should show a list of items (list is not relevant at the moment), and at the top of that list there should be a link, leading to another page in the same app, which would allow to add new items to the list. The form that is invoked first is here: manage_remittance/templates/manage_remittance/view_remittance.html {% extends "root.html" %} {% load static %} {% load crispy_forms_tags %} {% url 'manage_remittance:remittance_add' as remittance_add %} {% block title %} VIEW REMITTANCES PAGE {% endblock title %} {% block content %} <div class="list-group col-6"> <a href="{{ remittance_add }}" class="list-group-item list-group-item-action shadow-mt list-group-flush list-group-item-dark text-light">Click here to add remittance data</a> </div> I want to be able to get to another template (manage_remittance/templates/manage_remittance/remittance_add.html), but the {{ remittance_add }} has no value. In addition, when I specify exact name of the html file (remittance_add.html) in the a href (see above), and click on it, I get a following error: Using the URLconf defined in sanctions_project.urls, Django tried these URL patterns, in this order: admin/ [name='login'] login/ … -
Problem while transferring data between POST request and GET in django
I have a select tag, and what my logic is that after the user selects an option, we would send that response and search through the db to find similar records. The problem is how to access that data. After the user has selected an option, I would take them to other page which is just a GET request page. So how to access the select tag data(which is a POST request data) on a GET request page. -
How to pass a Django url in AJAX?
I'm trying to pass a Django URL in ajax after I get the data from the views.py but i get a page not found when I do so : data.forEach((item) => { var url = "{% url 'delete_user' 1 %}".replace('1', item.id); tableBody.innerHTML += '<tr><td>'+item.username+'</td><td>'+ item.first_name+'</td><td>'+item.last_name+'</td><td>'+item.email+ '</td><td><a href='+url+'><i class="fa fa-trash btn btn-danger"></i></a></td>' + '<td><a href="{% url \'admin_edit_profile\''+ item.id +'%}"><i class="fa fa-edit btn btn-warning"></i></a></td></td></tr>' }); i've Tried this i saw it somewhere here : var url = "{% url 'delete_user' 1 %}".replace('1', item.id); but it doesn't seem to work the error i get : Not Found: /admin_users/{% url 'delete_user' item.id %} [12/Jun/2021 11:04:23] "GET /admin_users/%7B%%20url%20'delete_user'%20%20%20item.id%20%20%%7D HTTP/1.1" 404 7099 -
How to allow Django container to use Docker SDK without permission error?
I have a container running a Django application from which I need to spawn other containers on the host machine. I'm using the Docker SDK for Python within one of my views however when running the application I get a Permission Denied error. Dockerfile: # syntax = docker/dockerfile:experimental FROM python:slim-buster MAINTAINER "" "" RUN mkdir -p /opt/app && \ mkdir -p /opt/app/pip_cache WORKDIR /opt/app COPY ./config ./src /opt/app/ RUN chmod +x web/start-server.sh && \ chmod +x web/wait-for-it.sh && \ chmod +x web/setup.sh && \ python3 -m pip install --upgrade pip && \ python3 -m pip install -r requirements.txt --cache-dir pip_cache && \ chown -R www-data:www-data /opt CMD ./web/start-server.sh STOPSIGNAL SIGTERM docker-compose.yaml: version: "3" services: nginx: build: ./config/nginx container_name: nginx restart: always ports: - "8084:80" - "443:443" command: nginx -g "daemon off;" volumes: - static:/static/ - media:/media/ links: - web:web depends_on: - web web: build: . container_name: web restart: always expose: - "8010" links: - db:db volumes: - static:/static/ - media:/media/ - /var/run/docker.sock:/var/run/docker.sock env_file: - config/web/django.env depends_on: - db stdin_open: true tty: true db: image: postgres:latest container_name: postgres restart: always ports: - "5432:5432" env_file: - config/postgres/database.env volumes: static: media: views.py: import docker from django.http import HttpResponse def container_view(request): if request.method == … -
Django cms in action menu in something went wrong error
In Django cms framework in when clicking on page models(action menu) showing an error and getting an error on the backend side. This is traceback : Internal Server Error: /admin/cms/page/1/actions-menu/ Traceback (most recent call last): File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.8/contextlib.py", line 75, in inner return func(*args, **kwds) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/cms/admin/pageadmin.py", line 343, in actions_menu return render(request, self.actions_menu_template, context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/base.py", line 170, in render return self._render(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/defaulttags.py", line 401, in render return strip_spaces_between_tags(self.nodelist.render(context).strip()) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/defaulttags.py", line 305, in render match … -
Can I expose the API URL to the public in a Python library?
I have built a Django API which has a lot of proprietary algorithms for analyzing stock portfolios. The API is hosted in AWS and this API is also connected to the website where I show the visualizations of the calculated metrics. I want to build a library to provide these metrics in Python like pandas. Users can install this package using pip install . In my Python library code, I would expose only the API URL and I will call the API with different parameters and endpoints. Paid users will get a unique access code in email using which only they can access the Python package functions. I don't want to expose my Django API code to the public as the analysis itself requires a lot of stock price data from the Database and also there are a lot of proprietary algorithms. Does the solution make sense? Should I hide the API URL or just leave it. -
Django - python manage.py runserver error - TypeError: function takes at most 3 arguments (4 given)
I'm running into this error for the first time today and can't find any solution on other threads. Here is the response I'm getting when I run 'python manage.py runserver' ➜ duncs_django python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check_migrations() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/base/base.py", line 235, in _cursor self.ensure_connection() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) … -
Django: Voting System Not Working With Radio Buttons
I am trying to make a simple reddit clone with a voting system that is basically just upvotes - downvotes however now that I changed from using buttons for voting to radio buttons so that you could only vote once, no votes are being counted at all. If anybody could help me out with this that would be great. My Html: {% extends 'thefeed/base.html' %} {% block content %} <div class="announcement"> <h5 style="background: yellow;">Forum.Chat is the Internet's home for debate on any topic, keep it civil!</h5> </div> <br> {% for post in object_list %} <div style="margin-bottom: 2%;"> <h3><a href="#" style="color: red;">{{post.ranking}} </a><a href="{% url 'feed-post' post.pk %}">{{post.title}}</a><a href="#"></h3> <p><a href="#">By: {{post.author}}</a><a href="{% url 'edit-post' post.pk %}"> Edit Post</a></p> <form action=""> <p> <input class="btn btn-outline-primary" type="radio" name="vote"> <a href="{% url 'upvote-post' pk=post.pk %}" style="color: black; font-weight: bold;"></a> </input> <input class="btn btn-outline-danger" type="radio" name="vote"> <a style="font-weight: bold; color: black;" href="{% url 'downvote-post' pk=post.pk %}"></a> </input> </p> </form> </div> <hr> {% endfor %} {% endblock %} My Urls: path('post/<int:pk>/downvote', views.DownvoteView, name='downvote-post'), path('post/<int:pk>/upvote', views.UpvoteView, name='upvote-post'), My Model: class post(models.Model): title = models.CharField(max_length=200) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) ranking = models.IntegerField(default=0) My View: def UpvoteView(request, pk): selected_post = post.objects.get(pk=pk) selected_post.ranking+=1 selected_post.save() return redirect('feed-home') … -
How to have 2 textboxes as mutually exclusive in an html form?
I would like to have 2 mutually exclusive fields. One will be a FileField and other TextBoxField. Is there a ready html form I can get my hands on to. I have searched the web and couldnt find any.