Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
xlsxwriter to http response (download file) but with user data (forms) in django
I'm stuck, I want to user on page create template to input data on based witch will be created a template. Here is what I got so far, but it wont work, I have tried with examples online, but those are usually don't take a data from users to create template. This is views.py from django.http import HttpResponse from django.shortcuts import render import xlsxwriter from xlsxwriter import workbook from django.forms import Form, CharField, ChoiceField, IntegerField from django.core.validators import MaxValueValidator, MinValueValidator def home(request): return render(request, 'my_app/home.html') def create_template(request): return render(request, 'my_app/create_template.html') class TemplateForm(Form): doc_name = CharField(label='Document name') sheetnames = CharField(label='Sheetnames') choices = [] for year in range (1900, 2050): choices.append( (year, year) ) year1 = ChoiceField(label='Starting Year', initial=2021, choices=choices) year2 = ChoiceField(label='Ending Year', initial=2022, choices=choices) row_names = CharField(label='Column names') def create_template(request): if request.method == 'GET': form = TemplateForm() return render(request, 'my_app/create_template.html', {'form':form}) else: form = TemplateForm(request.POST) def create_form(doc_name, sheetnames, years, row_names): workbook = xlsxwriter.Workbook(doc_name + '_template.xlsx') worksheet_introduction = workbook.add_worksheet( "introduction" ) for i in sheetnames: worksheet_data = workbook.add_worksheet(i) worksheet_data.write_row(0, 1, years) worksheet_data.write_column(1, 0, row_names) workbook.close() return workbook This is my_app/templates/my_app/create_template.html {% extends "my_app/base.html" %} {% block content %} <form action="create_template" method="GET"> {% csrf_token %} <h1>Create your template</h1> <div class="item"> <table> {{ … -
Error 400 on appengine ping, by python requests
Hello beautiful people! I have a Django server deployed to google AppEngine. I am trying to send a json request with python to a views.py function that looks like this: def my_test_json_data(request): json_data = (json.loads(request.body.decode('utf-8'))) #print(json_data) if json_data['apikey'] != 'YOUR_API_KEY_HERE': return HttpResponseNotFound('not today') data = {'test':'ok'} return JsonResponse(data) and the python code looks like this: import requests data = {'test1':'1'} url = 'https://fliby.eu/my_test_json_data/' headers = {'Content-Type':'application/json',} payload = {'json_payload': data, 'apikey': 'YOUR_API_KEY_HERE'} session = requests.Session() r = session.get(url,headers=headers, json=payload) print(r.status_code) When the server is hosted locally there is no problem and everything works correctly! (code 200) When I try to requst trough appengine it returns code 400 Can I get some hints please, Thank you! -
An error NoReverseMatch appears when I try to edit a post using UpdateView in Django
When I click on the update post link, an error appears: Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['post/(?P[-a-zA-Z0-9_]+)$']. My Post model looks like this: class Post(models.Model): title = models.CharField(max_length=200, verbose_name='Заголовок') slug = AutoSlugField(populate_from=['title']) title_image = models.ImageField(upload_to=user_img_directory_path, blank=True, verbose_name='Изображение') description = models.TextField(max_length=500, verbose_name='Описание') body = FroalaField(options={ 'attribution': False, }, verbose_name='Текст') post_date = models.DateTimeField(auto_now_add=True, verbose_name='Дата публикации', db_index=True) post_update_date = models.DateTimeField(auto_now_add=True, verbose_name='Дата обновления публикации') post_status = models.BooleanField(default=True, verbose_name='Опубликовано') class Meta: ordering = ['-post_date'] def get_absolute_url(self): return reverse('articles:post_detail', kwargs={'slug': self.slug}) def __str__(self): return self.title My DetailView and UpdateView classes in views.py: from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView class PostDetail(DetailView): model = Post template_name = 'articles/post_detail.html' context_object_name = 'post' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class UpdatePost(UpdateView): model = Post template_name = 'articles/update_post.html' fields = ['title', 'title_image', 'description', 'body'] My urls.py file: from .views import PostsList, PostDetail, CreatePost, UpdatePost app_name = 'articles' urlpatterns = [ path('', PostsList.as_view(), name='posts_list'), path('post/<slug:slug>', PostDetail.as_view(), name='post_detail'), path('create/', CreatePost.as_view(), name='create_post'), path('post/edit/<slug:slug>', UpdatePost.as_view(), name='update_post'), ] update_post.html template looks like this: {% extends 'layout/basic.html' %} {% load static %} {% load django_bootstrap5 %} {% block content %} <form method="post" class="form"> {% csrf_token %} {{ form.media }} {% bootstrap_form form %} {% bootstrap_button button_type="submit" … -
How do I implement Google Sign-In, keep getting Forbidden CSRF Error
I'm building a simple Login page using Python and Django. I want to give the users the choice to login using either the Django account or Google Sign-In. I've build some simple HTML and functions to flow between 4 pages: Main, login_success,logout_success and already_logged_in As far as I've understand, I've set up at the very least a button on my login page, with some relevant scripts. So, then I deploy to my Google Cloud, access the site, see the button and click on it and it redirects me to a Google Sign-In page where I can choose my account. I click on the account and I get a Forbidden: CSRF Error. Am I missing something? I am not sure how to debug this. This is my Main login HTML.(I'm not sure if the rest are needed to be shown?) {% load i18n %} {% block content %} <!DOCTYPE html> <html> <meta charset="UTF-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" media="all" /> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script> <head> <title>Google Signin Testing</title> <style> .left { float: left; width: 40%; padding-left:32%; padding-top:13%; height: 75% } .right { float: left; width: 40%; padding-top:5%; height: 100% … -
Can I detect ManyToManyField mutations before they are applied?
I have a Django app that broadcasts changes of some of its models to its clients, to keep them up-to-date. I have a separate app for that, that binds to the post_save signal of these models and triggers the broadcast. Problems have come with models with ManyToManyFields. I am not very familiar with Django's handling of this but I understand that these fields are actually updated after the model is saved. I was able to use the m2m_changed signal to react to the post_* actions and dispatch the broadcast after the object is all up-to-date. However, in the post_save handler, I still need to detect that the m2m field is going to be mutated, to avoid broadcasting incomplete data. How can I detect this , either in the post_save signal handler or the model's save method ? Is there a way to raise a flag on an object when a m2m field is about to be mutated ? Here's what I've tried : Handle the pre_* actions of the m2m_changed signal to detect incoming mutation of the field but that does not work, because the signal gets fired after post_save, which is too late (data has already been broadcasted). Store … -
Issue with mock return value in py test?
I have the following post function in my view and I want to mock the return values of customer.get_customer_data and customer.update_customer_data in my test function. However, it seems like only one of the mock return values is getting allocated. def post(self, request, *args, **kwargs): try: data = request.data status_code, response = customer.get_customer_data( data["customer_id"], "id," ) if status_code == 401: auth.generate_new_access_token("buyer") status_code, response = customer.get_customer_data( data["customer_id"], "id," ) if status_code == 401 or status_code == 200: id = response[0]["message"][0]["id"] status_code, response = customer.update_customer_data(id, data) tests.py @patch("app.views.customer.get_customer_data") @patch("app.views.customer.update_customer_data") def test_customer_view(self, mock_customer_data, mock_update_customer_data): customer_update_data = { .... } mock_customer_data.return_value = 200, [{"message": [{"id": 1234}]}] mock_update_customer_data.return_value = 200, 'Success' req = RequestFactory().post("/app/customer/create/", customer_update_data, content_type='application/json') resp = views.EditCustomerView.as_view()(req) resp.render() assert json.loads(resp.content) == "Success" assert mock_customer_data.called assert resp.status_code == 200 I am getting the following error when I run the test id = response[0]["message"][0]["id"] TypeError: string indices must be integers Seems like this one is getting called for the wrong function. It's getting patched with the get_customer_data function instead of update_customer_data What could I be doing wrong? -
Why does Django/console give me an error of missing value for stripe.confirmCardPayment intent secret, saying it should be a client secret string?
I'm trying to learn this tutorial, the custom payment flow last bit to integrate stripe with Django https://justdjango.com/blog/django-stripe-payments-tutorial in my views.py, I have these views class StripeIntentView(View): def post(self, request, *args, **kwargs): try: req_json = json.loads(request.body) customer = stripe.Customer.create(email=req_json['email']) price = Price.objects.get(id=self.kwargs["pk"]) intent = stripe.PaymentIntent.create( amount=price.price, currency='usd', customer=customer['id'], metadata={ "price_id": price.id } ) return JsonResponse({ 'clientSecret': intent['client_secret'] }) except Exception as e: return JsonResponse({'error': str(e)}) class CustomPaymentView(TemplateView): template_name = "custom_payment.html" def get_context_data(self, **kwargs): product = Product.objects.get(name="Test Product") prices = Price.objects.filter(product=product) context = super(CustomPaymentView, self).get_context_data(**kwargs) context.update({ "product": product, "prices": prices, "STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLIC_KEY }) return context and in my urls I have from django.contrib import admin from django.urls import path from products.views import stripe_webhook from products.views import StripeIntentView, CustomPaymentView urlpatterns = [ path('admin/', admin.site.urls), path('create-payment-intent/<pk>/', StripeIntentView.as_view(), name='create-payment-intent'), path('custom-payment/', CustomPaymentView.as_view(), name='custom-payment') and in my custom_payment.html I have {% load static %} <!DOCTYPE html> <html> <head> <title>Custom payment</title> <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script> <script src="https://js.stripe.com/v3/"></script> <link rel="stylesheet" href="{% static 'products/global.css' %}"> </head> <body> <section> <div class="product"> <div class="description"> <h3>{{ product.name }}</h3> <hr /> <select id='prices'> {% for price in prices %} <option value="{{ price.id }}">${{ price.get_display_price }}</option> {% endfor %} </select> </div> <form id="payment-form">{% csrf_token %} <input type="text" id="email" placeholder="Email address" /> <div id="card-element"> <!--Stripe.js injects the … -
Django data from RichTextField renders with html tags
I have a website which in its one page it renders data from a specific object which has 1 integer, 1 string and 2 rich text values (ckeditor, RichTextField). The class is represented belov; class Chapter(models.Model): chapter_id = models.IntegerField(primary_key=True, default=None) chapter_title = models.CharField(max_length=100, default=None) chapter_text = RichTextField(default=None) chapter_footnotes = RichTextField(default=None, blank=True) When I try to render the data from RichTextFields it renders with the html elements as a text. Example: <p><span style="color:#757575"><span style="background-color:#ffffff">Why a sword?&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">There are so many different weapons in the world, so why did I choose the sword?&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">That&#39;s because swords represent perfection.&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">A sword has two edges.&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">One edge to hurt the enemy, one edge to protect me.&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">It protects me by killing my enemies.&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">That is the purpose of a sword.&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">And that is exactly how I use my chosen weapon, my sword.&nbsp;</span></span></p> How can I make it so that It renders itself without showing but applying its html element tags. Note: The code that renders the data: {% block chapters %} <div class="chapter_text"> <h1>{{ chapter_info.chapter_id }}: {{ chapter_info.chapter_title }}</h1><br> {{ chapter_info.chapter_text }} <hr> {{ chapter_info.chapter_footnotes }} </div> {% endblock chapters … -
Why I need to clear local storage manually from console. Every time my site load
I made a shopping cart and make update cart function in JavaScript that working fine but when I navigate to other page my cart no automatically turn to (1 ) and an error rise in console like this: Uncaught TypeError: Cannot set property 'innerHTML' of null at updateCart ((index):447) at (index):411 My java script code is: <script> // Find out the cart items from localStorage if (localStorage.getItem('cart') == null) { var cart = {}; } else { cart = JSON.parse(localStorage.getItem('cart')); document.getElementById('cart').innerHTML = Object.keys(cart).length; updateCart(cart); } // If the add to cart button is clicked, add/increment the item $('.cart').click(function() { var idstr = this.id.toString(); if (cart[idstr] != undefined) { cart[idstr] = cart[idstr] + 1; } else { cart[idstr] = 1; } updateCart(cart); }); //Add Popover to cart $('#popcart').popover(); updatePopover(cart); function updatePopover(cart) { console.log('We are inside updatePopover'); var popStr = ""; popStr = popStr + " <h5>Cart for your items in my shopping cart</h5><div class='mx-2 my-2'>"; var i = 1; for (var item in cart){ popStr = popStr + "<b>" + i + "</b>. "; popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0,19) + "... Qty: " + cart[item] + '<br>'; i = i+1; } popStr = popStr + "</div>" console.log(popStr); document.getElementById('popcart').setAttribute('data-content', popStr); … -
Why does Django/Postgres appear to save but doesn't, gives 'connection already closed'?
I'm using Django + Postgres on Windows 10 WSL Ubuntu 18.04.5 LTS. Saving data to postgres seems to work, yet when I access the table using psql on the command line, the data isn't there. Refreshing the webpage (reloading Django) also shows the old data previous to the save. There are no errors in the postgresql log. I don't have caching explicitly turned on in Django's settings.py. It all worked perfectly for years, but to be sure I upgraded Django to 3.2.6, Python to 3.8.11, postgresql to 12, and psycopg2 to 2.9.1, plus the necessary dependencies. Same result. Here's the code in Django: try: nodeToUpdate.save() # Hit the database. node = Node.objects.get(pk=itemID, ofmap=mapId) # Retrieve again to confirm it was saved # This shows the correct data: print("STORE TO MAP:" + str(node.ofmap_id) + " NODE:" + str(node.id) + " label:" + str(node.label)) except psycopg2.InterfaceError as err: print(str(err)) raise Exception(err) except ValidationError as err: raise Exception(err) The clue to what's going on comes when I run unit tests: Traceback (most recent call last): File "/var/www/mysite/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 237, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/var/www/mysite/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/mysite/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 236, in create_cursor cursor = self.connection.cursor() **psycopg2.InterfaceError: connection … -
how to make a data fetch form in django?
I want the user to have a form for fetching data from the database, for example, as in /admin: Form in admin So that the user can select multiple entries and, for example, delete them, how can I do this? -
Why doesn't this django url run on Mac?
I'd like to apply pose estimation Python code in url below to the Django view. But it works well on Windows, but not on Mac. 127.0.0:8000/pose_feed doesn't work without any error messages. I installed requirement.txt in venv, and Python version is 3.7 for both venv. https://www.analyticsvidhya.com/blog/2021/05/pose-estimation-using-opencv/ urls.py urlpatterns = [ path('pose_feed', views.pose_feed, name='pose_feed'), ] views.py def index(request): return render(request, 'streamapp/home.html') def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def pose_feed(request): return StreamingHttpResponse(gen(PoseWebCam()), content_type='multipart/x-mixed-replace; boundary=frame') cameras.py class PoseWebCam(object): def __init__(self): # self.vs = VideoStream(src=0).start() self.cap = cv2.VideoCapture(0) # self.mpPose = mp.solutions.pose self.mpPose = mp.solutions.mediapipe.python.solutions.pose self.pose = self.mpPose.Pose() self.mpDraw = mp.solutions.mediapipe.python.solutions.drawing_utils self.pTime = 0 def __del__(self): cv2.destroyAllWindows() def get_frame(self): success, img = self.cap.read() imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) results = self.pose.process(imgRGB) if results.pose_landmarks: self.mpDraw.draw_landmarks(img, results.pose_landmarks, self.mpPose.POSE_CONNECTIONS) for id, lm in enumerate(results.pose_landmarks.landmark): h, w,c = img.shape cx, cy = int(lm.x*w), int(lm.y*h) cv2.circle(img, (cx, cy), 5, (255,0,0), cv2.FILLED) cTime = time.time() fps = 1/(cTime-self.pTime) self.pTime = cTime cv2.putText(img, str(int(fps)), (50,50), cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0), 3) # cv2.imshow("Image", img) # cv2.waitKey(1) frame_flip = cv2.flip(img,1) ret, jpeg = cv2.imencode('.jpg', frame_flip) return jpeg.tobytes() home.html <html> <head> <title>Video Live Stream</title> </head> <body> <h1>Video Live Stream</h1> <!-- <img src="{% url 'video_feed' %}"> --> <!-- <img src="{% … -
1 time of 10 get error json.decoder.JSONDecodeError: Expecting ','
i have this ugly noob func: def run_prog(compile_container, user_input, container_file_path): # bash doesnt support single quotes or quotes inside double quotes so @# = ' time_check_command = '/usr/bin/time -f "@# , @#memory@#:@#%M@# , @#time@#:@#%e@#"' result = compile_container.exec_run( f"/bin/bash -c 'echo {user_input} | {time_check_command} ./a.out'", workdir=container_file_path)[1].decode('utf-8') result = '{"result":"' + result + ',}' result = result.replace('@#', '"') result_dict = json.loads(result) if result_dict['time'] == '0.00': result_dict['time'] = '<0.01' return result_dict Most of time it retrun json like this: { "result": "888", "memory": "1792", "time": "<0.01" } But one time of 10 or mb 20 it raise an error and i dont know why. Same input always. Can u please tell what is wrong? -
Django run function periodically in background
I have a function that fetches data and needs to be run periodically. All I care about is running it every 30 seconds. I searched and found the following options - celery django-apscheduler Apscheduler I have tried Apscheduler using BackgroundScheduler and it has this problem that it'll run a new scheduler for each process. I am completely new to scheduling functions and have no idea which one I should use or if there is a better way. -
How to serialize a related object Django Rest Framework
class Flight(models.Model): field_1 field_2 field_3 class Approach(models.Model): flight_object(models.ForeignKey, 'Flight') approach_type number Approach is related as an InlineFormset. How can I serialize Approach nested into Flight with the ability to create new approach objects. I'm unsure of the correct terminology which is making this more difficult to realize. My goal is to create a new Flight object with Approach as a related object in the FlightForm from a React Native project. -
I want to get data from the user without them using a form
I'm currently working on a website which posts a web novel. I need a system to make user send the chapter id and get the chapter which uses that id maybe like: <a href="chapters/1">Chapter1</a> <a href="chapters/2">Chapter2</a> <a href="chapters/3">Chapter3</a> I don't want to create a specific html page for every novel chapter that we posts and use a system to maybe get the links "/chapter/id" part or send the id when clicked to an element and pull data from the database using the id given. I searched up in the net and couldn't find anything useful. Note: The database is like this; class Chapter(models.Model): chapter_id = models.IntegerField(primary_key=True, default=None) chapter_title = models.CharField(max_length=100, default=None) chapter_text = RichTextField(default=None) chapter_footnotes = RichTextField(default=None, blank=True) -
How to convert image from django template?
I have some HTML code. I have added some dynamic data from DB to the HTML code in Django/FastAPI. How can I generate an image of that template? Also, how can do the same in FastAPI> -
With Django REST framework, how do I parse a RESTful string parameter?
I'm using Python 3.9 with Django==3.1.4 djangorestframework==3.12.2 I want to pass a restful param ("author" string) to my GET method. In my urls.py file I have urlpatterns = [ ... path('user/<str:author>', views.UserView.as_view()), And then in my UserView class (defined in my views.py file), I have class UserView(APIView): def get(self, request): ... author = self.kwargs.get('author', None) but when i execute GET http://localhost:8000/user/myauthor I get the error TypeError: get() got an unexpected keyword argument 'author' What else do I need to do to properly access my RESTful param in the URL? -
django: how to display ManyToManyField in html file?
I want to display ManyToManyField in Django in html page. This code is in the models.py file: class Keyword(models.Model): keyword = models.CharField(max_length=20, null=True) rank = models.IntegerField(null=False) dateCreated = models.DateField(auto_now_add=True) def __str__(self): return '#' + self.keyword class Article(models.Model): CATEGORY = ( ('programming', 'programming'), ('language', 'language'), ('other', 'other') ) title = models.CharField(max_length=200, null=False) image = models.ImageField(null=True) content = models.TextField(null=False) category = models.CharField(max_length=45, null=False, choices=CATEGORY) dateCreated = models.DateField(auto_now_add=True) keyword = models.ManyToManyField(Keyword) def __str__(self): return self.title and in the views.py: def articles(request): article = Article.objects.all() keyword = Keyword.objects.all() context = { 'keyword': keyword, 'article': article } return render(request, 'articles.html', context) and in the html file: {% for item in article %} <tr> <th scope="row">{{item.id}}</th> <td>{{item.title}}</td> <td>{{item.image}}</td> <td>{{item.content}}</td> <td>{{item.category}}</td> {% for key in item.keyword.all %} <td>{{key}}</td> {% endfor %} </tr> {% endfor %} But nothing is shown in the keyword section in the html output. what do I do? -
Cannot assign "'Test'": "BlogPostComment.blog_post" must be a "BlogPost" instance
I am trying to create an REST API for posting comments. I am not using normal ```request.POST`` views as I don't want a new page redirect to submit a comment. My plan is to AJAX to comment. But I am getting this error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/blog/test/create_comment Django Version: 3.2.6 Python Version: 3.9.6 Installed Applications: ['blog', 'whitenoise.runserver_nostatic', 'rest_framework', 'django_summernote', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\My_Stuff\Blogistan\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\My_Stuff\Blogistan\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\My_Stuff\Blogistan\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\My_Stuff\Blogistan\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\My_Stuff\Blogistan\env\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "C:\My_Stuff\Blogistan\blog\views.py", line 44, in CreateComment serializer.create(request.data) File "C:\My_Stuff\Blogistan\env\lib\site-packages\rest_framework\serializers.py", line 939, in create instance = ModelClass._default_manager.create(**validated_data) File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\db\models\query.py", line 451, in create obj = … -
how to use js variable in Django template tag through a JS call to update html content?
I am trying to update the html content of a with id "samples-list" with a Django template tag that includes an html file with two parameters ({% include "measures/sample_list_rows.html" with object_list=classifier.samples search_filter=search %}). the first parameter object_list is populated by the Django object classifier.samples, the second parameter search is retrieved by the id of the clickable object that will generate the update (id="search=device:{{ device.serial_number }}, labsubstance:{{ classifier.substance.slug }}") $("[id^=search]").click(function () { var keys = $(this).attr('id').split('=') var search = keys[keys.length-1] $('#samples-list').html(`{% include "measures/sample_list_rows.html" with object_list=classifier.samples search_filter=search %}`) how can I use the javascript variable search in the search_filter parameter of the Django template tag? -
the first model is the price of the product and the second model is the input of the first model, multiplied by 4
I wanted to make 2 models for the price of my products, the first model is the price of the product and the second model is the input of the first model, multiplied by 4, how can I do the same, thank you -
Django admin object change action
I am developing a courier management service using Django. So far, I have made three models, Customer DelveryAgent Parcels Here is the Parcel model: class Parcel(models.Model): type = models.CharField(max_length=20) city = models.CharField(max_length=20) street = models.CharField(max_length=100) zip = models.CharField(max_length=100) email = models.CharField(max_length=100) phone = models.CharField(max_length=100) status = models.CharField(max_length=100, choices=STATUS, default='pending') booked_by = models.ForeignKey(Customer, on_delete=models.CASCADE) delivery_agent = models.ForeignKey(DeliveryAgent) Initially, the parcel status is pending, and the delivery agent is None. When the admin assigns a delivery agent to the parcel from the admin site, I want the relative customer to get notified with the details of the delivery agent. How can I do that? -
Macbook Air M1 mysql issues
(base) touresouleymane@192 Prions Projects % python3 prions/manage.py runserver Exception in thread django-main-thread: Traceback (most recent call last): File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/init.py”, line 18, in from . import _mysql ImportError: dlopen(/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so Expected in: flat namespace in /Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so During handling of the above exception, another exception occurred: Traceback (most recent call last): File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/threading.py”, line 932, in _bootstrap_inner self.run() File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/threading.py”, line 870, in run self._target(*self._args, **self._kwargs) File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/utils/autoreload.py”, line 53, in wrapper fn(*args, **kwargs) File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/core/management/commands/runserver.py”, line 110, in inner_run autoreload.raise_last_exception() File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/utils/autoreload.py”, line 76, in raise_last_exception raise _exception[1] File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/core/management/init.py”, line 357, in execute autoreload.check_errors(django.setup)() File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/utils/autoreload.py”, line 53, in wrapper fn(*args, **kwargs) File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/init.py”, line 24, in setup apps.populate(settings.INSTALLED_APPS) File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/apps/registry.py”, line 114, in populate app_config.import_models() File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/apps/config.py”, line 211, in import_models self.models_module = import_module(models_module_name) File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/importlib/init.py”, line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File “”, line 1014, in _gcd_import File “”, line 991, in _find_and_load File “”, line 975, in _find_and_load_unlocked File “”, line 671, in _load_unlocked File “”, line 783, in exec_module File “”, line 219, in _call_with_frames_removed File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/contrib/auth/models.py”, line 2, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/contrib/auth/base_user.py”, line 48, in class AbstractBaseUser(models.Model): File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/db/models/base.py”, line 122, in … -
Unable to delete object from Django admin panel with MongoDB
I have a Django project using a MongoDB connected by Djongo. I created a simple model which looks like: from django.db import models # Create your models here. class Property(models.Model): name = models.CharField(max_length=128, blank=False) property_type = models.CharField(max_length=24, blank=True) include_on = models.CharField(max_length=256, blank=True) format_example = models.TextField(blank=True) notes = models.TextField(blank=True) After registering the model by using the line admin.site.register(Property) in the admin.py file I end up seeing my model appear. After adding a test Property I see the line The property “Property object (61226db9f4f416b206c706e5)” was added successfully. Which tells me the item was added. It also appears on the admin panel but it looks like: Property object (None) If I select the property I get an error that says: Property with ID “None” doesn’t exist. Perhaps it was deleted? If I try to delete the property I get a ValueError with error of: Field 'id' expected a number but got 'None'. Since I am currently learning Django/MongoDB I actually ran across the ValueError once before. The fix was to delete the entire database and start over. The issue is I don't want to run into this in the future and want to know what I have to do to fix it, or …