Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
{% csrf_token %} is empty string but {{ csrf_token }} returns a value - Django
I have to submit a form via POST method. I added to my html form the {% csrf_token %} tag but from the DOM I'm getting this: <input type="hidden" name="csrfmiddlewaretoken" value=""> But if I type {{ csrf_token }} in the template I can see the value. Why can't I set my token in the form? This is my form: <form action="{% url 'aj_upload_file' %}" method="POST"> {% csrf_token %} <a id="upload-file-btn" href="javascript:;" class="btn btn-success mr-2"> <i class="fa fa-upload" aria-hidden="true"></i> </a> <input class="d-none" multiple type="file" id="upload-file"> </form> Thank You. -
dictionary not coming in for loop despite correct syntax
I am doing crud project which has models PRoducts,categories,sub categories ,color,size. I am trying to get a django dropdown using SERIALIZERS and have connect categories and subcategories via foreignkeys below are the models below is the function of isnerting in views.py of sub categories and below is the html code for the dropdown using for loops I also tried {{c}} even that didnt work the drop down still doesnt have any options,where am I going wrong? -
How to access a foreign key related field in a template when using Django model form
My Objective Access the field name in the Parent Model ParentModel and display its content in a form instance in the template. For example, let the field parent be a foreign key in the ChildModel as described below. What I have tried Access the parent field in the form as {{ form.parent.name }} in the template Errors received Tried looking up form.parent.name in context models.py class ParentModel(models.Model): name = models.CharField() class ChildModel(models.Model): parent = models.ForeignKey(ParentModel) forms.py class ChildModelForm(ModelForm): class Meta: model = ChildModel fields = '__all__' widgets = {'parent': forms.Select(),} views.py def childView(request, pk): template = 'template.html' child = ChildModel.objects.get(parent=pk) form = ChildModelForm(instance=child) if request.method == 'POST': form = ChildModelForm(request.POST, instance=child) if form.is_valid(): form.save() else: form = ChildModelForm(instance=child) context = {'form': form, } return render(request, template, context) template.html <form method="POST" action=""> {% csrf_token %} {{form.parent.name}} <button type="submit">Save</button> </form> Now the child model form displays pk I want to display the name of the parent field I have also tried using this Django access foreignkey fields in a form but it did not work for me. -
DRF ManyToMany instances add not create
I have the following code of my model: class Recipe(BaseModel): """ Recipe model class using for contains recipe, which can be sent to chat with coach. In text recipe contains RecipeStep. """ ingredients = models.ManyToManyField( Product, verbose_name=_("ingredients"), related_name="ingredients" ) portion_size = models.PositiveSmallIntegerField( _("portion size") ) # TODO: add "add_to_meal" logic (user can add recipe to his meal). # it can be reached by using M2M with user and creating new relation for # user and recipe on user click on special button. def __str__(self) -> str: return f"recipe \"{self.title}\"" def __repr__(self) -> str: return f"Recipe({self.pk=}, {self.title=}, {self.is_published=})" class Meta: verbose_name = _("recipe") verbose_name_plural = _("recipes") BaseModel is abstract class, that has basic structure of Article-like models (title, description, published_at, etc.). And the following code of serializers for model: class RecipeSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) title = serializers.CharField(min_length=1, max_length=200, required=True) ingredients = ProductSerializer(many=True, read_only=False) portion_size = serializers.IntegerField(min_value=0, required=True) is_published = serializers.BooleanField(required=False, default=False) publish_date = serializers.DateField( allow_null=True, required=False, read_only=True ) image_add_id = serializers.UUIDField(required=True) def create(self, validated_data): validated_data.pop('image_add_id', None) return super().create(validated_data) class Meta: model = Recipe fields = "__all__" I need to create Recipe with passing list of existing ingredient pks, and not create new ingredients like: { ... "ingredients": [ "d6c065a2-7f80-47f3-8c0e-186957b07269", "4b8359d2-073a-4f41-b3cc-d8d2cfb252d5", "b39e4cc2-18c3-4e4a-880a-6cb2ed556160", … -
ModuleNotFoundError: No module named 'app' on new Django installation
I am trying to set up a simple Django==4.0.6 dev environment on my Ubuntu 20.04. I'm creating a project folder, create and activate a venv first. Then I'm installing Dajngo using pip. I'm then creating a new project in the very same directory and then for testing this out, run the usual python manage.py command. Here's a quick list of commands I am using: mkdir project && cd project python3 -m venv venv source venv/bin/activate pip install django==4.0.6 django-admin startproject major . python manage.py migrate But I'm getting the following error: Traceback (most recent call last): File "/project/venv/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/project/venv/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/project/venv/lib/python3.8/site-packages/django/core/management/base.py", line 95, in wrapped saved_locale = translation.get_language() File "/project/venv/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 210, in get_language return _trans.get_language() File "/project/venv/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 65, in __getattr__ if settings.USE_I18N: File "/project/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/project/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/project/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, … -
Javascript is not working properly inside djagno project
While my code is working when used outside of a Django project, when I place it inside one it's acting strange. More specifically, the document object does not have a body, but only the head of my html. Thus I am not able to access its classes. My guess is that something's wrong in the linking between the html and js files. settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>index.html</title> {% load static %} <link rel="stylesheet" href="{% static 'style.css' %}"/> <script src="{% static 'script.js' %}"></script> </head> <body> HelloWorld! </body> </html> script.js console.log(document.getElementsByTagName('html')[0].innerHTML) The return of script.js: <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>index.html</title> <link rel="stylesheet" href="/static/style.css"> <script src="/static/script.js"></script></head> -
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