Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: a bytes-like object is required, not '_io.BytesIO' | Django | Pillow
I have been working one a Django project and I need to save an image file manually. So, I tried using PIL. Here's the code in my Django view that breaks- import PIL.Image as PilImage image_file = request.FILES.get("pic").file image = PilImage.open(io.BytesIO(image_file)) I don't understand it because io.BytesIO is a byte-like object, right? I couldn't find any solution anywhere so I'd appreciate any help. The full error is below - Traceback (most recent call last): File "G:\Workspace\Rabo\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "G:\Workspace\Rabo\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\Workspace\Rabo\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "G:\Workspace\Rabo\venv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "G:\Workspace\Rabo\App\utils\login_required.py", line 25, in wrapper return f(self, request, user_id) File "G:\Workspace\Rabo\App\views\user_views.py", line 125, in post image = PilImage.open(io.BytesIO(image_file)) TypeError: a bytes-like object is required, not '_io.BytesIO' -
how to create new tag or select from current tags using Django forms
I have 3 tables, Products, Articles, and tags products and articles both have a "tags" field which has ManyToMany relation with the "tags" table I want to be able to reference multiple tags or create new tags while adding a product or an article (in one field)(using Django forms) for example, "test1" and "test2" are already in the tags table, I want the field to be like this: 1.I type "te" in the tags field 2.A drop down with "test1" and "test2" is opened which I can choose each one of them to be added in the field 3.I type "test3" (which isn't already in the tags table)and hit enter and "test3" is added to the field products and articles both have a "tags" field which has ManyToMany relation with the "tags" table (just like tags in a post in StackOverflow) I think Django built-in forms can handle this but I'm overwhelmed by the documentation and lost in the configuration of my Django forms. what kind of fields and widgets should I use for this purpose? Excuse me if the question is vague I'm new to Django and I would appreciate any kind of help. -
Django UpdateView returns a blank rendered template
I am using django allauth for user authentication, in my adapter I have modified the get_login_redirect_url to redirect new users to an ONBOARD_URL so they can complete registration process while regular users get the expected LOGIN_REDIRECT_URL class UserAccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): if request.user.is_authenticated and (not request.user.name or not request.user.avatar or not request.user.mobile): url = settings.ONBOARD_URL else: url = settings.LOGIN_REDIRECT_URL return resolve_url(url) I have two functions handling the view and they both inherit from UpdateView and DetailView respectively. class UpdateUserAfterSignupView(LoginRequiredMixin, UpdateView): model = User form_class = UpdateUserAfterSignupForm template_name = 'users/user_form.html' context_object_name = 'user' success_url = reverse_lazy('users:detail') class UserDetailView(LoginRequiredMixin, DetailView): model = User slug_field = 'username' slug_url_kwarg = 'username' template_name = 'users/user_detail.html' context_object_name = 'user' def get_object(self, queryset=None): return get_object_or_404(self.model, username=self.request.user.username) In my DetailView, if i leave out the get_object it returns a PageNotFound 404, but when its present as is, I get a blank page in the rendered template. This is the template: <p>welcome {{user}}</p> <form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <button type="submit" value="submit">submit</button> </form> and my url conf looks like this [ path('<str:username>/', views.UserDetailView.as_view(), name='detail'), path('complete-signup/', views.UpdateUserAfterSignupView.as_view(), name='complete_signup'), ] Again, all of these results in a blank rendered template, nothing at all. Could you please suggest things … -
Django queryset to string does not return the string in a test
I'm trying to write a unit test for this model: ADMIN = 1 FULL_USER = 2 LIMITED_USER = 3 class Role(models.Model): """ The class stores the model to store the different role which will be used to assign permissions to the users. """ ROLE_CHOICES = ( (ADMIN, 'admin'), (FULL_USER, 'full_user'), (LIMITED_USER, 'limited_user') ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True) name = models.CharField('name', max_length=30) def __str__(self): """String for representing the Model object.""" if self.name: return self.name return self.id So I wrote this test: from example.models import Role from rest_framework.test import APITestCase class RoleModel(APITestCase): fixtures = ["initial_data/role.json"] def test_get_admin_role(self): role = Role.objects.filter(id=1) self.assertEqual(str(role), 'admin') But I'm not able to understand why it fails with this: AssertionError: '<QuerySet [<Role: admin>]>' != 'admin' - <QuerySet [<Role: admin>]> + admin I have read similar questions on how to get the string of the queryset and it should be the one defined in __str__. but I don't know why it is surrounded by <QuerySet [<Role: HERE_IS_MY_STRING]> if I'm asking for the string representation of the object. -
I need help. I am hosting site first time in my life. I want to deploy my Django site on AWS
when I will deploy the website at that time virtual env folder will helpful or only the requirement.txt file will enough. -
Dajngo: Get the ID of a clicked button
I am using django. In my views I want to know which button was pressed. My template.html looks like: {% for post in posts %} <button name="{{ post.pk }}" type="submit">{{ post.title }}</button> {% endfor %} I know that in my views.py I can check if button x was pressed by just: if '12345' in request.POST: # do something elif '23456' in request.POST: #do something else But is there a way to get the primary key without checking every key possible? I would love something like this: #PSEUDOCODE post_primary_key = request.POST.get_name() If my approach is fundamentally bad, I am also open to alternative ways of solving my problem. -
How to debug django-select2 dropdown
Id like to create a text search field based on dropdown options from a model. I chose on django-select2 but it isn't working. This is the output html <form class="add_new container" method="post"> <h3 class="text-center">Issue Book</h3><hr><br> {% csrf_token %} <h4> Choose the student to issue book to</h4><br> {% for field in form %} {{ field }} {% endfor %}<hr><br> <input type="submit" value="Issue" class="btn btn-dark text-right" style="float:right"> </form> This is the form class NewIssueForm(forms.ModelForm): def __init__(self,*args, pk,school,issuer, **kwargs): super(NewIssueForm, self).__init__(*args, **kwargs) self.fields['issuer'].initial = issuer self.fields['borrower_id'].queryset = Student.objects.filter(school=school) self.fields['book_id'].initial = pk #Sets the field with the pk and it's hidden again class Meta: model = Issue fields = ['issuer','book_id','borrower_id'] widgets = { } widgets = { 'book_id':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'issuer':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'borrower_id': Select2Widget, } Settings.py hs the following CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, 'select2': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } -
Digital Ocean Forbidden You don't have permission to access this resource
I am using Django I do not know how to setup config file ''' Alias /static root/pixlfy/googlesheet/static <Directory root/pixlfy/googlesheet/static> Require all granted <Directory root/pixlfy/googlesheet/googlesheet> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess pixlfy python-home=root/pixlfy/projectenv python-path=root/pixlfy/googlesheet WSGIProcessGroup pixlfy WSGIScriptAlias / root/pixlfy/googlesheet/googlesheet/wsgi.py <Directory root/pixlfy/googlesheet/googlesheet> Order allow,deny Allow from all </Directory> ''' -
Django template variable not rendering
So I am trying to render a django template variable, but for some reason it is not rendering out. I have the following code: Views.py ... def get_search(request, *args, **kwargs): context = {} context = {"test":"abcde"} return render(request, 'search.html', context) ... Urls.py urlpatterns = [ path("", home_view), path("articles/", include("papers.urls")), path("admin/", admin.site.urls), path("search/", search_view), path("submit/", submit_article_view, name="submit"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) search.html {extends 'base.html'} {% block content %} <p> {{ test }} hi </p> ... {% endblock %} base.html {% load static %} <!DOCTYPE html> <html> <head> <title>Title</title> <link rel="stylesheet" type ="text/css" href="{% static 'css/stylesheet.css' %}"> </head> <header> {% include 'navbar.html' %} </header> <body> {% block content %} {% endblock %} </body> <footer> {% include 'footer.html' %} </footer> </html> Now, whenever I run the server and go to the search page, everything else gets rendered out, but the {{ test }} doesn't. The 'hi' does get rendered out. I have followed every tutorial and StackOverflow question out there, to no avail. Anyone has any idea what might be going on? Also, StackOverflow newbie, let me know if I did something wrong regarding that :). -
how do I take files from local file system (django) and render it to the frontend (react)
I am currently working on a web application which will only run on my machine. I want django to access my local file system using a python script and then send it to the react front-end in which it can be shown to the user. Is this possible? I can find no information on this except that django can access files from the media and static directories only. -
creating sidebar in django using CSS but appears nothing
i was trying to create sidebar base on codewithtim however it appears that it didn't read any of the css code below is my home.html: {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html> <head> <style type="text/css"> .sideenv a{ padding: 6px 8px 6px 18px; text-decoration: none; font-size: 25px; color: : #818181; display: block; } </style> <title>{% block title %}home{% endblock %}</title> </head> <body> <div class="sidenav"> <a href="">home</a> <a href="/vendor">vendor</a> <a href="/search">search</a> </div> </body> {% endblock %} and here is my base.html: <!doctype html> <html> <head> <title>{% block title %}prototype{% endblock %}</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> </head> <body> <!--{% include 'navbar.html' %}--> {% block content %} replace me {% endblock %} </body> </html> The only thing different from my code than codewithtime is i am trying to use block content to override some bolck. it might be wrong here, but i have no idea how to correct it ================================================================== And i have another question about using css in django when i google "css in django" usually the doc shows code below <head> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>Linguist</title> </head> why did codewithtim can ignore the implementation and just include css might … -
ModuleNotFoundError: No module named 'xxxx.yyy'
I am very new to python programing and django.. I have not found any resources addressing this issue on web hence reaching out community. I have a django rest api with following code MyApi.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions from django.contrib.auth.models import User class MyOwnView(APIView): def get(self, request): return Response({'some': 'data'}) My module is not found in the url.py file, below is url.py file And urls.py file is here: from django.contrib import admin from django.urls import path from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions from django.contrib.auth.models import User from jpbapi.api.MyApi import MyOwnView urlpatterns = [ path('admin/', admin.site.urls), ] This fails loading my module please see my project structure below, not sure where i am wrong. -
Is there a way in Django to unlock the resources before the transaction is over or to auto restart the transaction if the deadlock is found?
I have a model Orders in my Django rest-framework app. I am retrieving a list of orders based on some filter parameters and at the same time I am also locking orders using select_for_update(). Each order in the Orders model has a status and it could be OPEN, PARTIALLY_COMPLETED, COMPLETED or CANCELLED. However, one of my filter parameters will only consider the order with status OPEN or PARTIALLY_COMPLETED. So the retrieved list will have order with OPEN or PARTIALLY_COMPLETED status only. Furthermore, each order in Orders model also has the parameter units. This represents the units at which the order was created. If the order is in OPEN state then all the units are unsold or if the order is in PARTIALLY_COMPLETED then unsold_units = units - sold_units. Deriving the unsold units for PARTIALLY_COMPLETED orders is done after retrieving the list of orders. Now, let's assume the retrieved order list has 10 order and the total of unsold_units of the list is 1000. However, I just need 100 units so if the unsold_units of the first 3 orders is equal or over 100 units than the remaining orders must be unlocked immediately so that the other transaction can use it. … -
'int' object has no attribute 'user_list'. (Django Rest Framework)
I have a feature where user can remove an item from a list. The code below does successfully remove (delete) the item from the list but also returns the following error (and my AJAX call doesn't complete successfully): Got AttributeError when attempting to get a value for field `user_list` on serializer `UserVenueSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'user_list'. I am not sure how to debug this/why this error is being thrown. Here is my serializers: class UserVenueSerializer(serializers.ModelSerializer): venue = mapCafesSerializer() class Meta: model = UserVenue fields = ['user_list', 'venue'] Here is my views class RemoveVenueViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserVenueSerializer authentication_classes = [CsrfExemptSession] def get_queryset(self): user_list = self.request.GET.get('user_list', None) venue = self.request.GET.get('venue', None) data = UserVenue.objects.filter(user_list = user_list, venue= venue) print(data) return data.delete() Here is the traceback: <QuerySet [<UserVenue: UserVenue object (142)>]> Internal Server Error: /api/removevenue/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 457, in get_attribute return get_attribute(instance, self.source_attrs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 97, in get_attribute instance = getattr(instance, attr) AttributeError: 'int' object has no attribute 'user_list' During handling of the above exception, another exception occurred: Traceback (most recent call … -
Order a queryset by a field in another queryset
In my django blog app, I have a model for Bookmark, which includes fields pointing to Post and User, and a field for when the bookmark was created. # models class Post(models.Model): # ... title = models.CharField(max_length=70) body = RichTextField() author = models.ForeignKey( UserProfile, on_delete=models.CASCADE, related_name='posts') created_on = models.DateTimeField(default=timezone.now) # ... class Meta: ordering = ['created_on'] class Bookmark(models.Model): post = models.ForeignKey( Post, on_delete=CASCADE, related_name="bookmarked_post" ) user = models.ForeignKey( User, on_delete=CASCADE, related_name="bookmarks" ) created_on = models.DateTimeField(default=timezone.now) class Meta: ordering = ['created_on'] I have a view to display my users' bookmarks. I want to order the posts queryset in the order they were bookmarked, with the recently bookmarked posts first. # views.py @login_required def bookmarks_view(request): bookmarks = Bookmark.objects.filter(user=request.user) bookmarked_posts = Post.objects.filter( bookmarked_post__in=bookmarks).order_by(???) return render(request, 'bookmarks.html', posts=bookmarked_posts) I'm struggling to figure out how to order my Posts queryset by the created_on field in the Bookmark model. To add additional complexity, both the Post and Bookmark model have a created_on field. Can anyone point me in the right direction with this? I've scoured the django documentation and SO and not finding what I need, possibly I just don't know the right keywords... Or have I set up my models incorrectly to achieve what I … -
How to get individual users data after login in django?
iam new to django.Can anyone send me the code of signup and login page to get particular details of the username (i.e if we login with some usename then it should only give details of that username not remaining). -
django ajax like button with css classes
hello I have a post model which has a like(m2m) and user(forgeinkey) model field and Im trying to check if the request.user has liked the post and if they have, I should show them a red heart button else a blue heart should be shown, now since there are multiple posts and likes, Im looping through each like object to check if the request.user has liked it or not. Unfortunately for some reason, I couldn't implement a good logic and I see like button for every user. Some help would be appreciated. Here's my model: class post(models.Model): user = models.ForeignKey(User,default='' , related_name='has_liked', on_delete=models.CASCADE) caption = models.CharField(max_length=100) image = models.FileField(upload_to='images/', null=True, blank=True) video = models.FileField(upload_to='videos/', null=True, blank=True) created = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField(User, null=True, blank=True, default='') The View: @login_required def usersfeed(request): users = User.objects.all() posts = post.objects.filter(Q(user__in=request.user.profile.friend.all()) | Q(user=request.user)).order_by('-created') comments = Comment.objects.all() status_form = StatusForm(request.POST) friend_requests = FriendRequest.objects.filter(to_user=request.user) friends = request.user.profile.friend.all() for i in posts: likes = i.like.all() print(likes) for like in likes: if like.username == request.user.username: if request.user: Hasliked = True print('liked') else: Hasnotliked = True print('not liked') context = { 'Post':posts, 'User':users, 'form':PostForm(), 'Profile':profile, 'Form':CommentForm(), 'Comment':comments, 'Status':status_form, 'fr':friend_requests, 'friend':friends, 'Hasliked':Hasliked, 'Hasnotliked':Hasnotliked, } return render(request, 'social_media/feed.html', context=context) The view for … -
NoReverseMatch at / Reverse for 'url' with arguments '('',)' not found
I am trying to pass URL as a parameter in dynamic URL. The URL contains ? which is making django search for the keys. How do I make Django ignore '?' that are present in my URL. Custom URL: https://www.amazon.in/Samsung-Galaxy-M12-Storage-Processor/dp/B08XGDN3TZ/ref=sr_1_1_sspa?dchild=1&keywords=redmi+9&qid=1622011804&sr=8-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFZSlE5U0lEUzBFUVQmZW prd.Url is passed as a parameter {% for prd in prds %} {{ prd.name }} <a href="{% url 'url' prd.Url %}">Click</a> {% endfor %} urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='index'), path('create/', createProfile.as_view(), name='create_profile'), path('update/<pk>', UpdateProfile.as_view(), name='update_profile'), path('url/<my_url>', url, name='url') ] -
Django filter and paginate not working. (Using AJAX)
I have a table for tracking job applications and im trying to implement a filter feature. On choosing a filter for instance closing date, the jobs are sorted by closing date and displayed in table. The query is working fine. I have printed the results. Is there a way I update the page without refresh and paginate the new results? Please help.... Here is my code: template file <ul id="filter_list" class="dropdown-menu"> <li><a href="#">Alphabetical Order (A-Z)</a></li> <li><a href="#">Application Date (Ascending)</a></li> <li><a href="#">Application Date (Descending)</a></li> <li><a href="#">Closing Date</a></li> </ul> <div id="table_results"> <div> <script> $(".dropdown-menu a").click(function(){ var selected_filter = $(this).text(); $.ajax({ url:'{% url "stu_filter_applications" %}', data:{ "filter_category": selected_filter, }, dataType:'json', success: function (response) { //I want the page to not refresh here }, error: function (response) { console.log(response.errors); }, }); }); </script> views.py: def stu_filter_applications(request): filter_cat = request.GET.get("filter_category", None) student = StudentUser.objects.get(user=request.user) if filter_cat == "Alphabetical Order (A-Z)": int_applications = InternshipApplication.objects.filter(student=student). order_by('internship__internship_title') if filter_cat == "Application Date (Ascending)": int_applications = InternshipApplication.objects.filter(student=student). order_by('application_date') if filter_cat == "Application Date (Descending)": int_applications = InternshipApplication.objects.filter(student=student). order_by('-application_date') if filter_cat == "Closing Date": int_applications = InternshipApplication.objects.filter(student=student). order_by('-internship__internship_deadline') applications = [] for app in int_applications: internship = Internship.objects.get(id=app.internship.id) recruiter = Recruiter.objects.get(id=internship.recruiter.id) applications.append((internship,recruiter,app)) for internship, recruiter, app in applications: print(internship) print(recruiter) … -
how to create a decorator/ wrapper class in python to pass the attributes of error logs as a single parameter?
@api_view(['GET']) def test_api_method(self): print('This is Test API') db_logger = logging.getLogger('db') try: 1 / 0 except Exception as e: db_logger.exception(e, extra={'user': self.user.username, 'class_name': self.__class__.__name__,'method_name':sys._getframe().f_code.co_name, 'module_name':__package__,'ip_address': socket.gethostbyname(socket.gethostname())}) return Response({'data': True}, status=status.HTTP_200_OK) I want to create a decorator or a wrapper class to pass the parameters in the db_logger.exception() as a sin single parameter. Mainly, I wanted to replace this dictionary---> extra={............} with a single parameter so that this error logging method can be used to log errors across all classes and methods. -
Change Django Database : SQLITE3 to MARIADB
I am new to Django and python! I made a project on Django with the default database which is sqlite3. I want to now transfer the database from sqlite3 to Mariadb. There is no data which is present in current sqlite3. I just want to know how can I transfer the default database. I have followed the following documentation: And added, this to my settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Altiostar', 'USER': 'satharkar', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '', } } I am not sure, how things will work with this now. I am looking if someone can help me with this. So what I did is by now : I deleted the db.sqlite3 from my project folder. Tried to run python manage.py makemigrations but it is throwing error that mysql client is not installed. I have followed the documentation and installed everything mentioned their. How will things work after this ? So whenever I will try to submit the form in my django project, database, table will be created and data will be then stored under the mariadb? I am new to all this, looking for a resolution in this case or any suggestions on … -
I am making an affiliate website where we can copy product link and share it in other medias. please help to get me with it with a little idea
This is the product page. I have highlighted the portion of which i want to convey about. Here, in the 'Get Link' option i want to create a link for this product so that if a user copies and shares it to other media, it will open this page. P.S: Project is still in development URLS.py urlpatterns = [ path('', views.blink_network), # redirect to root - path path('blink_network/', views.blink_network, name='blink_network'), path('AddNewProduct/', views.AddNewProduct, name='AddNewProduct'), path('blink_viewproduct/', views.showproduct), path('blink_viewproduct/', views.blink_viewproduct, name='blink_viewproduct'), path('blink_updateproduct/', views.blink_updateproduct, name='blink_updateproduct'), ]+static (settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Views.py def AddNewProduct(request): if request.method == "POST": current_user = request.user product_title =request.POST['product_title'] uid = request.POST['uid'] specification =request.POST['specification'] sale_price = request.POST['sale_price'] discount = request.POST['discount'] img1 = request.FILES['img1'] img2 = request.FILES['img2'] promote_method = request.POST['promote_method'] terms_conditions = request.POST['terms_conditions'] newproduct = AffProduct(user_id=current_user.id, product_title=product_title, uid=uid, specification=specification, sale_price=sale_price, discount=discount, img1=request.FILES.get('img1'), img2=request.FILES.get('img2'), promote_method=promote_method, terms_conditions=terms_conditions) newproduct.save() # Status message messages.success(request, 'Product added successfully') return render(request, 'blink_network.html') else: return render(request, 'blink_network.html') #Display only single-user products def showproduct(request): if request.user.is_authenticated: current_user = request.user# define current user result = AffProduct.objects.filter(user_id=current_user.id) return render(request, 'blink_viewproduct.html', {'result': result}) HTML File <div class="row py-3"> <div class="col-lg-12 col-md-12"> <h5 class="text-center"><b>Product Details</b></h5> <table class="table table-striped table-hover table table-responsive table-responsive-lg table-responsive-md table-responsive-sm"> <thead> <tr class="bg-primary text-white"> <th scope="col">Product ID</th> <th scope="col">Product Title</th> <th scope="col">Sale … -
if request.method == "POST": the pointer is not coming in the if statement can anybody tell?
views.py ... @login_required() def candidate_view(request): if request.method == "POST": can = candidate.objects.filter(position = 'President') return render(request,'poll/candidate.html',{'can':can}) else: return render(request, 'poll/candidate.html') ... ... vote.html {% extends 'base.html' %} {% block title %}Positions{% endblock %} {%block body%} <form action="" method="POST"> {%csrf_token%} <ul> <li><h2><a href='candidate_view'> President</a></h2></li> <li><h2><a href='candidate_view'> Vice President </a></h2></li> <li><h2><a href="#"> Secratary </a></h2></li> <li><h2><a href="#"> Vice Secratary </a></h2></li> </ul> </form> {% endblock %} ... Caandidate.html ... {% extends 'base.html' %} {% block title %}Positions{% endblock %} {%block body%} <form action="" method="POST"> {%csrf_token%} <ul> <li><h2><a href='candidate_view'> President</a></h2></li> <li><h2><a href='candidate_view'> Vice President </a></h2></li> <li><h2><a href="#"> Secratary </a></h2></li> <li><h2><a href="#"> Vice Secratary </a></h2></li> </ul> </form> {% end block %} ... -
How to pass a decimal value when making a post request in django?
I am trying to make a post request to a third party application along with some data and the data also have a decimal value up to two points, which I am getting from database (order.amount) but after making the request getting error saying data is not serializable to json then i passed it as '"%s"' % round(order.amount,2) then also getting error post data is empty.Looking for suggestion to solve this problem. request = Transfer.request_transfer(beneId=beneficiary_id, amount=round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer") getting error: decimal is not json serializable print('"%s"' % round((order.amount),2) #"5000.23" request = Transfer.request_transfer(beneId=beneficiary_id, amount='"%s"' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer") getting error : PreconditionFailedError: Reason = Post data is empty or not a valid JSON:: response = {"status": "ERROR", "subCode": "412", "message": "Post data is empty or not a valid JSON"} but when hardcoding amount then it is working request = Transfer.request_transfer(beneId=beneficiary_id, amount= "5000.23" transferId=transfer_identifier,remarks="Test transfer") -
Handling oracle database clob field in djangorestframework to get rid of to_clob()
I have an oracle database with a clob field as below: Name Null? Type ----------------------- -------- ------------- ID NOT NULL NUMBER MOVIE NOT NULL VARCHAR2(100) PLOT CLOB I am writing an API to retrieve this data and have the models.py defined as below: class MovieInfo(models.Model): id = models.IntegerField(primary_key=True) movie = models.CharField(max_length=100, unique=True) plot = models.TextField(null=True, blank=True) class Meta: managed = False db_table = 'movie_info' My serializer is defined as: class MovieInfoSerializer(serializers.ModelSerializer): class Meta: model = MovieInfo fields = '__all__' Views: class MovieInfoViewSet(viewsets.ModelViewSet): queryset = MovieInfo.objects.all() serializer_class = MovieInfoSerializer http_method_names = ['get'] However when I issue a get request, the data I'm getting looks as below: {"id":1,"movie":"Gravity","plot":"to_clob('The crew of the Space Shuttle Explorer is working on the STS-157 mission. Mission Commander Matt Kowalski, medical engineer Dr. Ryan Stone - who is on her first ever space mission - and flight engineer Shariff Dasari are on a space walk when they learn from Houston control that an explosion has just occurred at a Russian satellite. Before the crew can do anything about it, the explosion debris comes hurtling toward Explorer, irreparably damaging the shuttle and station, immediately killing all the crew except Kowalski and Stone, and knocking out at least incoming communication …