Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Post to django rest framework
I'd like to post to my Django server using post so I can add a todo item. Here is the model: class Todo(models.Model): title = models.CharField(max_length=200); text = models.TextField() completed = models.BooleanField(default=False) created_at = models.DateTimeField(default=datetime.now, blank = True ) def __str__(self): return self.title And serializers: class TodoSerializer(serializers.ModelSerializer): class Meta: model = Todo fields = ("id", 'title','text', 'completed', 'created_at') And view: class TodoList(APIView): def get(self,request): todo=Todo.objects.all() serializer=TodoSerializer(todo,many=True) return Response(serializer.data) def post(self,request): Todo.objects.create( title=request.POST.get('title'), text=request.POST.get('text')) return HttpResponse(status=201) My post request is { "title": "new title", "text": "a test text"} And it told me IntegrityError at /todos/ (1048, "Column 'title' cannot be null") As a newbie at Django, I don't understand this error. Any ideas? -
Django cannot delete on shell
I was try to a delete user. But it's doesn't work. I'm sorry if the question it's to easy for you all, But i'm very new about django. I was try it on shell. >>> from django.contrib.auth.models import User >>> a = User.objects.get(username='zayn') >>> a.delete() I got the following error. django.db.utils.ProgrammingError: relation "girl_user_profile" does not exist -
django unable to load admin css file
I'm using Apache to host my main website, and having a django project set aside with it. 1.Apache proxypass was configured to listen to 8001 port, as long as proxypassReverse in the django project settings.py, django.contrib.staticfiles is added to INSTALLED_APPS STATIC_ROOT is set to os.path.join(BASE_DIR, 'static'), where the BASE_DIR is the absolute path of my project STATIC_URL is set to '/static/' operation python manage.py collectstatic is already performed and a file named "static" is in my project folder the page that can't get css files is www.whiletrue.cc/paradox/admin -
How to redirect user to the same page after allauth django?
Hello and thank you for your time. Situation: I'm using allauth in my Django Project User is on some random page (call it first page) of my site He clicked on Facebook icon and call href="/accounts/facebook/login/?process=login" He sign up with his Facebook account He redirected to LOGIN_REDIRECT_URL = 'some_page', from settings.py I need redirect him back to the first page. Is it a way of how i can do it? -
Django Query Filtering: Choosing maximum between fields
This is a question about a specific querying technique in Django (current version 1.11). Here are some notional models: class CompanyAccount(models.Model): account_number = models.IntegerField() account_name = models.CharField(max_length=255) created_on = ... ... class Payment(models.Model): account = models.ForeignKey(CompanyAccount, related_name='payments') amount = models.DecimalField() date = models.DateField() class CanceledOrder(models.Model): account = models.ForeignKey(CompanyAccount, related_name='canceled') reason = models.CharField(max_length=255) date = models.DateField() I am trying to find a query that returns updated model instances of CompanyAccount by comparing both Payment.date and CanceledOrder.date to some user input date. Do I have to use Q objects ... ... Yes. Yes I do. updated = CompanyAccount.objects \ .annotate(date1=Max(payments__date)) \ .annotate(date2=Max(canceled__date)) \ .filter(Q(date1__gte=user_input_date) & Q(date2__gte=user_input_date)) Thanks SO! What's it called when you're documenting your problem on SO and the act of writing it out fixes the problem? I'll leave it here for the next person. Backup Question: What's the performance hit of something like this, versus storing metadata like last_updated_date in a small, separate model? -
How can I convert class CustomObtainAuthToken(ObtainAuthToken) to generic view?
I noticed that my Django Swagger Documentation is working properly only when I have generic views with serializer_class. I am trying to convert this class to generic view without effects. Any suggestions? class CustomObtainAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): response = super(CustomObtainAuthToken, self).post(request, *args, **kwargs) token = Token.objects.get(key=response.data['token']) return Response({'token': token.key, 'id': token.user_id}) At this moment I send just username and password. In response I get something like this: { "token": "23213718fbe2eewq2205f45cb71c27391324ed", "id": 8 } -
How do you retrieve Django objects from a recursive many to many relationship?
I have a Django class representing articles. Sometimes one article comments on one or more other articles and I have represented this relationship in the class using a recursive many-to-many relationship as follows: class Article(models.Model): comments_on = models.ManyToManyField('self', blank=True) I think that I've successfully associated articles with one another in the admin interface by selecting multiple articles in the comments_on field. Let's say that one article (id1) comments on two other articles (id2 and id3). I don't know how to access the comments_on attribute of id1 so that id2 and id3 appear in my Django template. I tried: {{ [instance of Article object].comments_on }} but all I get is: [name of my app].Article.None I'd like to know (1) how do I access this attribute and get it to display? And (2) how do I access one of the associated articles at a time? For example, if id1 comments on both id2 and id3, how can I display just id2 or just id3? -
Error installing Django on Raspberry Pi
Zero experience here and I'm hitting super early road blocks trying to install Django on a Raspberry Pi. I'm following this tutorial(http://raspberrypituts.com/raspberry-pi-django-tutorial-2017/) and hitting an error I can't google a solution for. When I run the command virtualenv venv && source venv/bin/activate I get the following error. New python executable in /home/pi/¬/projects/django-rpi/venv/bin/python Traceback (most recent call last): File "<string>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 9: ordinal not in range(128) ERROR: The executable /home/pi/¬/projects/django-rpi/venv/bin/python is not functioning ERROR: It thinks sys.prefix is u'/home/pi/\xac/projects/django-rpi' (should be u'/home/pi/\xac/projects/django-rpi/venv') ERROR: virtualenv is not compatible with this system or executable Any ideas? -
Two virtual environments for a single Django project?
I have a Django project for which I have created a virtual environment with the packages it requires. Now for development, I was looking for a tool where I could try some code before includng it to my project. I had a good experience with Jupyter a little while ago and I thought that would be nice to work with this tool again. In order to avoid cluttering the minimal virtual environment with the dependencies of Jupyter, I duplicated it and installed jupyter alongside with django-extensions. In my settings.py, I have: if os.environ.get("VENV_NAME") == "jupyter-sandbox": INSTALLED_APPS += ['django_extensions'] so that I can still be able to use the minimal virtual environment without django_extensions. It works fairly well for now apart from the fact that I cannot run the server from my Jupyter-enabled virtual environment. This is because my project uses django-images and django can't find a migration file in this environment (in sites-packages/django_images/migrations). The error message is below: raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration core.0001_initial dependencies reference nonexistent parent node ('django_images', '0002_auto_20170710_2103') Would it be a good idea to create a symlink so that both virtual environments share the same migrations folder or would it mess up completely my project? … -
Can you refer to more than one base template in django?
I have a Django app with one base template called "base.html". This template provides for the look and feel of all pages in the website. On many - though not all - of these pages, I want to pull data from my database and display it in a consistent format. I'd like to create the template for that format in a different base called, say, "base2.html". This would mean that on pages where I present data, I will need to extend both "base.html" and "base2.html". How do I extend from two html pages on the same page? -
Django Allow Users to insert dynamic content into email
I want to allow my end users to create email templates and in the template allow them to specify dynamic info like in mail chimp. Example: "Hello Mr.{{last_name}} I am calling regarding an issue." -
Dynamically update image processed through Python Django AJAX
I am currently developing a simple website and I am having trouble as I am new to Django and AJAX. I would like for the user to select an image from their computer and then be able to process and display the image without refreshing the page. I was able to do simple color thresholding using only JavaScript, however some of the more complex processing will need to be done using Python, which is why I am using Django. Javascript $("#interactBtn").click(function() { var img = document.getElementById('inputImageFileInput').files[0]; $.ajax({ type: "POST", url: '{% url "threshold" %}', //does this look okay? data: img, }).done(function(data) { var canvas = document.getElementById('imagesTabProccessedImg'); var context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); context.putImageData(data, 0, 0); } }); views.py def threshold(img): # how to load image as OpenCV image # imagine proccessing here return img I'm not quite sure where to go from here. From what I have researched, I think it should be possible, I'm just lost. Will my ajax request send the image data? In what format will the image be sent to the python code? Thanks in advance for the help! -
Bootstrap navbar collapse not working on Django.
I'm trying to build a navbar with the collapse dropdown menu for smaller screens. While the button itself seems to be showing up, and the targeted content disappears as intended, the button doesn't seem to be working (nothing happens when I click on it). I can't tell if its something wrong with my code, or if its a back-end/installation issue. I feel like I took all necessary steps, but maybe someone here can help me out. Here is my code: <!DOCTYPE html> <html lang="en"> <head> <title> EnPowered Press Page </title> <meta charset="utf-8" /> {% load staticfiles %} <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.js"> </script> <link rel='stylesheet' href="{% static 'Press/css/bootstrap.min.css' %}" type='text/css'/> <link rel='stylesheet' href="{% static 'Press/css/PressStyle.css' %}" type='text/css'/> <meta name="viewport" content = "width=device-width, initial-scale=1.0"> </head> <!-- Nav-Bar goes here --> <body> <nav class="navbar navbar-toggleable-md EnPoweredNav navbar-inverse"> <div class="navbar-nav"> <a class="navbar-brand" href="#"><image src="http://res.cloudinary.com/duocsoiqy/image/upload/v1499450095/Enpowered_Logo_k69cqw.png" style="margin-left:30px;"> </a> </div> <div class="container"> <div class="collapse navbar-collapse" id="MainNavBar"> <div class="navbar-nav"> <a class="navitem nav-link navbutton" href="#" style="margin-top:10px;margin-left:150px;color:white;font-size:12px;white-space:nowrap;overflow:hidden;"> WHY ENPOWERED </a> <a class="navitem nav-link" href="#" style="margin-top:10px;color:white;font-size:12px;white-space:nowrap;overflow:hidden;"> FIX YOUR BILL </a> <a class="navitem nav-link" href="#" style="margin-top:10px;color:white;font-size:12px;white-space:nowrap;overflow:hidden;"> HOW IT WORKS </a> <a class="navitem nav-link" href="#" style="margin-top:10px;color:white;font-size:12px;white-space:nowrap;overflow:hidden;"> LEARN WITH US </a> <a class="navitem nav-link" href="#" style="margin-top:10px;color:white;font-size:12px;white-space:nowrap;overflow:hidden;"> COMMERCIAL </a> </div> </div> <div class="navbar-nav"> <a … -
Trying to add each element from a for loop into an array in javascript
I have a html file index.html which displays a mySQL table: <body> <div class="container"> <table align="center"> <tr> <th bgcolor="#f0a00c">Col1</th> <th bgcolor="#f0a00c">Col2</th> <th bgcolor="#f0a00c">Col3</th> <th bgcolor="#f0a00c">Col4</th> <th bgcolor="#f0a00c">Col5</th> </tr> {% for b in obj %} <tr> <td>{{ b.col1 }}</td> <td>{{ b.col2 }}</td> <td>{{ b.col3 }}</td> <td>{{ b.col4 }}</td> <td>{{ b.col5 }}</td> </tr> {% endfor %} </table> </div> <!-- /container --> </body> I want to put each value from b.col2 & b.col3 into separate lists. So, I'm trying to add it as follows: {% for b in obj var c1 = []; c1.push(b.col1); var c2 = []; c2.push(b.col2); %} But it is not working. What is the correct way? -
How to get default object from one to many relationship for display in django-admin and be able to filter?
I'm looking at this tutorial from the Mozilla library. I want to create a list view in admin on a database relationship. For example I have a Vehicle model and a statusUpdate model. Vehicle is a single instance with many statusUpdates. What I want to do is select the most recent statusUpdate (based on the dateTime field I have created) and have that data available to me in the list view. The tutorial mentions: Note: Getting the genre may not be a good idea here, because of the "cost" of the database operation. We're showing you how because calling functions in your models can be very useful for other reasons — for example to add a Delete link next to every item in the list. Sub Question: However mine is a one to many relationship, would this be any different in this case? class Vehicle(models.Model): unit = models.IntegerField() vin = models.CharField(max_length=18) vclass = models.CharField(max_length=10) year = models.IntegerField() make = models.CharField(max_length=20) vmodel = models.CharField(max_length=20) color = models.CharField(max_length=20) plate = models.CharField(max_length = 8) state = models.CharField(max_length = 2) ownLocation = models.CharField(max_length = 20) altId = models.IntegerField() def __str__(self): return str(self.unit) class statusUpdate(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) odometer = models.DecimalField(max_digits=7, decimal_places=1) gasLevel = … -
Overriding django form field clean() method returns validation error 'Select a valid choice. That choice is not one of the available choices.'
I have a ModelForm called RecipeForm with a field called yeast, which is a a related model field class Recipe(models.Model): name = models.CharField(max_length=100, null=True, blank=True, default=default_name) yeast = models.ForeignKey('Yeast', null=True, blank=True) I am trying to override the clean_yeast method for the yeast field. Sometimes in the form, a user will specify an option for yeast that doesn't exist. In these instances, I just want to return one that does exist. class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['name','yeast'] def clean_yeast(self): yeast = self.cleaned_data['yeast'] if not self.cleaned_data['yeast']: yeast = Yeast.objects.all()[1] return yeast When I attempt to validate the form however, I still get an error: Select a valid choice. That choice is not one of the available choices. -
Internal Server Error when uploading large files
I have a Django API in AWS that is manage by Elastic Beanstalk, the compose it is, EC2, RDS and for storage is the S3. So, the upload file work fine until 200MB, when is more it, the foloowing exception is throwed: The Postman app: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html> <head> <title>500 Internal Server Error</title> </head> <body> <h1>Internal Server Error</h1> <p>The server encountered an internal error or misconfiguration and was unable to complete your request. </p> <p>Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error. </p> <p>More information about this error may be available in the server error log. </p> </body> </html> The Elastic Beanstalk log: MemoryError During handling of the above exception, another exception occurred Some observation: The S3 bucket limit per file is 5T In my local server all works fine -
How to make a post request with the Python requests library?
I am using the following filters in Postman to make a POST request in a Web API but I am unable to make a simple POST request in Python with the requests library. First, I am sending a POST request to this URL (http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets) with the following filters in Postman applied to the Body, with the raw and JSON(application/json) options selected. Filters in Postman { "filter": { "filters": [ { "field": "RCA_Assigned_Date", "operator": "gte", "value": "2017-05-31 00:00:00" }, { "field": "RCA_Assigned_Date", "operator": "lte", "value": "2017-06-04 00:00:00" }, { "field": "T_Subcategory", "operator": "neq", "value": "Temporary Degradation" }, { "field": "Issue_Status", "operator": "neq", "value": "Queued" }], "logic": "and" } } Second, I am using the following code to apply a simple filter with the requests library. import requests payload = {'field':'T_Subcategory','operator':'neq','value':'Temporary Degradation'} url = requests.post("http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets",data=payload) But what I've got is the complete data of tickets instead of only those that are not temporary degradation. Third, the system is actually working but we are experiencing a delay of 2-3 mins to see the data. The logic goes as follows: We have 8 users and we want to see all the tickets per user that are not temporary degradation, then we do: def get_json(): … -
One model is matching another different model in the database in Django
I'm trying to create a form that adds events to a list that is attributed to different schedule instances, and I'm coming up with something screwy in the database. Here is my code. models.py class Schedules(models.Model): course_name = models.ForeignKey(Course) location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield') room = models.CharField(max_length=128, choices=ROOM_CHOICES, default='A') start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today) start_time = models.CharField(max_length=128, choices=START_TIME_CHOICES, default='eight-thirty am') end_time = models.CharField(max_length=128, choices=END_TIME_CHOICES, default='eight-thirty am') instructor = models.ForeignKey(Instructor) total_hours = models.CharField(max_length=128, choices=TOTAL_HOURS_CHOICES, default='six') frequency = models.CharField(max_length=128) status = models.CharField(max_length=128, choices=STATUS_CHOICES) interval = models.CharField(max_length=128, choices=INTERVAL_CHOICES, default='1 day') initiated_by = models.CharField(max_length=128, null=True) schedule_id = models.IntegerField(default=0) def save(self, flag=True, *args, **kwargs): super(Schedules, self).save() if flag: self.schedule_id = self.id + 10000 self.save(flag=False, *args, **kwargs) @property def end_date(self): days = get_days(self.interval) return self.start_date + datetime.timedelta(days=days) def __str__(self): return self.course_name class Event(models.Model): name = models.CharField(max_length=128, choices=EVENT_CHOICES, default='final exam') instructor = models.ForeignKey(Instructor, null=True) schedule = models.ForeignKey(Schedules, null=True) date = models.DateField(auto_now=False, auto_now_add=False, null=True) start_time = models.CharField(max_length=128, null=True) end_time = models.CharField(max_length=128, null=True) note = models.TextField() def __str__(self): return self.name forms.py class EventForm(forms.ModelForm): date = forms.DateField(input_formats=['%m/%d/%Y'], label="Date", widget=DateInput(format='%/m/%d/%Y'), help_text="MM/DD/YYYY") name = forms.ChoiceField(choices=EVENT_CHOICES, initial='Final Exam', label="Event", widget=forms.Select(attrs={'class': 'form-control'})) instructor = InstructorChoiceField(queryset=Instructor.objects.all(), label="Instructor", widget=forms.Select(attrs={'class': 'form-control'})) start_time = forms.CharField(max_length=128, label="Start Time", widget=forms.TextInput(attrs={'class': 'form-control'})) end_time = forms.CharField(max_length=128, label="End Time", widget=forms.TextInput(attrs={'class': 'form-control'})) notes = … -
Apache2.4 mod_wsgi error: Forbidden You don't have permission to access / on this server
I'm using Ubuntu 14.04. I create a django project under /opt/cashpro/python_app/cashsite/trunk/cash and create a wsgi file cash.wsgi in the same directory Here is the content of cash.wsgi import os import sys path = '/opt/cashpro/python_app/cashsite/trunk/' sys.path.insert(0, path) from cash import settings import django.core.management sys.path.insert(1, '/opt/cashpro/python_app/cashsite/trunk/cash/') django.core.management.setup_environ(settings) utility = django.core.management.ManagementUtility() command = utility.fetch_command('runserver') command.validate() import django.conf import django.utils django.utils.translation.activate(django.conf.settings.LANGUAGE_CODE) import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() and here is what I add to my httpd.conf: <VirtualHost *:443> ServerName www.abcd.org DocumentRoot /var/www/test SSLEngine on SSLCipherSuite HIGH:+MEDIUM:!SSLv2:!EXP:!ADH:!aNULL:!eNULL:!NULL SSLCertificateFile "/opt/certs/www.abcd.org.crt" SSLCertificateKeyFile "/opt/ssl/www.abcd.key" SSLCertificateChainFile "/opt/certs/DigiCertCA.crt" #SSLCertificateChainFile "/opt/ssl/IntermediatesCA3.crt" BrowserMatch ".*MSIE.*" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 Alias /media-cash/ /opt/cashpro/cashfiles <Directory /opt/cashpro/cashfiles> Options MultiViews AllowOverride None Require all granted </Directory> WSGIPassAuthorization On WSGIScriptAlias /site /opt/cashpro/python_app/cashsite/trunk/cash/cash.wsgi ErrorLog /var/log/apache2/serror.log CustomLog /var/log/apache2/saccess.log common </VirtualHost> The problem is, when I visit https://www.abcd.org/site, it says Forbidden You don't have permission to access / on this server. -
Django - NameError: name 'app1' is not defined
I have just set up virtualenv and then created a new app, called "app1", under a new project, "devp1". I have edited the files as the following: views.py in in "app1" dir from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse("wow my first page") settings.py in "devp1" dir INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', ] url.py in "devp1" dir urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'','app1.views.home'), ] However, when I run the server, I receiving the following error, I have not found why it is not able to see "app1". Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f7ab830b400> Traceback (most recent call last): File "/home/usr1/dev/lib/python3.4/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/usr1/dev/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/home/usr1/dev/lib/python3.4/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/usr1/dev/lib/python3.4/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/usr1/dev/lib/python3.4/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/usr1/dev/lib/python3.4/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/usr1/dev/lib/python3.4/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/home/usr1/dev/lib/python3.4/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/home/usr1/dev/lib/python3.4/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/usr1/dev/lib/python3.4/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = … -
Running custom manage command from view in custom adminpage
What is the best way to extend django admin templates and render them via custom admin view? I need to call custom manage.py command from the view in admin. So it will be like /admin/commands/dummycommand/ which will render template with form to fill command parameters and run it. I have found some guides how to do custom admin page (via admin.ModelAdmin, where I would override the get_urls method), but never figured out how to include it in the urls.py or where can I override the original admin urls. -
Django: And conditional in Case
I want to do something like this: all_objects.annotate(c=Count( Case( When(hit__question=A AND hit__participant=B, then=1 ) How would i go about this? -
How to output the input form data with extra model fields Django
I'm looking for a way to output the input of a form (in a div) after the form has been submitted. After a lot of research, I can't find a solution. I think I need to use AJAX, but are not certain. Is there a proper Django way of getting this done, or do I need to work with AJAX? something like this with AJAX? <script> var xhr = new XMLHttpRequest(); xhr.open('GET', '???'); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { document.getElementById('ajax').innerHTML = xhr.responseText; } }; function sendAJAX() { xhr.send(); } </script> views.py def scan_product_view(request): if request.method == 'POST': form = forms.ScanProductForm(request.POST or None) if form.is_valid(): barcode_input = form.cleaned_data.get("barcode_input") amount_input = form.cleaned_data.get("amount_input") p = AddProduct.objects.get(barcode=barcode_input) p.sold = F("sold") + amount_input p.stock_amount = F("stock_amount") - amount_input p.save() messages.success(request, '%s was successfully scanned' %p.title) return HttpResponseRedirect('/scan/') else: form = forms.ScanProductForm() return render(request, 'scanapp/barscan.html', {'form': form}) template html {% block content %} <div class="scan-form-master"> <form method="POST" action=""> {% csrf_token %} <div class="scan-con"> <div> <div class="scan-form"> {{ form }} <input type="submit" class="btn btn-primary" value="Add"> </div> <div class="conf-btn"> <div id="load" onclick="sendAJAX()"> <p>* I want to show the input of the above field input here after the client hit the Add button.</p> </div> <p><input … -
Do not parse my method more than once
models.py class Contract(TimeStampedModel): customer = models.ForeignKey('customers.CustomerProfile') template = models.ForeignKey('configurations.ContractTemplate') product = models.OneToOneField('products.CustomerProduct') signed_at = models.DateTimeField(_('Date signed'), blank=True, null=True) cancelled_at = models.DateTimeField(_('Date cancelled'), blank=True, null=True) html_source = models.TextField(_('HTML source'), blank=True, null=True) pdf_file = models.OneToOneField('documents.Meta', on_delete=models.SET_NULL, blank=True, null=True) is_signed = models.BooleanField(_('Is signed'), default=False) is_cancelled = models.BooleanField(_('Is cancelled'), default=False) signature_uuid = models.UUIDField(_('Signature UUID'), primary_key=False, default=uuid.uuid4, editable=False) signature_ip = models.GenericIPAddressField(_('Signature IP'), blank=True, null=True) ... def sign(self, ip): from loanwolf.contracts.utils import render_html_contract, store_pdf_contract self.html_source = render_html_contract(self.template, self.customer, self.product) store_pdf_contract(self) self.signature_ip = ip self.signed_at = datetime.datetime.now() self.is_signed = True self.save() if self.request.state.is_signature: self.request.sign() return True views.py class ContractAsHtmlView(DetailView): model = Contract pk_url_kwarg = 'uuid' def get_object(self, queryset=None): try: return self.model.objects.get( signature_uuid=self.kwargs.get('uuid')) except self.model.DoesNotExist: return None def render_to_response(self, context, **response_kwargs): if self.request.GET.get('lang'): lang = self.request.GET.get('lang') else: lang = translation.get_language_from_request(self.request) if self.object.template.language == lang: template = self.object.template else: try: template = ContractTemplate.objects.get( slug=self.object.template.slug, language=lang) except ContractTemplate.DoesNotExist: template = self.object.template html = render_html_contract( template, self.object.customer, self.object.product) return HttpResponse(html) def get_context_data(self, **kwargs): import ipdb; ipdb.set_trace() context = super(ContractAsHtmlView, self).get_context_data(**kwargs) context.update({ 'signature_ip': self.viewing_signature_ip, }) @property def viewing_signature_ip(self): import ipdb; ipdb.set_trace() contract = Contract.objects.get(pk=1) if contract.sign == True: return contract.signature_ip In the moment, sign() method returns a Boolean argument, but it can't be parsed more than once. Hence, I can't use that …