Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django authentication fails with nginx and gunicorn but works with run_server
I have read countless articles and poured over this problem but I don't have an answer yet. I have a standard system running in docker with docker-compose that has nginx as a reverse proxy to gunicorn and the default django authentication system. I reskinned the login pages by setting form classes but that is all the customization I have. When I run my website in run_server to debug it, everything works. I go to the login page, log in successfully, and get redirected. is_authenticated produces the excepted results. I run the exact same pages behind nginx and gunicorn and I get very strange behavior. Often I will successfully log in, my sessionid matches the session in the database, the csrf token matches what is in the database but is_authenticated is false. But only about 90% of the time. Often, I will hit a page that requires a login using the login_required decorator on the url (login_required(view.as_view()) and it will have me log in multiple times, is_authenticated is false every time, until it works and when it works, is_authenticated is set to false once past the login page. This is my nginx configuration. Please note that django is an ip address … -
POST request for nested objects
I have models like this class Survey(models.Model): name = models.CharField(max_length=120) ... class Question(models.Model): survey = models.ForeignKey(Survey, related_name='questions', on_delete=models.CASCADE) ... class Option(models.Model): question = models.ForeignKey(Question, related_name='options', on_delete=models.CASCADE) ... Serializers looks like: class OptionSerializer(serializers.ModelSerializer): class Meta: model = Option exclude = ('question','id') class QuestionSerializer(serializers.ModelSerializer): options = OptionSerializer(many=True) class Meta: model = Question exclude = ('survey',) class SurveyDetailSerializer(serializers.ModelSerializer): creator = serializers.StringRelatedField(read_only=True) questions = QuestionSerializer(many=True) class Meta: model = Survey exclude = ('is_active',) GET request is clear, i get survey with all questions and options views.py class SurveyDetailView(generics.RetrieveAPIView): """Detail Survey view with all survey's questions""" queryset = Survey.objects.all() serializer_class = SurveyDetailSerializer Result { "id": 3, "creator": "nvbr", "questions": [ { "id": 5, "options": [ { "text": "OPTION A" }, { "text": "OPTION B" } ], "answer_type": "single option", "text": "QUESTION 1?" } ], "name": "stackoverflow survey", "description": "Example", "created_at": "2021-09-23T13:07:19.679174Z" } but how can I make POST to save Survey, Questions and Options? Or should I always create separate endpoints for all models? SPA frontend if it important -
while downloading the uploaded file in django model it downloads only the .html file but not the actual doc file...?
I am writing a code on Django for uploading pdf files to model and downloading it from the HTML page. here I have written 2 functions In first function def syllabus(request): syllabus_file=McaSyllabus.objects.all().order_by("-id") n=len(syllabus_file) print("hello",syllabus_file) params={'syllbs':syllabus_file,'total_items':n} return render(request,'syllabus.html',params) model class McaSyllabus(models.Model): pattern_choice = ( ('new','NEW'), ('old', 'OLD')) Name=models.CharField("Name of file ",max_length=50,default="Syllabus ") Year=models.CharField("Year ",max_length=10,default="##") sem=models.CharField("Semester ",max_length=5,default="##") docFile=models.FileField(upload_to ="media") pattern=models.CharField("Pattern ",choices=pattern_choice,max_length=10,default="##") def __str__(self): return self.Name and in 2nd function def pdfNotes(request,sem,sub): pdfNotes_file=PDF_Notes.objects.all().filter(subject=sub) n=len(pdfNotes_file) print("hello",pdfNotes_file) params={'pdfnote':pdfNotes_file,'total_items':n} return render(request,'pdfNotes.html',params) model class PDF_Notes(models.Model): pattern_choice = ( ('new','NEW'), ('old', 'OLD')) name=models.CharField("File name",max_length=100) subject=models.CharField("Subject",max_length=50) course=models.CharField("Course",max_length=50) semester=models.CharField("Semister",max_length=50,null=True,default="#") year=models.CharField("Year",max_length=50,null=True,default="#") pattern=models.CharField("Pattern ",choices=pattern_choice,max_length=10,default="##") source=models.CharField("Source",max_length=100) file=models.FileField(upload_to="media/MCA/PdfNotes") def __str__(self): return self.name pdfNotes.html and written notes.html have almost the same working here, so I m writing for one only {% if syllbs%} <table id="dataTAble"> <tr> <th># </th> <th>NAME</th> <th>DOWNLOAD FILE</th> </tr> {% with counter=1 %} {% for item in writtennote %} <tr> <td id="id">{{ forloop.counter}}</td> <td id="name">{{item.name}}</td> <td id="downloadBtn"> <a href="{{item.docFile.url}}" class="btn-outline-success" download >DOWNLOAD</a></td> </tr> {% endfor %} {% endwith %} </table> {% else %} <b>No data available! </b> {%endif%} here, from function1 when I download a file then the file will be downloading as its original format, but when I trying to download the file from the 2nd function then instead of downloading … -
my django app only display the source code (not the formated page)
I screwed up when I try to install vue.js in my django app witch was already working... I try to use vue by using django_rest_framwork on my django app named "backoffice" and now, some of my urls dont work normaly. In fact, when I go to "http://127.0.0.1:8000/backoffice/acceuil" it display only the source code but if I go to another url inside my backoffice app like "http://127.0.0.1:8000/backoffice/logout/" it display the normal formated page. I went back to the old code (before making all the vue.js installation) but the probleme is still here... I don't know if my question is clear but if you can help me I will be pleased to answer all of your question. If you have some informations to understand how I broked my app and how I can fix it just let me know. Regards, Thibaud -
Crispy form: render a field as HTML
I've a form that contains various fields, some of them should be read-only, but instead of using a "read-only" field i would like to rednder them as HTML. there's the HTML tag that works as a template, but I can't figure out how (and if) i can use it. Assuming that my field is called text, what should I use to render it? HTML("This is the text {{text}}") this does not work :( Or should I create a new template for a new Field in oreder to render it as I want? -
Django-autocomplete-light==3.8.2 & Dajngo formset rendering issue
I'm working on a Django project and I need autocomplete on select input. I have used django-autocomplete-light==3.8.2 with Django formset_factory for dynamic forms. So the features works fine for me to think about it, but I'm facing 1 particular issue, when I add new forms the django-auto-complete fields gets messed up (See Image). I think the issue is occurring due to my jquery code handling dynamic form creation. I'm not an expert on jquery or javascript. Here is my forms.py from dal import autocomplete from django import forms from django.forms import inlineformset_factory, formset_factory from .models import Country, Customer class TForm(forms.ModelForm): country = forms.ModelChoiceField( queryset=Country.objects.all(), widget=autocomplete.ModelSelect2(url='country-autocomplete') ) class Meta: model = Customer fields = ('__all__') # formset used to render multiple 'TForm' TFormFormset = formset_factory(TForm, extra=1) class PersonForm(forms.ModelForm): country = forms.ModelChoiceField( queryset=Country.objects.all(), widget=autocomplete.ModelSelect2(url='country-autocomplete') ) class Meta: model = Customer fields = ('__all__') Here is my template code {% extends 'home.html' %} {% load static %} {% block content %} <br><br> <div> {{formset.media}} <form action="" method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row form-row"> <div class="form-group col-md-3"> {{ form.name.errors }} <label class="panel-body-text">Name:</label> {{ form.name }} </div> <div class="form-group col-md-4"> {{ form.country.errors }} <label class="panel-body-text">Country:</label> {{ … -
Django Channels with MQTT
Am trying to create websocket using django channels and integrate mqtt with channels and mqtt publish message should be received by the function inside consumer.py should be sent to websocket client. I have consumer channel like below consumer.py from channels.consumer import AsyncConsumer from paho.mqtt import client as Mqtt class Testing(AsyncConsumer): async def websocket_connect(self, event): obj = Mqtt.Client() obj.connect("localhost", 1883, 60) obj.on_message = self.updater obj.subscribe("Testing") obj.loop_start() async def updater(self, arg1, arg2, message): print(message) await self.send({ "type": "websocket.send", "text": message}) async def websocket_receive(self, text_data): pass In the above mqtt connection has happened but if I publish a message to the topic its not working. updater function inside consumer.py is not being called. How to achieve this ? -
Changing django default modeladmin breadcrumbs
i have a little problem with django default breadcrumbs. lets say i have the following model: class SomeModel(models.Model): id = ObjectIdField(db_column='_id') some_name = models.CharField(max_length=250) class Meta: verbose_name_plural = "Some Models" let's say some_name field value will be the same across all SomeModel objects. now i have a specific admin for the model, i have some table in there, nothing special really. right now in the breadcrumbs line it will show: Home >> Some Models i want it to show: Home >> Some Models - some_name (the value in some_name field) is it possible? if no, is there a way to insert some custom title in the admin that will be the value of some_name field. thanks in advance. -
state and cities dropdown
i have two 3 models Account : class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) name = models.CharField(max_length=150) phone = models.CharField(max_length=50) picture = models.ImageField(blank=True, null=True , upload_to='profile' ) profession = models.ManyToManyField(Profession) state= models.ForeignKey(Wilaya,on_delete=models.SET_NULL,null=True, blank=True) city = models.ForeignKey(Commune,on_delete=models.SET_NULL,null=True,blank=True) State : class State(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name City class city(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) name = models.CharField(max_length=30) i want to handle the dropdwon list with forms.py and without ajax can i do it ?? if not i need the ajax method -
Why does the variable give me a TypeError but the function doesn't?
I'm trying to run the following code but "full_name" gives me the following error. TypeError: unsupported operand type(s) for +: 'CharField' and 'str' from django.db import models class user(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) full_name = first_name + ' ' + last_name def __str__(self): return self.full_name When I change the "full_name" from a variable to a function, the TypeError goes away and my code works fine. from django.db import models class user(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) def full_name(self): return self.first_name + ' ' + self.last_name def __str__(self): return self.full_name() Why does the variable give me a TypeError but the function doesn't? Don't they do the same thing? -
Django-cors-headers not adding Access-Control-Allow-Origin header
I'm trying to use the django-headers library to restrict allowed origins to only my own domain. However, I cannot seem to get it working for any value other than the * wildcard. My configuration in settings.py: INSTALLED_APPS = [ ..., 'corsheaders' ..., ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # Placed at the top of the middlewares ... ] CORS_ALLOWED_ORIGINS= [ 'https://example.com' ] With this configuration, I get no Access-Control-Allow-Origin header on any of my requests at any of my domain's endpoints (e.g. POST https://example.com/profile). I also tried to check if I can trigger any errors by only allowing some random origins, hoping that the browser will throw CORS errors, e.g.: CORS_ALLOWED_ORIGINS = [ 'https://example.org' ] To my surprise, nothing happened and the browser succeeded in executing every request I tried. The header was not included in the response either. Finally, I noticed that setting the flag CORS_ALLOW_ALL_ORIGINS = True will add the Access-Control-Allow-Origin header with value *. However, I do not want to allow all origins in my configuration. I tested this behavior on both Chrome and Firefox. Did I configure something wrong? Some additional info on my versioning: python: 3.6 django: 3.1.0 django-cors-headers: 3.8.0 -
Can not load custome tag in django
i have a problem load a custome tag in django templates i have this tree for my app: and i have register the app "auctions" in my django project: But when i try to load my "categoryTag" i have the follow error TemplateSyntaxError at /: Here is my categoryTag.py module: from ..models import Auction from django import template register = template.Library() @register.simple_tag def listCategories(): return Auction.objects.all() and here i try to load the tag and use it, but get the error: {% load categoryTag %} {% for category in listCategories %} <li><a class="dropdown-item" href="{% url 'indexF' category.category %}">{{ category.category }}</a></li> {% endfor %} i follow this guide, but i do not know what i am doing wrong -
create an instance with data of a specific formset
Ho un problema con la creazione di formset nidificati. Voglio che il formset dell'esercizio prenda come gruppo ciò che gli passo dal formset del gruppo. mi dà solo un errore perché ci sono più istanze di gruppo che non so come fargli capire che voglio quella singola istanza def creazioneView(request): #inizializzazione formset gruppiFormSet = formset_factory(GruppiForm, extra=1) eserciziFormSet = formset_factory(EserciziForm, extra=1) #metodo POST if request.method == "POST": schede_form = SchedeForm(request.POST) gruppi_formset = gruppiFormSet(request.POST, prefix='gruppi') esercizi_formset = eserciziFormSet(request.POST, prefix='esercizi') if schede_form.is_valid() and gruppi_formset.is_valid() and esercizi_formset.is_valid(): #schede schedaName = schede_form.cleaned_data['nome_scheda'] scheda = schede_form.save(commit = False) scheda.utente = request.user scheda.save() #gruppi for gruppo in gruppi_formset: gruppi_instance = gruppo.save(commit = False) gruppi_instance.gruppi_scheda = Schede.objects.get(nome_scheda = schedaName) gruppoName = gruppi_instance.gruppi_scheda print(gruppoName) gruppi_instance.save() #esercizi for esercizi in esercizi_formset: esercizi_instance = esercizi.save(commit = False) #this esercizi_instance.gruppo_single = DatiGruppi.objects.get(dati_gruppo = gruppoName) esercizi_instance.save() #redirect return redirect('/lista-gruppi/') #metodo GET else: #inizializzazione 3 form vuoti con GET schede_form = SchedeForm() gruppi_formset = gruppiFormSet(prefix='gruppi') esercizi_formset = eserciziFormSet(prefix='esercizi') #creo la pagina context = {'schede_form': schede_form, 'gruppi_formset': gruppi_formset, 'esercizi_formset': esercizi_formset} return render(request, "crea.html", context) -
How to use VideJS AudioTracks API?
I have the following code at my Django application: {% for track in tracks %} <tr> <td> <audio id=player controls> <source src="{{ track.file.pk|s3_audio_link }}" type="application/x-mpegURL"> </audio> </td> <td>{{ track.track }}</td> <td> <small>{{ track.title|safe|slice:":100"|linebreaksbr }} {% if track.title|length > 40 %} ... {% endif %}</small> </td> <td> <small>{{ track.artist.title }} </td> <td><small>{{ track.duration_conversion }}</td> </tr> {% endfor %} As type="application/x-mpegURL" already indicates, I want to use a HLS stream for playback. As I already use VideoJS for video playback I thought it would be nice to also have this for audio playback as I don't wanted to deal with different libs. For Audio track only processing using VideoJS I found the following at the VideoJS Docs: https://docs.videojs.com/tutorial-audio-tracks.html But I'm not sure how to implement it. Basically I want to add all tracks within my for loop to the player in first place and then? How can I make the playlist actually play? While thinking about it, I came across the Idea that I need many players in the end. One player that contains all tracks and than also one player for each track of the album within the for loop (I guess). Please correct me when I'm wrong with this. Thanks … -
Django: Create a Model instance with the build-in User Model fields
So i have a Car model. And every car is submitted is assigned to a user. Also every user has his own dashboard where they can submit cars (Only for logged in users). from django.db import models from django.contrib.auth.models import User class Car(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,null=True) model_car= models.CharField(max_length=200) description = models.TextField() car_image = models.ImageField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) This is my forms.py where i create cars. And then i render this form to the frontend. from django import forms from django.forms import ModelForm from tasks.models import Car class CreateCarForm(ModelForm): class Meta: model=Car fields='__all__' exclude = ('user',) Views.py def create_car(request): form = CreateCarForm() if request.method=="POST": form = CreateCarForm(request.POST,request.FILES) if form.is_valid(): form.save() messages.success(request,'Car was Created') return redirect('create_car') context={'form':form} return render(request, 'dashboard/create_car.html',context) Now it just creates a car instance, but with no selected user. What i would like to do is to create this Car instance, but in the user field, to auto assign the current logged-in user username. How can i achieve this? -
How to server side pagination in flask
How to do pagination in flask without sqlalchemy. I'm doing server side connection instead of client side so I'm confused how to do that. Thanks for any help :D btw I did something like this from documentation but it doesnt work :/ My idea was that i made that pagination inside wrong function but I would ask someone who knows flask well. @APP.route('/api/names', methods=['GET', 'POST']) def data(): d = private.run_sql(get_query_per_technology("Names", None)) return {'data': d} @APP.route('/users', methods=['GET', 'POST']) def _TABLE_finder(): return render_template('table.html') that is table.html temple {% extends "base.html" %} <HTML> {% include 'web_head.html' %} {% block content %} {{ pagination.info }} {{ pagination.links }} <table id="data" class="table table-striped" width="80%"> <thead> <tr> <th scope="col">name</th> <th scope="col">adress</th> <th scope="col">phone</th> </tr> </thead> <tbody> {% for user in users %} <tr> <td>{{ loop.index + pagination.skip }}</td> <td>{{ user.name}}</td> <td>{{ user.adress}}</td> </tr> {% endfor %} </tbody> </table> {{ pagination.links }} {% endblock %} {% block scripts %} <script> $(document).ready(function () { $('#data').DataTable({ ajax: '/api/names', // "ajax": { // "url": "raport_table.py", // "type": "POST"}, serverSide: true, lengthMenu: [[10, 15, 20, 25], [10, 15, 20, 25]], bProcessing: true, bjQueryUI: true, columns: [ {data: 'names'}, {data: 'adress'}, {data: 'phone'},],}); $('.loader').remove(); }); </script> {% endblock %} </HTML> -
What's the most productive way to start a Django web application?
As stated in the title, what's the most productive way to start a Django web application? I always prefer to take a toy application as starting point that demonstrate 1) framework features and 2) best practices and adapt it to my concrete application needs. For example, in most Scala web frameworks you can find an application seed. After searching a bit I wasn't able to find any Django application seeds. -
finding ip address in django on pythonanywhere
i have a website hosted on pythonanywhere and i now i want to block an ip adress if a user fail to login 3 times,i want to block that ip for 12 hours i am doing this to avoid brute force in my web site.but i am not able to get the ip adress because the ip is the same for every user.i tried ip = request.headers['X-Real-Ip'] and ip = request.headers['X-Forwarded-For'] why i am always getting the same ip for all users.i tried to find a solution on pythonanywhere and i found a link on how to get the ip but the same problem remains.i will appreciate any explanation. -
how to copy data of a DB from one django app to another app
I have Django app, one is in local machine and other is in production server after deploying in production server i see i lost all my local data lost so I want to know how I can copy all my data from db and paste into production server so is there any way please share how to do it -
Uploading Image/Images via Django Rest Framework endpoint
I aiming at having images uploaded via an endpoint eg.(localhost/posts/) unto which i've looked at most of the previous questions and answers but i haven't suceeded on having this work. Besides the django rest framework I'm using drf-flex-fields and versatileimagefield packages. When the image is added from admin side then everything works well, therefore i'm suspecting the issue lies within my serializer create method. Below is my code that does not work via Postman: #Models class Post(models.Model) content = models.TextField() image = models.ForeignKey(PostImage, related_name='posts_images') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey("profiles.Profile", on_delete=models.CASCADE, null=True, related_name='posts') class PostImage(models.Model): image = VersatileImageField('Image',upload_to='images/',ppoi_field='image_ppoi') image_ppoi = PPOIField() #Serializers class PostImageSerializer(FlexFieldsModelSerializer): image = VersatileImageFieldSerializer( sizes=[ ('full_size', 'url'), ('thumbnail', 'thumbnail__300x300'), ] ) class Meta: model = PostImage fields = ('image',) class PostSerializer(serializers.ModelSerializer): image = PostImageSerializer(many=True, required=False) class Meta: read_only_fields = ('author', ) model = Post fields = [ 'id', 'content', 'author', 'created', 'image', ] expandable_fields = {'image': ('posts.PostImageSerializer', {'many': True}),} def create(self, validated_data): request = self.context['request'] images = self.context['request'].FILES post = Post.objects.create(author=request.user.profile, **validated_data) for image in images: PostImage.objects.create(**image) return post #Viewset class PostViewSet(FlexFieldsModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() -
Django CKEditor not working on Production
I am implementing the CKEditor on my website and it's working absolutely fine on development, but as soon as I try to update it on production,the Editor is not working at all. Any idea as to why this is happening? P.S-> I have tried collectstatic I am using nginx and aws s3 in production. -
Why isn't call_command( ... stdout=f ) intercepting stdout? At my wits end
Help! I am unable to get testing for my management command to work. The command works fine when tested manually: $ ./manage.py import_stock stock/tests/header_only.csv Descriptions: 0 found, 0 not found, 0 not unique StockLines: 0 found, 0 not found, 0 not unique but not in a test. It's outputting to stdout despite call_command specifying stdout=f (f is a StringIO()). Running the test, I get $ ./manage.py test stock/tests --keepdb Using existing test database for alias 'default'... System check identified no issues (0 silenced). Descriptions: 0 found, 0 not found, 0 not unique StockLines: 0 found, 0 not found, 0 not unique Returned "" F ====================================================================== FAIL: test_001_invocation (test_import_stock_mgmt_cmd.Test_010_import_stock) make sure I've got the basic testing framework right! ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/nigel/django/sarah/silsondb/stock/tests/test_import_stock_mgmt_cmd.py",line 32, in test_001_invocation self.assertIn('Descriptions: 0', text) # do-nothing AssertionError: 'Descriptions: 0' not found in '' ---------------------------------------------------------------------- Ran 1 test in 0.006s FAILED (failures=1) Preserving test database for alias 'default'... The test code which generates this is as follows. print(f'Returned\n"{text}"') shows that I'm getting a null string back from do_command (which creates the StringIO() and invokes call_command ). What I'm trying to intercept is being written to the console, just as when I invoke the command … -
In Django: Even after using "queryset = objects.none()" in forms.py, I still see the dropmenu with all the options
While rendering the form in web browser, the dropdown menu of CPA_Clients should be empty since I've used "self.fields['name'].queryset = CPA_Client.objects.none()" (Since I'll be making it chained dropdown) in forms.py file, but I still see all the contents of CPA_Clients in dropdown. Where did I go wrong? forms.py from django import forms from .models import Task, CPA_Client class TaskDetails(forms.Form): class Meta: model = Task fields = '__all__' def __init__(self, *args, **kwargs): super(TaskDetails, self).__init__(*args, **kwargs) self.fields['name'].queryset = CPA_Client.objects.none() models.py . . . class CPAsList(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Meta: verbose_name_plural = 'CPAs' class CPA_Client(models.Model): CPA = models.ForeignKey(CPAsList,on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100) def __str__(self): return self.name class Meta: verbose_name_plural = 'CPA\'s Clients' class Task(models.Model): CPA = models.ForeignKey(CPAsList, on_delete=models.SET_NULL, null=True) Client_of_CPA = models.ForeignKey(CPA_Client, on_delete=models.SET_NULL, null=True) def __str__(self): return self.Subject_Line def get_absolute_url(self): return reverse('task-detail', kwargs={'pk': self.pk}) . . . -
Django extra + where: how to escape identifiers
I have an extra filter in Django with a where clause, but the table name is dynamic. filtered_queryset = queryset.extra( where=[ f'({table_name}.modified_on, {table_name}.id) > (%s, %s)', ], params=(after_ts, after_id), ) How can I best avoid the f-string to make really sure it's not open to SQL injection? -
Model filed values are not updating in django
Am building this voting platform, users will have to but the votes. They will input the number of votes to they want to buy, then make payment. After a successful payment, The number of votes they just bought should be added to their old votes in the database. For instance, say a user buys 2 votes and have 3 votes already, the 2 should should be added to the 3 to make it 5. My problem is that the new votes fails to the added. models.py class Nomination(models.Model): Fullname = models.CharField(max_length=120) Nominee_ID = models.CharField(max_length=100) Category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to='nominations_images') slug = models.SlugField(max_length=150) votes = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.Fullname views.py def process_payment(request, slug, amount): trans_id = request.GET.get('transaction_id') status = request.GET.get('status') reason = request.GET.get('reason') transaction_id = request.GET.get('transaction_id') if status == 'approved': transaction = SuccessfulTransactionHistory( nominee_name=slug, transaction_id=transaction_id, amount=amount ) transaction.save() nomination = Nomination.objects.filter(slug=slug).values('votes') Nomination.objects.filter(slug=slug).update(votes=int(nomination[0]['votes']) + int(amount[:-2])) return redirect('/success') else: context = { 'error': reason } transaction = FailedTransactionHistory( nominee_name=slug, transaction_id=transaction_id, amount=amount ) transaction.save() return render(request, 'payment_error.html', context=context)