Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why we use cleaned_data on forms in django
Why we use cleaned_data firstname= form.cleaned_data.get("first_name") What is the point in this and why is it necessary? -
No Module Named 'my_appdjango' while migrating django app
I am following this tutorial to setup my django (v 3.0.8) app. Below is my folder structure. +my_site +my_app +migrations __init__.py __init__.py admin.py apps.py models.py tests.py urls.py views.py +my_site __init__.py asgi.py settings.py urls.py wsgi.py manage.py I have added 'my_app' to INSTALLED_APPS in settings.py. But while executing command python manage.py makemigrations my_app on Windows, I get the below error: File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'my_appdjango' Why is it looking for my_appdjango when I have clearly defined my_app? -
Django rest framework foreign key returning as Integer
I tried to serialize a model in django with drf but now the problem I am facing is that the author which is a foreign key is being returned as an Integer. I am using Vue.js as frontend. Someone please help Serializers.py: from rest_framework import serializers from .models import Post class PostSerialiers(serializers.ModelSerializer): class Meta: model = Post fields = "__all__" Views.py: from django.shortcuts import render from .models import Post from .serializers import PostSerialiers from rest_framework import viewsets class PostView(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerialiers def Home(request): return render(request, 'Content/Home.html') models.py: from django.db import models from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100, blank=True, null=True) caption = models.CharField(max_length=1200, blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) Template: <div v-for="post in obj" style="width: 100%;" class="ui card"> <div class="content"> <div class="header">[[post.title]]</div> <div class="meta">2 days ago</div> <div class="description"> <p>[[post.caption]]</p> </div> </div> <div class="extra content"> <i class="check icon"></i> [[post.author]] </div> </div> <script> function loadDoc() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var app = new Vue({ el: '#root', delimiters: ['[[', ']]'], data:{ "obj" : JSON.parse(this.responseText) } }) } } xhr.open('GET', 'http://localhost:8000/apiposts/', true); xhr.send() } loadDoc() </script> Someone please … -
how to create javascript PERT chart for my website
I trying to lot of pert chart plugin, but not working anyone knows javascript PERT charts for websites like visual-paradigm but I want in javascript coding -
How to implement unique together in Django
im working on a sales team project where i'm trying to implement a function to upload their daily visit plan. While uploading i want to put a validation that, if visit for one customer is already uploaded then for same another wouldn't be uploaded and would raise a error like" Visit plan for this customer already exists on this date". I have read some where that unique together would help me to validate but im not sure how to use unique together in View. please find the below codes for your reference and help. Thanks in advance Model: class BeatPlan(models.Model): beat_id = models.CharField(unique=True, max_length=15, null=True) beat_dealer = models.ForeignKey(Dealer, null=True, on_delete=models.SET_NULL) beat_user = models.ForeignKey('account.CustomUser', null=True, on_delete=models.SET_NULL) beat_stake_holder = models.ForeignKey(StakeHolder, null=True, on_delete=models.SET_NULL) beat_date = models.DateField(null=True) create_date = models.DateField(null=True) beat_status = models.CharField(choices=(('Not visited', 'Not visited'), ('Visited', 'Visited')), default='Not visited', max_length=40, null=True) beat_location = models.CharField(max_length=200, null=True) beat_type = models.CharField(choices=(('Not planned', 'Not planned'), ('Planned', 'Planned')), max_length=50, null=True) beat_reason = models.CharField(max_length=200, null=True) class Meta: unique_together = ('beat_date', 'beat_dealer') def __str__(self): return str(self.beat_user) + str(self.beat_dealer) + str(self.beat_date) View: def upload_beat(request): global u_beat_dealer, beat_user_id, beat_date template = "upload_beat.html" data = BeatPlan.objects.all() l_beat = BeatPlan.objects.last() l_beat_id = l_beat.id print(l_beat_id) current_month = datetime.datetime.now().strftime('%h') # prompt is a context variable that … -
D.R.Y approach to splitting a queryset into many different sub groups?
I have a single query allnames = self.object.person_othernames.all().prefetch_related("nametype") This returns all the names related to a person's object, each related name has a "nametype" field ("English name", "stage name", etc). I want to display the names in the template which is no problem but if there are multiple names that use the same "nametype" then I want to separate them behind their "nametype" header. So if there are multiple names with the nametype "English name" then it would be displayed as: English Names: name1, name2 The approach I have tried already seems like it would work just fine but I feel like there would be a much better D.R.Y approach. So what I tried was to make a single query to the database using the code at the top, then I filtered down that queryset for each nametype. english_names = allnames.filter(nametype__nametype__iexact="english name") stage_name = allnames.filter(nametype__nametype__iexact="stage name") The problem with the above code is that I'd need to do this for every "nametype" and if there are many "nametypes" then each one would need to be individually filtered and sent through the context. So my inexperience is probably shining bright at the moment but if anyone has any suggestions I'd appreciate … -
Django: This site can’t be reached : localhost refused to connect
I am a newbie to the django and doing a course from udemy and got stuck at the admin page. I am unable to load the django default admin login page. It throws the following error: This site can’t be reached localhost refused to connect. I am still at the very beginning of the course and just created a function in the model.py file and made the migrations and tried accessing the default login page. Here's the code: from django.db import models class Student(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email_id = models.EmailField(max_length=254) phone_no = models.IntegerField() I have tried all the steps mentioned in the previous answers. But still, the issue isn't resolved. I strongly feel that it is due to system settings regarding the localhost. No error displayed in the command prompt. I have changed my firewall settings, tried adding localhost, '*' and every other alternative that I've found. Please help..!! Thanks, -
Which hosting will be better option for hosting django site?
I want host my django site but what will be suitable option rather than free and I am a Beginner. And how can I use images in site or where I should put them. -
Django register form POST data not validated by view in production?
For some reason the POST data from my Django app's user sign up form doesn't get validated by the signup view. It works perfectly in development on my local machine, but not in production. I have also inspected the web content and the POST data gets created but the page just reloads an empty form. What could cause this? signup.html <form method="POST" autocomplete="off" novalidate> {% csrf_token %} {% cache 86400 signup %} ... <button type="submit">Sign up</button> {% endcache %} </form> views.py def signup_view(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() return redirect('home') else: form = UserRegisterForm() context = { 'title': 'Sign up', 'form': form, } return render(request, 'users/signup.html', context) -
Issue with Djangoitem import in scrapy
I've tried to install pip install scrapy-djangoitem, but output is still the same. What is the problem? items.py import scrapy from scrapy_djangoitem import DjangoItem from article.models import Article class ArticleItem(DjangoItem): django_model = Article author = scrapy.Field() dictionary = scrapy.Field() title = scrapy.Field() Output: (env) taranchik@Dell:~/Public/My Files/IT/work/projects/TEONITE/source/crawling$ scrapy crawl teonite_blog Files/IT/work/projects/TEONITE/source/crawling/spiders/teonite_spider.py", line 3, in <module> from crawling.items import ArticleItem File "/home/taranchik/Public/My Files/IT/work/projects/TEONITE/source/crawling/items.py", line 7, in <module> from scrapy_djangoitem import DjangoItem ModuleNotFoundError: No module named 'scrapy_djangoitem' -
How to change some stuff from the css file for my form?
I have a file that extends my base HTML file and this file contains a form. I want to create a margin for the form and also change the color of the submit button and form text box to match the theme of my website. How do I go about doing this in my CSS file? As of now, the margin does not seem to be working and I am also not sure how I would change the color as I mentioned earlier. search.html file {% extends 'base.html' %} {%load static%} <link rel="stylesheet" type= "text/css" href="{% static 'css/form.css' %}" > <body> {% block content %} <container > <center> <form action="/searchoutput/" method="post"> {% csrf_token %} Input Text: <input type="text" name="param" required> <br><br> {{data_external}}<br><br> {{data}} <br><br> <input type="submit" value="Check for Service"> </form> </container> </center> {% endblock %} </body> form.css file form { margin-top: 200px; } -
How to get a value of a foreign key?
I recently started to learn django, so I am not even sure how to ask this question. I want to build an api and I am using django rest framework. Now I have two main models Product and Category. class Category(models.Model): id = models.CharField(max_length=100, primary_key=True) name = models.CharField(max_length=100) class Product(models.Model): id = models.CharField(max_length=100, primary_key=True) title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.FloatField(default=0.0) And I have some functions @api_view(['GET']) def productList(request): products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) @api_view(['POST']) def addProduct(request): serializer = ProductSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) All of these seems to work fine and I am getting a response from an api, but when I try to pull category name from a response I only get id of a category and not its name. Can you please help me figure this out? Thank you -
Django Channels doesn't detect WebSocket request with NGINX
I am deploying a website on AWS. Everything works fine for HTTP and HTTPS. I am passing all requests to Daphne. However, incoming websocket connections are treated as HTTP requests by Django. I am guessing there is some header that isn't set in Nginx, but I have copied alot of my nginx config from tutorials. Nginx Config: upstream django { server 127.0.0.1:9000; } server { listen 80; server_name 18.130.130.126; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name 18.130.130.126; ssl_certificate /etc/nginx/certificate/certificate.crt; ssl_certificate_key /etc/nginx/certificate/private.key; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; location / { include proxy_params; proxy_pass http://django; } } Daphne is binded to 0.0.0.0:9000. Channels has very basic setup. A ProtocolTypeRouter, with AuthMiddlewareStack and then URLRouter, as shown on the Channels tutorial. And then a Consumer class. I am using redis for channel layer, but that doesn't seem to be a problem. This is some data about the request on response from fiddler. The request headers say Upgrade to websocket, but it returns a 404 HTTP request, as it doesn't see it as a websocket request. Thanks for any help. -
when done migration its shown AttributeError: 'bool' object has no attribute 'replace'
when running the code *python manage.py migrate* its shown: **self.verbose_name = self.name.replace('_', ' ') AttributeError: 'bool' object has no attribute 'repla ce'** **model.py:** from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=False) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) data_orderd = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product = models.ForeignKey(Product,on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, name=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address = models.CharField(max_length=200, null=True) city = models.CharField(max_length=200, null=True) state = models.CharField(max_length=200, null=True) zipcode = models.CharField(max_length=200, null=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address please correct my error if you could it would be so kind of yoj if you could help me im new to python and programming thankyou in advance i would like to know the explanation of the error so that i could avoid such … -
RecordModifiedError : While calling save method on a self referencing model in django
Here is my Django model class Member(models.Model): family_designation = models.CharField(max_length=20, null=True, blank=True) family_head = models.ForeignKey( "self", to_field='member_id', ) def preprocess(): if self.family_head: self.family_head.family_designation = "family_head" self.family_head.save() and here is save method def save(self,*args,**kwargs): self.preprocess() super.save(*args,**kwargs) I don't know why I'm getting RecordModifiedError. I'm not able to reproduce it but while looking for the solution I came to know that it is due to multiple save calls in the same model. -
i'm trying to have a multiple form based on the variable number input
** for exemple i will give a number of cars for each garage : when i put 3 cars for garage number1 i will have 3 forms of cars and if i put 2 i only get two . and all this in the same view and when i submit all the cars it will be in the data base in the same time... is it possible to do this in django ? ** def car_form(request): if request.method == "GET": form = carForm() return render(request , "django_projects/car_form.html", {'form': form}) else: form = carForm(request.POST) if form.is_valid() : form.save() else: return HttpResponse('Please add a valid car ! ') return redirect('/car/list') ////////////////////// {% block content %} <form action="" method="post" autocomplete="off"> {% csrf_token %} {{form.garage_name|as_crispy_field}} {{form.car_number_model|as_crispy_field}} </form> {% endblock content %} //////////////////// {% block content %} <form action="" method="post" autocomplete="off"> {% csrf_token %} {{form.car_name|as_crispy_field}} {{form.car_model|as_crispy_field}} {{form.color|as_crispy_field}} {{form.place|as_crispy_field}} </form> {% endblock content %} -
how to set default extra fields number to to a formset through th template
i need a way to increase number of formset fields by default depend on a parent field I am working on a project for a mobile store which working with IMEI of mobiles. Each single mobile has its own unique imei. when the admin adds a new mobile phone in MobileStorage for example quantity= 20 mobile iphone11X have 20 different IMEIs. I want to allow the admin, whenever he add new mobile phone, and then select the quantities (20) then extra fields will be 20. If he had filled 10 in quantity field extra fields then, IMEI will be 10. i dont want to do it manually , i used jquery.formset.js this is my models.py class Mobile(models.Model): mobile = models.CharField(max_length=50,unique=True) class MobileStorage(models.Model): mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Imei(models.Model): imei = models.CharField(max_length=50,verbose_name='IMEI',unique=True) mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) i have make inlineformset whenever i wanted add a new MobileStorage then at the same time i add its IMEI's ! my forms.py class MobileStorageForm(forms.ModelForm): mobile = forms.ModelChoiceField(queryset=Mobile.objects.all(),empty_label='mobiles') class Meta: model = MobileStorage fields = [ 'mobile','quantity' ] class ImeiForm(forms.ModelForm): class Meta: model = Imei fields = ['imei'] MobileStorageInlineFormSet = inlineformset_factory( MobileStorage,Imei,form=ImeiForm,fields=('imei'),extra=1,can_delete=False ) and this is my views.py class CreateMobileStorageView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = MobileStorage form_class … -
Django : send_mail() using the data I just created
I want to make an API to allow client to order online. When the order is validated, I want to send an email to the client to confirm his order. For that, I need the data that I just created (the order id, the delivery day and the delivery place). This is my code : models.py : class memberArea(AbstractBaseUser): username = models.CharField(max_length=255) email = models.EmailField(max_length=255, unique=True) phone = models.TextField() date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) deliveryAddress = models.TextField() postalCode = models.CharField(max_length=255) forget = models.TextField(null=True, blank=True) city = models.CharField(max_length=255) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) class order(models.Model): user = models.ForeignKey(memberArea, on_delete=models.CASCADE) comment = models.TextField(null=True, blank=True) orderDay = models.DateTimeField(auto_now_add=True) deliveryDay = models.DateField() deliveryAddress = models.CharField(max_length=255) state = models.CharField(max_length=255, null=True, blank=True, default="En attente") price = models.TextField(null=True, blank=True) response = models.TextField(null=True, blank=True) class orderDetail(models.Model): order = models.ForeignKey(order, on_delete=models.CASCADE) product = models.ForeignKey(product, on_delete=models.CASCADE) byProduct = models.ForeignKey(byProduct, on_delete=models.CASCADE) quantity = models.CharField(max_length=255) serializer.py : class orderDetailSerializer(serializers.ModelSerializer): class Meta: model = orderDetail fields = '__all__' read_only_fields = ('order',) class MakeOrderSerializer(serializers.ModelSerializer): orderDetail = orderDetailSerializer(many=True) class Meta: model = order fields = ['user', 'comment', 'deliveryAddress', 'deliveryDay', 'orderDetail'] def create(self, validated_data): order_detail_data = validated_data.pop('orderDetail') new_order = order.objects.create(**validated_data) new_order.save() for product in … -
Celery and RabbitMQ I am not receiving updates for my task
How are you? I am working on django 2.2, celery 4.4.2 and In my tasks.py file I have the following code @shared_task def start_task(dict): objectLogic = LogicProcess() # print('dict', dict) task = objectLogic.RunProcess(parameters=dict) print("Estado de la tarea: {}\r".format(task)) return task it calls a function, at the end of it I update it but I don't receive a response. current_task.update_state( state = 'PROGRESS', meta = { 'current': oer_number, 'total': TotalOER, 'percent': int((oer_number * 100) / TotalOER) } ) ah yes ... at the end of the task I make it return return {'current': TotalOER, 'total': TotalOER, 'percent': 100} well if i get one (the first update) i can't see the others celery -A ost worker -l info -n worker task 528454cb-724e-48bc-b95e-9d3a124b22e1 Task status {} task 528454cb-724e-48bc-b95e-9d3a124b22e1 Task status {'state': 'PROGRESS', 'result': {'current': 2, 'total': 66, 'percent': 3}} or task_id=528454cb-724e-48bc-b95e-9d3a124b22e1 HTTP/1.1" 200 2 task_id=528454cb-724e-48bc-b95e-9d3a124b22e1 HTTP/1.1" 200 74 task_id=528454cb-724e-48bc-b95e-9d3a124b22e1 HTTP/1.1" 200 110 or just nothing but the one it calls if it works, it's just the state that doesn't return me in both files tasks.py and function.py import from celery import shared_task, current_task the celery.py file contains # from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default … -
How do I search for a Django model by a primary key that doesn't match its type without throwing an error?
I'm using Django 3 and Python 3.7. I have a model (MySql 8 backed table) that has integer primary keys. I have code that searches for such models like so state = State.objects.get(pk=locality['state']) The issue is if "locality['state']" contains an empty string, I get the below error Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1768, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/test_serializers.py", line 132, in test_coop_create_with_incomplete_data assert not serializer.is_valid(), serializer.errors File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 234, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 433, in run_validation value = self.to_internal_value(data) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 490, in to_internal_value validated_value = field.run_validation(primitive_value) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 565, in run_validation value = self.to_internal_value(data) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/relations.py", line 519, in to_internal_value return [ File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/relations.py", line 520, in <listcomp> self.child_relation.to_internal_value(item) File "/Users/davea/Documents/workspace/chicommons/maps/web/directory/serializers.py", line 26, in to_internal_value state = State.objects.get(pk=locality['state']) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 404, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line … -
Can I use my Django backend for creating a hybrid mobile app?
I wrote a website with a log-in function and different apps behind the log-in using HTML, CSS, JS and Python/Django for the backend. Now I would like to create a hybrid mobile app but I don't know where to start. I want to be able to use the database I created using Django for the mobile app. And I also need to mobile app to be automatically synced with the web app. Is there a way to do this? And how would this be possible? Thanks guys! -
my update view is working when i click the update button it dosent work
when i click on the update button it just shows me the original post unedited i am using the post_create template for the post_update too here is the code. i have been trying to solve for half an hour any help would be great thanks views.py from django.shortcuts import render from django.shortcuts import HttpResponseRedirect from .models import Post from .forms import PostForm def post_list(request): posts = Post.objects.all() context = { 'post_list': posts } return render(request, "posts/post_list.html", context) def post_detail(request, post_id): post = Post.objects.get(id=post_id) context = { 'post': post } return render(request, "posts/post_detail.html", context) def post_create(request): form = PostForm(request.POST or None) if form.is_valid(): form.save() return HttpResponseRedirect('/posts') context = { "form": form, "form_type": 'Create' } return render(request, "posts/post_create.html", context) def post_update(request, post_id): post = Post.objects.get(id=post_id) form = PostForm(request.POST or None, instance=post) if form.is_valid(): form.save() return HttpResponseRedirect('/posts') context = { "form": form, "form_type": 'Update' } return render(request, "posts/post_create.html", context) urls.py from django.urls import path from .views import post_list, post_detail, post_create, post_update urlpatterns = [ path('', post_list), path('create/', post_create), path('<post_id>/', post_detail), path('<post_id>/update', post_update), ] -
Open a download python django project from GitHub
I am new in the field of programming under python and Django, I download python-Django examples to improve my skills but, none of the projects works well under IDE, Pycharme, what are the steps or the files to check and to modify so that the projects work and I can read them and learn more, thank you -
Cannot make the views counter
I'm Trying to create a Views Counter in my django blog. Their are 3 apps in the project. The views counter on the writings app works fine but on the blog app it throws an error 'NoneType' object has no attribute 'views' and shows the error at post.views+=1. However the same code works in the writings app. I cannot find where the problem lies. Maybe the code is returning a empty set that's why it's not working but if so then why the code works when I remove just this views counter code? Here are the code snippets for Blog and Writings app. Blog app Views.py:- post = Post.objects.filter(slug=slug).first() post.views +=1 post.save() tech = Tech.objects.filter(slug=slug).first() tech.views +=1 tech.save() pcomments = BlogComment.objects.filter(post=post,parent=None) preplies = BlogComment.objects.filter(post=post).exclude(parent=None) #Creating Reply Dictionary and iterating it preplyDict = {} for reply in preplies: if reply.parent.sno not in preplyDict.keys(): preplyDict[reply.parent.sno] = [reply] else: preplyDict[reply.parent.sno].append(reply) tcomments = BlogComment.objects.filter(tech=tech,parent=None) treplies = BlogComment.objects.filter(tech=tech).exclude(parent=None) #Creating Reply Dictionary and iterating it treplyDict = {} for reply in treplies: if reply.parent.sno not in treplyDict.keys(): treplyDict[reply.parent.sno] = [reply] else: treplyDict[reply.parent.sno].append(reply) context = {'post': post,'tech': tech,'pcomments':pcomments,'tcomments':tcomments,'preplyDict':preplyDict,'treplyDict':treplyDict} return render(request,'blog/blogPost.html',context) Writings views.py:- def wPost(request,slug): w = Writing.objects.filter(slug=slug).first() w.views = w.views+1 w.save() comments = WComment.objects.filter(wpost=w, parent=None) replies = … -
Exception happened during processing of request from ('127.0.0.1', 9464)
I don't know why this eror I wrote it from a tutorial but It's happend this is view.py file here import view as view from django.shortcuts import render from django.http import HttpResponse from django.views import View # Create your views here. from teams.models import Team class HomePageView(View): def get(self,requests): all_teams = Team.objects.all() context = {"teams": all_teams} return render(requests,"teamlist.html",context) this is my admin.py file this is my admin.py file:here from django.contrib import admin # Register your models here. from teams.models import Team, Player, GameScore admin.site.register(Team) admin.site.register(Player) admin.site.register(GameScore) that's my first question on stack over flow I don't know I ask True or not . I just need some help :)