Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin keeps the users data when removed from the like-list
I created a like button with django which saves the information of the users who clicked the button. When the same user click the button again and 'unlike' it, the counter beside the button goes back to the number before the user clicked and the user is supposed to be removed from save-list. However, the data set in the admin keeps the user listed as one of whom clicked the button once after they clicked it. The code shows no error and I have no idea where to modify to remove the users who 'unlike'd from the data set because the code post_obj.liked.remove(user) seems running properly. My models.py is: class Post(models.Model): posts = models.CharField(max_length=420, unique=True) slug = models.SlugField(max_length=42) date_created = models.DateTimeField(auto_now_add=True) liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') def __str__(self): return str(self.posts) LIKE_CHOICES = ( ('like', 'like'), ('unlike', 'unlike'), ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='like', max_length=10) My views.py is: def likes(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if request.user.is_authenticated: if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == … -
Django Channels. How to avoid exception RuntimeError: Task got Future attached to a different loop?
I use `Django Channels` with `channel_layers` (`RedisChannelLayer`). Using Channels I only need to get live messages from signals when post_save event happens. I try to send a message from the `signals.py` module. The fact that the message is sending properly, I got it successfully in the console, but then **disconnection** from the socket happens **with an Exception**: `RuntimeError: Task got Future attached to a different loop.` It refers to *`...redis/asyncio/connection.py:831`* All my settings were done properly in accordance with the documentation. My project also uses `DRF`, `Celery`(on Redis), `Redis` itself, `Daphne` server. I only try to implement it with Debug=True mode, let alone production. I have no idea what happens and how to solve it. Here are snippets from my code: consumers.py class LikeConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = "likes" await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'type': 'chat', 'message': message })) signals.py channel_layer = get_channel_layer() @receiver(post_save, sender=Like) def new_like(sender, instance, **kwargs): async_to_sync(channel_layer.group_send)( 'likes', { "type": "chat_message", "message": "1212341324, 213413252345" } ) script.js const likeSocket = new WebSocket(url); likeSocket.onmessage = function(e) { let data = JSON.parse(e.data); console.log(data); }; -
django eccomerce website problem with first() function
when i use first() it repeting first name to all products also when i use first() for loop is not working i just want to display correct name for products i really stucked here helping are appreciated thank you -
Import "django.urls" could not be resolved from source
I am expecting the solve please help me I m new at that. I tried searching but I could not find anything. -
Could not parse the remainder: ':' from '1:'
TemplateSyntaxError at /challeges/1 Could not parse the remainder: ':' from '1:' This is my challege.html {% if month == 1: %} <h1>This is {{ text }}</h1> {% else: %} <p>This is {{ text }}</p> {% endif %} This is my views.py def monthly_challege(request, month): return render(request, "challeges/challege.html", { "text": "Your Url Is Empty", month: month }) This is my urls.py urlpatterns = [ path("<month>", views.monthly_challege), ] -
How to stop DRF's ModelSerializer to use model field's default value?
I'm stucked with this strange bug(?) with BooleanField. While partial_update, serializer is always set all boolean values to false, if it is not set in request. My models.py class User(AbstractUser): agree_email = BooleanField(blank=True) agree_sms = BooleanField(blank=True) serializers.py class UserChangeSerializer(serializers.ModelSerializer): class Meta: model = AZUser fields = "first_name", "agree_email", "agree_sms" When i trying to set agree_email to True - it's validating as {'agree_email': True, 'agree_sms': False}, and if i try to set agree_sms to true - it'll validate it as {'agree_email': False, 'agree_sms': True} and update User object respectively. How to prevent such behavior of DRF? -
Table without primary key and two FKs - Django
I'm doing an API from a existing database (which means it's not an option to change de DB schema) with Django and rest_framework. I have a single table (foos_bars) with 2 FKs only. bar_id (FK) | foo_id (FK) 1 |1 2 |2 When I use the endpoint, I get: django.db.utils.OperationalError: (1054, "Unknown column 'foos_bars.id' in 'field list'") There is a way to work with? -
Single-query get_or_create in Django and Postgres
Currently Django performs get_or_create as a series of separate two calls: 1. try get 2. perform create if the DoesNotExist exception was thrown This can lead to IntegrityError exception being raised if the instance was created right after the DoesNotExist exception was thrown. Is there any existing solution that allows to swap current django code for a postgres-specific single-query get_or_create? No problem if the solution only works with postgres as the db backend. Bonus points if it allows async aget_or_create as well. I know this should be possible on posgres as in the accepted answer in this SO question: Write a Postgres Get or Create SQL Query But I want to look for existing solutions before customising the calls in my code one by one. -
Django Ajax Form Upload with Image
I am using Django + Ajax, and i'm trying to send a POST request to upload a form with an image. However, i still get an error KeyError: 'file' HTML form (notice i've added enctype="multipart/form-data"): <form id="addProduct" method="post" enctype="multipart/form-data"> <label class="form-label required-field" for="file">Image</label> <input class='form-control' id='file' name="file" type="file" accept="image/*" required/> </form> Javascript using AJAX requests: $("#addProduct").on("submit", function (e) { e.preventDefault() var data = new FormData(this); $.ajax({ url: '/admin/product/add/', data: data, type: 'post', success: function (response) { var result = response.result console.log(result) if (result == false) { alert("Add product failed") } else { alert("Add product successfully") } }, cache: false, contentType: false, processData: false }) } Django View - views.py: class ProductAddPage(View): def post(self, request): img = request.FILES['file'] try: #further processing except: traceback.print_exc() return JsonResponse({"result":False}, status=200, safe=False) return JsonResponse({"result":True}, status=200, safe=False) Traceback: Internal Server Error: /admin/product/add/ Traceback (most recent call last): File "D:\Codes\Django\env\lib\site-packages\django\utils\datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) KeyError: 'file' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Codes\Django\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\Codes\Django\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Codes\Django\env\lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "D:\Codes\Django\env\lib\site-packages\django\contrib\auth\mixins.py", line 73, in … -
Django: Object of type QuerySet is not JSON serializable
I am trying to remove items from cart using Jquery and Django, i have written the logic to do this but i keep getting this errror that says Object of type QuerySet is not JSON serializable, i can seem to know what the problem is because i have tried converting the code below to list using list() method in django and also values() but it still does not work as expected. views.py def RemoveWishlist(request): pid = request.GET['id'] wishlist = Wishlist.objects.filter(user=request.user) wishlist_d = Wishlist.objects.get(id=pid) delete_product = wishlist_d.delete() context = { "bool":True, "wishlist":wishlist } t = render_to_string('core/async/wishlist-list.html', context) return JsonResponse({'data':t,'wishlist':wishlist}) function.js $(document).on("click", ".delete-wishlist-product", function(){ let this_val = $(this) let product_id = $(this).attr("data-wishlist-product") console.log(this_val); console.log(product_id); $.ajax({ url: "/remove-wishlist", data: { "id": product_id }, dataType: "json", beforeSend: function(){ console.log("Deleting..."); }, success: function(res){ $("#wishlist-list").html(res.data) } }) }) wishlist-list.html {% for w in wishlist %} {{w.product.title}} {% endfor %} traceback Internal Server Error: /remove-wishlist/ Traceback (most recent call last): File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Destiny\Desktop\E-commerce\ecomprj\core\views.py", line 453, in RemoveWishlist return JsonResponse({'data':t,'wishlist':wishlist}) File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\http\response.py", line 603, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 234, in dumps return cls( … -
staticfiles.W004 Error, The directory '/app/static' in the STATICFILES_DIRS setting does not exist. Postgres tables are 0,
django project deployment on heroku was successful https://ddesigner.herokuapp.com/ "heroku run python collectstatic" fails with following error ?: (staticfiles.W004) The directory '/app/static' in the STATICFILES_DIRS setting does not exist. 1395 static files copied to '/app/staticfiles'. "heroku run python makemigrations" also gives same error although new migrations are made ?: (staticfiles.W004) The directory '/app/static' in the STATICFILES_DIRS setting does not exist. "heroku run python migrate" also gives same error and I see that migrations are applied (as displayed) but not actually. because postgres tables in heroku are zero. Please help me to fix this issue. I have tried removing STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] and also by changing STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') to STATIC_ROOT = os.path.join(BASE_DIR, 'static') but the error is same. -
How do I prefill django-simple-history HistoricalRecords with pre-existing admin model history?
I have a model with pre-existing history When I switch my admin from the Django default admin.ModelAdmin to django-simple-history simple_history.admin.SimpleHistoryAdmin I lose this history Note that this history is only lost from the user's perspective, switching back to ModelAdmin returns the history. Is it possible to prefill django-simple-history with prior history, or if not, to show the two alongside one another in the admin? -
first product name repeting to all others django eccomerce
hii i am newbie here creating a eccomerce website no errors showing in during template rendering but the problem is my first product name is repeting to all other products views.py def product_view(request,cate_slug,prod_slug): if(Category.objects.filter(slug=cate_slug, status=0)): if(Products.objects.filter(slug=prod_slug, status=0)): product = Products.objects.filter(slug=prod_slug, status=0).first() else: messages.warning(request,"product not found") return redirect("collection") else: messages.error(request,"something went wrong") return redirect("collection") return render(request,"product_view.html",{'product':product}) and i found an error when i remove first() from product its not showing product names but if i am not removing first() its showing first product name to all other remaning products i really stcuked this anyone help me please i want to display coorect name for every products here is repeting same name to all other name because of first() function i stucked this into 5 hours any one help me please -
google_link,google_text = google(result) make cannot unpack non-iterable NoneType object djanog BeautifulSoup
i try to make search google with BeautifulSoup in socialnetwork django site project i download it as open source and when i try to make that i receve a error message cannot unpack non-iterable NoneType object thats search.py import requests from bs4 import BeautifulSoup done def google(s): links = [] text = [] USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36' headers = {"user-agent": USER_AGENT} r=None if r is not None : r = requests.get("https://www.google.com/search?q=" + s, headers=headers) soup = BeautifulSoup(r.content, "html.parser") for g in soup.find_all('div', class_='yuRUbf'): a = g.find('a') t = g.find('h3') links.append(a.get('href')) text.append(t.text) return links, text and thats the view.py def results(request): if request.method == "POST": result = request.POST.get('search') google_link,google_text = google(result) google_data = zip(google_link,google_text) if result == '': return redirect('Home') else: return render(request,'results.html',{'google': google_data }) and thats a template {% for i,j in google %} <a href="{{ i }}" class="btn mt-3 w-100 lg-12 md-12">{{ j }}</a><br> {% endfor %} i reseve the message cannot unpack non-iterable NoneType object for google_link,google_text = google(result) -
Django _id in FK Model
I'm doing an API from a existing database (which means it's not an option to change de DB schema) with Django and rest_framework. I have 2 tables, Foos and Bars. foo_id 1 2 bar_id | foo_id (FK) 1 |1 2 |2 Bars model: foo = models.ForeignKey('Foos', on_delete=models.CASCADE) The Django Model changes de 'foo_id' FK into 'foo' only. There is a way to keep the FK with the '_id' suffix? -
Why am i getting TemplateDoesNotExist at /rapport/?
i would like to view my home page/ index view but i keep getting this error, what do i need to do to get rid of this error message below? Any help would be appreciated. Here is the error message: TemplateDoesNotExist at /rapport/ rapport/index.html, rapport/description_list.html Request Method: GET Request URL: http://127.0.0.1:8000/rapport/ Django Version: 4.0.4 Exception Type: TemplateDoesNotExist Exception Value: rapport/index.html, rapport/description_list.html Exception Location: C:\Users\sbyeg\anaconda3\envs\new_env\lib\site-packages\django\template\loader.py, line 47, in select_template Python Executable: C:\Users\sbyeg\anaconda3\envs\new_env\python.exe Python Version: 3.8.6 Python Path: ['C:\\Users\\sbyeg\\django_projects\\rship', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\python38.zip', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\DLLs', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\lib', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env', 'C:\\Users\\sbyeg\\AppData\\Roaming\\Python\\Python38\\site-packages', 'C:\\Users\\sbyeg\\AppData\\Roaming\\Python\\Python38\\site-packages\\win32', 'C:\\Users\\sbyeg\\AppData\\Roaming\\Python\\Python38\\site-packages\\win32\\lib', 'C:\\Users\\sbyeg\\AppData\\Roaming\\Python\\Python38\\site-packages\\Pythonwin', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\lib\\site-packages', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\lib\\site-packages\\win32', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\lib\\site-packages\\win32\\lib', 'C:\\Users\\sbyeg\\anaconda3\\envs\\new_env\\lib\\site-packages\\Pythonwin'] Server time: Mon, 07 Nov 2022 12:32:56 +0300 Here is my code: views.py from django.shortcuts import render from django.urls import reverse from django.views import generic from .models import Description # Create your views here. class IndexView(generic.ListView): template_name = 'rapport/index.html' context_object_name = 'description_list' def get_queryset(self): """Return the last five keyed entries""" return Description.objects.order_by('-event_date')[:5] urls.py from django.urls import path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), index.html template {% extends "base_generic.html" %} {% block content %} <h1>Description List</h1> <ul> {% if description_list %} {% for description in description_list %} <li> <a href="{{ description.get_absolute_url }}">{{ description.title }}</a> </li> {% endfor %} </ul> {% else %} <p>There are no entries in the … -
Can someone please suggest me that how can I print the output in my desired format using nested serializers?
I am trying to send messages using django-rest framework.I have created serializers for both user and message.I am using django default user model for storing user's details. I am pasting my model and serializers here: class MessageModel(models.Model): message = models.CharField(max_length=100) created_at = models.DateTimeField(default=now) updated_at = models.DateTimeField(default=now) user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user') class UserSerializer(ModelSerializer): class Meta: model = get_user_model() fields = ['id','username','email'] class MessageSerializer(ModelSerializer): created_by = UserSerializer(read_only=True) class Meta: model = MessageModel fields = ['id','message', 'created_at', 'updated_at','user','created_by'] View : class MessageViewSet(viewsets.ModelViewSet): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] queryset = MessageModel.objects.all() serializer_class = MessageSerializer After creating message,I am getting response like below: { "id": 6, "message": "Lorem ipsum", "created_at": "2022-11-07T09:21:19.492219Z", "updated_at": "2022-11-07T09:21:19.492237Z", "user": 2 } but my output should looks like in below format,everytime when a new message is created : { "id": 102, "message": "Lorem ipsum", "created_at": "created time in UTC", "updated_at": "last updated time in UTC", "created_by": { "id": 3, "username": "testuser", "email": "test@mail.com", } } In case of any error, return the error message. Thank you in advance. -
Change the api's documentation in swagger
I want to use swagger for my python-Django project and I want to documente my api, I'm using the file schema.yml and even if I edit it nothing change in my swagger interface I don't know where's the problem. Any help is highly appreciated. This is my schema.yml : openapi: 3.0.3 info: title: My documentation version: 0.0.0 paths: /add-nlptemplate: post: operationId: add_nlptemplate_create .... And this is my urls.py : from django.contrib import admin from django.urls import path, include from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView urlpatterns = [ path('', include('ocr.urls')), path('api/schema/', SpectacularAPIView.as_view(), name='schema'), path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), ] I think the problem is in the second path because it always return the default schema.yml and not the edited one. -
JS: the use of edatagrid
I have problem in using edatagrid. [] The red area is a select, the yellow area is *table *by edatagrid. I want to refresh the content of the table when I change the selected value of the select. I attempted to separate the table from the whole page. When I change the selected value, send a ajax post request to get new data. But the result was the table's style was not like before, and the content of the table was not get refreshed. Like this, [] Here is the code. The whole page:test_plan.html {% extends 'base.html' %} {% load static %} {% block title %} NRLabLims - 测试管理 {% endblock %} {#控制表格的cs操作#} {% block css %} <link href="{% static 'vendor/datatables/dataTables.bootstrap4.min.css' %}" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/icon.css"> <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/color.css"> <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/demo/demo.css"> <link href="{% static 'css/sb-admin-2.min.css'%}" rel="stylesheet"> {% endblock %} {% block js %} <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="https://www.jeasyui.com/easyui/jquery.easyui.min.js"></script> <script type="text/javascript" src="https://www.jeasyui.com/easyui/jquery.edatagrid.js"></script> <script src="{% static 'vendor/datatables/jquery.dataTables.min.js' %} "></script> <script src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js' %}"></script> <script src="{% static 'js/demo/datatables-demo.js' %}"></script> {% endblock %} <div> {% block content %} <div class="container-fluid"> <!-- 页头 --> <h1 class="h3 mb-2 text-gray-800">测试管理</h1> <a class="mb-4">测试管理包含<a href="/lab/test/plan">test plan</a>、<a href="/lab/test/initial">原始记录单</a>、<a href="/lab/test/record">时间记录</a>、<a href="/lab/test/problem">错误记录</a>、<a … -
Checked = true not working together with other events on same element
I'm using Django inline formsets and trying to use the delete checkbox dynamically with Javascript. Everything works as it is supposed to, however the checked = true property (although showing true in the console) won't check the box as long as updateSunForm() and totalForms.setAttribute(...) are present. {% load crispy_forms_tags %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" type="text/css" href="{% static 'css/availability_update_new.css' %}"> </head> <body> <form id="all-add-form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <legend class="bottom mb-4">Profiles Info</legend> {{ sun_bool.sunday|as_crispy_field }} {{ sunday_formset.management_form }} {% for sun_form in sunday_formset %} {% for hidden in sun_form.hidden_fields %} {{ hidden }} {% endfor %} <div class="sun_time_slot_form"> {{ sun_form }} <button class="delete-sun-form" type="button" id="delete-sun-btn" onclick="one();"> Delete This Sunday Timeslot </button> </div> {% endfor %} <button id="add-sun-form" type="button" class="button">Add Other Sunday Times</button> <input type="submit" name="submit" value="Submit" class="btn btn-primary"/> </form> <script type="text/javascript" src="{% static 'js/add_timeslot.js' %}"></script> </body> </html> {% endblock content %} const sunForm = document.getElementsByClassName('sun_time_slot_form'); const mainForm = document.querySelector('#all-add-form'); const addSunBtn = document.querySelector("#add-sun-form"); const submitFormBtn = document.querySelector('[type="submit"]'); const totalForms = document.querySelector("#id_id_sunday_formset-TOTAL_FORMS"); let formCount = sunForm.length - 1; addSunBtn.addEventListener('click', function (e) { e.preventDefault(); const newSunForm = sunForm[0].cloneNode(true); const formRegex = RegExp(`id_sunday_formset-(\\d){1}-`, 'g'); formCount++; newSunForm.innerHTML = newSunForm.innerHTML.replace(formRegex, `id_sunday_formset-${formCount}-`); … -
How does Django channels utilise rooms? is it good practice to always create a room
I have written this code in which a client sends continous messages, could anyone help me understand what does the room do and what happens If I remove the room? class ResrvationEventProducer(AsyncWebsocketConsumer): GROUP_NAME = "rsv_event" async def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = self.GROUP_NAME + "_" + self.room_name await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() await self.send_message('connected to producer socket successfully') async def receive(self, text_data): try: json_payload = json.loads(text_data) logging.info(payload) except Exception as e: traceback.print_exc() logging.error('An error occurred while reading text from producer socket') -
products not showing in product view page django
i created a function to view products in products view page i tried so many times but cant find any one help me please here is my code views.py def product_view(request,cate_slug,prod_slug): if (Category.objects.filter(slug=cate_slug, status=0)): if (Products.objects.filter(slug=prod_slug, status=0)): product = Products.objects.filter(slug=prod_slug, status=0) contex = { 'product':product, } else: messages.warning(request,"product not found") return redirect("collection") else: messages.error(request,"something went wrong") return redirect("collection") return render(request,"product_view.html",contex) urls.py path('collection/str:cate_slug/str:prod_slug',views.product_view,name="product"), product view.html {% extends 'auth.html' %} {% load static %} {% block content %} {{ products.name }} {% endblock %} i just want to see product detils in product view html page any one help me because i am new to django -
Django - getting properly formatted decimals in forms (+crispy)?
I have the following model: class Probe(models.Model): name = models.CharField("Probe name", max_length=200, blank=True, null=True) order = models.IntegerField("ordering", default=1) digits = models.IntegerField("trailing zeroes", null=True, blank=True, default=5) class ProbeInst(models.Model): probe = models.ForeignKey(Probe, on_delete=models.CASCADE, null=True, verbose_name="probe") value = models.DecimalField("Value of probe", max_digits=10, decimal_places=5, null=True, blank=True) I am trying to display the entry form with ModelForm and CrispyForms, which will display the necessary number of trailing zeroes according to digits field.. However when i see the actual form - i get something like this.. Basically when i enter "2" - i get "2.00000", but when i enter "81.4" - i get "81,4" for some reason... I have tried overriding the modelform like this class ProbeEntryForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'instance' in kwargs: step = 1 / 10 ** kwargs['instance'].probe.digits super(ProbeEntryForm, self).__init__(*args, **kwargs) self.fields['value'].decimal_places = kwargs['instance'].probe.digits self.fields['value'].widget = forms.NumberInput( attrs={'min': 0, 'placeholder': "Значение", 'step': step, }) self.fields['textvalue'].widget = forms.HiddenInput() But after saving the form - i still have this float styled values displayed like "81,4" I want to show all values with fixed number of tralining zeroes - like "81.40000" and "2.00000 Can someone please elaborate? -
How to get transaction information from etherscan site from a specific address using Django rest framework?
I want to know that how can I connect models views and templates to show the transaction information like "from","to","timestamp","hashaddress" Just want the implementation idea. -
401 error drf django when enable withCredentials in axios
I use NextJs and Axios to request after login, I save the cookie in NextJs : export default function handler( req: CustomeNextApiRequest, res: NextApiResponse<Data> ) { res.setHeader( "Set-Cookie", cookie.serialize("Token", req.body?.access_token, { httpOnly: true, maxAge: 60 * 60 * 24, sameSite: "lax", path: "/" // domain : '.' // secure : }) ) res.status(200).json({ status: 'success' }) } When I enable "withCredentials" in Axios: export const callApi = (url?: string) => { const instanse = axios.create({ baseURL: url || "/api/v1/", timeout: 20000, withCredentials:true }); return instanse; } After, When I request something API on another page, I receive 401 from drf Django. My Config Django: SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'JWT_AUTH_HEADER_PREFIX': 'Token', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=60), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAdminUser', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', ], 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 2, 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } CORS_ALLOW_ALL_ORIGINS = …