Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading multiple csv files in Django using multiple file field form
I have tried uploading one csv file using Django file field form and it works well. However, switching the file field form into multiple file field form yields to an error when trying to read the csv file. What I initially tried for single csv file: in forms.py class UploadForm(forms.Form): file_field = forms.FileField(allow_empty_file = False) in views.py input_file = request.FILES['file_field'] data_set = input_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) model_list = [] for row in csv.reader(io_string, delimiter = ',', quotechar = "|"): #create Django model object based on the row and append it to model_list Sample_Model.objects.bulk_create(model_list) What I currently try for multiple csv files: in forms.py: class UploadForm(forms.Form): file_field = forms.FileField(allow_empty_file = False, widget=forms.ClearableFileInput(attrs={'multiple': True})) in views.py: input_files = request.FILES.getlist('file_field') for file in input_files: data_set = file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) model_list = [] for row in csv.reader(io_string, delimiter = ',', quotechar = "|"): #create Django model object based on the row and append it to model_list Sample_Model.objects.bulk_create(model_list) I got a Stop Iteration error at the next(io_string) line. Upon browsing for its meaning and analysing the code, it seems data_set = file.read().decode('UTF-8') is the source of the problem as it does not work properly now. Thank you! -
Static files moved to a STATIC_ROOT but still none are being shown
Trying to deploy my site and everything is working fine except that the CSS in the admin page is non-existent. I have looked through all of the other posts where people have had this issue but i have already done the steps most of them forgot. I have the static files directed to the base directory with STATIC_ROOT = os.path.join(BASE_DIR, 'static'), when I ran python manage.py collectstatic, they all seemed to move into the base DIR just fine. Heres the code/file structure: In settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' Then the structure that this created after collectstatic: Obviously something isn't right or I wouldn't be here but Im stuggling to figure out what is incorrect. All help is appreciated. Thank you! -
FOREIGN KEY constraint failed - Django, SQLite3
My application allows Tenantprofiles to apply for Property viewings that are listed by Landlord profiles. I can't seem to link the two tables together I can't get past FOREIGN KEY constraint failed error. views.py from django.shortcuts import render, redirect from projects.models import Properties, Property_Applications, Property_Reviews from users.models import Landlord_Profile, Tenant_Profile from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import CreatingListingForm, ListingApplicationForm def property_apply(request, pk): project = Properties.objects.get(pk=pk) applyButton = ListingApplicationForm(request.POST) profile = request.user.tenant_profile if request.method == "POST": link = applyButton.save(commit=False) link.tenant_apply = profile link.listing=project link.save() messages.success(request, f'You have applied!') return redirect('/tenantportal/') else: link = applyButton context = {'project': project, 'applyButton': link} return render(request, 'application_submit.html', context) models.py - projects from django.db import models from PIL import Image from django.contrib.auth.models import User from django.contrib.auth import get_user_model from django.conf import settings from users.models import Landlord_Profile, Tenant_Profile class Property_Applications(models.Model): tenant_apply = models.ForeignKey(Tenant_Profile, on_delete=models.CASCADE, default=1) property_owner = models.ForeignKey(Landlord_Profile, on_delete=models.CASCADE,default=1) listing = models.ForeignKey('Properties', on_delete=models.CASCADE) app_description = models.TextField(default='app description') created = models.TextField(default=1) class Properties(models.Model): User = settings.AUTH_USER_MODEL landlord = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=100) rentPrice = models.FloatField() description = models.TextField() bedRooms = models.IntegerField() bathRoom = models.IntegerField() tenantCondtions = models.CharField(max_length=100) image = models.ImageField(upload_to='house_preview/') models.py - users from django.db import models from django.contrib.auth.models import User from PIL … -
expired confirmation email to return a JSON response in django-rest-auth
using Django-rest-auth and Django-allauth to handle email verification and signup in my rest api. When a user tries to verify their email after the link has expired, I get an unpleasant error page. ---> I would like to get a JSON response saying the email has expired. Below is the error message I get when I confirm the expired verification email. -
custom form validation errors in template
how can i pass custome form validation errors in template? forms.py '''' def clean_username(self): inputusername = self.cleaned_data['username'] if len(inputusername) < 6: raise forms.ValidationError('Sorry, your username must be between 6 and 30 characters long.') else: return inputusername '''' views.py '''' def signup(request): signup_form = CreateUserForm() if request.method == 'POST': signup_form = CreateUserForm(request.POST) if signup_form.is_valid(): signup_form.save() context = {'signup_form':signup_form} return render(request, 'formvalidationapp/signupform.html', context) '''' temlate '''' <form method="post" action="{% url 'signup' %}"> {% csrf_token %} <div class="row"> <div class="col-sm-6"> <h1>Sign Up</h1> </div> </div> <div> #i want to pass error here </div> '''' -
Why can't my user can't check their inbox?
So I am attempting to query and display messages between two users in an inbox. I am running into a problem where no messages are appearing for request.user's inbox. It's showing as empty when there are messages. However, when I go into an inbox for another user that my request.user has messaged while still logged in to request.user, I can see the messages from both parties there and displayed correctly. For the life of me, I don't understand why this is happening. Hell, request.user.username is passed through the template and my user's username actually prints. Yes, django.template.context_processors.request is already in my context processor. I tried doing if msg.receiver_id == request.user but that still doesn't work. What the hell am I doing wrong here? views.py/messages def messages(request, profile_id): messages = InstantMessage.objects.filter(Q(sender_id=request.user, receiver_id=profile_id,) | Q(sender_id=profile_id, receiver_id=request.user,) ).\ values('sender_id','receiver_id', 'message', 'date', ).\ order_by('date',) return render(request, 'dating_app/messages.html', {'messages': messages,}) messages.html {% for msg in messages %} {% if msg.receiver_id == user.id %} <li class="text-right list-group-item">{{ msg.message }}<br/>{{ msg.date }}<br/>{{ request.user.username }}</li> {% elif msg.sender_id == user.id %} <li class="text-left list-group-item">{{ msg.message }}<br/>{{ msg.date }}</li> {% endif %} {% empty %} {%endfor %} urls.py/messages path('messages/<int:profile_id>/', views.messages, name='messages') models.py class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): … -
how to fix "Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL" Error?
public static void main(String[] args) throws Exception { // check if the user enter the right args from the command line. if(args.length != 2){ System.out.println("Usage: java Reverse " + "http://<location of your servlet/script> " + "string_to_reverse");// display the error. System.exit(1); // exit the program. } /**the sting that will be reversed may contain spaces or other * non-alphanumeric characters. These characters must be * encoded because the string is processed on its way to the server. * the URLEncoder class methods encode the characters.*/ String stringToReverse = URLEncoder.encode(args[1], "UTF-8"); // create object for the specified url for the command line. URL url = new URL(args[0]); // sets the connection so that it can write to it. URLConnection connection = url.openConnection(); connection.setDoOutput(true); // I tried the follow things to fix the error but still not working. //connection.setRequestProperty("http.agent", "Chrome"); //connection.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); // connection.setRequestProperty("User-agent", "Mozilla/5.0"); // connection.setRequestProperty("User-agent", "Mozilla"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); // The program then creates an output stream on the connection // and opens an OutputSteamWriter on it; OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream()); // the program writes the required information t the output // stream and closes the stream. out.write("string = " … -
Django user model. 1 admin account, 1 customer account with the same email and different password
Im trying to handle a use case where i have 2 roles. (admin , customer) There will be an admin portal and a customer portal (2 different login pages ). An admin can invite a customer An admin can be a customer as well , can invite himself into the customer portal An admin account must not share the same password as the customer account. Email is used as the unique field for both admin and customer account. For example : Admin account - customer@email.com /password1 Customer account - customer@email.com /password2 Solution 1: - Permission. Having 1 account with admin permission and customer permission. (This cant work to fit the bussiness use case) Based on this article: https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html Solution 2: - Creating 2 django projects. One for each user model since both accounts cant share password. The reason for separating into 2 projects is because resources such as session,login, logout will not be shared. So each portal(admin,customer) has their own resource. A create Customer API to allow admin to create a customer account in customer django project. A shared db to share related data This is the only way i can think of to handle the use case. Please let … -
How to test a Django+Celery application with multiple queues
I am wondering if it is feasible to write functional tests for a Django application using multiple Celery queues. For a single queue, I used the solution explained here, and it worked great. What I would basically want to do is the following: from celery.contrib.testing.worker import start_worker from django.contrib.staticfiles.testing import StaticLiveServerTestCase from mysite.celery import app class MyTestCase(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.celery_worker1 = start_worker(app, perform_ping_check=False, queue="myqueue1") cls.celery_worker1.__enter__() cls.celery_worker2 = start_worker(app, perform_ping_check=False, queue="myqueue2") cls.celery_worker2.__enter__() @classmethod def tearDownClass(cls): super().tearDownClass() cls.celery_worker1.__exit__(None, None, None) cls.celery_worker2.__exit__(None, None, None) This code has two problems: I get the message /home/user/.local/lib/python3.7/site-packages/kombu/pidbox.py:74: UserWarning: A node named gen18391@Machine is already using this process mailbox! which leads me to think that multiple workers aren't handled properly. The "queue" argument isn't in the documentation and is likely not parsed at all. Consequently, the task sent to the second queue isn't being executed. -
What is the best practice for an internal API call in django
I've developed a chess API in django. I intend to develop a client for it as well. What would be the best practice for a client? Develop the client as another app in the same project in django, and perform internal API calls using requests(Is it better than calling the API externally performance wise? ) Develop the client as another app in the same project in django, and call the API's views using Django. (How would I do this, as the API expects JSON data in request) Develop the client as a standalone. -
django // conditional settings depend on aws instance server
Environment django 2.2 python 3.6 AWS EC2 ubuntu instance gunicorn nginx My setting Now I'm using one production server aws ubuntu instance. I separated settings.py depond on local and production server as follows. # local : Project/setting/dev.py DEBUG = True ALLOWED_HOSTS = ['localhost'] database = { ..skip.. } # production : Project/setting/real.py DEBUG = False ALLOWED_HOSTS = ['~real_server_host of ec2~'] database = { ..AWS RDS instance for real.. } # manage.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project.settings.dev") # wsgi.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project.settings.real") Question I have to operate one more aws instance for test before deploy to real. So I made same EC2 instance and RDS instance(dumped from real rds) for test. But I don't have any nice idea how to seperate os.environ.setdefault in wsgi.py Once I made one more settings file for test server. # Project/setting/test.py DEBUG = True ALLOWED_HOSTS = ['~test_server_host of ec2~'] database = { ..AWS RDS instance for test.. } I expect the code below to work. # wsgi.py if realserver: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project.settings.real") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project.settings.test") and I have to use another api url depend on real or test. # views.py if real: get_data = requests.get(real_api.apiurl.com) else : get_data = requests.get(test_api.apiurl.com) How do I? -
How can I solve this problem SMTPAuthenticationError? [django]
I uploaded my website on the free host on Heroku and now when I click on forget password and send theSMTPAuthenticationError (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials l189sm7124459qkd.112 - gsmtp') I don't completely understand what is going on anybody can explain this issue -
DJANGO FORM RETURN HTML RAW CODE IN BROWSER
So im new in django and im learning to use django form i already try several tutorial but m django form return html raw code and idk where i did wrong please help # Create your views here. from django.shortcuts import render from django.http import HttpRequest from django.http import HttpResponse from .forms import SettingForm from django import forms def setting(request): form = SettingForm(request.POST or None) if form.is_valid(): form.save() context = { 'form' : form } return render(request, 'setting.html', {'name': 'Navin'}, context) this is my view from django import forms from .models import myform class SettingForm(forms.ModelForm): class Meta: model = myform fields = '__all__' my django forrms.py {% load static %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript %} <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>WOMBASTIS</title> <style> .hidden{ display:none; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> function myFunction() { var x = document.getElementById("myDIV"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> </head> <body> <h1>Hello {{name}}</h1> <form> {% csrf_token %} {{ form }} </form> </body> </html> the return was exactly that raw code in browser page -
Can one use Django for web scraping into a database?
I have a seemingly rare problem as I cannot find any resources on my issue. I have a fully functioning Django Rest-API framework backend that interacts with a database. I need to continuously scrape live data from the web and feed it into the same database for my application to work. I have already built a multi-threaded python web-scraping script (using Selenium) that runs in a "while True:" loop meant to never stop running, but I am unsure whether to add this code to my existing Django project, a separate and new Django project, or a separate file altogether. Since my database is made up of Django's object oriented models, my scraping script would run best inside of a Django framework as it can feed the database with ease. I am however, open to other methods. Note, I plan to push all of this to Amazon Web Service soon. My question is: Is Django fast enough for my purposes? Or is there a better way to do this? Thank you for your ideas in advance. -
(Rest framework, Django) __init__() takes 1 positional argument but 2 were given
I'm trying to create a new API file with django-rest-framework and use serializers, but for some reason I keep getting this error even if i do everything exactly as the tutorials(yes, I've tried more than one and they all lead to the same error). my basic model (Models.py @blog): class BlogPost(models.Model): title=models.CharField(max_length=12) description=models.TextField() name=models.IntegerField(default=0) def __str__(self): return self.title Serializers.py @blog.api: class BlogPostserializer(serializers.ModelSerializer): class Meta: model=BlogPost fields=('title','description','name') viewsets.py @blog.api class BlogPostView(viewsets.ModelViewSet): queryset=BlogPost.objects.all() serializer_class= BlogPostserializer Thanks in advance. -
Navbar toggle doesn't show icons after click on small screen
Django, Bootsrap 4; I have this navbar with toggle: <nav class="navbar navbar-expand-lg navbar-dark fixed-top bg-dark white scrolling-navbar" role="navigation"> <div class="container"> <a class="navbar-brand waves-effect" href="{% url 'product-list' %}"> <img src="../../../media/Logo.png" width="40" class="d-inline-block align-top"> <strong class="blue-text">Marche Saluk</strong> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <!-- Left of navbar --> <ul class="navbar-nav mr-auto"> {% if request.user.is_staff %} <li class="nav-item active"> <a class="nav-link waves-effect" href="{% url 'product-create' %}"> <span class="clearfix d-none d-sm-inline-block"> <i class="fa fa-plus-square-o" aria-hidden="true"></i> Create Product </span> </a> </li> {% endif %} {% if request.user.is_staff or request.user|has_group:"limited_staff" %} <li class="nav-item active"> <a class="nav-link waves-effect" href="{% url 'orders-view' %}"> <span class="clearfix d-none d-sm-inline-block"> <i class="fa fa-list-ul" aria-hidden="true"></i> Orders <span class="badge badge-pill badge-danger">{% orders_count request.user %}</span> </span> </a> </li> {% endif %} </ul> <!-- Right of navbar --> <ul class="navbar-nav nav-flex-icons"> {% if request.user.is_authenticated %} <li class="nav-item active"> <a class="nav-link waves-effect" href="{% url 'product-list' %}"><span class="clearfix d-none d-sm-inline-block"> <i class="fa fa-bars" aria-hidden="true"></i> Products List </span> </a> </li> <li class="nav-item active"> <a href="{% url 'cart-view' %}" class="nav-link waves-effect"> <span class="clearfix d-none d-sm-inline-block" style="color: greenyellow;"> <i class="fa fa-shopping-cart" aria-hidden="true"></i> Cart </span> <span class="badge badge-pill badge-danger">{% cart_items_count request.user %}</span> </a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" … -
Caching base.html only in Django
My base.html template, which is extended in nearly all of my pages, contains a header that I never want to be cached since it contains the username of the current user. I have two pages where it keeps getting cached though. I tried adding a {% cache 0 base request.user.username %} for the header, but to no avail. I don't want to have to add a @never_cache since I want to keep most of the DOM cached. Is there a way to add a never_cache decorator/functionality to my extended base.html only? -
Cannot resolve keyword 'slug' into field. Choices are: ... in django
hello guys is searched a lot and test the changing slug_url_kwarg but still problem does not solved! can anyone say why this error happening? here is my model.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #additional blood_type = models.CharField(max_length=2,blank=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) description = models.TextField(blank=True) case =models.CharField(max_length=30,blank=True) def __str__(self): return self.user.username and here is my views.py: basically I want to set a view that shows every person that has same blood_type to the person who loged in and case field is for whether a person is a donor or reciver and we want to match this people so i need the opposite case of the person who loged in for example if the loged in person is "reciver" with "blood type" : A+ i need a detail views of all the "blood donor" with "blood type" A+ class ProfileDetailView(DetailView,LoginRequiredMixin): model = UserProfile template_name = 'basicapp/detail_view.html' context_object_name = 'pro_detail' def get_queryset(self): user = UserProfile.objects.get(user=self.request.user) bloodType = user.blood_type Case = user.case return UserProfile.objects.filter(blood_type__exact=bloodType and ~Q(case__exact=Case)) and here is my url.py: urlpatterns = [ path('',views.index, name='index'), path('register/', views.register,name='register'), path('<slug:slug>/',views.ProfileDetailView.as_view(),name='detail_view') ] -
Reading and Writing to PDFs stored in Django Models.py
I apologize if this question seems silly, I am still learning Django. My goal is to Have PDF's stored in Models.py Have User input data Transfer Data to string type Print strings on PDF Store new PDF in user account. Can I store PDFs in Django Models.py under ImageField? Documentation doesn't seem to mention PDFs much. I'm thinking of trying something along the lines of: from django.db import models class Model(models.Model): text = models.CharField(max_length=30, unique=False) pdf = models.ImageField(upload_to='media/pdfs') with a form.py structured like this: from django import forms from model.models import Model class textForm(forms.ModelForm): class Meta: model = Model fields = ('text',) With a Views.py structured like this: def user_view(request): text = form.cleaned_data.get('text') can.drawString(10, 100, Model.text) existing_pdf = PdfFileReader(open("media/01.pdf", "rb")) page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) PdfFileWriter().addPage(page) return render(request, "app/fill_form.html", context) Any help or advice would be much appreciated. Thank you. -
not able to create a ForeignKey in the django models
I am creating quiz app in which each user can store there choices to question and I want Choice model as ForeignKey of model Question but getting error while makemigrations models : class Choice(models.CharField): ans = models.CharField(max_length=50) def __str__(self): return self.ans class Meta: ordering = ['ans'] class Question(models.Model): que = models.CharField(max_length=200) choice = models.ForeignKey(Choice,on_delete=models.CASCADE) def __str__(self): return self.que class Meta: ordering = ['que'] error : (venv) bhupesh@Laptop:/home/mydata/challenges$ python manage.py makemigrations Traceback (most recent call last): File "/home/mydata/challenges/venv/lib/python3.6/site-packages/django/db/models/fields/related.py", line 786, in __init__ to._meta.model_name AttributeError: type object 'Choice' has no attribute '_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/mydata/challenges/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/mydata/challenges/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/mydata/challenges/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mydata/challenges/venv/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/mydata/challenges/venv/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/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 … -
Problem reading file with pandas uploaded to a django view
I'm uploading some excel and csv files to a django view using axios, then i pass those files to a function that uses pandas read_csv and read_excel functions to process them, the first problem i had was with some excel files that had some non utf-8 characters that pandas was unable to read, the only solution i found was to set "engine = 'python'" when reading the file (changing the encoding to utf-8-sig or utf-16 didn't work). This works when i'm testing the script from my terminal, but when i use the same script on a view i get the following error: ValueError("The 'python' engine cannot iterate through this file buffer.") This is the code i'm using: try: data = pandas.read_csv(request.FILES['file'], engine="python") except: print("Oops!",sys.exc_info(),"occured.") trying the same function through the terminal works fine pandas.read_csv("file.csv", engine="python") -
Levels of Authorization depending on Authentication method - Django
Using Django, I am trying to figure out how to limit a users permissions depending on the method used to login. In my specific case, a user will scan a QR code, (or let's say he went to a less secure login page)then he will only have basic permissions. If he went to the website and logged in fully, he would have fully authenticated permissions. How would I go about implementing this using Django? -
Django-simple-history to display logs on webpage other than admin website
I have been successful to register Django-simple-history with admin page. I have now been trying to get audit (CRUD) logs to display on a webpage other than the admin site. The page currently displays blank. Here is my attempt to get this working - views.py file def audit_trail(request, id): if request.method == "GET": obj = My_Model.history.all(pk=id) return render(request, 'audit_trail.html', context={'object': obj}) audit_trail.html file {%extends "did/base.html" %} {% block content %} {% for h in object%} {{ h.id }} {{ h.carrier }} {% endfor %} {% endblock content %} url pattern path('audit_trail/', views.audit_trail, name='audit_page'), ** Model File ** from django.db import models from django.utils import timezone from django.contrib.auth.models import User from simple_history.models import HistoricalRecords class My_Model(models.Model): field1 = models.CharField(max_length=100) field2 = models.DateTimeField(default=timezone.now) field3 = models.CharField(max_length=100) history = HistoricalRecords() -
Easiest way to run a Python script on a website
I want to run a script on a website that just takes one input does some web scraping and then prints some data on the website. I know very little about websites (just some about the html and css) and I'm wondering what the easiest approach is for me. Is it to use Django or Flask somehow on a XAMPP server or is there an easier way? All help is greatly appreciated! -
Combining fields for a historic overview of equity portfolio performance
I'm trying to create an equity portfolio app but are having trouble creating an overview of the historic performance of a portfolio. I have four models on my django site: One for Company details class CompanyDetail(models.Model): ticker = models.CharField(max_length=100) name = models.CharField(max_length=250) description = models.TextField() def __str__(self): return self.ticker One for historic prices for each company: class EquityEOD(models.Model): equity = models.ForeignKey( 'asset_details.CompanyDetail', on_delete=models.CASCADE, ) date = models.DateField(default=date.today) close = models.DecimalField(decimal_places=4, max_digits=15, default=0) def __str__(self): return self.equity.ticker One for the portfolio information: class Portfolio(models.Model): portfolio_name = models.CharField(max_length=200) def __str__(self): return self.portfolio_name And then finally a model for each trade class Trade(models.Model): portfolio = models.ForeignKey( Portfolio, on_delete=models.CASCADE, ) equity = models.ForeignKey( 'asset_details.CompanyDetail', on_delete=models.CASCADE, ) trade_date = models.DateField(default=date.today) amount = models.IntegerField(default=0) buy_price = models.DecimalField(decimal_places=2, max_digits=15, default=0) def totalcost (self): totalcost = self.buy_price*self.amount return totalcost def lastEOD (self): lastEOD = EquityEOD.objects.filter(equity=self.equity).order_by('-date')[0] return lastEOD def holdingvalue(self): holdingvalue = self.lastEOD().close*self.amount return holdingvalue def __str__(self): return self.equity What I'm trying to do now is to take the last years EquityEOD (equity end of day closing price) for each portfolio holding and adding them together to get an overview of how the entire portfolio have performed during the year. But I'm completely stuck on how to solve this.