Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how do you decide which model to put foreign key?
Lets say I have two models that looks like this: class Album(models.Model): pub_date = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=250, blank=False, unique_for_date="pub_date") class Track(models.Model): title = models.CharField(max_length=250, blank=False, unique_for_date="pub_date") album = models.ForeignKey(Album) What is the difference between putting the ForeignKey (one-to-many) relationship on the Track model versus the Album model? How does one decide such a thing? -
Django Queryset get list for the day of a particular type, unique foreignkey id using Postgres database
I am trying to find a query to get a list of latest attendance for a particular day, with unique employee that has checked in (CHECKIN = 1) Below is my model, records and what I am trying to accomplish. My model has 2 models: class Employee(models.Model): fullname = models.CharField(max_length=30, blank=False) class Attendance(models.Model): CHECKIN = 1 CHECKOUT = 2 ATTENDANCE_TYPE_CHOICES = ( (CHECKIN, "Check In"), (CHECKOUT, "Check Out"), ) employee = models.ForeignKey(Employee) activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN) timestamp = models.DateTimeField(auto_now_add=True) Assuming I have the records below: Employee {"id":1, "employee":"michael jackson", "id":2, "fullname":"mariah carey", "id":3, "fullname":"taylor swift"} Attendance {"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day "id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13", "id":3, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 11:30", "id":4, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13", "id":5, "employee": 3,"activity_type": 2, timestamp: "2017-12-05 18:30", "id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day "id":7, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 20:30", -interested in this for the activity type (1 for … -
How can I upgrate plan on Heroku from Hobby-dev to Hobby Basic?
I would like to upgrate plan on Heroku with my Django app from Hobby-dev to Hobby Basic? At the moment heroku pg:info returns: Plan: Hobby-dev Status: Available Connections: 0/20 PG Version: 9.6.4 Created: 2017-11-12 19:20 UTC Data Size: 135.9 MB Tables: 19 Rows: 1272760/10000 (Above limits, access disruption imminent) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql-cub... I tried to use this but I am not sure which way should I choose. Any ideas how can I do this upgrade? -
How to move a file from a model's folder to another?
I have two models [1] TempFile(models.Model) and Company(models.Model) , when the view [2] save_records(request) is called I'd like to save & move the image from TempFile(models.Model) which is in folder /temporary_files/ to Company(models.Model) which is in folder /company_logo/. [1] models.py class Company(models.Model): logo = models.FileField(upload_to="company_logo") ... class TempFile(models.Model): unique_id = models.CharField(max_length=8) image = models.FileField(upload_to="temporary_files") ... [2] views.py def save_records(request): if request.method == 'POST': temp_file = TempFile.objects.get(unique_id=request.session['uuid']) Company.objects.create( logo = temp_file.image ... ) Here's the problem with this method, while the logo is saved the path of the folder stays /temporary_files/. I'd like to know how to save or move the image without quality loss and performance issue to Company(models.Model)'s company_logo folder ? -
Not able to send email from elastic beanstalk environment through my gmail email id
I'm using Django as the framework, Running inside docker and docker is running on AWS elastic beanstalk docker platform.So, I'm Trying to send email using my Gmail id it works fine in the local environment(in docker). BUt the same docker image running on elastic beanstalk docker fails to send emails and it is not even giving me an error or something.It is just not sending emails. If it is working fine in local environment why is that it not sending an email when running in the cloud? -
Why doesn't custom save method update another model while running Django test?
I have a custom save method on one model that updates the value of another model based on whether the current model is created or updated. I am trying to run a test to see if the value changes. Here is my code in the test. test.py yr.__setattr__('quantity_rcv', 200) yr.save() self.assertEqual(yr.quantity_rcv, lc_item.yarn_rcv) Over here lc_item.yarn_rcv should have changed to the yr.quantity_rcv value based on the custom save method which works fine when I test it with Django admin. Is the custom save method not working when I run test? -
Can't get object through publish__month
I write a blog according by the book Django by Example. # blog/models.py from django.contrib.auth.models import User from django.db import models from django.utils import timezone # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique_for_date='publish') author = models.ForeignKey( User, related_name='blog_posts', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.localtime) class Meta: ordering = ('-publish', ) def __str__(self): return self.title When I get a post in blog/views.py: def post_detail(request, year, month, day, slug): post = get_object_or_404( Post, slug=slug, publish__year=year, publish__month=month, publish__day=day ) return render(request, 'blog/post_detail.html', {'post': post}) It returns 404. If I modify blog/views.py, just filter year, it returns fine: def post_detail(request, year, month, day, slug): post = get_object_or_404( Post, slug=slug, publish__year=year, ) return render(request, 'blog/post_detail.html', {'post': post}) It seems the problem is publish__month. But Django support this method. I can't figure out how to fix it. -
Raven Configuration Git HEAD Error
here is my config: RAVEN_CONFIG = { 'dsn': 'somedsn', 'release': raven.fetch_git_sha(os.path.abspath(os.pardir)), } When I run the server with python manage.py runserver, there is no problem. When I run it with uwsgi I get following error: raven.exceptions.InvalidGitRepository: Cannot identify HEAD for git repository But everything else is just fine. How can I make it to look into right directory in both cases? -
Getting 'DatabaseError' object has no attribute 'message' in DJango
I am trying to run the following code here to save information to the database. I have seen other messages - but - it appears that the solutions are for older versions of Python/DJango (as they do not seem to be working on the versions I am using now: Python 3.6.3 and DJango 1.11.7 if form.is_valid(): try: item = form.save(commit=False) item.tenantid = tenantid item.save() message = 'saving data was successful' except DatabaseError as e: message = 'Database Error: ' + str(e.message) When doing so, I get an error message the error message listed below. How can I fix this so I can get the message found at the DB level printed out? 'DatabaseError' object has no attribute 'message' Request Method: POST Request URL: http://127.0.0.1:8000/storeowner/edit/ Django Version: 1.11.7 Exception Type: AttributeError Exception Value: 'DatabaseError' object has no attribute 'message' Exception Location: C:\WORK\AppPython\ContractorsClubSubModuleDEVELOP\libmstr\storeowner\views.py in edit_basic_info, line 40 Python Executable: C:\WORK\Software\Python64bitv3.6\python.exe Python Version: 3.6.3 Python Path: ['C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP', 'C:\\WORK\\Software\\OracleInstantClient64Bit\\instantclient_12_2', 'C:\\WORK\\Software\\Python64bitv3.6\\python36.zip', 'C:\\WORK\\Software\\Python64bitv3.6\\DLLs', 'C:\\WORK\\Software\\Python64bitv3.6\\lib', 'C:\\WORK\\Software\\Python64bitv3.6', 'C:\\Users\\dgmufasa\\AppData\\Roaming\\Python\\Python36\\site-packages', 'C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP\\libintgr', 'C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP\\libmstr', 'C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP\\libtrans', 'C:\\WORK\\AppPython\\ContractorsClubBackofficeCode\\libintgr', 'C:\\WORK\\AppPython\\ContractorsClubBackofficeCode\\libmstr', 'C:\\WORK\\TRASH\\tempforcustomer\\tempforcustomer\\libtempmstr', 'C:\\WORK\\AppPython\\ContractorsClubBackofficeCode\\libtrans', 'C:\\WORK\\Software\\Python64bitv3.6\\lib\\site-packages', 'C:\\WORK\\Software\\Python64bitv3.6\\lib\\site-packages\\django-1.11.7-py3.6.egg', 'C:\\WORK\\Software\\Python64bitv3.6\\lib\\site-packages\\pytz-2017.3-py3.6.egg'] Server time: Sat, 9 Dec 2017 08:42:49 +0000 -
Django autoescape is not working in render_to_string(template)?
I am drafting an email template to users when they successfully updated their passwords. I used {{ autoescape off }} in the template, which is rendered by using render_to_string(). However, the email content shows the HTML angle brackets directly like this: Hi <span style='color:blue'>user! </span> Your password is updated successfully! I am using Django2.0 and my code looks like this: views.py from django.core.mail import send_mail from django.template.loader import render_to_string def sendmail(request, title) email_title = title email_content = render_to_string('template.html',{'username':request.user.username}) recipient = request.user.email send_mail( email_title, email_content, 'myemail@email.com', [recipient,], ) template.html {{ autoescape off}} Hi <span style='color:blue'>user! </span> Your password is updated successfully! {{ endautoescape }} Is there anything wrong with my code? Otherwise, is autoescape always on while using render_to_string()? -
django: same api url different results with browser and axios/postman
i am using django restframework. i am having an api url. it returns a list of items. The following api url should return the ingredients in the reverse order of name column http://127.0.0.1:8000/api/ingredients/?ordering=-name by Axios/postman: it returns the list but not ordered. with browser url: it returns the list with sorted names. whats happening i am not able to understand -
Ionic 3 sending http post request as application/x-www-form-urlencoded to Django backend
I'm trying to make a post request to my Django backend with Ionic 3 as the front end app. Right now my post method looks like this: register(username, password, email, first_name, last_name) { let url = "https://www.example.com/api/create_user/"; let headers = new Headers(); headers.append("Content-Type", "application/x-www-form-urlencoded"); return this.http.post(url, {"first_name": first_name, "last_name": last_name, "email": email, "username": username, "password": password}, {headers: headers}) .map(res => res.json()); } But Django is receiving it like this: <QueryDict: {'{\n "first_name": "bob",\n "last_name": "bob",\n "email": "bob@bob.bob",\n "username": "bob",\n "password": "bob"\n}': ['']}> And changing the JSON object to a string. I want to properly send form data on my front end so I don't have to do an janky fixes on my Django backend. I tried to add a transformRequest to the header, but this triggers a preflight response because the content-type either gets stripped away or is automatically changed to undefined. How do I change this to properly send the form data so the QueryDict isn't so messed up? -
Create and update data many to many with CreateView and View
I'm very new with Python and Django, currently I'm learning insert many to many in single form, the case I create new Photo with multiple Tags, here the simple version of my code: Models: class Tag(models.Model): tag_title = models.CharField(max_length=50) tag_slug = models.SlugField(max_length=200) class Photo(models.Model): photo_title = models.CharField(max_length=200) taken_at = models.DateTimeField() tags = models.ManyToManyField(Tag) Forms: class AlbumPhotoForm(forms.ModelForm): album_id = forms.NumberInput() tag_list = forms.CharField(max_length=150) class Meta: model = Photo exclude = ('album', 'tags') Template: <div class="form-group"> <label for="photo_title">Photo Title</label> <input class="form-control {% if form.photo_title.errors %} is-invalid {% endif %}" id="photo_title" name="photo_title" placeholder="Put awesome photo title" value="{{ form.photo_title.value|default:'' }}" required> <span class="invalid-feedback">{{ form.photo_title.errors.0 }}</span> </div> <div class="form-group"> <label for="photo_title">Taken At</label> <input class="form-control date-picker {% if form.taken_at.errors %} is-invalid {% endif %}" required id="taken_at" name="taken_at" placeholder="The date photo is taken" value="{{ form.taken_at.value|default:''|date:"m/d/Y" }}"> <span class="invalid-feedback">{{ form.taken_at.errors.0 }}</span> </div> <div class="form-group"> <label for="tags">Tags and Keywords</label> <input class="form-control tags {% if form.tags.errors %} is-invalid {% endif %}" id="tags" name="tag_list" placeholder="Tag separated by comma" value="{{ form.tags.value|default:'' }}"> <span class="invalid-feedback">{{ form.tags.errors.0 }}</span> </div> The problem I can figure what best way to insert new tag and fetch if it exists before in CreateView or Update view, input tag_list contain tag title separated by comma (like: vitage,awesome,family,etc). Here what … -
elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]')
I am using haystack with elasticsearch backend for full text searching. I am wanting to show the search result using ajax. However I am getting an error of elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]') . Here is my code url(r'^search', views.search_furniture, name="search-furnitures"), def search_furniture(request): furnitures = SearchQuerySet().autocomplete(content_auto=request.POST.get('search_text', '')) context = {'furnitures': furnitures} return render(request, 'search/ajax_search.html', context) class FurnitureIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True, template_name="search/indexes/furniture/furniture_text.txt") name = indexes.CharField(model_attr='name') category = indexes.CharField() content_auto = indexes.EdgeNgramField(model_attr='name') def get_model(self): return Furniture def index_queryset(self, using=None): return self.get_model().objects.all() ajax_search.html {% if furnitures.count > 0 %} {% for furniture in furnitures %} <li>{{ furniture.object.name }}</li> {% endfor %} {% else %} <li>None to show</li> {% endif %} base.html {% block navbar %} {% include "includes/navbar.html" %} {% endblock navbar %} {% block js %} {% include "includes/js.html" %} <script> $('.search').keyup(function() { $.ajax({ type: "POST", url: "/search/", data: { 'search_text' : $('.search').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search-results').html(data); } </script> {% endblock js %} navbar.html {% include 'search/search.html' %} search.html <form method="post" action="/search" class="navbar-form search" role="search"> {% csrf_token %} {{ form.non_field_errors }} <div class="form-group"> {{ form.as_p }} </div> <div class="input-group"> <input type="text" name="q" class="form-control search" placeholder="Search"> … -
the migrate in django give me this error
i want to run a django app i use python3.6 manage.py makemigrations something the something is name of apps that i write here then i write python3.6 manage.py migrate Operations to perform: Apply all migrations: searchapp, account, payment, sessions, contenttypes, baang, redirects, sites, support, myprofile, posts, management, sidebars, myresources, auth, admin Running migrations: Rendering model states... DONE Applying account.0001_initial... OK Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying baang.0001_initial... OK Applying myprofile.0001_initial... OK Applying payment.0001_initial... OK Applying management.0001_initial... OK Applying management.0002_auto_20171209_1006... OK Applying myresources.0001_initial... OK Applying posts.0001_initial... OK Applying sites.0001_initial... OK Applying redirects.0001_initial... OK Applying searchapp.0001_initial... OK Applying sessions.0001_initial... OK Applying sidebars.0001_initial... OK Applying sites.0002_alter_domain_unique... OK Applying support.0001_initial... OK` and then it gives me this error Traceback (most recent call last): File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 112, in execute return self.cursor.execute(query, args) File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/MySQLdb/cursors.py", line 226, in execute self.errorhandler(self, exc, value) File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorvalue File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/MySQLdb/cursors.py", line 217, in execute res = self._query(query) File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/MySQLdb/cursors.py", line 378, in _query rowcount = self._do_query(q) … -
how do i check my email is available in database or not
i wrote one model that is having email field i added some emails in it by admin what i need is when i typed any email that should check with my database email if exist it should show email is already there models.py #in my database already some data is there class Friend(models.Model): email = models.EmailField(max_length=100) def __str__(self): forms.py class FriendForm(forms.ModelForm): class Meta: model = Friend fields = ['email'] views.py def check(request): form = FriendForm(request.POST or None) if form.is_valid(): form = Friend.objects.filter(**form.cleaned_data) context = { 'form': form } return render(request, "one.html", context) i imported every thing when i am trying this code it is directly rendering to one.html i need is it should check if email is there in database then only it should render i am new to django so please help me -
User Authentication for aws using Python
I'm working on a project with Python(3.6) & Django(1.10) in which I'm using aws apis but I'm new to aws and don't know how to authenticate a user. My scenario is: I need to access user's aws resources like projects list, buckets list etc, for that, I need to authenticate the user when making a request to a particular API. How can I do that in python? I'm new to aws.So, please don't mind my question. Help me, please! Thanks in advance! -
Upload_Path_Handler file path for Django ImageField not fetchable from HTML file
I've attempted to use Upload_Path_Handler in order to allow for dynamic folder names (such as the upload date, item ID, etc.) in saving image files uploaded by users, so as to prevent duplicate instances. The problem is that the directory which I've returned is too 'deep' to be retrieved through the HTML file, in that, it begins with the name of the app (in this case, 'vault'). The broken path served for the image in the HTML file is as follows: <img src="vault/static/vault/images/recordimages/r_1/2017-12-09_03-27-42/300x300.jpg"> However, by using inspector element to exclude the app name 'vault' at the beginning, I am able to successfully retrieve the image: <img src="/static/vault/images/recordimages/r_1/2017-12-09_03-27-42/300x300.jpg"> The broken path is served in the raw html file as: <img src="{{ record.w_image }}"> And the model referenced, w_image, is as follows in models.py: w_image = models.ImageField(null=False, blank=True, verbose_name='Record Image:', upload_to=upload_path_handler) Then, of course, is upload_path_handler: def upload_path_handler(self, filename): return "vault/static/vault/images/recordimages/r_{id}/{date}/{file}".format(id=self.id, file=filename, date=datetime.datetime.utcnow().strftime('%Y-%m-%d_%H-%M-%S')) If I were to begin the return path at /static/, it would then instead save the images in WebsiteName/static/../.. as opposed to WebsiteName/vault/static/../.. (Remember, the aim here is to keep the /static/ directory a subdirectory of our app, 'vault') How can I allow for the image to be retrievable … -
Websockets on production chat apps:
As I am beginning to work my way through web-sockets using Python (Django Channels in this case), I am beginning to wonder how companies scale chat applications. Take this specific problem: User A has a list of "group messages" that they are involved in. User A is capable of receiving notifications from each of the groups. Lets suppose User A has 5 different groups he would like real time notifications for. Does User A have 5 separate web socket connections? This is easiest, but the bulkiest and surely wont scale (what if we had 20 chats per user). It is quite easy to make a Django Channels "Group" that listens and sends notifications to one specific group of people. Does User A instead have 1 web socket connection taking all notifications from many different locations? If so, what is User A subscribing to on the backend? In Django Channels, a websocket is made when users subscribe to a "Group". If we wanted one user per "Group', this would seem counter intuitive. In this case, User A is subscribing to their own personal "Group" and other backend services are delivering messages to that specific "Group" based on other logic that is … -
Export a File (CSV, PDF) From Django Admin from Form Inputs
All within the Django admin, I'd like to enter form fields related to generating a report. Fields you'd expect in a report: report name, report type, start and end dates, report fields, etc. How would one take these inputs, grab the inputs from the request, pass these inputs to an API (in the background), then process it (in queue-like fashion), finally create a CSV or PDF to download? I'm fine with creating the admin model form and I think grabbing the inputs when the form is submitted in the admin, then I think I simply pass those inputs to my other API code to process... My questions are: When the third-party API is processing the request, is there a special way to handle this lag time? Where and how would I return the result - which is a CSV or PDF - in the admin interface? The /change/ page? Is there best-practice for this? I haven't been able to find an example of this when dealing with the admin. I'm not new to Python but am somewhat new to Django. -
Why is my django urlpattern not resolving?
So I'm creating a small ecommerce website for a friend and cannot work out why the url won't resolve itself. For the sake of simplicity whilst making the website I'm using a product called "number 1". It has a slug field of "number-1" and on the product page clicking on the product takes a user to "/shop/number-1" My url pattern for this is: url(r'^<slug:url>', views.item, name='products') with the view: def item(request, url=""): products = product.objects.get(url=url) return render(request, 'shop\product.html', {'products', products}) As far as I can tell this should render my product.html template but instead it returns a 404 and I'm not sure why? If it helps I have other views, such as product types set within the same views and they work fine so as far as I can tell its that the slug:url isn't being used in the views.item, or the view isn't getting the context properly. Also I'm on django 1.11.7 for this project. Thanks in advance. -
Model Form drop-down (select) field not displaying correct rows to choose from
I have a Parent Model that uses a Foreign Key that points to a Child Model. In this case, the "Child Model" is called Mstrgensalutationtype (which is really Salutations). The Parent Model is being used to create a Model Form Basically, below is what I get when trying to choose a Salutation Type. What I need to see is Mr. Ms. Mrs. Prof. Dr. Question: What am I doing wrong here? TIA models.py - used as a Child Model class Mstrgensalutationtype(models.Model): saltypeid = models.BigIntegerField(primary_key=True) lang = models.CharField(max_length=2, blank=True, null=True) shortval = models.CharField(max_length=7, blank=True, null=True) salutationlong = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'MstrGenSalutationType' def __unicode__(self): return u'%s ' % ( self.shortval ) models.py - used as a Parent Model class Mstrstorehead(models.Model): tenantid = models.BigIntegerField(primary_key=True) extrefacctno = models.CharField(max_length=20, blank=True, null=True, verbose_name="Account Reference No") [... snip ...] contactsalutationid = models.ForeignKey(Mstrgensalutationtype, models.DO_NOTHING, db_column='contactsalutationid', blank=True, null=True, verbose_name="Salutation") [... snip ...] class Meta: managed = False db_table = 'MstrStoreHead' -
disabled field is marked as required after passing null=True
I have a form where there is a field like quantity, rate, basic_amount(disabled), vat, other_expenses and net_amount(disabled). The basic_amount field is the calculation from quantity and rate and net_amount is the calculation of basic_amount, other_expenses and vat. For this I used signal for saving to the database when user submits the form. When i submit the form, I get an error saying basic_amount and net_amount is required, though I have passed blank=True, null=True attribute to them. How can i now save basic_amount and net_amount? Here is my code class PurchaseOrder(models.Model): item = models.ForeignKey(Item, blank=True, null=True) quantity = models.PositiveIntegerField(default=0) rate = models.DecimalField(default=0.0, max_digits=100, decimal_places=2) basic_amount = models.DecimalField(default=0.0, max_digits=100, decimal_places=2, blank=True, null=True) vat = models.CharField(max_length=10, blank=True, null=True) other_expenses = models.DecimalField(default=0.0, max_digits=100, decimal_places=2) net_amount = models.DecimalField(default=0.0, max_digits=100, decimal_places=2, blank=True, null=True) def save_basic_amount_and_net_amount(sender, instance, *args, **kwargs): if (instance.quantity and instance.rate): instance.basic_amount = instance.quantity * instance.rate if (instance.basic_amount and instance.vat and instance.other_expenses): instance.net_amount = instance.amount - instance.other_expenses - instance.vat pre_save.connect(save_basic_amount_and_net_amount, sender=PurchaseOrder) class PurchaseOrderForm(forms.ModelForm): basic_amount = forms.DecimalField(disabled=True) net_amount = forms.DecimalField(disabled=True) class Meta: model = PurchaseOrder exclude = ('office', 'timestamp', 'updated', ) def purchase_order(request): form = PurchaseOrderForm(request.POST or None) if request.method == "POST" and form.is_valid(): office_instance = OfficeSetup.objects.get(owner=request.user) new_form = form.save(commit=False) new_form.office = office_instance new_form.save() messages.success(request, 'Thank … -
How can I upgrate plan on Heroku from Hobby-dev to Hobby Basic?
I would like to upgrate plan on Heroku with my Django app from Hobby-dev to Hobby Basic? At the moment heroku pg:info returns: Plan: Hobby-dev Status: Available Connections: 0/20 PG Version: 9.6.4 Created: 2017-11-12 19:20 UTC Data Size: 135.9 MB Tables: 19 Rows: 1272760/10000 (Above limits, access disruption imminent) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql-cub... I tried to use this but I am not sure which way should I choose? -
Package backend.apps missing Django
I've been trying to setup a Django site, but when I run python3 manage.py make migrations I get the error ModuleNotFoundError: No module named 'backend.apps' I have installed Django and package backend.