Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Use a read-only database within django test suite
In my Django project, I'm using two databases, one of which is my own PostgreSQL database where I have the read and write rights, and the other one is an external PostgreSQL database in which I only have read-only rights. It works perfectly in the context of the project, I can access both databases. However when I use the Django test suite using ./manage.py test, Django is trying to create a test database for the external database. I don't want that, I want to be still able to access the external PostgreSQL database within the test suite without needing to create a test database on this external PostgreSQL database. It also gives me this error: /usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py:323: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. But I don't have access to the 'postgres' database in the external database and I don't want to run initialization queries against it. Here is the configuration for the external read-only database connection: DATABASES["aact"] = { … -
Accepting JSON format, parsing him and having endpoints to accessing the data (Django)
Hello I want to ask how can I create models and API in Django that accepts JSON format, parsing it and then access it in some of the endpoints. I need to have [POST] endpoint /import which will accept the data and parse them, [GET] /detail/<name_of_the_model> will show list of records from the JSON file based on the name of the model and finally /detail/<name_of_the_model>/<id> which shows all the data for the exact record from the JSON file. I think I can manage things with the models/modelForms but I can't figure out how to implement it with JSON. Thanks for any help. -
Django. How to update form field on other field change without Javascript?
Is it possible to update form field when user changes value of the other field without using Javascript? class PurchaseOrderItemForm(forms.ModelForm): class Meta: model = PurchaseOrderItem fields = [ 'product', 'price_per_unit', 'quantity', ] class PurchaseOrderItemCreateView(LoginRequiredMixin, CreateView): model = PurchaseOrderItem template_name = 'purchases/purchase_order_item_create.html' form_class = PurchaseOrderItemForm For example I want the price of the product to be set automatically when user selects a product from the list. Or is JS mandatory in this case? -
Redirect urls in django
We have a blog created with Django 4. And have articles where for each article exists a url like this www.example.com/id/slug but for some of them we changed the id and we want to redirect the old urls to the new one. For example we want to turn www.example.com/2/slug1 to www.example.com/56/slug1 How can we do this in Django 4? -
Gunicorn (Django + NGINX) keeps date till Gunicorn restart
I'm moving Django apps from Apache2 to Nginx/Gunicorn and have one problem. I used simple tutorial from Digital Ocean to setup Nginx/Gunicorn environment apps and all is steady, working fine. But i found out i have some strange problem with date. It looks like all my apps run the same day, the day app was started/restarted. Queries to DB for yesterday items return 0 rows. When i reset gunicorn or run the app via ./manage.py runserver all works as expected. Same code using old server (running Apache2) works fine too. So there is no problem with the code, but config issue. Somehing like Gunicorn freezes in time(date) and needs to be regularly restarted? Or I'm missing something in my settings? My socket file: [Unit] Description=VKCRM [Socket] ListenStream=/run/vkcrm.sock [Install] WantedBy=sockets.target my service file: [Unit] Description=VKCRM daemon Requires=vkcrm.socket After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/var/www/virtuals/crm/vkcrm ExecStart=/var/www/virtuals/crm/bin/gunicorn --access-logfile - --workers 1 --timeout 100 --bind unix:/run/vkcrm.sock vkcrm.wsgi:application [Install] WantedBy=multi-user.target Thanks for any help, it must be some basic settings stuff. Maybe restart Gunicorn each day, restart workers after jobs done or something like this? But can't find out what i'm missing. -
I get this error when I want to do makemigrations : 'PosixPath' object has no attribute 'startswith'
python manage.py makemigrations: Traceback (most recent call last): val = self._add_script_prefix(val) Development-/venv/lib/python3.9/site-packages/django/conf/init.py", line 135, in _add_script_prefix if value.startswith(('http://', 'https://', '/')): AttributeError: 'PosixPath' object has no attribute 'startswith' -
Session id and csrf token not set in cookie
I am using django as backend and react as frontend,in local the session auth working fine,but when I deploy in secure mode(https) csrf and sesion id is not set in the cookie,but I recieve the response header for set-cookie. This is my setings.py file CSRF_TRUSTED_ORIGINS = [ "https://'prod link'", 'http://localhost:3000', 'http://127.0.0.1:3000', ] # PROD ONLY CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True ACCESS_CONTROL_ALLOW_ORIGIN = [ "https://'prod link'", 'http://localhost:3000', 'http://127.0.0.1:3000', ] CORS_ALLOWED_ORIGINS = [ "https://'prod link'", 'http://localhost:3000', 'http://127.0.0.1:3000', ] CORS_EXPOSE_HEADERS = ['Content-Type', 'X-CSRFToken'] CORS_ALLOW_CREDENTIALS = True Set-Cookie in network tab -
How to pass arbitrary Python object (e.g. InMemoryUploadFile) to a different Django view
This question will likely betray my inexperience in web development, so please let me know if I'm solving entirely the wrong problem. I'm building a web application where users are asked to upload a data file. After uploading, the users are shown some aggregate statistics of the data contained in the file to help catch any errors. The user can then confirm this is the right data. Only then will the file will be stored somewhere on other people's computers in the cloud. I Django, I have defined three views/templates: Upload: the template contains the form that allows the user to select a file to upload. Check: the template shows the aggregate statistics and contains a form with buttons to go back or confirm that the uploaded file is correct. Confirm: the page shows that the file was stored. The problem is that the file is uploaded in the Upload view/template; but I only want to determine the aggregate statistics on the Check page and store the file after the user has confirmed its aggregate statistics in the Check view/template. I'm not sure how I can pass the file (which will be an InMemoryUploadFile object) from the Upload view to … -
datatable with chartjs problem while changing row numbers
I'm trying to integrate datatable with chartjs, it works fine if i dont change the row numbers, or not do any filtration, from UI, when i change the row numbers for example, by default its 10, when i change it to 25, the charts also change, but when i move the mouse cursor to the chartjs canvas sometimes it shows the previous data(the 10 row data). how to fix it, or update the chartjs canvas data to the new Here is my code: $(document).ready(function(){ var list_daily_prices = document.getElementById('list_daily_prices') if(list_daily_prices){ $('#list_daily_prices').DataTable({ "serverSide":true, "processing":true, "ordering": false, "ajax":function(data,callback,settings){ $.get('/prices/daily/data',{ start:data.start, limit:data.length, filter:data.search.value, },function(res){ callback({ recordsTotal:res.length, recordsFiltered:res.length, data:res.objects }); }, ); }, "columns":[ {"data": "counter"}, {"data": function(data,type,dataToSet){ const date = new Date(data.day).toLocaleDateString('fr-CA') return date }}, {"data": "total_quantity"}, {"data": "total_price"}, {"data": "income"}, ], "drawCallback":function(settings){ var daily_date = [] var qnt = [] var total_price = [] var income = [] for(counter=0;counter<settings.aoData.length;counter++){ daily_date.push(new Date(settings.aoData[counter]._aData['day']).toLocaleDateString('fr-CA')) qnt.push(settings.aoData[counter]._aData['total_quantity']) total_price.push(parseFloat(settings.aoData[counter]._aData['total_price']).toFixed(2)) income.push(parseFloat(settings.aoData[counter]._aData['income']).toFixed(2)) } var dailyPriceCanvas = $('#list_daily_prices_charts').get(0).getContext('2d') var dailyPriceData = { labels: daily_date, datasets: [ { label:'quantity', data: qnt, backgroundColor : '#9D0CA6', }, { label:'total price', data: total_price, backgroundColor : '#1392BE', }, { label:'income', data: income, backgroundColor : '#00a65a', }, ] } var dailyPriceOptions = { responsive : true, maintainAspectRatio : … -
How to store user auto in database?
I created a form for adding products to an e-Commerce site. The form isn't working perfectly. First issue: I want to store the user automatically by submitting the form. I actually want to store Who did add the product individually. Second Issues: The image field is not working, the image is not stored in the database. How can I fix these issues? help me forms.py: from django import forms from .models import Products from django.forms import ModelForm class add_product_info(forms.ModelForm): class Meta: model = Products fields = ('product_title','product_image') model.py: class Products(models.Model): user = models.ForeignKey(User, related_name="merchandise_product_related_name", on_delete=models.CASCADE, blank=True, null=True) product_title = models.CharField(blank=True, null=True, max_length = 250) product_image = models.ImageField(blank=True, null=True, upload_to = "1_products_img") views.py: def add_product(request): if request.method == "POST": form = add_product_info(request.POST) if form.is_valid(): form.save() messages.success(request,"Successfully product added.") return redirect("add_product") form = add_product_info context = { "form":form } return render(request, "add_product.html", context) templates: <form action="" method="POST" class="needs-validation" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div class="d-flex align-items-center"> <button type="submit" class="btn btn-outline-dark ms-auto" style="font-size:13px;">Add</button> </div> </form> -
Why DecimalField are serialized sometimes as number sometime as string numer
I have a django app with rest framework and I noticed that some DecimalField are serialized as string, others as numbers. Why? Here's my model: class TestModel(models.Model): quantity1 = models.DecimalField("quantity1", default=0.0, max_digits=10, decimal_places=3) quantity2 = models.DecimalField("quantity2", default=0.0, max_digits=10, decimal_places=3) quantity3 = models.DecimalField("quantity3", default=0.0, max_digits=10, decimal_places=3) latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) Here's the serialization "quantity1": "1.000", "quantity2": "1.000", "quantity3": "1.000", "latitude": 45.49907, "longitude": 9.18749, I am aware of the problem of serialize floating point and their precision (see here), but why quantities are represented as string while lat/lon are numbers? They are both decimalFields... -
how to start overriding file after it reaches certain size?
Is there a way to start overriding a file when it reaches, for example, 50 MB size? Currently I started with: with open("mylogfile.log", "a") as myfile: myfile.write(something) I want to keep adding text at the end of my file as long as it is under 50 MB size. Then, I want to start overriding, I mean saving the new lines of text but delete the text from the beginning of the file. How do I do that? -
OSError at / [Errno 22] Invalid argument: 'C:\\Users\\HP\\OneDrive\\Desktop\\datascience\\EED\\Emotion\\emotion\templates\\index.html'
Exception Type: OSError at / Exception Value: [Errno 22] Invalid argument: 'C:\Users\HP\OneDrive\Desktop\datascience\EED\Emotion\emotion\templates\index.html' {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Emotion Detection Website</title> <link rel="stylesheet" href="../static\css\style.index.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font- awesome/5.15.3/css/all.min.css"/> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.11/typed.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" /> </head> <body> <div class="scroll-up-btn"> <i class="fas fa-angle-up"></i> </div> <nav class="navbar"> <div class="max-width"> <div class="logo"><a href="home">Xim<span>ple.</span></a></div> <ul class="menu"> <li><a href="home" class="menu-btn">Home</a></li> <li><a href="#about" class="menu-btn">About</a></li> <li><a href="#services" class="menu-btn">Services</a></li> <li><a href="#skills" class="menu-btn">Skills</a></li> <li><a href="#teams" class="menu-btn">Teams</a></li> <li><a href="#contact" class="menu-btn">Contact</a></li> </ul> <div class="menu-btn"> <i class="fas fa-bars"></i> </div> </div> </nav> <!-- home section start --> <section class="home" id="home"> <div class="max-width"> <div class="home-content"> <div class="text-1"><text style="color: rgb(240, 40, 40);font- size:50px;">Ximple. </text> provides mission-critical IT services that <br>transform global businesses. .</div> <div class="text-3">And we are <span class="typing"></span></div> <a href="login">Get Started</a> </div> </div> </section> </body> -
How to implement Token Authentication in Django Rest Framework without using a password?
How to implement Token Authentication in Django without using a password? Can we override is_authenticated() ? Can we use a pin number instead of password? -
django dropdown not coming even after adding for loops
Hi I am new to django and I am doing CRUD using serializers having Products,categories,sub categories,size and color as models I am trying to make a django dropdown IN MODELS SUBCATEGORIES below is the model of subcategoires: class SUBCategories(models.Model): category_name = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=20) sub_categories_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) below is the insert function def insert_sub_categories(request): if request.method == "POST": insertsubcategories = {} insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') form = SUBCategoriesSerializer(data=insertsubcategories) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') print(form.errors) return redirect('sub_categories:show_sub_categories') else: category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict,many=True) hm = {'context': category} print(hm) # print(form.errors) return render(request,'polls/insert_sub_categories.html') else: category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict,many=True) hm = {'context': category} print(hm) return render(request,'polls/insert_sub_categories.html',hm) below is the for loop in html page for dropdown <td>category name</td> <td> <select name="category_name" id=""> {% for c in hm %} <option value="{{c}}">{{c}}</option> {% endfor %} </select> </td> in print statement the hm dictionary is showing : {'context': CategoriesSerializer(<QuerySet [<Categories: Categories object (5)>, <Categories: Categories object (6)>]>, many=True): id = IntegerField(label='ID', read_only=True) category_name = CharField(max_length=10, required=False) category_description = CharField(max_length=10) isactive = BooleanField(required=False)} even though the data of models Category is saved in the database successfully, where am I going wrong? -
How to create a timetable in the shape of a donut chart with django
I want to make a webpage that manages time using Django. Managing the time I'm talking about means checking the start time and end time of an activity and displaying it on a donut chart with a specific color. Currently, only temporary html is created. I want to display a donut chart on a calendar. <div class="footer"> <div class="input_content"> <form> <label>Input activity</label> <input> <button>play / pause</button> <button>stop </button> </form> </div> </div> html above: enter image description here Example image I want to draw in html: enter image description here What I am currently thinking about is: Enter a color and activity in html and press the play button to save data (date, color, activity, start time) to Django's sqlite, and press the end button to save the end time to sqlite. Render the donut chart in html using the saved data (date, color, activity, start time, end time) using views.py. Activities on the same day should be displayed on one chart. I'd like to ask if what I'm thinking of is implementable, or if there is a better way. Thank you in advance. -
How to fork Django project from github without previous superuser info?
I forked a Django project. I created myself as a new superuser and logged in to the admin page. But the models had previous info already which were added by the one whose project I forked? Can we delete all his info that he added in his version? -
Unable to impliment Comments xtd in my blog
Hi mates i am trying to implement comments xtd to my django blog and getting below error anyone here can help in resolving the issue. settings done in the code are given below and also the error i am receiving is also listed below. Error produces when i try to explore the article AttributeError at /postpage/first/ 'str' object has no attribute '_meta' Request Method: GET Request URL: http://127.0.0.1:8000/postpage/first/ Django Version: 3.1.14 Exception Type: AttributeError Exception Value: 'str' object has no attribute '_meta' Exception Location: C:\Users\navee\OneDrive\Desktop\script\VENV\lib\site-packages\django\contrib\contenttypes\models.py, line 27, in _get_opts Python Executable: C:\Users\navee\OneDrive\Desktop\script\VENV\Scripts\python.exe Python Version: 3.8.10 Python Path: ['C:\\Users\\navee\\OneDrive\\Desktop\\script\\admin', 'c:\\program files\\python38\\python38.zip', 'c:\\program files\\python38\\DLLs', 'c:\\program files\\python38\\lib', 'c:\\program files\\python38', 'C:\\Users\\navee\\OneDrive\\Desktop\\script\\VENV', 'C:\\Users\\navee\\OneDrive\\Desktop\\script\\VENV\\lib\\site-packages'] Server time: Tue, 05 Jul 2022 06:28:17 +0000 Error during template rendering In template C:\Users\navee\OneDrive\Desktop\script\admin\firmApp\templates\firmApp\basic.html, error at line 0 'str' object has no attribute '_meta' 1 {% load static %} 2 {% load comments %} 3 <!doctype html> 4 <html lang="en"> 5 <head> 6 <meta charset="utf-8"> 7 <meta name="viewport" content="width=device-width, initial-scale=1"> 8 9 <title >{% block title %} {% endblock %}</title> 10 Settings done in Article.html {% get_comment_count for object as comment_count %} <div class="py-4 text-center"> <a href="{% url 'blog:post-list' %}">Back to the post list</a> &nbsp;&sdot;&nbsp; {{ comment_count }} comment{{ comment_count|pluralize }} … -
AttributeError: 'QuerySet' object has no attribute 'add_message'
Can anyone please tell me how to add messages in Django rooms for chat applications. Ex: For making comments in a blog or having conversation in chat rooms. Here is my error page after adding message. The problem is message are saved in the database and shown when he go to room page where we added the message but on hitting enter page displays an error AttributeError: 'QuerySet' object has no attribute 'add_message'. Rooms page page shows error in this image but message is saved in this image Here are the views.py file and room.html file views.py file, here room is the view for storing all rooms this is room.html linked to room function from views.py file for displaying messages using templates on webpage -
Azure SDK for Python: Copy blobs
For my current Python project I' using the Microsoft Azure SDK for Python. I want to copy a specific blob from one container path to another and tested already some options, described here. Overall they are basically "working", but unfortunately the new_blob.start_copy_from_url(source_blob_url) command always leads to an erorr: ErrorCode:CannotVerifyCopySource. Is someone getting the same error message here, or has an idea, how to solve it? I was also trying to modify the source_blob_url as a sas-token, but still doesn't work. I have the feeling that there is some connection to the access levels of the storage account, but so far I wasn't able to figure it out. Hopefully someone here can help me. -
Passing Data to D3.js Line Chart with Django Backend
I am following a tutorial to create dashboard with D3.js plots. I am facing errors while passing data to the Line Chart plot. I am using the code extracted from here. Instead of using the data from csv I want to use the data which is extracted from the database. I can't figure out where should the data be referred within the code? Following is the index.html file {% load static %} <html> <script src="https://d3js.org/d3.v4.js"></script> <body> <h1> Hello! </h1> <div id="my_dataviz"></div> </body> <script> // set the dimensions and margins of the graph var margin = {top: 10, right: 30, bottom: 30, left: 60}, width = 460 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; // append the svg object to the body of the page var svg = d3.select("#my_dataviz") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); //Read the data // d3.csv("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/3_TwoNumOrdered_comma.csv", var data = {{ AAPL|safe }}, // When reading the csv, I must format variables: function(d){ return { date : d3.timeParse("%Y-%m-%d")(d.date), value : d.Close } }, // Now I can use this dataset: function(data) { // Add X axis … -
Dynamically updating Django template with new data
I am creating a cricket website which shows the live scores of cricket matches using Django. Below I have shown the sample views.py for my website: Views.py def livescores(): # generates livescores and returns a dict containing live scores return scores def display_scores(request): # calls the livescores function and gets the dict and #passes it to django template for rendering purposes scores = livescores() return render(request, 'LiveScores/display_scores.html', scores) Here is the Django template to which it passes that dict: <!DOCTYPE html> <html> <head> <title>{{MatchName}}</title> {% load static %} <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.5/dist/umd/popper.min.js" integrity="sha384-Xe+8cL9oJa6tN/veChSP7q+mnSPaj5Bcu9mPX5F5xIGE0DVittaqT5lorf0EI7Vk" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.min.js" integrity="sha384-kjU+l4N0Yf4ZOJErLsIcvOU2qSb74wXpOhqTvwVx3OElZRweTnQ6d31fXEoRD1Jy" crossorigin="anonymous"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link href="{% static 'LiveScores/style.css'%}" rel="stylesheet" type="text/css"> </head> <body> <header> <nav class="navbar"> <div class="container-fluid"> <a class="navbar-brand" href="#"><h1>Live Cricket Scores</h1></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About Us</a> </li> <li class="nav-item"> <a class="nav-link">Contact Us</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> More </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Live Matches</a></li> <li><a class="dropdown-item" href="#">Terms & Services</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Sources</a></li> </ul> </li> </ul> <form … -
ErrorDetail(string='This field is required.', code='required' )
Hi I am new to django html and I have been making a CRUD with Products having categories,sub categories,colors,size using SERIALIZERS.When I am trying to add a the data isnt getting displayed on webpage heres the error: "{'category_name': [ErrorDetail(string='This field is required.', code='required')]}" below is the model of categories: class Categories(models.Model): #made changes to category_name for null and blank category_name = models.ForeignKey(Products,on_delete=models.CASCADE) category_description = models.CharField(max_length=10) isactive = models.BooleanField(default=True) below are the show and insert functions def show_cat(request): showcategory = Categories.objects.filter(isactive=True) #print(showall) serializer = CategoriesSerializer(showcategory,many=True) #print(serializer.data) return render(request,'polls/show_cat.html',{"data":serializer.data}) def insert_cat(request): if request.method == "POST": insertcategory = {} insertcategory['category_name.id']=request.POST.get('category_name') insertcategory['category_description']=request.POST.get('category_description') form = CategoriesSerializer(data=insertcategory) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') return redirect('categories:show_cat') else: print(form.errors) return redirect('categories:show_cat') else: return render(request,'polls/insert_cat.html') below are the htmls of insert and show respetively <tr> <td>Category Name</td> <td> <input type="text" name="category_name" placeholder="CATEGORIES"> </td> </tr> <tr> <td>Description</td> <td> <textarea name="category_description" id="" cols="30" rows="10"> </textarea> </td> </tr> <td><b>{{result.category_name}}</b></td> <td><b>{{result.category_description}}</b></td> <td style="position: relative;left:50px;"> <a href="categories/edit_cat/{{result.id}}"> <button class="btn btn-primary"> <i class="fa-solid fa-pen-to-square">EDIT</i> </button> </a> </td> where am I going wrong in the code? -
Wagtail Streamblocks for logged in users
I would like to create a streamblock that can be limited to logged in users. A the moment I have this: class DefaultBlock(blocks.StructBlock): loggedin_only = blocks.BooleanBlock(required=False) class FramedVideoBlock(DefaultBlock): title = blocks.CharBlock(max_length=128, required=False) video = EmbedBlock() button = ButtonBlock(required=False) styling = blocks.ChoiceBlock(choices=STYLINGCHOICES) class Meta: template = 'streamblocks/framed_video_block.html' icon = 'radio-full' and in the template this: {% if self.loggedin_only == True and request.user.is_authenticated or self.loggedin_only == False %} <div class="bg_video_title"> ... </div> {% endif %} But I have the idea this can be done better. Maybe with a mixin? Any ideas? -
Celery task is not getting registerd
So I am using celery to run a task in an assigned time. I used ClockedSchedule since I wanted to run the task only one time in a particular time. clocked, _ = ClockedSchedule.objects.get_or_create( clocked_time=time PeriodicTask.objects.create( name=slug, task="account.tasks.send_money", clocked=clocked, one_off=True ) # creating periodic task using celery to run the task at scheduled time So when i run the code, PeriodicTask object is created. Task(custom) field is saved. but Task(registered) field is not being saved. So when it tries to run the task, I get the following error: [2022-07-05 11:19:00,035: ERROR/MainProcess] Received unregistered task of type 'account.tasks.send_money'. The message has been ignored and discarded. Please help me to find out the reason behind it.