Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Multiple Categories And Sub Categories
View Page Unless I comment out Category Slug, the Designer slug errors "No Category matches the given query" from django.shortcuts import render, get_object_or_404 from .models import Category, Product, Designer from cart.forms import CartAddProductForm from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator def product_list(request, category_slug=None, designer_slug=None): category = None designer = None categories = Category.objects.filter() designers = Designer.objects.filter() products = Product.objects.filter(available=True) count_filter = Product.objects.filter().count() # Query Data From Database # Create Pagination Ability page = request.GET.get('page', 1) paginator = Paginator(products, 48) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category) if designer_slug: designer = get_object_or_404(Designer, slug=designer_slug) products = Product.objects.filter(designer=designer) context = { 'category': category, 'categories': categories, 'designer': designer, 'designers': designers, 'products': products, 'count_filter': count_filter } return render(request, 'shop/product/list.html', context) from django.urls import path from . import views app_name = 'shop' urlpatterns = [ path('', views.product_list, name='product_list'), path('/', views.product_list, name='product_list_by_category'), path('/', views.product_list, name='product_list_by_designer'), path('//', views.product_detail, name='product_detail'), ] -
Serializing models polymorphically in django
I've a inheritance model like this, Base class, class PrivateMessage(Base): sender = models.ForeignKey(User, related_name='privatemessage_set', on_delete=models.CASCADE, null=True) room = models.ForeignKey(PrivateRoom, on_delete=models.CASCADE, related_name='message_set', null=True) message_type = models.CharField(max_length=255, null=True) Children. class PrivateTextMessage(PrivateMessage): body = models.TextField(null=True, blank=True) class PrivateImageMessage(PrivateMessage): image = models.ImageField(upload_to=attachment_images_path, null=True, blank=True) I'm serializing them polymorphically, class PublicMessageSerializer(serializers.ModelSerializer): class Meta: model = PublicMessage fields = '__all__' def to_representation(self, obj): if isinstance(obj, PublicTextMessage): return PublicTextMessageSerializer(obj, context=self.context).to_representation(obj) elif isinstance(obj, PublicImageMessage): return PublicImageMessageSerializer(obj, return super(PublicMessageSerializer, self).to_representation(obj) class PublicTextMessageSerializer(serializers.ModelSerializer): sender = UserSerializer(read_only=True) receiver = RoomSerializer(read_only=True) class Meta: model = PublicTextMessage fields = ('id', 'sender', 'receiver', 'body', 'message_type', 'created', 'modified',) class PublicImageMessageSerializer(serializers.ModelSerializer): sender = UserSerializer(read_only=True) receiver = RoomSerializer(read_only=True) image = serializers.ImageField(use_url=True) class Meta: model = PublicImageMessage fields = ('id', 'sender', 'receiver', 'image', 'message_type', 'created', 'modified',) The problem is that only the fields that are there in the base class are rendered by the serializer. For example the image field in the PublicImageMessage never gets rendered. Can someone help me with the conditional rendering where all fields of the class are rendered. PS: The classes have a PublicMessageType object. I've tried using that and serializing, but outside of that being clunky, in that case the fields are rendered with null value. -
Django and Postgres, OperationalError when deleting an object
I have a Django app and a Postgres DB deployed and dockerized. This is my docker-compose.yml version: '3' services: web: build: . container_name: web command: python manage.py migrate command: python manage.py runserver 0.0.0.0:8000 volumes: - ./src:/src ports: - "8000:8000" depends_on: - postgres postgres: image: postgres:latest container_name: postgres environment: POSTGRES_USER: my_user POSTGRES_PASSWORD: my_secret_pass! POSTGRES_DB: my_db ports: - "5432:5432" Everything works great, I can create, update or delete objects of any of my 10 apps, however, when I try to delete an object of the class Story, which is the following, it fails: class Story(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField(blank=True, null=True) image = models.ImageField(upload_to="stories", null=True, blank=True) There are also a few other classes that have a ForeignKey to Story, such as Like, View or Comment. My problem is that I get an operational error whenever I try to delete a Story. The funny fact is that I can create or update as many stories as I want, just not delete them. When I try to delete any story, I get the following exception: OperationalError: FATAL: the database system is in recovery mode If I look at the queries performed, I see nothing wrong: DELETE … -
Django: what is the right href to individual url?
I have a model Post. Each individual post extends post_detail.html and has it's own url: urlpatterns = [ path('news/<int:pk>/', views.PostDetailView.as_view(), name='news_page'), ... ] The model consists of title, description, image etc. On main.html I show the title and the image of the last post, the second last post, and the third last post. My views.py looks like class PostListView(ListView): model = Post template_name = 'html/main.html' def get_context_data(self, **kwargs): posts = Post.objects.all().order_by('-id') kwargs['last_post'] = posts[0] kwargs['second_last_post'] = posts[1] kwargs['third_last_post'] = posts[2] return super().get_context_data(**kwargs) Here I have the title of the last and the second last post in my template: <h5 href="#">{{ last_post.title }}</h5> <h5 href="#">{{ second_last_post.title }}</h5> Now I want to connect these titles to their own urls. I mean when I click on the title of the last post in main.html I want to open individual url of that post. How can I do that? -
django models many subclasses
I am trying to make two subclasses of a model and call it in the following way: base_class.sub. But I can not do it since I can not put "sub" as related_name to the two subclasses class BaseClass(models.Model): name = models.CharField(max_length=20) class SubClassA(BaseClass): base_class = models.OneToOneField(BaseClass, parent_link=True, related_name='sub') class SubClassA(BaseClass): base_class = models.OneToOneField(BaseClass, parent_link=True, related_name='sub') -
Django-import-export customization with related fields
I need to update my table every time a new value of "sku" is entered (not to create a new entry), but it does have to happen only if the "client" selected is the same. If the "client" is different, then the model should add a new object with the same "sku", but with different "clients". One StackOverflow user gave me the solution: class ProductList(models.Model): id_new = models.IntegerField(primary_key=True) sku = models.CharField(primary_key=False, max_length=200) client = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) name = models.CharField(max_length=256) description = models.CharField(max_length=1000) storage = models.CharField(max_length=256) cost_price = models.CharField(max_length=256) sell_price = models.CharField(max_length=256) ncm = models.CharField(max_length=256) inventory = models.IntegerField(null=True) class Meta: unique_together = (('sku', 'client'),) def save(self, *args, **kwargs): if self.pk: current_instance = self.__class__.objects.get(pk=self.pk) if current_instance.client != self.client: self.pk = None return super(ProductList, self).save(*args, **kwargs) After I added the save function the problem got solved. However, if I try to update an existing table I get the following problem for each field in my file: Line number: 1 - get() returned more than one ProductList -- it returned 2! 345, Teste 1, Descrição 1, 87654, 59,99, 180, 65, 884, 25 Traceback (most recent call last): File "/home/checkstore/.local/lib/python3.6/site-packages/import_export/resources.py", line 453, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/home/checkstore/.local/lib/python3.6/site-packages/import_export/resources.py", line 267, in get_or_init_instance … -
Can I use different account to send mail via Gmail
I have a question, I want to send email via Gmail. Below is django code: EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = 'xxxx' #my gmail password EMAIL_HOST_USER = 'aaa@gmail.com' #my gmail username EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = 'bbb@example.com' CanI use different domain or address on DEFAULT_FROM_EMAIL? My other mail bbb@example.com is still use Google service(Google G Suite) Thanks. -
Django - How to represent the view count of any post in post app via highchart.js according to date
I have a basic django post app which displays post and its details when clicked , it also counts the view count.But actually i am unable to associate a time to when the post was actually viewed. I want to represent data on highchart.js for each day that how many time a post was viewed. The chart want to be horizontal and at each instance it shows recent 7 days data relative to each day. total a screen representing a graph with 7 columns of how may time post was viewed each day. If you can , pls include views.py and models.py for better understanding. -
How to have React Dev debug info available when DRF serves React
During development using Django Rest Framework (DRF) and ReactJS, I build my React frontend (npm run build), and then have the Django dev server serve the frontend files, through Django a Django view/views. (So, this may be repetition, but I am not running the React Dev server.) Now, the nice thing about the React dev server is the abundant debugging info. This I am now missing. Main question: Is it possible to still have the debug info available in a setup similar to what I have currently? And if so, can anyone advice me on how to set that up? -
Generate Ipv4 address of a specific subnet with factory_boy and faker for django model
Gretings everyone! Below is a script to populate a model using faker. Faker allows using 'address_class' argument. Specifiying address_class='a' narrows in down but only to 10.0.0.0/8. How to adjust the generator further, for example to 10.10.10.0/24? import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") django.setup() from workplace.models import IpAddress import factory import faker from faker.providers import internet faker = faker.Factory.create() class IpAddressFactory(factory.django.DjangoModelFactory): class Meta: model = IpAddress django_get_or_create = ('ip_address',) ip_address = faker.ipv4_private(address_class='a') ip = IpAddressFactory() print(ip) -
Django pure controller functions
I am wondering on how to implement pure controller functions in a Django's' "biased" MVC scheme. Let me explain it on an example. Let's say I have a model of an Invoice, which has some attributes (say net, gross etc.). I can present it to the user using a view + template. And that's fine and easy. But now, I want to send this invoice to a client. This is a more complicated thing, inluding more models (i.e. create an addressed Package model, get a number and let's say few other thing including creating and modifying not only Invoice model itself, but also creating and updating few other model types and instances. I want this "action" to be available in multiple places of my web application, so going by the book I need to create a view with those actions implemented and bind it to some URL. Probably it should be implemented in POST action. My questions are: What kind of generic view should it be (just View? DetailView? other?). Where should this View redirect after succesfull "send"? The simplest answer would be to redirect to the same referring page, but is this a correct way? What if I want … -
Django format email django errors
hi i would like create a format for django email errors, the email is automatic send by django in this case get the typical error format: i would like get in the email report the project name, all type errors(404/500/etc)... This is my settings: ADMINS = ( ('Diego Avila', 'diego.loachamin@test.com'), ) #CONFIGURAR PARAMETROS EMAIL EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_SSL = True EMAIL_HOST = 'mail.test.com' EMAIL_HOST_USER = 'diego.loachamin@test.com' EMAIL_HOST_PASSWORD = 'dsdsad' EMAIL_PORT = 465 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } please someone suggest or idea.. thanks..!! -
Django views rendering just one page and wont render the rest
So im using django 1.8 on macosx and i have problem while configuring html, namely when i try to load another page except one that is set at default one(index is the default one), it just refreshes the default one i have set in urls.py and i cant access any other page except that one but in the url bar i can see that im accesing the proper html file because it says so but the page is not changing....heres my code: app/urls.py----------- urlpatterns = [ url(r'^contact/', views.contact, name='contact'), url(r'^projects/', views.projects, name='projects'), url(r'^services/', views.services, name='services'), url(r'^', views.index, name='index'), url(r'^about/', views.about, name='about'), these are all the pages im trying to install main urls.py------------- from app import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^',include('app.urls')), ] and this is my views.py----------- def contact(request): return render(request, 'app/template/contact.html',{}) def about(request): return render(request, 'app/template/about.html',{}) def projects(request): return render(request, 'app/template/projects.html',{}) def services(request): return render(request, 'app/template/services.html',{}) def index(request): return render(request, "app/template/index.html",{}) -
Import Error: No module named 'mysite' when trying to import django model
I have been trying to import a django model to my python script to extract its fields as below` #!/usr/bin/env python3 import sys sys.path.append("/home/tutorial/device_interfaces/mysite") import json import re import os.path import pathlib import uuid import subprocess from models.py import ConfigInfo def info(): creds=ConfigInfo.objects.first() SSID_name='SSID' psk_name='psk' sIP='sIP' netmask='netmask' ` but, when i python3 manage.py runserver 127.0.0.1:8000 i get File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ImportError: No module named 'mysite' I tried .models import ConfigInfo, but it brought the same traceback. I wonder if the file. I also tried import ConfigInfo but it also did not work. The two python files that are invloved are in the same folder. How do i import my models correctly to get access to its data? -
Adding multiple Django users with a blank email
I have a Django app using a PostgreSQL db, where the user migration has an email field with unique=True. My User model has: email = models.EmailField(_('email address'), unique=True, blank=True) I want to be able to create multiple users with blank emails, but when the email is not blank it has to be unique. Currently, when I create two users with a blank email I get this error: duplicate key value violates unique constraint "accounts_user_email_b2644a56_uniq" -
Displaying d3 chart in django
I was going through the library NVD3 and have found this as an example on the website: d3.json('cumulativeLineData.json', function(data) { nv.addGraph(function() { var chart = nv.models.cumulativeLineChart() .x(function(d) { return d[0] }) .y(function(d) { return d[1]/100 }) //adjusting, 100% is 1.00, not 100 as it is in the data .color(d3.scale.category10().range()) .useInteractiveGuideline(true) ; chart.xAxis .tickValues([1078030800000,1122782400000,1167541200000,1251691200000]) .tickFormat(function(d) { return d3.time.format('%x')(new Date(d)) }); chart.yAxis .tickFormat(d3.format(',.1%')); d3.select('#chart svg') .datum(data) .call(chart); //TODO: Figure out a good way to do this automatically nv.utils.windowResize(chart.update); return chart; }); }); The image is something like this: Check the live demo here: http://nvd3.org/examples/cumulativeLine.html The json file is here: Json file for example Now I was willing to include such charts in the django example. So I went on checking the implementation of Django-NVD3. But I could not find anything related to it and the documentation written by author is not understood by me. Please let me know how I can include d3 chart in the django frame in real time. -
the proper way to run django rq in docker microservices setup
I have somehow bad setup of my docker containers I guess. Because each time I run task from django I see in docker container output of ps aux that there is new process created of python mange.py rqworker mail instead of using the existing one. See the screencast: https://imgur.com/a/HxUjzJ5 the process executed from command in my docker compose for rq worker container looks like this. #!/bin/sh -e wait-for-it for KEY in $(redis-cli -h $REDIS_HOST -n 2 KEYS "rq:worker*"); do redis-cli -h $REDIS_HOST -n 2 DEL $KEY done if [ "$ENVIRONMENT" = "development" ]; then python manage.py rqworkers --worker-class rq.SimpleWorker --autoreload; else python manage.py rqworkers --worker-class rq.SimpleWorker --workers 4; fi I am new to docker and wondering a bit that this is started like this without deamonization... but is it a dockerish way of doing thing, right? -
Django complex query through builder
I have not been able to make a complex query using ORM for some time. I know that this is possible, so I will forgive help. class Game(models.Model): no matter class Competition(models.Model): game = models.ForeignKey(to='game.Game', verbose_name=_('game'), related_name='competitions', on_delete=models.PROTECT) class User(models.Mode): no matter class Balance(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE, primary_key=True) class BalanceTransaction(models.Model): TYPES = ( (TYPE_COMMISSION, _('commission')), } balance = models.ForeignKey(to=Balance, on_delete=models.CASCADE, related_name='transactions') amount = models.DecimalField(_('Transaction amount'), default='0.0', max_digits=28, decimal_places=18, null=False, blank=False) type = models.CharField(_('type'), max_length=10, default=TYPE_DEPOSIT, choices=TYPES, null=False, blank=False I have to return a queryset of games, where each element will have an additional "income" field that stores the sum of all transactions of this game with the type "commission" Game.objects.filter(publisher__owner=self.request.user.pk).annotate( income=Sum(Case( When( Q(publisher__owner__balance__transactions__type=BalanceTransaction.TYPE_COMMISSION), then=???, ) )) It seems that this way it will not be possible and I have to use subquery, but so far I haven't succeeded. -
Object of type Company is not JSON serializable when writing tests
I'm having an issue in Django RestFramework in testing. I have the following test: def test_update_coupon(self): response = self.make_coupon_request( kind="put", version="v1", id=2, data=self.valid_coupon_data ) self.assertEqual(response.status_code, status.HTTP_200_OK) Where make_coupon_request has a return of: return self.client.put( reverse("coupon", kwargs={ "version": kwargs["version"], "pk": kwargs["id"] } ), data=json.dumps(kwargs["data"]), content_type='application/json' ) and valid_coupon_data where the problem is occurring is: self.valid_coupon_data = { "company": Company.objects.get(id=1), "name": "Coupon Updated", "added": "2018-11-30", "code": "TESTCODE" } The error I am getting is in make_coupon_request that json.dumps cannot serialize valid_coupon_data: "TypeError: Object of type Company is not JSON serializable" I have a serializer for Company: class CompanySerializer(serializers.ModelSerializer): coupons = CouponSerializer(many=True, read_only=True) class Meta: model = Company fields = ("name", "coupons") And for coupon: class CouponSerializer(serializers.ModelSerializer): class Meta: model = Coupon fields = ("company", "name", "added", "code") Basically I know that somehow I need to use a serializer in order to make my test work, as json.dumps isn't accepting the raw Company object... but I am not sure how nor do I quite understand why. Here are my 2 models for reference: class Company(models.Model): name = models.CharField(max_length=255, null=False) class Meta: verbose_name_plural = "Companies" class Coupon(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, related_name='coupons') name = models.CharField(max_length=100) added = models.DateField(auto_now_add=True) code = models.CharField(max_length=255, null=False) -
Ansible django_manage throws UnicodeDecodeError on ubuntu server 18.04 but running the command manually works fine
I have a project (python 3.6, django v2.1) that I deploy using Ansible v2.4.6 to my VM ubuntu server 18.04 (on the old ubuntu server 16.04 there is no problem, everything works fine). I have a custom Django management command called ensure_initial_data: from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): perm_list = [ { 'content_type': ContentType.objects.get( app_label='app_accounting', model='account'), 'codename': 'account_list', 'name': 'ver lista de cuentas', }, { 'content_type': ContentType.objects.get( app_label='app_accounting', model='summary'), 'codename': 'summary_list', 'name': 'ver lista de resúmenes', }, ] self.stdout.write('Creating missing permissions ...') for i, kwargs in enumerate(perm_list): p, _ = Permission.objects.get_or_create(**kwargs) self.stdout.write(' {:03d} {:15s} {:40s} {}'.format( i + 1, p.content_type.app_label, p.codename, p.name)) Which I try to call it in Ansible like this: - name: run django "ensure_initial_data" django_manage: command: 'ensure_initial_data' app_path: '{{ django_app_base_dir }}' virtualenv: '{{ django_app_base_dir }}/.venv' notify: restart gunicorn app in supervisor it throws the following error (because of the letter with accent in the second Permission, in the word resúmenes): TASK [webserver : run django "ensure_initial_data"] ****************************************************************************************************** fatal: [ubuntu1]: FAILED! => { "changed": false, "cmd": "./manage.py ensure_initial_data", "failed": true, "msg": " stdout: Creating missing permissions ... 001 app_accounting account_list ver lista de cuentas contables stderr: … -
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty - Even when SECRET_KEY is set in settings.py
I'm having this error while trying to run my Teonite_project/web_scrapper.py script: File "C:/Users/kfhei/Desktop/Teonite_project/Teonite_project/web_scrapper.py", line 9, in <module> django.setup() File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\kfhei\Desktop\Teonite_project\Teonite_project\Teonite_project\settings.py", line 15, in <module> django.setup() File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\kfhei\Desktop\Teonite_project\env\lib\site-packages\django\conf\__init__.py", line 125, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. My script: from bs4 import BeautifulSoup from urllib.request import Request, urlopen #import simplejson as json import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Teonite_project.settings") import django django.setup() from words.models import Word from authors.models import Author URL_DOMAIN = 'https://teonite.com/blog/' def get_links(url): ''' Returning the array of links to blog articles … -
Postgres: subdivide table by a field
I have a spatial table with 100 million ish rows. When updating my data, I have often had to update all the rows that fall in some US state. I find that trying to do any operations on the 100 million record table is very slow. All of the rows have a state field (e.g. state_code=RI), but I can't figure out how to make good use of it. However, if I create a new table with just the rows in the state that needs updating, all read and update operations are very fast (maybe 100x faster). My question: is there a good way to quickly index by state, or should I just make a different db or table for each state? -
Get model attribute from other class in same model
How do I get value of another class in the same model? Can I also use properties? I want to use Finance.net_income and Finance.net_margin inside the Stats Class. I tried searching for an anwser but I couldnt find it, I am also new to django. class Stats(models.Model): stock = models.ForeignKey(Stock, on_delete=models.CASCADE) shares_outstanding = models.FloatField(default=0) @property def earnings_per_share(self): ####### ISSUE IS HERE ##### return Finance.net_income / self.shares_outstanding class Finance(models.Model): stock = models.ForeignKey(Stock, on_delete=models.CASCADE) total_revenue = models.FloatField(default=0) operating_income = models.FloatField(default=0) date = models.DateField(null=True, blank=True) net_income = models.FloatField(default=0) cash = models.FloatField(default=0) total_debt = models.FloatField(default=0) @property def operating_margin(self): if self.total_revenue: now = (self.operating_income / self.total_revenue)*100 else: now = 0 return now @property def net_margin(self): if self.total_revenue: now = (self.net_income / self.total_revenue)*100 else: now = 0 return now -
gunicorn and Django project
I just followed instructions from DigitaL Ocean. After: sudo gunicorn --bind 0.0.0.0:8000 nameofmyproject.wsgi:application bind Gunicorn my site is not available.I tried to change port from 8000 to 80, and then site is reachable, but without any static files like css and images. Don't know why this happens. sudo ss -naptu state listening | grep :80 Output is: tcp 0 128 *:8000 *:* users:(("gunicorn",pid=18461,fd=5),("gunicorn",pid=18455,fd=5)) What can I do? -
Django queryset values to be altered and sent to user in plain txt copy
This is my code able to sent plain text file to user with all queryset results but requirement is alignment of results by removing symbols. def save_search(request,q="deve"): filename = "mytext.txt" content =Buildkb.objects.values("text","knowledge","created_by_email"). filter(Q(knowledge__icontains=q)|Q(text__icontains=q)) response = HttpResponse(content, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename{0}'.format(filename) return response output:- {'knowledge': 'Deve Category.', 'created_by_email': 'user1@gmail.com', 'text': 'Deve'}{'knowledge': 'Software development life cycle (SDLC) is a series of phases that provide a common understanding of the software building process. How the software will be realized and developed from the business understanding and requirements elicitation phase to convert these business ideas and requirements into functions and features until its usage and operation to achieve the business needs. The good software engineer should have enough knowledge on how to choose the SDLC model based on the project context and the business requirement.', 'created_by_email': 'user3@gmail.com', 'text': '1.1'}{'knowledge': 'Software development life cycle (SDLC) is a series of phases that provide a common understanding of the software building process. How the software will be realised and developed from the business understanding and requirements elicitation phase to convert these business ideas and requirements into functions and features until its usage and operation to achieve the business needs. The good software engineer should have enough …