Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I view my django site from other devices which are connected to the same network
I wanted to view my django site from another device. I ran this command py manage.py runserver 0.0.0.0:8888 Then I went to my phone web browser and entered this url (Network ip address):8888 It was searching for that url and a little while later the connection timed out. What do I do -
Django dynamically generated serializer
Is there a way how to dynamically generate a django rest framework serializer? Considering this: class BlogSerializer(serializers.ModelSerializer): class Meta: model = models.Blog fields = get_all_model_fields(models.Blog) class PostSerializer(serializers.ModelSerializer): class Meta: model = models.Post fields = get_all_model_fields(models.Post) class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = get_all_model_fields(models.User) I am wondering if something like the following example could be possible: from django.apps import apps models = [model for model in apps.get_models()] for model in models: type(model.__name__+'Serializer',(serializers.ModelSerializer,),{ type("Meta",(),{ "model":model, "fields": get_all_model_fields(model) }) }) Or is there any other way how to generate DRF serializers because I have got a huge amount of models to serialize. -
Stripe Webhooks: Invoice.paid vs Checkout.Session.Completed
I use Stripes' webhooks and want to get notified, if the customer successfully "paid the bill". I came across two webhooks, which in my opinion both could do the job: Webhook "invoice.paid" - According to Stripe doc: Occurs whenever an invoice payment attempt succeeds or an invoice is marked as paid out-of-band. Webhook "checkout.session.completed" - According to Stripe doc: Occurs when a Checkout Session has been successfully completed. My questions are: I don't understand the second part of the "invoice.paid" webhook: "invoice is marked as paid out-of-band" -> What does "out-of-band" mean? Is this to be considered a successful payment? Regarding "checkout.session.complete" -> This can also occur, if payment fails - correct? Which webhooks shall I consider (or are there other webhooks) to see the status "customer paid the bill successfully"? What is more, I don't really know if disputes should be considered as successful payments or not: On one hand, I get a invoice.paid webhook, on the other hand, I get a charge.dispute.created webhook. geeezus... I appreciate your help! Thanks. -
How can I work on a django project in my external harddrive
I have an external drive from my old PC and I would like to continue working on some projects there, I have set up python but on my VSCode I keep getting "workspace contains pipfile but pipenv was not found". What's the solution to this? -
Using dictionary from Django view in .html Javascript loop (SyntaxError - unexpected token: ')
I'm working on a Django project, and when I try to load a dictionary using Javascript, I get SyntaxError - unexpected token: &#x27 In my .html file, I am using {{ customer_tabledata }} to import from my views. The problem is it's trying to load &#x27 and not the quotation mark. How can I convert from &#x27 to "? In my .html file: <script> let tableData = {{ customer_tabledata }}; function loadTableData(tableData) { const tableBody = document.getElementById('tableData'); let dataHTML = ''; for(let data of tableData) { dataHTML += `<tr><td>${data}</td></tr>` ; } tableBody.innerHTML = dataHTML; </script> In my views: customer_tabledata = {'site_1' : {'revenue' : 900 }, {'partner_share' : 450}, 'site_2 : {'revenue' : 1500 }, {'partner_share' : 750}} -
Custom navbar for each View
I try to do navbar for each View different. Can I code it better for example using href="{% url 'polls:detail' question.id %} ? Now I create navbar.html {% for name, link in navbar.items%} <li class="nav-item"> <a class="nav-link" href={{link}}>{{name}}</a> </li> {% endfor %} and Views class ArticleListView(generic.ListView): model = Article template_name = 'blog/article_list.html' context_object_name = 'articles' queryset = Article.objects.all() def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data() context['navbar'] = {"Main Page":"/blog/","create":"/blog/create"} return context class ArticleDetailView(generic.DetailView): template_name = 'blog/article_detail.html' context_object_name = 'article' queryset = Article.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data() context['navbar'] = { "Main Page": "/blog/", "create": "/blog/create", "edit": f"/blog/{Article.objects.get(id=self.object.id).id}/update", "delete": f"/blog/{Article.objects.get(id=self.object.id).id}/delete", } return context -
How would one go about making a file-sharing app in Django
How could I make a file sharing app in Django and Django-rest-framework? How would I start and what technologies would I use? -
Django+Apache: [wsgi:error] ModuleNotFoundError: No module named django_project1'
Launching my first Django application through Linode using Apache. Everything was going fine until I had to finalize the launch. When I try to access the IP of the site I am receiving a '500 Internal Server Error'. Based on the error log I am seeing there is an wsgi error. This error states that there is a module not found 'django_project1' (this is the name of my project). I have seen many examples of this error however there doesn't seem to be a comprehensive explanation of why its occurring and not one example has the same solution. Any feedback is appreciated. Below I have included my: Error Log [Tue Nov 10 19:22:25.784084 2020] [wsgi:error] [pid 63086:tid 140172442277440] [remote 169.45.99.51:49639] File "<frozen importlib._bootstrap>", line 991, in _find_and_load [Tue Nov 10 19:22:25.784090 2020] [wsgi:error] [pid 63086:tid 140172442277440] [remote 169.45.99.51:49639] File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked [Tue Nov 10 19:22:25.784094 2020] [wsgi:error] [pid 63086:tid 140172442277440] [remote 169.45.99.51:49639] File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed [Tue Nov 10 19:22:25.784099 2020] [wsgi:error] [pid 63086:tid 140172442277440] [remote 169.45.99.51:49639] File "<frozen importlib._bootstrap>", line 1014, in _gcd_import [Tue Nov 10 19:22:25.784104 2020] [wsgi:error] [pid 63086:tid 140172442277440] [remote 169.45.99.51:49639] File "<frozen importlib._bootstrap>", line 991, in _find_and_load [Tue … -
A way to copy files from one Caprover image to another
I uploaded a website using caprover and django and works well. Everything works fine, but I noticed whenever I updated the project user files get lost, although everything gets updated quite well. I understand caprover is build on top of nginx and docker, but I'm new to them. Every time I update caprover it builds a new image( I guess docker image) and this makes user images to disappear (I guess left in the previous image) is there a way to copy those files? Thanks in advance -
I get AuthFailed after trying to social login in my Django app using linked in
I have a web application that has profiles for alumnus, on each profile there are some information like work I want to let the user be able to connect to his linkedin profile so he can get information like work so I started with social-auth-core library in python to get information from the user but after the linkedin login pop ups and I click on allow I keep receiving this error AuthFailed at /social-auth/complete/linkedin-oauth2/ Authentication failed: HTTPSConnectionPool(host='www.linkedin.com', port=443): Max retries exceeded with url: /oauth/v2/accessToken?grant_type=authorization_code&code=AQSg1PcOoIT3zrtriLVJRtn-NGYcrmEbWptBEWrr-dU0tNs80lgv1503bN6mTf6K65mpOqcBAKwYQ3yPxp7Fp2KvXUgCBXFzPbVe2K4iWukuFuZgc3qzrz5VyzyV4zTqdpWVXK14Q28en6EpD7TKDCc886ei_2CC8m2UqM6HQGOlmrkI6wPvZm5qWYmsCw&client_id=77hqh7fm6bhtar&client_secret=wYy0wVVhUIuRQCPF&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fsocial-auth%2Fcomplete%2Flinkedin-oauth2%2F (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x05204DA8>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it')) Request Method: GET Request URL: http://127.0.0.1:8000/social-auth/complete/linkedin-oauth2/?code=AQSg1PcOoIT3zrtriLVJRtn-NGYcrmEbWptBEWrr-dU0tNs80lgv1503bN6mTf6K65mpOqcBAKwYQ3yPxp7Fp2KvXUgCBXFzPbVe2K4iWukuFuZgc3qzrz5VyzyV4zTqdpWVXK14Q28en6EpD7TKDCc886ei_2CC8m2UqM6HQGOlmrkI6wPvZm5qWYmsCw&state=9oPFIPwkeUI1uzEjmzIq2sLA8y11vf2a Django Version: 2.2.7 Exception Type: AuthFailed Exception Value: Authentication failed: HTTPSConnectionPool(host='www.linkedin.com', port=443): Max retries exceeded with url: /oauth/v2/accessToken?grant_type=authorization_code&code=AQSg1PcOoIT3zrtriLVJRtn-NGYcrmEbWptBEWrr-dU0tNs80lgv1503bN6mTf6K65mpOqcBAKwYQ3yPxp7Fp2KvXUgCBXFzPbVe2K4iWukuFuZgc3qzrz5VyzyV4zTqdpWVXK14Q28en6EpD7TKDCc886ei_2CC8m2UqM6HQGOlmrkI6wPvZm5qWYmsCw&client_id=77hqh7fm6bhtar&client_secret=wYy0wVVhUIuRQCPF&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fsocial-auth%2Fcomplete%2Flinkedin-oauth2%2F (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x05204DA8>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it')) Exception Location: C:\Users\lebda\.virtualenvs\final-thesis-HeIACWIb\lib\site-packages\social_core\backends\base.py in request, line 236 Python Executable: C:\Users\lebda\.virtualenvs\final-thesis-HeIACWIb\Scripts\python.exe Python Version: 3.8.5 Python Path: ['E:\\final-thesis', 'C:\\Users\\lebda\\.virtualenvs\\final-thesis-HeIACWIb\\Scripts\\python38.zip', 'c:\\users\\lebda\\appdata\\local\\programs\\python\\python38-32\\DLLs', 'c:\\users\\lebda\\appdata\\local\\programs\\python\\python38-32\\lib', 'c:\\users\\lebda\\appdata\\local\\programs\\python\\python38-32', 'C:\\Users\\lebda\\.virtualenvs\\final-thesis-HeIACWIb', 'C:\\Users\\lebda\\.virtualenvs\\final-thesis-HeIACWIb\\lib\\site-packages'] Server time: Thu, 12 Nov 2020 17:22:55 +0000 and I don't understand where is the problem my project … -
CSRF token missing or incorrect in django Sign up page
i have a problem with my sign up page, after completing the form and clicking submit button am receiving an error: Access denied (403) CSRF verification failed. The request was aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, … -
Django sites redirect if Site matching query does not exist
I am using the Django "sites" framework and I am having problems handling a DoesNotExist exception it raises when I try to "access" a Site not currently in my database. In my settings.py I am not specifying any SITE_ID. Rather, I am letting Django figure it out automatically by looking at requests. Some of the domains currently in my database are: www.app.com (International version of the app), us.app.com (American version of the app), es.app.com (Spanish version of the app), ... With this being the state of my database, the problem arises when I try to access, say, about.app.com. Since about.app.com is not in my database I get the following DoesNotExist error... Site matching query does not exist. Desired behavior Instead of throwing an exception, I would like Django to redirect all invalid sites to www.app.com. Question Where could I handle that DoesNotExist exception and how could I redirect the user to www.app.com if the exception were thrown? -
why does django add each character to the list
Given a variable task = 'abc' we update the session variable as follows: request.session['tasks'] = [task] this works but seems like we are adding a list to a list. If we try the following: request.session['tasks'] = task our session variable becomes ['a','b','c'] instead of ['abc'] could someone explain why the second approach doesn't work? -
How to create a view for nested comments in Django rest framework?
I want to have a nested comment system for my project. I have product model so I want to clients can comment on my products. I have my product and comment models and serializers and I related comments to products in product serializer so I can show product comments. what should i do to clients can write their comment for products??? the comments must be nested. this is my code: #models class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='comments') parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True,blank=True, related_name='replys') body = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user} - {self.body[:30]}' class Meta: ordering = ('-created',) #serializers: class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['id', 'user', 'product', 'parent', 'body', 'created'] class ProductSerializer(serializers.ModelSerializer): comments = CommentSerializer(many=True, read_only=True) class Meta: model = Product fields = ['id', 'category', 'name', 'slug', 'image_1', 'image_2', 'image_3', 'image_4', 'image_5', 'description', 'price', 'available', 'created', 'updated', 'comments'] lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } #views: class Home(generics.ListAPIView): queryset = Product.objects.filter(available=True) serializer_class = ProductSerializer permission_classes = (permissions.AllowAny,) filter_backends = [filters.SearchFilter] search_fields = ['name', 'category__name', 'description'] class RetrieveProductView(generics.RetrieveAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = (permissions.AllowAny,) lookup_field = 'slug' -
How do I reinstall the db.sqlite3 file in django
I am a beginner with django and I accidentally deleted the db.sqlite3 file in my django project. I made a new django project but the db.sqlite3 file was not in it. I also uninstalled and reinstalled django and project but the db.sqlite3 file still wasn't there in the project. What do I do. Thank you. -
How can send variable data from one function to another function in Django
Is this possible to send variable data of one function into another function in Django? Note:- both functions received request as an argument and render in return for example:- in views.py def func1(request): user = 'username' email = 'email' context = {'user':user,'email':email} render return(request,'template.html', ,context) def func2(request): #want to received user and email value in this function render return(request,'template.html') -
Trix rendering html tags such as div and br tags in Django
I am using Trix as a rich text editor in Django, however i run into a problem, when going to save the data, If i type, Hey trix check, it will return trix check backk and it also adds br tags as well, if you want to check it can be seen on www.brogrow.in Can anyone help on it? For login you can use - Username - new & password - Nov@2020 -
CharField of Form not showing up in Django Project
I have created Comment Model for my Project but the CharField is not showing in the LocalHost for some reason. The submit button is working but there is no field to place text. I am trying to know why the CharField is not showing and how to show it in the website? Here is the models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField(max_length=300) def __str__(self): return f"{self.post}-{self.user}-Comment No.{self.pk}" Here is the views: class Comment_create(CreateView): model = Comment fields = ['body'] template_name = 'blog/post_detail.html' form = CommentModelForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug'])) Here is the forms.py class CommentModelForm(forms.ModelForm): body = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Add a comment...'})) class Meta: model = Comment fields = ('body',) Here is the urls.py path('blogs/<slug:slug>/comment/', Comment_create.as_view(), name='comment-post'), Here is the template: <div class="container-fluid mt-2"> <div class="form-group row"> <form action="{% url 'blog:comment-post' post.slug %}" method="post" class="comment-form" action="."> {% csrf_token %} {{ form }} <input type="submit" value="Submit" class="btn btn-outline-success"> </form> </div> </div> -
How to get the windows username with Django web page
How can I get the Windows username of the person running my Django web page? I don't know if and how it matters, but I should note that my site is internal to my company but it's not under my company's domain. Do they need to be on the same domain for security reasons? Thanks. -
ImportError : cannon import name 'path' | django
I'm trying to learn Django and when I tried to run it for the first time, that's the error that I had. PS C:\Users\Alnis\Documents\CS20\lecture3> python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x0000000004067EB8> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 256, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\Alnis\Documents\CS20\lecture3\lecture3\urls.py", line 17, in <module> from django.urls import path ImportError: cannot import name path I tried to update django, but that did nothing. Can somebody help me please ? -
Resize bokeh plot from CustomJS
Resize bokeh plot from CustomJS. window.setXYDimension = function (width, height) { fig.plot_width = width; fig.plot_height = height; console.log({fig}); fig.reset(); //reset doesn't exist fig.resize(); //resize doesn't exist fig.layout(); //layout doesn't exist }; Any help is appreciated. -
Why is my Django Server Responding with a List of nulls to a POST?
I am implementing a multi-file upload. The file upload works so far, i.e. I can select multiple files and send them to my server via postman. In the Django admin panel the files are displayed correctly. But even if the files are sent to the server and saved, the server's response is a list of nulls. The length of this list depends on the size of the last file. That is, the larger the file, the more nulls are displayed (see figure). Normally I would expect the server to answer with the created data. How can I actually achieve that the server answers me with the data it created and not with a list of nulls. Model: class Photo(models.Model): image = models.FileField(upload_to='audio_stories/') Serializer: class FileListSerializer (serializers.Serializer): image = serializers.ListField( child=serializers.FileField( max_length=1000, allow_empty_file=False, ) ) def create(self, validated_data): image=validated_data.pop('image') for img in image: print(img) photo=Photo.objects.create(image=img,) print(photo) return photo View: class PhotoViewSet(viewsets.ModelViewSet): serializer_class = FileListSerializer parser_classes = (MultiPartParser, FormParser,) http_method_names = ['post', 'head'] queryset=Photo.objects.all() -
How to add ruby to my python django app on heroku?
I am trying to deploy a python with django on heroku and use ruby with bundler. I am following this tutorial to add the nginx buildpack : https://elements.heroku.com/buildpacks/hq-mobile/v3-nginx-buildpack I managed to set the config var for ruby bundler using this: heroku config:add GEM_PATH=vendor/bundle/1.8 The problem is when the app is deployed I get this error: bin/start-nginx: line 37: bundle: command not found -
Django Import-export TypeError: clean() got an unexpected keyword argument 'row'
When importing csv files it deliver the following error. I think this is related to the date widget? This is an example of my csv: " , ICE, France, EST Current, HD, 4.59, EUR, GROSS, 01/01/08, , test" Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/import_export/resources.py", line 662, in import_row self.import_obj(instance, row, dry_run) File "/usr/local/lib/python3.6/site-packages/import_export/resources.py", line 516, in import_obj self.import_field(field, obj, data) File "/usr/local/lib/python3.6/site-packages/import_export/resources.py", line 499, in import_field field.save(obj, data, is_m2m) File "/usr/local/lib/python3.6/site-packages/import_export/fields.py", line 110, in save cleaned = self.clean(data) File "/usr/local/lib/python3.6/site-packages/import_export/fields.py", line 66, in clean value = self.widget.clean(value, row=data) TypeError: clean() got an unexpected keyword argument 'row' Resource is build like this As I said, I can't be sure what is the widget that is raising this error. That's why I paste all the Class here: (I know is too long) class retailResource(ModelResource): client = fields.Field( column_name='client', attribute='client', widget=widgets.ForeignKeyWidget(Client, 'name') ) country = fields.Field( column_name='country', attribute='country', widget=widgets.ForeignKeyWidget(Country, 'name') ) catalogue_type = fields.Field( column_name='catalogue_type', attribute='catalogue_type', widget=widgets.ForeignKeyWidget(CatalogueType, 'name') ) currency_in_report = fields.Field( column_name='currency_in_report', attribute='currency_in_report', widget=widgets.ForeignKeyWidget(Currency, 'iso3_code') ) start_date = fields.Field( attribute='start_date', widget=fields.Field( attribute='start_date', column_name='start_date', widget=widgets.DateWidget('%d/%m/%Y')) ) end_date = fields.Field( attribute='end_date', widget=widgets.DateWidget('%d/%m/%Y') ) class Meta(): model = RetailPrice fields = ('id','client', 'country', 'catalogue_type','quality','gross_retail_price', 'currency_in_report','reported_as','start_date','end_date','comments',) export_order = ['id','client', 'country', 'catalogue_type','quality','gross_retail_price', 'currency_in_report','reported_as','start_date','end_date','comments'] import_id_fields = ('id',) … -
AttributeError 'int' object has no attribute 'get'
I am getting an error that says: AttributeError at /series/ 'int' object has no attribute 'get' I don't know why and what is causing this error My models.py class Series(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) SeriesName = models.CharField(max_length=70, default="") NoEpisodes = models.PositiveIntegerField(default=0) EpisodesWatched = models.PositiveIntegerField(null=True, blank=True, default=0) CoverImage = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Series" My views.py: def seriesview(request): form = SeriesForm(request.POST or None) if request.method == 'POST': form = SeriesForm(request.POST) if form.is_valid(): # error raised here print("Form is valid") return render(request, 'series.html', {'form': form}) My forms.py: class SeriesForm(forms.ModelForm): class Meta: model = Series fields = ('SeriesName', 'NoEpisodes', 'EpisodesWatched', 'CoverImage') labels = { "SeriesName": "Series Name:", "NoEpisodes": "Number of episodes:", "EpisodesWatched": "Episodes watched:", "CoverImage": "Add a cover image:", } def __init__(self, *args, **kwargs): super(SeriesForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): if visible.field.widget.input_type == 'file': visible.field.widget.attrs['class'] = 'form-control-file' continue visible.field.widget.attrs['class'] = 'form-control' def clean(self): episodes = self.cleaned_data['NoEpisodes'] episodeswatched = self.cleaned_data['EpisodesWatched'] if episodeswatched > episodes or episodes < episodeswatched: raise forms.ValidationError('Error creating series, Episodes watched can\'t be greater than number of episodes') return episodeswatched and one line is highlighted by django when I get the error: if form.is_valid(): # this line is in views.py If you need any other information comment …