Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to connect to the silicon pay API but am not sure how to handle the callback URL to obtain the status of the transaction
am trying to connect silicon pay, a payment API but I have failed to under how to handle the callback URL to check if the transfer was successful or not in order to give value to my customers @login_required(login_url='accounts:login') def mobile_deposit(request): if request.method == 'POST': form = MobileDepositForm(request.POST or None) if form.is_valid(): pending_amount = form.cleaned_data.get('pending_amount') if pending_amount >= 37000: account = Account.objects.get(user=request.user) data_req = { "req": "mobile_money", "currency": "UGX", "phone": str(account.user.phone_number), "encryption_key": "", "amount": str(pending_amount), "emailAddress": str(account.user.email), 'call_back': "https://41ab-137-63-181-131.in.ngrok.io/callback", "txRef": generate_txRef() } account.txRef = data_req['txRef'] account.save() headers = { 'Content-Type': 'application/json' } response = requests.post('https://silicon-pay.com/process_payments', data=json.dumps(data_req), headers=headers) print(response.text) account.save() messages.success(request, "Please confirm your Transaction on your phone") return redirect("accounts:mobile-deposit") else: messages.warning(request, "Minimum deposit is UGX 37000") return redirect('accounts:mobile-deposit') else: messages.warning(request, "Form error") return redirect('accounts:mobile-deposit') else: form = MobileDepositForm(request.POST or None) context = { 'form':form } return render(request, "mobile_deposit.html", context) def generate_txRef(): return "CTF-"+str(random.randrange(111111,999999)) I have tried reading the documentation on silicon pay but its in PHP yet am implementing mine in python. My solution has crushed the site -
Brew install watchman on mac does run the service
I am on Mac ventura 13.0.1 (22A400) I am trying to install watchman however it is not getting installed as a service that can be run in service/daemon mode brew install watchman ==> Downloading https://formulae.brew.sh/api/cask.json Warning: watchman 2023.02.13.00 is already installed and up-to-date. To reinstall 2023.02.13.00, run: brew reinstall watchman However, it says that it cannot be run and loadable brew services info watchman watchman (homebrew.mxcl.watchman) Running: ✘ Loaded: ✘ Schedulable: ✘ Brew services list brew services list Name Status User File memcached started xxx ~/Library/LaunchAgents/homebrew.mxcl.memcached.plist rabbitmq started xxx ~/Library/LaunchAgents/homebrew.mxcl.rabbitmq.plist redis none stunnel none However I can use watchman in command line mode, but other programs that need to find watchman can't use it -
Best practices for storing encrypted data that needs to be decrypted
I have a use case where I need to store userIDs and passwords to access other systems in my DRF App with a PostgreSQL DB. I must be able to retrieve this information, but I don't want to store it in plain text in the data base. The credentials will be used to login to other systems to collect data. Hashing is not an option as I need to be able to decrypt the encrypted passwords as they will be used to log into other systems. I was thinking using a vault (hashicorp), but then I need to store the keys to access the vault. That seems just shifting the problem, but not a solution. I am looking for a encryption/decryption that has not more than 2 secrets (key and vector) that could be the same for all credentials and provides a single string per password that can be stored in the DB. No fancy PostgreSQL features that are not supported by Django/DRF. I am not looking for long explanations about that you should not store a userID/Password information in a DB! -
'POST' or 'PUT' or 'DELETE' is not working
Here the class WriteByAdminOnlyPermission is not working perfectly. This if request.method == 'GET': working but remaining condition is not working. My target is, only the admin can change information and the other people just can see. How can I do it? And where I did do wrong? please give me a relevant solution😥 views.py: class WriteByAdminOnlyPermission(BasePermission): def has_permission(self, request, view): user = request.user if request.method == 'GET': return True if request.method in['POST' or 'PUT' or 'DELETE'] and user.is_superuser: return True return False class ScenarioViewSet(ModelViewSet): permission_classes=[WriteByAdminOnlyPermission] serializer_class = ScenarioSerializer queryset = Scenario.objects.all() models.py: class Scenario(models.Model): id = models.CharField(primary_key=True, max_length=10, default=uuid.uuid4, editable=False) Title = models.CharField(max_length=350, null=True, blank=False) film_id = models.OneToOneField(Film, on_delete=models.CASCADE, related_name="ScenarioFilmID", null=True) serializer.py: class ScenarioSerializer(ModelSerializer): class Meta: model = Scenario fields = "__all__" urls.py: router.register(r"scenario", views.ScenarioViewSet , basename="scenario") -
Django Authentication to use both email and username in exiting app
I am struggling with adding custom AUTHENTICATION_BACKENDS for my exiting app. I have all done with my app but now want to login with username or EmailID. I am successfully able to login with username and password. now just want to add EmailID as well. I tried adding below code in my settings.py AUTHENTICATION_BACKENDS = ( 'authentication.backends.EmailOrUsernameModelBackend', 'django.contrib.auth.backends.ModelBackend', ) and in \authentication\backends.py I have from django.conf import settings from django.contrib.auth.models import User class EmailOrUsernameModelBackend(object): def authenticate(self, username=None, password=None): print("Inside EmailorUsernameModelBackend") if '@' in username: print("User with Email") kwargs = {'email': username} else: print("User with Username") kwargs = {'username': username} try: user = User.objects.get(**kwargs) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None where my \authentication\views.py def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) print("User=",user) if user is not None: login(request, user) return redirect("dashboard") else: msg = 'Invalid credentials' else: msg = 'Error validating the form' return render(request, "/login.html", {"form": form, "msg": msg}) I am trying to print some statement if authenticate method call from EmailOrUsernameModelBackend but none printing, so I guess for some … -
JAVASCRIPT: After sending Item to Database (POST) the window.location.reload() does not work. How to refresh the Data in HTML-Template?
I recode a Tutorial on Youtube. Django, Python, HTML an Javascript. Everthing works fine exept the window.location.reload() function. I try some workarounds with windows.reload(true), window.href = window.href location = self.location and some more. I have a hunch that the reload is executed before or during the code before the reload. But I do not know. The goal is to send the data from the input to the database and only then refresh the page. This ist the Code from the tutorial: index.html (shortened) <body> <header> <h1>Shoppinglist</h1> <div id="input-field"> <label for="item-input">Was möchtest du einkaufen?</label> <input type="text" name="item" id="item-input"> </div> <button id="btn" onclick="addItem()">+</button> </header> <div id="item-table"> {% for row in all_items %} <div class="list-item"> <input type="checkbox"> {{row.name}} </div> {% endfor %} </div> <script> function addItem(){ let itemName = document.getElementById("item-input").value; let formData = new FormData(); let token = '{{csrf_token}}'; formData.append('itemName', itemName); formData.append('csrfmiddlewaretoken', token); fetch('/mylist/', { method: 'POST', body: formData }); window.location.reload(); }; </script> </body> </html> views.py from django.shortcuts import render from .models import ShoppingItem # Create your views here. def mylist(request): if request.method == 'POST': print('Received date: ', request.POST['itemName']) ShoppingItem.objects.create(name = request.POST['itemName']) all_items = ShoppingItem.objects.filter(done = 0) return render(request, 'index.html', {'all_items':all_items}) models.py from django.db import models from datetime import date #Create your models … -
Multiple signin in django
I want to multiple role in django. I also create default auther user. But i want add login in second database table. I try to authenticate(username='john', password='secret') function but it is working only django default author. I want to use second database table then how can i authenticate the second user and login to the site. Please advice currently working django 4.1 version. -
Django Rest Framework get filtered queryset in custom get function
So I have an APIView like this: from rest_framework.views import APIView class MyAPIView(APIView): queryset = MyObject.objects.all() filter_backends = [MyCustomFilterBackend, DjangoFilterBackend] filterset_fields = ["field1", "field2"] def get(self, request): s = StatManager(self.queryset) return Response(s.dashboard()) where I filter bunch of stuff using MyCustomFilterBackend and DjangoFilterBackend. My goal is to give the filtered queryset to StatManager so it generates stats for the dashboard. Currently, s = StatManager(self.queryset) does not take filters into account. How can I provide the filtered queryset in my get function? I read the DRF documentation. I was expecting for APIView to have some function like get_filtered_queryset(). I read Filters of Django REST Framework inside GET function? and DJango filter_queryset but they have no adequate answers. -
how to disable django page caching
is there a way to prevent page caching in django? Because I have 2 views. view2 is only accessible if a request.session['iv'] exists. This is only created within view1 of a post request and is also deleted at the beginning of view1, so that access to view2 is not possible for the time being. If I am then redirected from view1 to view2 I can easily go back with the browser and land on view1. The problem is I can then go back to "show next page" and end up on view2 although the request.sesion no longer exists. This must be because the browser opens a cached version of view2, which I want to prevent. -
Websocket connection failing
`The WebSocket connection to 'ws://localhost:3000/ws/api/stocks_prices/AAPL/' failed: WebSocket is closed before the connection is established. React frontend views.js `useEffect(() => { const socket = new WebSocket(`ws://${window.location.host}/ws/api/stocks_prices/${symbol}/`); console.log("socket",socket) socket.onmessage = event => { const data = JSON.parse(event.data); setStockPrices(prevStockPrices => ({ ...prevStockPrices, data: [data, ...prevStockPrices.data.slice(0, 4)], })); console.log("websocket data",data); }; return () => { socket.close(); console.log("WebSocket closed"); }; }, [symbol]);` Using Django for backend routing.py `from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/api/stocks_prices/(?P<symbol>\w+)/$', consumers.StockConsumer.as_asgi()), ]` consumer.py `from channels.generic.websocket import AsyncWebsocketConsumer import json import yfinance as yf class StockConsumer(AsyncWebsocketConsumer): async def connect(self): self.stock_name = self.scope['url_route']['kwargs']['stock_name'] self.stock_group_name = 'stocks_prices/%s' % self.stock_name # Join room group await self.channel_layer.group_add( self.stock_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.stock_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) stock_name = text_data_json['stock_name'] # Fetch real-time stock data ticker = yf.Ticker(stock_name) data = ticker.history(period='1d') stock_price = { 'stock_name': stock_name, 'price': data['Close'].iloc[-1], } # Send real-time stock data to the client await self.channel_layer.group_send( self.stock_group_name, { 'type': 'stock_price', 'price': stock_price } ) # Receive message from room group async def stock_price(self, event): stock_price = event['price'] # Send real-time stock data to the client await self.send(text_data=json.dumps({ 'stock_name': stock_price['stock_name'], 'price': stock_price['price'] })) views.py … -
Merging converted pdf files in aws lambda function
Trying to acheive below functionality Uploading multiple files to s3 bucket. Non pdf files needs to get converted to pdf and then merge into single pdf file. The folder structure will be folder1/2/3/4. under folder 4 the files gets uploaded. Below is my code(lambda function) but the issue is the files(only some) are merging before all the files gets converted. convert to pdf has to occur successfully before the merging starts. import os import io from io import BytesIO import tarfile import boto3 import subprocess import brotli from PyPDF2 import PdfMerger from time import sleep #Directory where libre office open source s/w will be saved lambda tmp directory LIBRE_OFFICE_INSTALL_DIR = '/tmp/instdir' s3_bucket = boto3.resource("s3").Bucket("bucketname") def load_libre_office(): if os.path.exists(LIBRE_OFFICE_INSTALL_DIR) and os.path.isdir(LIBRE_OFFICE_INSTALL_DIR): print("Have a cached copy of LibreOffice, Skipping Extraction") else: print("No Cached copy of Libre Office exists , extracting tar stream from brotli file") buffer = BytesIO() with open('/opt/lo.tar.br','rb') as brotli_file: decompressor = brotli.Decompressor() while True: chunk = brotli_file.read(1024) buffer.write(decompressor.decompress(chunk)) if len(chunk) < 1024: break buffer.seek(0) print('Extracting tar stream to /tmp for caching') with tarfile.open(fileobj=buffer) as tar: # TODO: write code... print('opening tar file') tar.extractall('/tmp') print('LibreOffice caching done!') return f'{LIBRE_OFFICE_INSTALL_DIR}/program/soffice.bin' def convert_word_to_pdf(soffice_path, word_file_path, output_dir): conv_cmd = f"{soffice_path} --headless --norestore --invisible --nodefault … -
django listview order by model property
I have a model called Lap with a property calculated using data from the table class Lap(models.Model): team=models.ForeignKey('Team', models.DO_NOTHING) timestamp=models.IntegerField() num=models.IntegerField() @property def laptime(self): endtime=self.timestamp starttime=Lap.objects.get(team=self.team, num=self.num-1).timestamp) return time.timedelta(seconds=endtime-starttime) I am trying to create a listview for the model class FastestLap(ListView): model=Lap template_name='fastestlaps.html' context_object_name='laps' I want to order the list view by the laptime property. sorting by a column can be done using the ordering variable or by creating a get_queryset method and doing queryset.order_by(fieldname) in that method but I cant find a way to order by the property. How do I order by laptime? -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/register.html
Working on *django * on a test app, while creating a subpage as register in index/homepage, facing an error as follows: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: [name='index'] admin/ accounts ^media/(?P.*)$ The current path, accounts/register.html, didn’t match any of these. views.py: from django.shortcuts import render def register(request): return render(request,'register.html') urls.py: from django.urls import path from . import views urlpatterns = [ path("register",views.register, name="register") ] mysite url.py: from django.contrib import admin from django.urls import include , path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',include('Sell.urls')), path('admin/', admin.site.urls), path('accounts', include('accounts.urls')) ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html: <div class="container"> <div class="header_section_top"> <div class="row"> <div class="col-sm-12"> <div class="custom_menu"> <ul> <li><a href="#">Best Sellers</a></li> <li><a href="#">Gift Ideas</a></li> <li><a href="#">New Releases</a></li> <li><a href="accounts\register.html">Register</a></li> <li><a href="#">Customer Service</a></li> </ul> </div> </div> </div> </div> </div> #Although the register.html is in a templates folder but i tried it too but still not working. Register.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv='X-UA-Compatible' content="IE=edge"> <title>Register</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="main.css"> <script src="main.js"></script> </head> <body> <form action='register' method='post'> {% csrf_token %} <input type="text" name="first_name" placeholder="First Name"><br/> <input type="text" name="last_name" placeholder="Last Name"><br/> <input type="text" name="username" placeholder="username"><br/> <input … -
how to make my css style apply on my pages
I've been using django for a while but I'm just a beginner in css, I don't know much. I put style on my style.css file which is in the static folder and I placed the link in my template base.html but when I launch the server, the css style does not apply. what to do? mon templates base.html {% load static %} <html> <head> <title>Lax blog</title> <link rel="stylesheet" href="{% static 'style.css' %}" /> </head> <body> <div class="sidebar"> <h1>Lax Blog</h1> {% if user.is_authenticated %} {% if user.profile_photo %} <img class="avatar" src="{{ user.profile_photo.url }}" /> {% else %} <img class="avatar" src="{% static 'images/default_profile.png'%}" /> {% endif %} <p><a href="{% url 'home' %}">Accueil</a></p> <p> Vous etes connecté entant que {{request.user }} <a href="{% url 'deconnexion' %}">Se déconnecter</a> </p> {% endif %} </div> <div class="main">{% block content %}{% endblock content %}</div> </body> </html> mon fichier style.css body { background-color: white; color: blue; } html { font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif; } .sidebar { height: 100%; /* Full-height: remove this if you want "auto" height */ width: 220px; /* Set the width of the sidebar */ position: fixed; /* Fixed Sidebar (stay in place on scroll) */ z-index: 1; /* Stay on top … -
How to create password reset in Django Rest Framework
I have an app called API where I want to create a "Forgot Password" button for the user to insert their email, and a password reset is sent to them. In the same Django project, I have an application called users which implements this process in the backend. How can Django Rest Framework be used to reset the password? Do I link the URLs of the users app or create new URLs in API app Here is the users app urls.py app_name = 'users' urlpatterns = [ path('password/', user_views.change_password, name='change_password'), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html', success_url=reverse_lazy('users:password_reset_done')), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html',success_url=reverse_lazy('users:password_reset_complete')),name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),name='password_reset_complete'), ] here is the main urls.py urlpatterns = [ path('', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), path('api/', include('api.urls'), ), path('users/', include('users.urls'), ), here is the api app urls.py app_name = 'api' router = routers.DefaultRouter() router.register(r'users', UserViewSet, basename='user') urlpatterns = [ path('', include(router.urls)), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] -
Django-channels: How to delete an object?
I'm making a real-time chat app using django channels. I want to delete an object from database using django channels(actually deleting a message from the group). How can this be done? This is my backend code: import json from django.contrib.auth.models import User from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from .models import Room, Message class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): data = json.loads(text_data) print(data) message = data['message'] username = data['username'] room = data['room'] await self.save_message(username, room, message) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username } ) # Receive message from room group async def chat_message(self, event): message = event['message'] username = event['username'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username': username })) @sync_to_async def save_message(self, username, room, message): user = User.objects.get(username=username) room = Room.objects.get(slug=room) Message.objects.create(user=user, room=room, content=message) Should i use javascript? I tried to delete some objects by using Ajax but it didn't work. -
Is it possible to return render request and json response together?
I got a little function for rendering an html and I also wanna return a JsonResponse in the same page, is it possible to return both at the same time? I'll leave mi little function Below def addObservation(request): reservations= Reservation.objects.all() return render(request, 'observations/registerObservation.html', {'reservations': reservations}) I wanna add a Json response to get the reserveations list in js Thanks for your help -
I get this error when I try to render some html files in django: NoReverseMatch at / Reverse for 'it_languages' not found
When I try to render a html file in django project, I get this error, and I can't see the localhost page 'cause of this. The error is: NoReverseMatch at / Reverse for 'it_languages' not found. 'it_languages' is not a valid view function or pattern name. and it languages is url for in html Then it bolds me with yellow this: Home About Me **IT-languages** Projects Contact I expect to see my offline page rendered by django project Should I keep it like the original html version: Home About Me IT-languages Projects Contact -
Unable to add image in django
I am unable to display the image from local storage to the html page using django HTML code: <!DOCTYPE html> <html> <head> <title>Display Image</title> </head> <body> <img src="{{ image_path }}" alt="Image"> </body> </html> view.py code: from django.shortcuts import render def display_image(request): image_path = 'templetes\media\image.png' context = {'image_path': image_path} return render(request, 'valid.html', context) setting.py code: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/ -
Queryset ordered by must frequent values
I'm trying to order a simple queryset by the must frequent value in a column. For exemple, I have those models: class Keyword(models.Model): keyword = models.CharField(verbose_name='Keyword', null=False, blank=False, max_length=20) class BigText(models.Model): text = models.CharField(verbose_name='Big Text', null=False, blank=False, max_length=1000) class BigTextKeyword(models.Model): keyword = models.ForeignKey(Keyword, verbose_name='Keyword', null=False, on_delete=models.CASCADE) bigtext = models.ForeignKey(BigText, verbose_name='Big Text', null=False, on_delete=models.CASCADE) Then, I'm searching for the keywords passed on query params and returning the BigTextKeywords result found like this: class BigTextKeywordViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): queryset = BigTextKeyword.objects.all() serializer_class = BigTextKeywordSerializer def get_queryset(self): keyword_filter = Q() search_content = self.request.query_params.get('search_content', '') for term in search_content.split(' '): keyword_filter |= Q(keyword__icontains=term) keywords = Keyword.objects.filter(keyword_filter) result = BigTextKeyword.objects.filter(keyword__in=keywords) return result I want to order the result by the must frequent bigtext field. For example, if a bigtext occurs 3 times on the result, it should appears first than a bigtext that occurs 2 times. -
Tests failling after django and python upgrade
I've upgraded Django from 4.0.5 to 4.1.6 and python from 3.9 to 3.11 I've also upgraded dependencies: pip==23.0 pytest==7.2.1 pytest-django==4.5.2 coverage==7.1.0 pytest-cov==4.0.0 pylint==2.16.2 mock==5.0.1 These are my logs: django-admin test Traceback (most recent call last): File "/usr/local/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 394, in run_from_argv parser = self.create_parser(argv[0], argv[1]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 357, in create_parser self.add_arguments(parser) File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/test.py", line 54, in add_arguments test_runner_class = get_runner(settings, self.test_runner) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/test/utils.py", line 394, in get_runner test_module = __import__(test_module_name, {}, {}, test_path[-1]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django_coverage/coverage_runner.py", line 31, in <module> from django.db.models import get_app, get_apps ImportError: cannot import name 'get_app' from 'django.db.models' (/usr/local/lib/python3.11/site-packages/django/db/models/__init__.py) -
Incorrect type. Expected pk value, received str
how to post from html form in [enter image description here] (https://i.stack.imgur.com/fevLp.png) django rest framework api i am getting error as Incorrect type. Expected pk value, received str. -
Fullfill drf serializer attribute from dict by key name
Imagine I have a serializer with lower camel-named fields what I have to keep by contract: class SomeSerializer(serializers.Serializer): someField = serializers.CharField() And I have following data to serilaize where I want to keep key names in snake case to follow convention: data = {'some_field': 'I love python'} I want serializer to fullfill its someField from dict some_field key's value serialized_data = SomeSerializer(data=data) serialized_data.is_valid() serialized_data.data['someField'] == 'I love python' What I tried already: DRF serializer source - seems to be applicable to model-based serialzers? DRF serializer method field - seems to be hard to apply when there is few fields of different formats - charfields, datefeilds, intfields and all I need is just to pull values from dict Custom renderers - but they are applied after serialization and validation will fail and will affect whole view Any other suggestions? -
My view does not redirect after processing a form. Used HttpResponseRedirect
I am new to Django and I am trying to use custom forms. My problem is that my form does not do anything after I submit it. I am following the documentation here:https://docs.djangoproject.com/en/4.1/topics/forms/ I have the following files: urls.py: from django.urls import path from . import views app_name = 'home' urlpatterns = [ path('', views.index, name='index'), path('test', views.test_view, name='test') ] views.py: def index(request): return render(request, 'index.html', context) def test_view(request): if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): return HttpResponseRedirect('home:index') else: form = TestForm() return render(request, 'test.html', context={'form':form, 'text':'No text yet.',}) template: test.html <div> <form action="home:club-invite" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> <hr> <p>Your text: {{ text }}</p> </div> The problem is that the Submit button does nothing. I was expecting a redirect to the index page. But here is no error, no subsequent http request or redirect, nothing... Am I missing something here? PS:I also tried return redirect('home:index'). Still no success. -
Multiple Databases in 1 Django Project
I am planning to develop a AI-Enabled Stock Market Project using Django & Tensorflow For Clients, I plan to use MSSQL For Stock Tickers, I plan to use MongoDB How do I do it in Django? I am in Planning stage