Form select field that refreshes page with post data
I want to add a select field that is populated via a queryset, and when a choice is made refresh the template page (home.html) so that a variable inside my view changes and refreshes the JSON data being passed through to the template. Right now, I can manually change the value inside the view & manually refresh, but want the user to be able to select which value they want based on table object values. The range_chart(request) feeds home.html which loads a chartjs line chart with multiple series. I want the form to display all unique values from the rrSec field, and be ordered.
models.py:
from django.db import models
from datetime import datetime
class rr_values(models.Model):
rrDate=models.DateField(default=datetime.now)
rrSec=models.CharField(max_length=30)
rrTrend=models.CharField(max_length=30)
rrLow=models.FloatField()
rrHigh=models.FloatField()
rrClose=models.FloatField()
class Meta:
db_table='rr_values'
views.py:
thisSec = "COMPQ"
def home(request):
return render(request, 'home.html', {'rrSymbol': thisSec})
class SymbolForm(forms.Form):
formqs = forms.ModelChoiceField(queryset=rr_values.objects.all().values_list('rrSec', flat=True).distinct())
def range_chart(request):
labels = []
data = []
data1 = []
data2 = []
rrSymbol = thisSec
qs = rr_values.objects.all().filter(rrSec=rrSymbol).order_by("rrDate")
for entry in qs:
labels.append(entry.rrDate)
data.append(entry.rrClose)
data1.append(entry.rrLow)
data2.append(entry.rrHigh)
return JsonResponse(data={
'labels': labels,
'data': data,
'data1': data1,
'data2': data2,
})
See also questions close to this topic
-
403 Forbidden: AWS S3, Django, S3Boto3Storage, CKEditor
After several days of continuous attempts, I'm nearly ready to give up. I have a popular setup and I see many people have similar issues, but there is no comprehensive (and working!) answer.
I get this sort of errors in browser:
GET https://hull2hull-bucket.s3.amazonaws.com/ckeditor/ckeditor/?AWSAccessKeyId=AKIAVIMQUGHJHHUVNIPN&Signature=LDq%2F5bhKJUUIUIUUO3GGoH0Iksoho%3D&Expires=1618438498lang/en.js&t=K5H9 net::ERR_ABORTED 403 (Forbidden)
My website is powered by Django and hosted on Pythonanywhere. Static files are on Amazon S3 with a private policy. I connect Django and S3 bucket with S3Boto3Storage. Most of my static files (picture library, admin files etc) are working fine, but not when it comes to some js files or specific components. Particularly CKEditor and Debug Toolbar are refusing to work.
What I tried:
- make my bucket public - FAILED (but maybe did it wrong somehow? how can I check the effect?)
- edit CORS - FAILED (I had some CORS errors initially, those were fixed)
My current CORS:
[ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "HEAD", "GET" ], "AllowedOrigins": [ "https://hull2hull-bucket.s3.amazonaws.com", "http://127.0.0.1:8000", "http://127.0.0.1", "http://localhost", "http://localhost:8000" ], "ExposeHeaders": [] } ]
- change policy - FAILED
My current policy:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::hull2hull-bucket/" } ] }
- install corsheaders - FAILED (again, maybe helped with some CORS errors initially)
I really don't know what else is left to do. I believe I have quite popular setup for a website, there are tons of similar questions everywhere, and yet - no answer :(
-
working with Q in django and combining QuerySet
There are two models
Orders
andClients
, when created, the samerelated_uuid
is generated for each. That is, they are so connected. When searching on the site, you need to find all occurrences in both models and display allOrders
, including those whererelated_uuid
occurs in theClients
model.models.py
class Orders(models.Model): device = models.CharField(max_length=150) related_uuid = models.CharField(max_length=22, blank=True) def __str__(self): return self.device class Clients(models.Model): name = models.CharField(max_length=150) related_uuid = models.CharField(max_length=22, blank=True) def __str__(self): return self.name
views.py
def getQuery(self): search_query = self.request.GET.get('filter') results_query1 = Orders.objects.filter(Q(device__icontains=search_query)) results_query2 = Clients.objects.filter(Q(name__icontains=search_query)) conds = Q(related_uuid__icontains=results_query1) | Q(related_uuid__icontains=related_query2) search_filter_three = Orders.objects.filter(conds) return search_filter_three
- that is, I am looking for occurrences in both models.
- then I try to select all inputs in the
Orders
model by therelated_uuid
field from both models.
outputs
django.db.utils.OperationalError: (1241, 'Operand should contain 1 column (s)')
-
Настройка nginx для react и Django RESTfull api
Пытаюсь развернуть на одном сервере проект в связке React + Django + Nginx rest. Как мне настроить nginx, чтобы запросы с реакта приходили на джанго рест. На данный момент настройки вот такие, фронт отображается, но запрос по апи отправить не получается. Подскажите, пожалуйста, где туплю
server { listen 80; server_name_; location / { root /home/django/SocInve/frontend/build; index index.html index.htm; } keepalive_timeout 5; location /static/ { alias /home/django/SocInve/frontend/build/static/; } location /api/ { proxy_pass http://127.0.0.1:80/api/; } }
-
Adding POST parameters after form submit
I have this form:
<form name="form" action="course_submit.php" onsubmit="return validateForm()" method="post"> ... </form>
And I'd like to add a few json arrays to POST in validateForm() after validation, so that when validateForm() returns true, the updated POST will be sent to course_submit.php. What's the best wya to go about this? Thanks!
- View like this in Android
-
is there a code i can add to sort a dropdown list in alphabetical order?
I need to sort the location items in alphabetical order in this search form: http://v2trgmanagementcompanycom.temp312.kinsta.cloud/portfolio/
The locations should be listed alphabetically. Can someone help with updating the below code?
This is the current code:
<?php $array = OSF_Custom_Post_Type_Portfolio::getInstance()->get_all_meta_field_value(); ?> <div class="search-project"> <form action="<?php echo get_post_type_archive_link('osf_portfolio'); ?>" method="get"> <div class="d-flex justify-content-center project-group"> <div class="project-inner"> <select name="osf_portfolio_type"> <option value=""><?php echo esc_html__('I'm Looking For', 'rehomes'); ?></option> <?php foreach ($array['osf_portfolio_type'] as $item) { ?> <option value="<?php echo esc_attr($item); ?>" <?php echo esc_attr($item == $_GET['osf_portfolio_type'] ? 'selected' : ''); ?>><?php echo esc_html($item); ?></option> <?php } ?> </select> </div> <div class="project-inner"> <select name="osf_portfolio_location"> <option value=""><?php echo esc_html__('Location', 'rehomes'); ?></option> <?php foreach ($array['osf_portfolio_location'] as $item) { ?> <option value="<?php echo esc_attr($item); ?>" <?php echo esc_attr($item == $_GET['osf_portfolio_location'] ? 'selected' : ''); ?>><?php echo esc_html($item); ?></option> <?php } ?> </select> </div> <div class="project-inner align-self-end"> <button type="submit" class="btn btn-primary btn-block" style="color:white;background-color: black;"> Search </button> </div> </div> </form> </div>
-
how to get result from two query mysql
i want to fetch data from two table
table 1 : posts
user post no. 1 6 2 3 3 10 table 2 : my following (my no=1)
user other user id 2 1 1 3 i want to select all post which is not posted by me and user whose i am following.
how can i do this by mysql join ? also how to count that how many posts are there like this in db. sorry for bad english. thanks in advance .
-
Simplification of SQL Query
SQL is not my specialty. I have a working query that accomplishes what I need it to, but I know there has got to be a cleaner way of accomplishing my goal.
The query should return:
- Name - Date of most recent donation (if any) - Political Party guess as: R, D, or U, where: - R = Likely Republican (more republican donations than other donations) - D = Likely Democrat (more democrat donations than other donations) - U = Undtermined (no donations on record, or R and D are tied for first place. - Address
Here is a SQLFiddle link to where you can find the tables and my solution: http://sqlfiddle.com/#!9/f2303f/2. Alternatively, here is the schema build:
CREATE TABLE People ( ID INT UNSIGNED DEFAULT '0000' NOT NULL, Name CHAR(20) DEFAULT '' NOT NULL, Address CHAR(40) DEFAULT '' NOT NULL, PRIMARY KEY(ID)); INSERT INTO People VALUES (1, "Name1", "Idaho"), (2, "Name2","UCLA"), (3, "Name3", "Carolina"), (4, "Name4", "Portland"); CREATE TABLE Donations ( ID INT UNSIGNED DEFAULT '0000' NOT NULL, People_ID INT UNSIGNED DEFAULT '0000' NOT NULL, Donation_Date DATE NOT NULL, Party INT SIGNED DEFAULT '0000' NOT NULL, PRIMARY KEY(ID)); INSERT INTO Donations VALUES #Name1 (1, 1, "2000-06-23", 1), (2, 1, "2000-06-24",-1), #Name2 (3, 2, "2001-06-25", 1),(4, 2, "2001-06-26", 1), # Name3 (5, 3, "2002-06-26", -1),(6, 3, "2002-06-27", -1); #Name4 #None
And here is the query:
SELECT Name, IFNULL(donation_date, 'None') as 'Recent Donation', IFNULL(voting_guess, "U") as 'Party Guess', Address FROM people p LEFT JOIN donations on donations.people_id = p.id AND donations.donation_date = ( SELECT MAX(donation_date) FROM donations WHERE donations.people_id = p.id) LEFT JOIN (SELECT people_id, (CASE WHEN SUM(party) > 0 THEN "R" WHEN SUM(party) < 0 THEN "D" END ) AS voting_guess FROM donations GROUP BY people_id ) voting ON P.id = voting.people_id
Specifically, I'd like to try and condense the latter two left joins into one. Any advice?
-
Listbox as index to select item and goto row (cell)
I have a very large sheet and I want to use a Listbox as an index to click on it and jump (goto) to the rows, which contain the text from the Listbox. I have no experience with this and would like to know: How do I get all the rows starting with the # (e.g. # Test 1) in the list box? How can I jump to the row I click in the Listbox?
The screenshot below illustrates what I like to do.
Thanks a lot. enter image description here
-
NodeJS multiple databases
I am trying to send SQL over to multiple databases and create views in them. Is it possible to do this in NodeJS? Is there any better way to abstract the process by not having to write code for each database?
-
"'_reactNative.default.create' is undefined" Cant seem to find any solution
SO I created a project and copied components, assets and config folder from other laptop to this one. In this new project, I resolved dependencies still I am stuck at this error and cannot find any solution. Any help would be appreciated.
*
> TypeError: _reactNative.default.create is not a function. (In > '_reactNative.default.create({ > screen: { > flex: 1 > }, > view: { > flex: 1 > } })', '_reactNative.default.create' is undefined) ERROR Invariant Violation: Module AppRegistry is not a registered callable > module (calling runApplication). A frequent cause of the error is that > the application entry file path is incorrect. > This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.