Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django mongoengine unable to login using correct password
I am using mongoengine with django rest framework and default User model settings.py has : AUTHENTICATION_BACKENDS = ( 'mongoengine.django.auth.MongoEngineBackend', ) SESSION_ENGINE = 'mongoengine.django.sessions' SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer' MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User' AUTH_USER_MODEL = 'mongo_auth.MongoUser' views.py has : from django.contrib.auth import login, logout from mongoengine.django.auth import User @csrf_exempt def log_in(request): js = json.loads(request.body) try: #user = User.objects.get(username=request.POST['username']) user = User.objects.get(username=js['username']) print user.username print user.password print js['username'] print js['password'] print user.password==js['password'] #if user.check_password(request.POST['password']): if user.check_password(js['password']): user.backend = 'mongoengine.django.auth.MongoEngineBackend' user = authenticate(username=js['username'], password=js['password']) login(request, user) request.session.set_expiry(60 * 60 * 1) # 1 hour timeout return HttpResponse(user) else: return HttpResponse('login failed') except DoesNotExist: return HttpResponse('user does not exist') except Exception: return HttpResponse('unknown error') with the correct password, I am getting login failed. What can be the reason for this? -
Issue styling the image upload button
Basically I am trying to style my image upload form field. By following guidance from another question from here I ended up doing this: document.getElementById("uploadBtn").onchange = function () { document.getElementById("uploadFile").value = this.value; }; .fileUpload { position: relative; overflow: hidden; margin: 10px; } .fileUpload input.upload { position: absolute; top: 0; right: 0; margin: 0; padding: 0; font-size: 20px; cursor: pointer; opacity: 0; filter: alpha(opacity=0); } <input id="uploadFile" placeholder="Choose File" disabled="disabled"/> <div class="fileUpload btn btn-primary"> <span>Upload</span> <input id="uploadBtn" type="file" class="upload"/> </div> This works as it should but how do I bind it to my django form field ? If I replace class attribute inside the input from "upload" to "profile_pic", the main upload button will appear, which is bad. Or am I doing it wrong ? I just need the information to be passed to my form. photo = forms.ImageField(required=True, widget=forms.FileInput(attrs={'class': 'profile_pic'})) -
How to handle django dabase migrations with captain duck duck?
machine: docker 1GB when i try manage.py migrations (after a successful makemigrations) in my already deployed captain-definition, i get this error, Probably because migrations are not synced in my git repo and django cant detect which migrations are already applied to the database without the migrations folder Captain duck duck seems to destroy any changes to the file system in my docker conatiner and hence the migrations folder is not available after a restart. System check identified some issues: WARNINGS: Users.CustomUser: (auth.W004) 'CustomUser.phone_number' is named as the 'USERNAME_FIELD', but it is not unique. HINT: Ensure that your authentication backend(s) can handle non-unique usernames. Operations to perform: Apply all migrations: Exams, Users, account, admin, auth, contenttypes, sessions, sites, socialaccount Running migrations: Applying Exams.0002_auto_20180309_1911...Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column "owner_id" of relation "Exams_topic" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", … -
Passing a url variable after submitting a form
I'm working on a simple website where I can register isolated information systems in a simple database, and assign harddisks to each system using ForeignKeys. When deleting a system from the database, I use a DeleteView. In the DeleteView: To check if there are any harddisks associated with the system I use custom method. If no harddisks are found, it displays the DeleteView form. If there are any, a list of the relevant harddisks is displayed instead of the form, with a link to the UpdateView of each individual harddisk. I want to be able to click a link to one of these harddisk, make changes to it in the UpdateView, then be redirected back to the DeleteView to "check the list again". This is what I have so far (Media = harddisk/storage media) class MediaEdit(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = Media form_class = MediaForm template_name = 'dsl/media/media_create-edit.html' success_message = 'Media successfully changed!' def get_success_url(self): return reverse('dsl:media_edit', kwargs={'pk': self.get_object().id}) def get_context_data(self, **kwargs): context = super(MediaEdit, self).get_context_data(**kwargs) context['action'] = reverse('dsl:media_edit', kwargs={'pk': self.get_object().id}) next_url = self.request.GET.get('next', 'None') context['next_url'] = next_url return context I have tried using the "next_url" variable in my UpdateView form: {% if next_url %} <form class="" action="{{ next_url }}" method="post"> … -
Syntax error in "manage.py" file - django 2
I do not understand what the problem is but I keep getting a syntax error for the "from exc" line even though I did not alter the code. I have checked for un-closed parentheses and quotes and indentation look right to my beginner's eye. The issue is that this is the out-of-the-box code for the Django 2.0 virtual environment so I can only assume Sublime somehow formatted it wrong when the file was dragged into the text editor? import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) -
in my project how can i set http session tracking login time for 30 second only
In my project i want to set HTTP Session tracking for 30 second after 30 second user should be logout automatically, if user is not doing any think and also one more condition after login if user click on back button of my browser and than forward button of my browser than it must be transfer on login page for entering username and password. In my project i want to set HTTP Session tracking for 30 second after 30 second user should be logout automatically, if user is not doing any think and also one more condition after login if user click on back button of my browser and than forward button of my browser than it must be transfer on login page for entering username and password. In my project i want to set HTTP Session tracking for 30 second after 30 second user should be logout automatically, if user is not doing any think and also one more condition after login if user click on back button of my browser and than forward button of my browser than it must be transfer on login page for entering username and password. Views.py from django.shortcuts import render from django.http import … -
I need an explanation on how Django mobile apps work
So I want to create a mobile app with Django, that is basically like a sort of online store, I'm still very confused on how the process would work, but this is what I understand so far : The backend would be built with Django, which would manage users and data and all that, and then I would use MySQL to store the products and their relevant information, and Django would access that database and display the products as programmed. But then comes the matter of the interface of the app. I know that Django can display HTML pages so could those html pages act as the interface to the app, and how would I be able to achieve that on a mobile platform ? I know these kind of questions are not suitable for the stack overflow format but tbh I don't know where else to go so thanks. -
Can you help me find the error for querry in django?
So I am trying to make a search function which looks through the database to look for similar words in django database. My views.py: def result(request): # Shows the matched result request.GET.get('q') incubators = Incubators.objects.all() check = Incubators.objects.filter(incubator_name__icontains="q") return render(request, 'main/results.html', {'incubators':incubators,'check': check}) The problem is that my HTML page is not showing any result matching to the database when I know there is. Its just a black HTML page. {%extends 'main/base.html'%} {%block content%} {%for inc in check%} <p>{{inc.incubator_name}} <br> {{inc.city_location}}</p> <hr> {%endfor%} {%endblock%} I am new to Django and really confused what I am doing wrong here. -
Prevent server from interpreting uploaded files
I have a FileField where the user is meant to upload an image or video for their post: image = models.FileField(null=True, blank=True) Is there any measure I need to take to prevent users from uploading hostile files? Such as .php files? Or does Django's security already prevent that? -
"ailed to create process" when make new virtual environtment python
i using python 3.6.4 and only use it. I have install pip, v i r t u a l e n v, and v i r t u a l e n v w r a p p e r - w i n, but when i make new virtual environment using v i r t u a l e n v d j a n g o - e x a m p i have try use m k v i r t u a l e n v d j a n g o - e x a m p too, but both of it not worked, i have check it with pip freeze the result is good, i have installed all of them, but why i cannot make new virtual environment (i got message "failed to create process")? -
It is possible to check in django rest query filter using .upper()
How to compare value in db with request.data after changing both to upper case str_code = CustomerAccount.objects.filter(strAccountCode.upper() = request.data['strAccountCode'].upper(),chrDocumentStatus='N') -
What is the effective way of managing threads?
I am building a ToDo web-app in Django. This app will create a reminder and will send a text-based SMS to the given phone number. So I decide the given below algorithm: Take user input of Time and Reminder. Validate the input. If valid, store in database and create a thread for sending SMS. Else, display an error message. This algorithm was working well until I came across an article in which it has said that we should not use Threads in web app cause it will use a lot of resources. This is true for my app because I am planning to use my app in such a way that a user can create only 100 reminders. This will create 100 threads on my app per user. I decided to develop a Priority Queue which will insert these 100 threads based on the priority of Time user has provided as input. Now my question is : Does creating a Thread and putting it in a Queue decreases the load on CPU or not? If not, what is the alternative? NOTE : I already know about CELERY and REDIS. But I decided to go this way because I want to … -
Django - Simple User Register not working [Not saving to DB]
I have simple user registration page, but its not saving to the database. Issue: Register form displays, upon clicking submit button, doesn't do anything! Stays there (it should show a HttpResponse('User Registered') And save to db I've know I'm missing something, but what? ideas please. Views.py from django.shortcuts import render from django.views.generic import CreateView from website.forms import RegisterUserForm from django.http import HttpResponseForbidden # Create your views here. class RegisterUserView(CreateView): form_class = RegisterUserForm template_name = "account/register.html" # Overide dispatch func - check if the user is authenticated or return forbidden def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): return HttpResponseForbidden() return super(RegisterUserView, self).dispatch(request, *args, **kwargs) # Overide form valid method behaviour def form_valid(self, form): # False commit - don't save to db, locally cleaning users password first user = form.save(commit=False) user.set_password(form.cleaned_data['password']) user.save(); # Change to redirect - later one! return HttpResponse('User Registered') def Home(request): return render(request, 'account/home.html') Register.html {% extends 'base.html' %} {% block title %} Register {% endblock %} {% block head %} {% load static %} <link href="{% static 'forms.css' %}" rel="stylesheet"> {% endblock %} {% block heading %} <h1>Register</h1> {% endblock %} {% block body %} <div class="bg-contact2" style="background-image: url('images/bg-01.jpg');"> <div class="container-contact2"> <div class="wrap-contact2"> <form class="contact2-form validate-form"> <span class="contact2-form-title"> … -
Download a file using Django rest framework by authenticating the user
I am working on a project where I am using Django as the back end. I am working with Django rest framework, and I have an API to download a File. @detail_route(methods=['GET'], permission_classes=[IsAuthenticated]) def test(self, request, pk=None): try: ticket = Ticket.objects.get(id=pk, user=request.user) file_path = ticket.qrcode_file.path if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="image/jpeg") name = "%s %s %s %s.jpg" % (ticket.show.title, datetime.strftime(ticket.show.date_time, "%H_%M_%p"), datetime.strftime(ticket.show.date_time, "%d %B %Y"), ticket.id) response['Content-Disposition'] = "attachment; filename=%s" % name.replace(" ", "_") return response return Response({'error': 'Ticket doest not belong to requested user.'}, status=status.HTTP_403_FORBIDDEN) except Ticket.DoesNotExist as e: return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND) On the front-end I am using Nuxtjs (ssr for vuejs). This is a little snippet of code, where a user can download the file by clicking a link of target blank.: <a class="downloadBtn" target="_blank" :href="`${baseURL}/payments/api/tickets/${ticket.id}/download_ticket/`">Download e-ticket</a> The web app is running on Nuxtjs server (localhost:3000) and Django server is running on localhost:8000, only the API is used to communicate between the Nuxtjs and Django by using the auth token. When I click the download link it opens up a new tab and make a request from that new tab, where no token is passed with the request. And since, the django … -
DJango form.is_valid() function only clean the first form in an if statement
I notice that forms.is_valid only clean form for the first form in an if statement. Example code : if not user_detail_form.is_valid() and not user_location_form.is_valid(): return redirect('account:profile') Accessing cleaned data of user_detail_form works but when accessing cleaned data of user_location_form, it throws an error stating that cleaned_data does not exists. My question is What causes this? and is there a workaround for this? -
Django Nginx Proxy - Static content served with wrong mime type
I have a Django website setup on server using the following guide: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-local-django-app-to-a-vps Gunicorn is the server for the site, with nginx acting as a reverse proxy for serving static content. For some reason css and image files are being sent back to the browser with the "text/html" mime type in the response. How do I fix this? nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; default_type application/octet-stream; include /etc/nginx/mime.types; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } sites-available/project (Project configuration file) server { server_name ip_address; # actual ip is hidden here. access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location /static/ { autoindex on; alias /webapps/dragvenv/static/; } … -
Heroku Deployment - PermissionError: [Errno 13] Permission denied: '/etc/passwd-'
Can anyone help me with this error? I don't what's wrong with the code. is it a database credentials error? Is it an application code error? Is it a Linux/Unix related error? This is my first time to deploy my application on Heroku but I got this error message: PermissionError: [Errno 13] Permission denied: '/etc/passwd-' python ph_dorms/manage.py collectstatic --noinput Traceback (most recent call last): File "ph_dorms/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 353, in copy_file with source_storage.open(path) as source_file: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 33, in open return self._open(name, mode) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 218, in _open return File(open(self.path(name), mode)) PermissionError: [Errno 13] Permission denied: '/etc/passwd-' ! Error while running '$ python ph_dorms/manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, failed to compile Python … -
Connection error while indexing in Elastic search in aws
I want to use elastic search from aws for my usage. Following code works totally fine in my local elastic search but always give error when trying to connect to aws elasticsearch service. I am using python 2.7, django 1.10 and elastic search 5.1.1. Following is the error ConnectionError(HTTPSConnectionPool(host='https', port=443): Max retries exceeded with url: //search-test-abc-jlpfzhi64qcrhhqxycov5rzgcq.ap-south-1.es.amazonaws.com/:443/test-index/tweet/1 (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f1e2e5e2090>: Failed to establish a new connection: [Errno -2] Name or service not known',))) caused by: ConnectionError(HTTPSConnectionPool(host='https', port=443): Max retries exceeded with url: //search-test-abc-jlpfzhi64qcrhhqxycov5rzgcq.ap-south-1.es.amazonaws.com/:443/test-index/tweet/1 (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f1e2e5e2090>: Failed to establish a new connection: [Errno -2] Name or service not known',))) Also, here is the code that i am using host = AWS_ELASTIC_SEARCH_URL awsauth = AWS4Auth(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ELASTIC_SEARCH_REGION, 'es') es = Elasticsearch( hosts=[{'host': host, 'port': 443}], http_auth=awsauth, use_ssl=True, verify_certs=True, connection_class=elasticsearch.RequestsHttpConnection ) doc = { 'author': 'kimchy', 'text': 'Elasticsearch: cool. bonsai cool.', 'timestamp': datetime.now(), } res = es.index(index="test-index", doc_type='tweet', id=1, body=doc) It is giving error in last line. Also I have made full access to the elastic search url. -
id missing for session after loaddata from sqlite3 to mysql
I'm having this error message after running dumpdata command from sqlite3 database and using loaddata to store the json fixtures into mysql database. I can't seem to figure out why. It work fine on the sqlite3 database but errors on the mysql database. Please any help will be greatly appreciated. I checked the mysql database and there is no id field present in the django_session table I've ran makemigrations and migrate command and these don't work. Just in case anyone wants to post these as answers. Cannot resolve keyword 'id' into field. Choices are: expire_date, session_data, session_key I'm running python 3 and Django 1.10 -
How to show my data inside the template code?
I'm trying to display my content to the template page by django. here is the template code: <html> <body> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/projectapp/{{question.id}}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% elae %} <p>No polls are available.</p> {% endif %} </body> </html> here view.py page code: def index(request) latest_question_list = Question.object.order_by('-pub_date')[:5] template = loader.get_template('projectapp/index.html') context = { 'latest_question_list':latest_question_list, } return HttpResponse(template.render(context, request)) -
How to read a text file from within Django view function?
I have the following code in one of my view functions: def results(request): data_file = open('data.txt', 'r') data = data_file.read() context = {'rooms': data} return render(request, 'javascript/results.html',context) The file 'data.txt' is located in the same folder as my "views.py". However, I am getting "FileNotFoundError at /results" error. My 'results.html' looks like this: <p> {{ rooms }}</p> What is the correct way to pass data from a text file to a Django view function, and then display the data in the template? Should I use static files instead? -
Django edit user profile after success registration
I try to configure the project in such a way that the user goes through the primary registration, then logged in and from the personal cabinet could add additional information about himself. There are no problems with the initial registration, but when you try to change and supplement the information, there are no changes. My UserProfile model: models.py from customuser.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=True) surname = models.CharField(max_length=50, blank=True, default = None) avatar = models.ImageField(upload_to = 'images/profile/%Y/%m/%d/', blank=True, null=True) position = models.ForeignKey('Position',blank=True, default=None) role = models.ForeignKey('Role', blank=True, default=None) company = models.ForeignKey('Company',blank=True, default=None) status = models.ForeignKey('Status', blank=True, default=None) @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() forms.py from django import forms from django.forms import ModelForm from client.models import Profile class UserProfileForm(ModelForm): class Meta: model = Profile exclude = ['user'] views.py from customuser.models import User from client.models import Profile from .forms import UserProfileForm def edit_user(request, pk): user = User.objects.get(pk=pk) form = UserProfileForm(instance=user) if request.user.is_authenticated() and request.user.id == user.id: if request.method == "POST": form = UserProfileForm(request.POST, request.FILES, instance=user) if form.is_valid(): update = form.save(commit=False) update.user = user update.save() return HttpResponse('Confirm') else: form = UserProfileForm(instance=user) return render(request, 'client/edit.html', {'form': form}) -
django URLconf current path didn't match
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ [name='index'] admin/ The current path, polls/, didn't match any of these. My code is... from (app)polls urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] from (project)mysite urls.py from django.urls import include, path from django.contrib import admin urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] from views.py project file from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello world, you are at the polls index.") -
Django REST Framework - TypeError when using POST method
I am new to Django and trying to write an API using Django REST framework to be able to pass some data back and forth, using http POST method (either in JSON or other formats.). My models.py looks like this : from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.postgres.fields import ArrayField # Create your models here. class Config_Table(models.Model): entity_name = models.TextField(primary_key=True) category = models.TextField() description = models.TextField(blank=True,default='') class UserProfile(AbstractUser): "The Profile of a user with details are stored in this model." username = models.TextField(primary_key=True, max_length=11) first_name = models.TextField(max_length=50,blank=True,default='') last_name = models.TextField(max_length=100,blank=True,default='') # The default username is phone number (Ver. 1.0) phone_number = models.TextField(max_length=11,default=str(repr(username))) avatar = models.ImageField(default='../Static/1.jpeg') GENDER_CHOICES = ( ('M','Male'), ('F','Female'), ) gender = models.CharField(max_length=1,choices=GENDER_CHOICES, default='M') city = models.TextField(max_length=25, blank=True, default='NY') interests = models.ManyToManyField(Config_Table) def __str__(self): return str(UserProfile.username) Config table has been populated with some intitial data. My views.py looks like this : @api_view(['GET', 'POST']) def user_list(request): """ :param request: :return: List of all users, or create a new user """ if request.method == 'GET': userprofiles = UserProfile.objects.all() target_users = [] for user in userprofiles.iterator(): if user.is_superuser == False: target_users.append(user) serializer = UserProfileSerializer(target_users ,many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': # data = JSONParser.parse(request) serializer = UserProfileSerializer(data=request.data) … -
django-paypal suddenly stop recieving
I'm working on Paypal integration to my Django project using Django-Paypal package.I have successfully configured everything and it was working but suddenly the signals form PayPal has stopped. What issue can be occurred? Here's what i have done: from view.py: def payment_process(request): minutes = int(request.user.tagging.count()) * 5 testhours = minutes / 60 hours = str(round(testhours, 3)) # pdb.set_trace() # What you want the button to do. invoice = generate_cid() userInfo = { "name": str(request.user.first_name + ' ' + request.user.last_name), "hours": str(hours), "taggedArticles": str(request.user.tagging.count()) } paypal_dict = { "business": settings.PAYPAL_RECEIVER_EMAIL, "item_name": "Certificate of Completion from Nami Montana", "custom": userInfo, "invoice": str(invoice), "amount": "5.00", "notify_url": "https://6fd5e31b.ngrok.io/users/paypal/", # "return_url": "https://6fd5e31b.ngrok.io/users/profile/", "cancel_return": "https://6fd5e31b.ngrok.io/users/cancel/", } print(paypal_dict) # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form} return render(request, "users/generateCert.html", context) from urls.py: urlpatterns = [ url('^paypal/', include('paypal.standard.ipn.urls')), url('^profile/buildCertificate/$', views.CertificateProcess.as_view(), name='certificate'), url('^cancel/$', views.payment_canceled, name='cancel'), url('^done/$', views.payment_done, name='done'), url('^process/$', views.payment_process, name='payment'), ] From models.py: def show_me_the_money(sender, **kwargs): ipn_obj = sender custom = ipn_obj.custom # Undertake some action depending upon `ipn_obj`. if ipn_obj.payment_status == ST_PP_COMPLETED: print('Get success signal') user_info = ast.literal_eval(ipn_obj.custom) if int(user_info['taggedArticles']) > 11: # here i need to generate and send a pdf file to the user in a new tab pass else: print('Get fail …