Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how to display all users that are present?
I have created an attendance system in Django but I cannot seem to retrieve all users that are currently present. My code is displayed below: Models: class Meta: model = User fields = ("username", 'email', 'password1', 'password2') class is_Present(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(default=datetime.date.today) is_present = models.BooleanField(default=False) class clocked_Time(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(default=datetime.date.today) time = models.DateTimeField(null=True, blank=True) signed_out = models.BooleanField(default=False) views.py: # Displays admin attendance portal functions def attendance_portal(request): if not request.user.is_authenticated: messages.warning(request, f'Please sign in to mark attendance out') return redirect('login') elif not request.user.is_superuser or not request.user.is_staff: messages.warning(request, f'Must be admin to access this feature') return redirect('home') elif request.user.is_superuser: count_employees_all = count_employees() # shows count of employees present_employee_all = present_employees() # shows count present employees today present_employee_all_week = present_week_employees() # shows count present employees in last 7 days # Gets the employees present today today = datetime.today() # Gets employees displayed and paginated user = get_user_model() user_list = user.objects.all() p = Paginator(is_Present.objects.filter(date=today).filter(is_present=True).select_related('user').values('user__username'), 5) page = request.GET.get('page', 1) users = p.get_page(page) try: users = p.get_page(page) # returns the desired page object except PageNotAnInteger: # if page_number is not an integer then assign the first page users = p.page(1) except EmptyPage: # if page is empty … -
Django confuses same DB name runs on different ports
I am running two different MongoDB on different ports and configured DB router to find the proper database. Also, the DB name and tables are the same in both. Assume that I have 2 app first_app and second_app where the DB connection names are the same as well. settings.py ... 'first_app': { 'ENGINE': 'djongo', 'NAME': os.environ.get("FIRST_DB_DATABASE", 'mymongodb'), 'CLIENT': { 'host': os.environ.get("FIRST_DB_HOST", "localhost"), 'port': 27019, 'username': os.environ.get("FIRST_DB_USER"), 'password': os.environ.get("FIRST_DB_PASSWORD"), } }, 'second_app': { 'ENGINE': 'djongo', 'NAME': os.environ.get("SECOND_DB_DATABASE", 'mymongodb'), 'CLIENT': { 'host': os.environ.get("SECOND_DB_HOST", "localhost"), 'port': 27020, 'username': os.environ.get("SECOND_DB_USER"), 'password': os.environ.get("SECOND_DB_PASSWORD"), } }, ... and here is the reason why app names are the same as connection names to find proper DB in router based on app name: db_router.py class MultiDatabaseRouter: app_labels = {'first_app', 'second_app'} mongodb_app_labels = {'first_app', 'second_app'} def db_for_read(self, model, **hints): if model._meta.app_label in self.app_labels: return model._meta.app_label return None def db_for_write(self, model, **hints): if model._meta.app_label in self.app_labels: return model._meta.app_label return None def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): """Do not migrate MongoDB.""" if app_label in self.mongodb_app_labels: return False return None Also, I have the same Models in both apps using the same db_table. But, when I retrieve data in Django admin the result comes always … -
docs2pdf unable to convert the pdf
Traceback (most recent call last): File "C:\Users\jaint\Desktop\student_internship_backend\administration\views.py", line 3546, in deployCandidate response = pdf_genrator(candidate_name, application_no, adress, office_name, hod_dm, dept_dist) File "C:\Users\jaint\Desktop\student_internship_backend\administration\utils.py", line 356, in pdf_genrator convert("template/Name.docx") File "C:\Users\jaint\AppData\Local\Programs\Python\Python310\lib\site-packages\docx2pdf_init_.py", line 106, in convert return windows(paths, keep_active) File "C:\Users\jaint\AppData\Local\Programs\Python\Python310\lib\site-packages\docx2pdf_init_.py", line 19, in windows word = win32com.client.Dispatch("Word.Application") File "C:\Users\jaint\AppData\Local\Programs\Python\Python310\lib\site-packages\win32com\client_init_.py", line 117, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx) File "C:\Users\jaint\AppData\Local\Programs\Python\Python310\lib\site-packages\win32com\client\dynamic.py", line 106, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Users\jaint\AppData\Local\Programs\Python\Python310\lib\site-packages\win32com\client\dynamic.py", line 88, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance( pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None) 2022-03-09 19:36:49,588 administration.views INFO < =================== End - Deploy Candidate To Office =================== > -
Django missing data from database
Having a problem that shouldn't appear. Created a django project. all the steps on windows OS. Now when went to do everything the same on Ubuntu 20.04 then my index.html is not displaying any data from database even if there is a data ( i checked ) Html:: <!DOCTYPE html> <html lang="en"> <head> <title>Django CRUD Operations</title> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <table class="table table-striped"> <thead> <tr> <th>Flight ID</th> <th>Aircraft</th> <th>Registration</th> <th>Latitude</th> <th>Longtitude</th> </tr> </thead> <tbody> {% for c in flight %} <tr> <td>{{c.id}}</td> <td>{{c.aircraft}}</td> <td>{{c.registration}}</td> <td>{{c.latitude}}</td> <td>{{c.longtitude}}</td> </tr> {% endfor %} </tbody> </table> </div> </body> </html> Views.py:: from .models import Flights from django.shortcuts import render def show(request): flights = Flights.objects.all() return render(request,"show.html",{'flight':flights}) Database is connected. Any ideas? Maybe Ubuntu 20.04 has something that have to do differently like windows os? -
Passing a variable from views.py to models.py django
I am still very new to programming. My issue is this I have 2 models, one for Sale and one for Agent. now to render each Agent and the sales they made(with different attributes) uniquely I needed to write model methods under my sale model to allow to me to call them in the template. Now my issue is this, I want to be able to render that exact thing but by what dates the user chooses, I have tried manually doing this through my project files and it works, but I want to know is it possible to have those values moved from user into my method? What I mean is there is a basic form in the nav bar that allows the person to choose a from and to date, but those values I am not sure how to pass them into my models.py under the method where I need this date range applied. I will show an example. #this is my view that grabs relevant dates def asearch_stats(request): if request.method == 'POST': from_date = request.POST['from'] to_date = request.POST['to'] return render(request,"Sales/salesfilter.html",{"flookup":flookup}) # this is my model with the methods I'm referring to below: class SalesAgent(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True,related_name="sauser") … -
Why am I not getting CSRF warning from django?
So usually when you try to make a POST request to the server in Django without CSRF token it gave you this page but for the past 3 months I've been playing with DRF and custom user model and I didn't even realized until now that I've actually not been getting that error despite not using CSRF in my postman header. There's also some more details made it more confusing to me first I made a post request to TokenObtainPairView from djangorestframework_simplejwt containing username and password (I'm using base user model) for login and it was successful Right after that I made another post request to add a title (a model that only have 1 field which is a charfield) and then it gave me CSRF warning I also have an almost identical project to this the only difference being the other projects uses custom user model and it never gave me any CSRF warning. So I suspect this has something to do with the user model somehow So to summarize my question: Why doesn't it gave me CSRF warning in the first POST request? does this have anything todo with custom user model? if so what am I missing? … -
Django DRF: Take extra input from user using serializer but not present in the model
I have one ModelSerializer class which is used for user input & validation. I am using it with a ModelViewset which automatically creates a new entry in the database using the serializer. Now what I want to do is that I want to have a extra field in the serializer say roles which will be given by the user. It is an array of roles for a user. So I wrote my serializer like this, class UserCreateSerializer(serializers.ModelSerializer): """ Serializer to create new user """ class Meta: model = User fields = ["name", "email", "is_active", "roles"] read_only_fields = ['roles'] roles = serializers.MultipleChoiceField(choices=[(e.name,e.value) for e in AuthGroup]) def validate_roles(self, value): if not value: raise ValidationError(detail=constants.NAMED_FIELD_REQUIRED.format(field="roles")) My model looks like this, class User(AbstractBaseUser, PermissionsMixin): class Meta: db_table = "auth_user" app_label = "users" USERNAME_FIELD = "email" REQUIRED_FIELDS = [] name = models.CharField(max_length=255, null=True) email = models.EmailField("email address", unique=True, null=True) is_active = models.BooleanField(default=True) is_superuser = None is_admin = None is_verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() def __str__(self): return self.name or self.email def is_admin(self): return self.groups.filter(name=AuthGroup.ADMIN.name).exists() This is the request body which is coming from user. { "name": "test4", "email": "test4@example.com", "is_active": true, "roles": [ "ADMIN", "OPERATOR" ] } So … -
django 3.2 how to loop a field with foreign-keys
I'd like to loop a field based from the Question Model. Here are my models.## Heading ## models.py from django.db import models from django.db.models.deletion import CASCADE from django.conf import settings class Question(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=50, unique=True) question = models.CharField(max_length=255, unique=True) class Declaration(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='declarations', on_delete=models.CASCADE) class Checklist(models.Model): id = models.BigAutoField(primary_key=True) declaration = models.ForeignKey(Declaration, related_name='checklist_declaration', on_delete=models.CASCADE) question = models.ForeignKey(Question, related_name='checklist_question', on_delete=models.CASCADE, limit_choices_to={'is_active': 'True'}) is_yes = models.BooleanField() and my forms.py from django.utils.safestring import mark_safe from django import forms from declaration.models import Checklist, Question class HorizontalRadionRenderer(forms.RadioSelect): def render(self): return mark_safe(u'\n'.join([u'%s\n' % w for w in self])) class ChecklistForm(forms.ModelForm): is_yes = forms.TypedChoiceField( coerce=lambda x: x == True, choices=((True, 'Yes'), (False, 'No')), widget=forms.RadioSelect() ) class Meta: model = Checklist fields = ['is_yes'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) questions = Question.objects.filter(group='symptom') for q in questions: self.fields['question_id'] = q.id and here is my expected output enter image description here I dunno how to do it in the forms.py since django's only way to validate fields is through forms. -
sprite.svg not displaying icons when deployed to heroku but working locally (Django, Heroku, SVG)
I am coding a landing page using django, html, css. I have a sprite.svg file containing different icons(svg drawings wich can be accessed using "" for instance). The sprite.svg file is located in my static file. When I launch the page on my local server the icons appear with no problem. When I deploy to heroku the icons are not showing. Could you please help me with this problem? The architecture is the following django project -----main app ----------settings.py ----------urls.py -----second app -----static ----------css ----------img ---------------sprite.svg ----------js -----templates ----------secondapp ---------------index.html -----manage.py -----Procfile The settings.py file: Django settings for leadinsightmarketing project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, "templates") STATIC_DIR = os.path.join(BASE_DIR, "static") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-aorn6ipmi+r4pai&^e^edrn)v^80*q8!=x2=99a%rd4^9p6qcc' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost', '127.0.0.1', … -
After I made a migration I get this error RelatedObjectDoesNotExist at /admin/login/ User has no profile
I just start to learn django. I want to creat a bookmanager. First time I creat Model Book, after this I creat users and after this I create another model Categories. After this migration I get the error RelatedObjectDoesNotExist at /admin/login/ User has no profile. I can acces the old users profile, but I can not create new and can not acees it's profile. Also I can not acees the admin. How can I resolve the problem. models.py from django.contrib.auth.models import User from PIL import Image # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='person.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 500 or img.width > 500: output_size = (500, 500) img.thumbnail(output_size) img.save(self.image.path) signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwards): user = instance if created: Profile.objects.create(user=user) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwards): instance.profile.save() -
Django Redirect to Second URL
I'm trying to redirect to an custom url as it's coded in the below. However there might be a broken url. Therefore, I like to redirect to an second url in case of error. Is there any way to redirect to an second url in case of an error? page = self.request.POST.get('ex_page') return redirect(page) -
Authenticate users in my django app using an existing ASP.Net IdentityServer login app
I'm trying to authenticate users in my django app using an existing ASP.Net IdentityServer login app. I've seen the documentation has an example for an angular or react(Javascript based app) but not django. Does anyone have some sample code or tutorial that shows how to do in django? I'm new at this. Especially when it comes to the call back. I'm not sure i need to use an open iD client package to do this. Can this work with django? I appreciate any assistance https://identityserver4.readthedocs.io/en/latest/quickstarts/4_javascript_client.html?highlight=authority#add-your-html-and-javascript-files -
Objects created from celery task not firing django post_save signal
I have a celery task that creates a modal object. I'm trying to run some code after the object is created using django post_save signal. but for some reason, the signals are not firing. models.py class Alert(models.Model): description = models.TextField() @receiver(post_save, sender=Alert, dispatch_uid="create_jira_issue") def create_issue(sender, instance, **kwargs): //do something here tasks.py @shared_task def create_alert(): Alert.objects.create() this is how the code looks like. the Objects are being created through the celery task. but it's not triggering the post_save signal. any input is appreciated. -
crontab not getting my current envrioment variables
I want a cron job and everything is already set up and cron is also working but unfortunately, cron is not getting my environment variables. I'm getting my environment variables using os and they're working fine across the project but not in my cron. settings.py SECRET_KEY = os.environ.get('SECRET_KEY') # Cron Jobs CRONJOBS = [ ('* * * * *', 'projects.cron.notifications_cron', '>> /cron/django_cron.log 2<&1') ] crontab -e * * * * /usr/local/bin/python /app/manage.py crontab run 744fbefdbf3ad30bec13 error in log file raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") when I set the SECRET_KEY hardcoded in my settings.py then it is working fine but I want to get it from my environment variables. -
Django all-auth allow users to login allow only business emails
I am using the django-allauth, but it is allowing the all gmail accounts is there any way that we can restrict . only allow business emails like venkatesh@xyz.com instead of all@gmail.com -
Django: select_related query is ignored and the related queries are still executed
I have a menu model with the following fields: class MenuItem(models.Model): name = models.CharField() parent = models.ForeignKey(self, ...) and 2 serializers: class MenuItemSerializer(serializers.ModelSerializer): children = serializer.SerializerMethodField() class Meta: model = MenuItem def get_children(self, data): return MenuItemSerializer(data.children, many=True).data class MenuSerializer(serializers.Serializer): first_menu = serializer.SerializerMethodField() def get_default(self, __): return MenuItemSerializer(MenuItem.objects.filter(...).select_related("parent")), many=True).data I add a select_related to the menu item query, thinking that this should filter the menu items and then retrieve their children as well but there are a lot of queries executed. The first one is the join, but then there are 20+ other where each menu item is retrieved by id. Why isn't this working? -
Django customer user model and connexion
Hello, I'm developing a shop with Django [3.2] I would like to develop a login system for my customers so that they can see their invoices, pay online. I'm looking for documentation on how to manage their password but each time I come across back office user management. I obviously don't want my clients to have access to the back office. Should we make entries in the back office user table for front-end users (customers) and give them no right or should we develop a custom system. Are there things planned in Django for my case? Thanks a lot -
Setting up a working environment and using Django for Python on a Mac
I'm very new to programming especially on a Mac (only started using the terminal today). I need to set up python on this new Mac and setup virtual environments, then use Django to create simple Journal App. I have tried following various guides however I seem to struggle whenever I am asked to edit files as I don't know which files to edit, what their path is etc. I am using zsh not bash which makes a lot of guides redundant and I am using my work MacBook so I cannot change some of those settings. I have installed python 3.10 however my terminal still wants to use the default 2.7 which it had already, I have also installed honeybees, pip, Django, and some various other things these guides have instructed me to do. However I have no idea how this pathing stuff works and every time I try to use Django it essentially just doesn't recognise that I Have it installed. What I'm really asking for is a step by step guide to setting up Python and Working environments, (bearing in mind I'm unclear on how the pathing works) and then to use Django frameworks. If this is poorly … -
How to Integrate Product bundle like amazon buy it with in Django e-commerce site
i have built e-commerce site in django framework i want integrate one feature bundle like amazon buy it with feature is there any idea how to do like table relation and strategy. -
Creating a field in a model that allows multiple entries that is saved to the DB incrementally
I have a model called Handoff, users create a new handoff everyday and will add notes to this handoff to pass over to the next shift. I need a field that can capture user entry and save to the DB, but this field needs to be able to write to the database iteratively. For context, the user will add a new note each time they have something to add to the handoff and this needs to be written to the DB individually (for example, if the field was called new_note, the data should write to the DB and each new note will be saved as new_note_1). These notes will then be collated in a table to present to the next shift during a handoff. What are the best methods for approaching this? -
How to annotate django complex queryset
I want to have count of usecases. I have three models Customer (all users records), Usecase (all usecases records) and CustomerUsecaseAssociation (users and subscriptions records). I want to count the subscriptions of each usecase subscribed by users. and I want the union of two or more usecase if customers subscribed two amoung them. Models Class Customer(models.Model): customer_name = models.CharField(max_lenght=50) class Usecase(models.Model): usecase_name = models.CharField(max_lenght=50) class CustomerUsecaseAssociation(models.Mode): customer = models.ForignKey(Customer, on_delete=models.CASCADE) usecase = models.ForignKey(Usecase, on_delete=models.CASCADE) Preloaded Customer id customer_name 1 abc 2 efg 3 hij Usecase id usecase_name 1 AT 2 BT 3 CT CustomerUsecaseAssociation id usecase customer 1 1 1 2 2 1 3 2 2 4 3 3 Desired Output [ { "usecase_name": "AT-BT", "subscriptions": "1" }, { "usecase_name": "BT", "subscriptions": "1" }, { "usecase_name": "CT", "subscriptions": "1" } ] Notes I will highly recommend annotation if anyone would help me. -
Displaying Django form answers
I couldn't find a solution to this on the Django website, currently I have a form as shown: It saves to my models.py like the following: What I want to do is use the answers from a form and create a new form using the answers of this form as the questions for it, basically recreating this form and reusing the fields but changing the fields and displaying it on a unique URL class InitialForm(forms.Form): Teacher_Name = forms.CharField(label='Teacher Name') Test_Name = forms.CharField(label='Label this test') Subject = forms.CharField(label = 'Subject') Question = forms.CharField(label = 'What is the first question?') Topic = forms.CharField(label = 'What topic is this on?') Option1 = forms.CharField(label = 'What is the first option?') Option2 = forms.CharField(label = 'What is the second option?') Option3 = forms.CharField(label = 'What is the third option?') Option4 = forms.CharField(label = 'What is the fourth option?') Answer = forms.CharField(label = 'Which option is the correct option?', widget=forms.Select(choices=Options)) class Questions(models.Model): testID = AutoSlugField(unique=True) test_label = models.CharField(max_length=1000) teacherName = models.CharField(max_length=1000, null = True) studentID = models.ForeignKey(Student, on_delete=models.CASCADE, null = True) Subject = models.CharField(max_length=1000) Q1 = models.CharField(max_length=1000, null = True) Topic1 = models.CharField(max_length=1000) Option1_Q1 = models.CharField(max_length=1000) Option2_Q1 = models.CharField(max_length=1000) Option3_Q1 = models.CharField(max_length=1000) Option4_Q1 = models.CharField(max_length=1000) AnswerQ1 … -
Django Rest Framework Swagger Documentation
Good day everyone! I am writing a game application using Django and Django rest framework. I have been working on swagger documentation and the main problem is, that autogenerated schema is without any params. Here are examples of my realization: Tempaltes.html {% load static %} <!DOCTYPE html> <html> <head> <title>School Service Documentation</title> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" /> </head> <body> <div id="swagger-ui"></div> <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: "{% url schema_url %}", dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], layout: "BaseLayout" }) </script> Urls.py urlpatterns = [ path('api_schema/', get_schema_view( title='API Schema', version="3.0.0", description='Guide for the REST API', ), name='api_schema'), path('docs/', TemplateView.as_view( template_name='index.html', extra_context={'schema_url': 'api_schema'} ), name='swagger-ui'), path('admin/', admin.site.urls), path('game/', include('GameWorld.urls')) ] Views.py class EventDetailsView(GenericAPIView): serializer_class = serializers.EventDetailsSerializer """ hard_token event_type event_id = """ # schema = ManualSchema(fields=[ # coreapi.Field( # "hard_token", # required=True, # location="query", # schema=coreschema.String() # ), # coreapi.Field( # "event_type", # required=True, # location="query", # schema=coreschema.String() # ), # coreapi.Field( # "event_id", # required=True, # location="query", # schema=coreschema.Integer() # ), # ]) @auth def post(self, request, *args, **kwargs): event_id = request.data.get('event_id') for_user_events = engine_models.Event.objects.filter(owner__pk=request.user.pk) event = for_user_events.get(pk=event_id) return Response(event.data) As you can see in the post. I also tried to … -
How can I display a dynamic list of saved items in my application
I am trying to get Django to show the List of saved inputs from the user on the index page. ( I know my frankenstein-ed code is horrible, it has a lot of tiny bits of things I tried out and didn't get to work. I don't have much programming experience, I'm just trying to get this done for a graded project at my uni. ) The whole project should be a prototype for a food storage application, the user puts the food in via dropdown menu (I will expand it with subcategories e.g. Milk based food => cheese) and should be able to view what is in storage and be able to remove items. Right now I am getting stuck on making the list viewable by the user. Any help is much appreciated! Models.py from django.db import models # Create your models here. class FoodCategory(models.Model): MILK = 'MLK' VEGETABLE = 'VG' MEAT = 'MT' PASTA = 'PST' FRUIT = 'GR' FOOD_CATEGORY_CHOICES = [ (MILK, 'Milk based foods'), (VEGETABLE, 'Vegetables'), (MEAT, 'Meats'), (PASTA, 'Pasta'), (FRUIT, 'Fruits'), ] foodcategory = models.TextField( choices= FOOD_CATEGORY_CHOICES, default= MILK, ) class Meta: verbose_name = 'foodcategory' verbose_name_plural = 'food_list' def __str__(self): return self.foodcategory View.py class IndexView(generic.ListView): … -
PayTm payment gateway showing "KeyError at /payments/response/ 'CHECKSUMHASH'" in django
I am setting up paytm payment gateway for my django webapp. but I have a problem like this KeyError at /payments/response/ 'CHECKSUMHASH' . views.py def VerifyPaytmResponse(response): response_dict = {} if response.method == "POST": data_dict = {} for key in response.POST: data_dict[key] = response.POST[key] MID = data_dict['MID'] ORDERID = data_dict['ORDERID'] verify = Checksum.verify_checksum(data_dict, settings.PAYTM_MERCHANT_KEY, data_dict['CHECKSUMHASH']) if verify: STATUS_URL = settings.PAYTM_TRANSACTION_STATUS_URL headers = { 'Content-Type': 'application/json', } data = '{"MID":"%s","ORDERID":"%s"}'%(MID, ORDERID) check_resp = requests.post(STATUS_URL, data=data, headers=headers).json() if check_resp['STATUS']=='TXN_SUCCESS': response_dict['verified'] = True response_dict['paytm'] = check_resp # response_dict['pack_type'] = data_dict['PACK_TYPE'] return (response_dict) else: response_dict['verified'] = False response_dict['paytm'] = check_resp return (response_dict) else: response_dict['verified'] = False return (response_dict) response_dict['verified'] = False return response_dict @login_required def payment(request): order_id = Checksum.__id_generator__() pack_type = request.GET.get('pack_type') bill_amount = None if pack_type == '1': bill_amount = "199" elif pack_type == '2': bill_amount = "999" data_dict = { 'MID': settings.PAYTM_MERCHANT_ID, 'INDUSTRY_TYPE_ID': settings.PAYTM_INDUSTRY_TYPE_ID, 'WEBSITE': settings.PAYTM_WEBSITE, 'CHANNEL_ID': settings.PAYTM_CHANNEL_ID, 'CALLBACK_URL': settings.PAYTM_CALLBACK_URL, # 'MOBILE_NO': '7405505665', 'EMAIL': request.user.email, 'CUST_ID': '123123', 'ORDER_ID':order_id, 'TXN_AMOUNT': bill_amount, 'PACK_TYPE': pack_type, } # This data should ideally come from database data_dict['CHECKSUMHASH'] = Checksum.generate_checksum(data_dict, settings.PAYTM_MERCHANT_KEY) context = { 'payment_url': settings.PAYTM_PAYMENT_GATEWAY_URL, 'comany_name': settings.PAYTM_COMPANY_NAME, 'data_dict': data_dict } return render(request, 'payments/payment.html', context) @csrf_exempt def response(request): resp = VerifyPaytmResponse(request) if resp['verified']: # save success details to db; …