Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How i can add choice field related to other model and pass id current objects?
I have the form: class PersonForm(forms.ModelForm): amount = forms.DecimalField(label='Сумма') cars = forms.ModelChoiceField( queryset=CarProductData.objects.all() ) class Meta: labels = { 'last_name': 'Фамилия', 'first_name': 'Имя', 'middle_name': 'Отчество', 'amount': 'Сумма к списанию', } fields = ['amount', ] and i want to get queryset inside admin.ModelAdmin related to current object, something like this: def get_form(self, request, obj, **kwargs): from django import forms from taxi_billing.models import CarProductData form = super().get_form(request, obj, **kwargs) form.cars = forms.ModelChoiceField( queryset=CarProductData.objects.filter( product__subscriptionitem__subscription__customer__person__id=obj.id ) ) return form How can i make it done? -
How to save two forms in same template in models
This is my template. I have got 2 forms , one is for submitting the test and other is for subtest.When I try to submit one form, I get not null_constraint error . <form method="POST"> {% csrf_token %} <div class="icon-holder"> <i data-modal-target="test-popup" class="icon-cross"></i> </div> <div class="input-group"> <input type="text" name="name" placeholder="Test name" /> </div> <div class="button-group"> <button type="submit">Submit</button> </div> </form> </div> <div id="menu-test-popup"> <form method="POST"> {% csrf_token %} <div class="icon-holder"> <i data-modal-target="menu-test-popup" class="icon-cross"></i> </div> <div class="input-group"> <label for="test-select">Test Name:</label> <select name="test-select" id="test-select"> {% for test in test %} <option value="{{test.name}}" name="choices">{{test.name|title}}</option> {% endfor %} </select> </div> <div class="input-group"> <input type="text" name="subtest" placeholder="SubTest name" /> </div> <div class="input-group"> <input type="text" name="reference" placeholder="Reference rate" /> </div> <div class="input-group"> <input type="text" name="unit" placeholder="Unit" /> </div> <div class="button-group"> <button type="submit">Submit</button> </div> </form> this is my models . In my models I have test and subtest. class Test(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Subtest(models.Model): name = models.CharField(max_length=100) test = models.ForeignKey(Test,on_delete=models.CASCADE,related_name='subtest',blank=True, null=True) unit = models.CharField(max_length=10) reference_value = models.IntegerField() selected = models.BooleanField(default=False) def __str__(self): return self.name this is my view. And the 2nd one is the template_context_processor for my convience def home(request): name = None if request.method == 'POST': name = request.POST.get('name') choices = request.POST.get('choices') … -
Not displaying post reshare, user link & other post parameters
Im trying to add user link and post reshare user, but its not displaying parent user and link to both users. Below is the code post_list.html function attachPost(postValue, prepend, reshare){ var dateDisplay = postValue.date_display; var postContent = postValue.content; var postUser = postValue.user; var postFormattedHtml; if (reshare && postValue.parent){ var mainPost = postValue.parent postFormattedHtml = "<div class=\"media\"><div class=\"media-body\"><span class='grey-color'>Reshare via " + postUser.username + " on " + dateDisplay + "</span><br/>" + mainPost.content + "<br/> via <a href='" + mainPost.user.url + "'>" + mainPost.user.username + "</a> | " + mainPost.date_display + " | " + "<a href='/post/" + mainPost.id + "'>View</a>" + "</div></div><hr/>" } else { postFormattedHtml = "<div class=\"media\"><div class=\"media-body\">" + postContent + "<br/> via <a href='" + postUser.url + "'>" + postUser.username + "</a> | " + dateDisplay + " | " + "<a href='/post/" + postValue.id + "'>View</a>" + "</div></div><hr/>" } if (prepend==true){ $('#posts-container').prepend(postFormattedHtml) } else { $('#posts-container').append(postFormattedHtml) } } Python 3.8.0 Django '3.0.2' -
How to add an additional field in Django model form
I am trying to include some dummy fields in my model form and using the same in model formset factory. Model form: class DistForm(forms.ModelForm): dist_from_txt = forms.TextInput() ... class Meta: model: Distance fields = ('dist_from', 'dist_to', 'distance') widgets = { ... } However, when rendered the extra field does not show up on the form. Needlessly to mention here that I have searched (including here) and failed to find a possible solution. Question is: How to correctly add and render extra field/s in model form? -
Keeping the value salected in the drop-down list after the search
I have got a filter on my page, that filters my items by the category. You can choose the category from a drop-down list and then press search and the filtered content is displayed. The only problem is that, the drop-down list resets and doesn't show the category, that the current items are filtered by. Anyone knows how to solve this? views.py def HomeView(request): item_list = Item.objects.all() item_list = item_list.annotate( current_price=Coalesce('discount_price', 'price')) category_list = Category.objects.all() query = request.GET.get('q') if query: item_list = item_list.filter(title__icontains=query) cat = request.GET.get('cat') if cat: item_list = item_list.filter(category__pk=cat) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') if price_from: item_list = item_list.filter(current_price__gte=price_from) if price_to: item_list = item_list.filter(current_price__lte=price_to) paginator = Paginator(item_list, 10) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context = { 'items': items, 'category': category_list } return render(request, "home.html", context) html: <form method="GET" action="."> <div class="form-group col-md-4"> <label for="category">Category</label> <select id="cat" class="form-control" name="cat"> <option value="" selected>Choose...</option> <option value="" href="/home">All</option> {% for cat in category %} <option value="{{ cat.pk }}"> {{ cat }}</option> {% endfor %} </select> </div> <button type="submit" class="btn btn-primary">Search</button> </form> -
Saleor front-end installation
I am trying to install saleor front-end package from github.The documentation is outdated and i get an error when i try >>>nmp start Error: Environment variable API_URI not set I found this variable in different places but did not know what to change, and where to set it -
Django REST framework: how to wrap the response with extra fields .... and supply the current response in data field
So, I have the following: class ObjectViewSet( mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet ): """ REST API endpoints for Objects. """ serializer_class = ObjectSerializer queryset = Object.objects.all() This returns, say, for a list GET request: [ { "uuid": "787573a2-b4f1-40df-9e3a-8555fd873461", }, { "uuid": "2ab56449-1be1-47d7-aceb-a9eaefa49665", } ] However, how could I slightly alter this response for mixins to be similar to the following: { success: true, message: 'Some Extra Useful Message', data: [ { "uuid": "787573a2-b4f1-40df-9e3a-8555fd873461", }, { "uuid": "2ab56449-1be1-47d7-aceb-a9eaefa49665", } ] } Is this possible, or should I just write my own custom endpoint Response() and not utilise DRF's mixins capability? So, essentially, switching the custom: Response(data, status=None, template_name=None, headers=None, content_type=None) To: response = { 'success': true, 'message': 'Some Extra Useful Message', 'data': serializer.data } Response(response, status=None, template_name=None, headers=None, content_type=None) -
modifying class based view to add data to logged in user
hey there im trying to modify my todoapp to be user specific in terms of accessing todolists but i've encountered a challenge in changing my class based views in order to accomplish this for example ensuring that when i create a todo its added to the todolist of the logged in user here is my current code models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.utils import timezone import datetime # Create your models here. class TodoList(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="todolist", null=True) name = models.CharField(max_length=100) def __str__(self): return self.name class Todo(models.Model): todolist = models.ForeignKey( TodoList, on_delete=models.CASCADE) name = models.CharField(max_length=100, default='unamedTodo') description = models.CharField(max_length=200) Todo_date = models.DateTimeField('Todo Date') pub_date = models.DateTimeField('Date Published') def get_absolute_url(self): return reverse('ToDo:detail', kwargs={'id': self.id}) def get_back_home(self): return reverse('ToDo:todos', kwargs={}) def go_to_update(self): return reverse('ToDo:update', kwargs={'id': self.id}) def go_to_delete(self): return reverse('ToDo:delete', kwargs={'id': self.id}) views.py from .forms import TodoForm from .models import Todo from django.template import loader from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.contrib.auth.forms import UserCreationForm from django.views.generic import ( CreateView, ListView, DetailView, UpdateView, DeleteView ) from django.urls import reverse, reverse_lazy from django.shortcuts import render, get_object_or_404 # Create your views here. @method_decorator(login_required, name='dispatch') class TodoListView(ListView): template_name = 'ToDo/todo_list.html' queryset … -
Cannot set PeriodicTask schedule
I use Django Celery Beat in order to manage periodic tasks. Here, I create a periodic task and set it some schedule: new_instance = PeriodicTask.objects.create( name=f'L1 Synchonisation created at {timezone.now()}', task='integrations.tasks.test_task', ) schedule, _ = IntervalSchedule.objects.get_or_create( every=self.every, period=self.period ) new_instance.interval = schedule print(new_instance.interval) # new_instance.interval is not None new_instance.save() print(new_instance.interval) # None new_instance.refresh_from_db() print(new_instance.interval) # None My question is, why does new_instance.interval become None and how do I prevent it from doing so? -
Django Reverse Filter Queryset Foreign Key Example Not Working
I'm loosely following the example laid out here: Django Queryset with filtering on reverse foreign key Model: class Site(models.Model): name = models.CharField(max_length=50) class Profile(models.Model): Days = '1st' Mids = '2nd' Nights = '3rd' Work_Schedule_Choices = [ (Days, 'Day Shift'), (Mids, 'Mid Shift'), (Nights, 'Night Shift'), ] sitename = models.ForeignKey(Site, on_delete=models.CASCADE, related_name='profiles') title = models.CharField(max_length=100) schedule = models.CharField(max_length=3,choices=Work_Schedule_Choices,default=Days) totalusers = models.PositiveSmallIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(50)]) views: def sitedetail(request): site = Profile.objects.filter(id_in=Profile.sitename) if request.method == 'GET': return render(request, 'App/site-detail.html', {'profile_set': Profile.objects.all(site)}) When I load the page it gives a FieldError: Cannot resolve keyword 'id_in' into field. Choices are: id, schedule, sitename, sitename_id, title, totalusers Can someone help me understand what I am doing wrong? I see the same stack article referenced numerous times so I'm assuming it's Operator-Head-Space-Timing error :) Thanks in advance. -
Best practice for getting data from Django view into JS to execute on page?
I have been told it is 'bad practice' to return data from a Django view and use those returned items in Javascript that is loaded on the page. For example: if I was writing an app that needed some extra data to load/display a javascript based graph, I was told it's wrong to pass that data directly into the javascript on the page from a template variable passed from the Django view. My first thought: Just get the data the graph needs in the django view and return it in a context variable to be used in the template. Then just reference that context variable directly in the javascript in the template. It should load the data fine - but I was told that is the wrong way. So how is it best achieved? My second thought: Spin up Django Rest Framework and create an endpoint where you pass any required data to and make an AJAX request when the page loads - then load the data and do the JS stuff needed. This works, except for one thing, how do I get the variables required for the AJAX request into the AJAX request itself? I'd have to get them … -
How to add a model field calculated by data from to other model?
I have the following models: # models.py class Test(models.Model): name = models.CharField(max_length=40) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Tester(models.Model): test_id = models.ForeignKey(Test, on_delete=models.DO_NOTHING) class TestViewset(viewsets.ModelViewSet): serializer_class = TestSerializers permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): if self.request.user.is_superuser: return Test.objects.all() else: return Test.objects.filter(author=self.request.user) So each test can be made by many testers. My wish is to count how many testers conducted the test , i.e when I do a GET request to the TestViewset I wish to get in addition to current fields [name, author] a count field , for each test which specify how many testers have been tested. Appreciate the help! -
IntegrityError at /doctor/Appointment/
'''my code''' here is my model i am getting null constrain error class Patient(models.Model): patient_name=models.CharField(max_length=20, null=True,blank=True) date_of_birth=models.DateField(null=True) email=models.EmailField(null=True,blank=True) mobile_number=models.IntegerField(null=True) family_members=models.IntegerField(null=True) def __str__(self): return self.patient_name def is_staff(self): return self.mobile_number class Doctor(models.Model): doctor_name=models.CharField(max_length=20,null=True,blank=True) email_id=models.EmailField(null=True,blank=True) doctor_number=models.IntegerField(null=True) address=models.CharField(max_length=100,null=True,blank=True) def __str__(self): return self.doctor_name class Appointment(models.Model): user_name=models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='first') mobile_no=models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='second') def __str__(self): return self.user_name #here is my viewset class AppointmentViewSet(viewsets.ViewSet): def create(self,request): user_name=request.data.get('user_name') mobile_no=request.data.get('mobile_no') new=Appointment() new.user_name=user_name new.mobile_no=mobile_no new.save() return Response({'done':True}) -
Django Rest Framework - OneToOne reverse relation
I have a custom User model and the User Profile model. class User(AbstractUser): """Custom User authentication class to use email as username""" username = None email = models.EmailField(verbose_name='email', max_length=255, unique=True, error_messages={ 'unique': _( "A user is already registered with this email address"), }, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class UserProfile(models.Model): user = models.OneToOneField(User, to_field='email', on_delete=models.CASCADE) emp_id = models.CharField(max_length=20, blank=False, default='0', null=False) department = models.CharField(max_length=50, blank=True, default='', null=True) I am trying to write a serializer that combines both these models are produces a nested JSON. for example: { "email":"user@gmail.com", "is_active":true, "profile": { "emp_id":2, "department":2 } } This is what I tried to do class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id', 'user', 'emp_id', 'department') class UserPairSerializer(serializers.ModelSerializer): profile = UserProfileSerializer(read_only=True) class Meta: model = User fields = ('id', 'email', 'is_active', 'profile') But for some reason, there is neither the field profile in my response nor am I getting any errors. I tried following this docs: https://www.django-rest-framework.org/api-guide/relations/ What is the issue and how do I solve this? -
Error during travis ci integration in django and postgres
I integrated travis in to my project where i used postgres but when i tried to test i got stuck in with an unkwown error i.e $ python manage.py test Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/test/runner.py", line 629, in run_tests old_config = self.setup_databases(aliases=databases) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/test/runner.py", line 554, in setup_databases self.parallel, **kwargs File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/test/utils.py", line 157, in setup_databases test_databases, mirrored_aliases = get_unique_databases_and_mirrors(aliases) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/test/utils.py", line 258, in get_unique_databases_and_mirrors default_sig = connections[DEFAULT_DB_ALIAS].creation.test_db_signature() File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 295, in test_db_signature self._get_test_db_name(), File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 153, in _get_test_db_name return TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME'] TypeError: must be str, not NoneType The command "python manage.py test" exited with 1. I used postgres format as below in .travis.yml file services: - mongodb - postgresql before_script: - sleep 15 - psql -c 'create database myapp_test;' -U postgres What i will do? -
build generic query while triggering graphql api from django
Below is a graphql query that retrieves user details like id,username,city,pincode by passing a variable that matches with a cityname called 'osaka' : query = """ { userinfo (cityName: "osaka") { id user_name city pincode } }""" this query is being posted to an external graphql api using requests module of python url = 'http://192.168.200.58:8010/api/userdetails/v1/users' r = requests.post(url, query,headers=headers, auth=HTTPBasicAuth('api', 'api123')) json_data = json.loads(r.text) how to query this api by passing cityname dynamically , i tried the below code but that did not work json = {'query': """ { userinfo ($cityname: str) { id user_name city pincode } }""", "variables":{"cityName":"LA"} url = 'http://192.168.200.58:8010/api/userdetails/v1/users' r = requests.post(url, json=json,headers=headers, auth=HTTPBasicAuth('api', 'api123')) json_data = json.loads(r.text) -
Endpoints for Two factor authentication using Django REST
I am creating an api for authenticating the user with a two factor auth upon login. The Following view is redirected to after the login is successful. class TOTPView(APIView): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.verified = False self.last_verified_counter = -1 self.totp = self.generate_totp() def get(self, request, *args, **kwargs): logger.debug(self.totp) return Response({'success': True}, status=status.HTTP_201_CREATED) def post(self, request): token = int(request.data.get('totp_token')) # check if the current counter value is higher than the value of # last verified counter and check if entered token is correct by # calling totp.verify_token() if ((self.totp.t() > self.last_verified_counter) and (self.totp.verify(token))): # if the condition is true, set the last verified counter value # to current counter value, and return True self.last_verified_counter = self.totp.t() self.verified = True return Response({'success': True}, status=status.HTTP_404_NOT_FOUND) else: # if the token entered was invalid or if the counter value # was less than last verified counter, then return False self.verified = False return Response(status=status.HTTP_404_NOT_FOUND) def generate_totp(self): key = random_hex(20) totp = TOTP(key) totp.time = time.time() return totp Here, when the user posts the OTP code/token, the POST method calls self.totp and that overwrites its value by calling self.generate_totp() again. That never validates the TOTP. Am I doing something wrong here? -
How to solve the error Devtools failed to parse Sourcemap?
Whenever I load the site, it gives me a bunch of errors in the console and cmd. I don't know how to deal with that? Please help me to get rid of these errors. I went to those locations but have no idea what to do with these things? "GET /favicon.ico HTTP/1.1" 404 2264 [13/Feb/2020 13:32:06] "GET /static/home/js/popper.min.js.map HTTP/1.1" 404 1802 [13/Feb/2020 13:32:06] "GET /static/home/js/aos.js.map HTTP/1.1" 404 1781 [13/Feb/2020 13:32:06] "GET /static/home/js/typed.min.js.map HTTP/1.1" 404 1799 [13/Feb/2020 13:32:06] "GET /static/home/js/bootstrap.min.js.map HTTP/1.1" 404 1811 [13/Feb/2020 13:32:06] "GET /static/home/css/bootstrap-datepicker.css.map HTTP/1.1" 404 1838 [13/Feb/2020 13:32:06] "GET /static/home/css/aos.css.map HTTP/1.1" 404 1787 [13/Feb/2020 13:32:21] "GET / HTTP/1.1" 200 24434 [13/Feb/2020 13:32:22] "GET /static/home/css/bootstrap-datepicker.css.map HTTP/1.1" 404 1838 [13/Feb/2020 13:32:22] "GET /static/home/css/aos.css.map HTTP/1.1" 404 1787 [13/Feb/2020 13:32:22] "GET /static/home/js/popper.min.js.map HTTP/1.1" 404 1802 [13/Feb/2020 13:32:22] "GET /static/home/js/typed.min.js.map HTTP/1.1" 404 1799 [13/Feb/2020 13:32:22] "GET /static/home/js/bootstrap.min.js.map HTTP/1.1" 404 1811 [13/Feb/2020 13:32:22] "GET /static/home/js/aos.js.map HTTP/1.1" 404 1781 -
How to customize django rest auth email context
Similar to this question How to customize django rest auth password reset email content/template I would like to customize password reset (and other) emails automatically send by django rest auth. It perfectly works to use custom email templates with an custom serializer: class CustomPasswordResetSerializer(PasswordResetSerializer): def get_email_options(self): return { 'domain_override': settings.FRONTEND_URL, 'email_template_name': 'registration/custom_reset_email.txt', 'html_email_template_name': 'registration/custom_reset_email.html', } But additionally to customized templates I want to add custom context. Is there a simple way to do it? -
How am I able to filter post tags in Django
I have a blog type website where users can add tags to their posts and I want people to be able to filter by tag. Here is my models.py class Tag(models.Model): name = models.CharField(max_length=150,unique=True) def __str__(self): return self.name class Post(models.Model): author = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) title = models.CharField(max_length=75) text = models.TextField(null=True,blank=True) tag = models.ManyToManyField(Tag,related_name='tags',blank=True) I cut a lot of the irrelevant model fields out so you weren't bombarded with lots of text. Now here is my views.py class TagFilterView(ListView): model = Post template_name = 'mainapp/tags_.html' def get_queryset(self): object_list = Post.objects.filter(tags=tag).distinct() return object_list Here is my url pattern path('tag/<int:pk>/',views.TagFilterView.as_view(),name='tag_view'), And finally here is the HTML file {% extends 'mainapp/base.html' %} {% block content %} <h1>Tags</h1> {% for post in object_list %} <h2>{{ post }}</h2> {% endfor %} {% endblock content %} I have tried lots of different filter combos and filter tags, but this seems to be the closest I think. So basically I want to know how I can filter posts to the specific tags they have associated with them. So for example, if a post has a programming tag, and I go to /tag/1 or something like that, it will filter so only the posts with the programming tag are shown. … -
Django: apply filter on field of related model which is in another database
I've two tables in two database, Say policy in DB_A and quote in DB_B. policy has a field result_reference which is the id of quote table in DB_B policy in DB_A class Policy(models.Model): result_reference = models.IntegerField() policy_date = models.DateTimeField() Quote in DB_B class Quote(models.Model): quote_type = models.IntegerField() policy_type = models.CharField(max_length = 100) policy_premium = models.IntegerField() The policy type can be S for Single and M for Multiple I want to get the policies with policy date after 30 days along with policy type=M What i've tried import datetime start_date = datetime.datetime.now() + datetime.timedelta(30) p = Policy.objects.using(default_database).filter(policy_date__gte=start_date) but this returns policies that have policy_type S and M. How can i filter it for policy type M? -
Django CMS Custom Plugin and Page
I have created a custom Django CMS plugin. I want to create a dynamic dropdown in Plugin config. So If I have a country and state dropdown when I select country its state should be populated in state dropdown. I have no idea how to do it? One more issue is with page. How can I know the plugin content that is loaded in the page. I have check the navigation object also but no direct way to get it. -
Django calculate compounded interest for all objects in model
Using: Python 3.8.1, Django 3.0.1 I’ve spent hours on particularly Stack Overflow to get everything working the way I have it now and also to find a solution for my current problem. I’m not able to use answers from other questions and apply to my problem I’m busy with a finance application to track outstanding debits and calculate the interest on the outstanding balances. I have three models: Debtor - which contains the client’s personal information as well as the applicable interest rate, compounding period etc. DebtorAccount – is created whenever a new client is created. It also keeps a running balance and accrued interest. DebtorTransaction – records the type of transaction description, debit/credit, amount etc. models.py class Debtor(models.Model): name = models.CharField(max_length=200, default="") period = models.DecimalField(max_digits=100, decimal_places=2, default=0, null=True) interestrate = models.DecimalField(max_digits=100, decimal_places=2, default=0, null=True, blank=True) def __str__(self): return self.name @property def unique_id(self): return str(self.pk) class DebtorAccount(models.Model): accountname = models.OneToOneField(Debtor, on_delete=models.CASCADE) balance = models.DecimalField(max_digits=100, decimal_places=2, default=0) interest = models.DecimalField(max_digits=100, decimal_places=2, default=0) rate = models.DecimalField(max_digits=100, decimal_places=2, default=0) period = models.DecimalField(max_digits=100, decimal_places=2, default=0) def __str__(self): return str(self.accountname) def create_debtoraccount(sender, **kwargs): if kwargs['created']: debtor_account = DebtorAccount.objects.create(accountname=kwargs['instance']) post_save.connect(create_debtoraccount, sender=Debtor) class DebtorTransaction(models.Model): CREDIT = 'CREDIT' DEBIT = 'DEBIT' TRANSACTION_TYPES = ( ("CREDIT", "Credit"), ("DEBIT", "Debit"), … -
How to Deploy/Upload Wagtail Site to DigitalOcean through ssh?
Can Anyone tell me how to deploy Wagtail site to DigitalOcean. And by deploy I mean upload the site with media files that I have in local machine, through ssh. Any link or blog or suggestion will work. There are many links and instruction available where they show fresh deployment from git or directly. But I need to upload it from my local machine with existing database. I need to upload and get running this site through ssh. Any database is fine, sqlite, postgresql, anything. I dont know how to upload data from local machine to server and get it running. I use made a local site in Windows 10. IDE=PyCharm. DigitalOcean Server has Python=3.5. For ssh I am using Git Bash. Any Help? -
Opencv read image RGB
I am new here, do you know the form to read image in python with cv2. Is necessary to put the flags always? or the function "know" the format of image?