Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
aggregate values from mongo_Db in Django
I am using mongo-DB, I have django model called expense_claim which fields like employee_name , date, price , tax etc. i am trying to aggregate total claims and total value of claims initiated by a particular employee on monthly basis. so i want my output something like this. month employee total jan john 5000 jan jack 2500 feb john 4000 feb jack 0 I think there could be two ways of doing this either write a logic in the view or maybe some inbuilt django model function Thankss -
How to make a small part of code in views.py to run for every x minutes in django server (using gunicorn and nginx)
I have to run a reset the all values of a game every four minutes. Meanwhile, if the game runs for 2 minutes last 30sec should be used to compute the result. Following the above two criteria how to design my game. And I have made some effort to do this which is successful on localserver but on the production server it is not working properly. Here is my source code link Please help me to solve this issue. -
search_view() missing 1 required positional argument: 'slug'
error TypeError at /chat/search/ search_view() missing 1 required positional argument: 'slug' Request Method: POST Request URL: http://127.0.0.1:8000/chat/search/ Django Version: 3.0.7 Exception Type: TypeError Exception Value: search_view() missing 1 required positional argument: 'slug' my model: class UserProfile(models.Model) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') slug = models.SlugField(blank=True) image = models.ImageField(default='face.jpg', upload_to='images/avtar') friends = models.ManyToManyField("UserProfile", blank= True) def __str__(self): return self.user.username def get_absolute_url(self): return "/chat/{}".format(self.slug) def last_seen(self): return cache.get('last_seen_%s' % self.user.username) def post_save_user_model_receiver(sender, instance, created, *args, **kwargs): if created: try: Profile.objects.create(user=instance) except: pass post_save.connect(post_save_user_model_receiver, sender=settings.AUTH_USER_MODEL) My urls: url(r'^(?P[\w-]+)/$',search_view), url(r'^friend-request/send/(?P<id>[\w-]+)/$', send_friend_request), url(r'^friend-request/cancel/(?P<id>[\w-]+)/$', cancel_friend_request), my view: def search_view(request, slug): p = UserProfile.objects.filter(slug=slug).first() u = p.user;print(u) sent_friend_requests = FriendRequest.objects.filter(from_user=p.user) rec_friend_requests = FriendRequest.objects.filter(to_user=p.user) friends = p.friends.all() # is this user our friend button_status = 'none' if p not in request.user.profile.friends.all(): button_status = 'not_friend' # if we have sent him a friend request if len(FriendRequest.objects.filter( from_user=request.user).filter(to_user=p.user)) == 1: button_status = 'friend_request_sent' if request.method =='POST': query = request.POST.get('search') results = User.objects.filter(username__contains=query) context = { 'results':results, 'u': u, 'button_status': button_status, 'friends_list': friends, 'sent_friend_requests': sent_friend_requests, 'rec_friend_requests': rec_friend_requests } return render(request, 'chat/search.html', context) -
Django Mongodb output is same for each command
I have used MongoDbManager in my models to apply raw_query: class BatDataSoh(models.Model): _id = models.CharField( primary_key=True,max_length=100) bid = models.CharField(max_length=10) soh = models.IntegerField() cycles = models.IntegerField() objects = MongoDBManager() class Meta: db_table = "batDataSoh" This is my modal output: >>> b=BatDataSoh.objects.raw_query({'bid':'b10001'}) >>> print(len(b)) 9973 >>> b=BatDataSoh.objects.raw_query({'bid':'sdfj'}) >>> print(len(b)) 9973 In every query, the output is the same, Even in the 2nd query there is no bid with "sdfj" this name, If you know the solution, please post your answer. Thanks in advance -
Having problem in sending email through django using EmailMultiAltenatives
I am trying to send emails through django. This is my order.html file: <body> <img src="{% static 'assets/img/logo/original.jpg' %}" alt=""> {% for order in orders1 %} <h1>Your order number is <strong>{{order}}</strong></h1> {% endfor %} </body> This is my order.txt file: {% for order in orders1 %} Your order number is {{order}} {% endfor %} And this is my views.py: from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.template import Context def email(request): orders1=Order.objects.filter(id=20) d = { 'orders': Order.objects.filter(id=20) } subject, from_email, to = 'hello', settings.EMAIL_HOST_USER, 'vatsalj2001@gmail.com' text_content = get_template('emails/order.txt').render(d) html_content = get_template('emails/order.html').render(d) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return render(request,'emails/order.html',{'orders1':orders1}) The concern is that the email which is being sent only contains the subject('hello') and in the email body there shows an icon(with a cross) instead of image that I want and also no text shows up which I set in template. Also what is the need and requirements of having a text and html file for email? -
why my submit button's not working in updateview in Django?
When I click on submit button it goes nowhere and does nothing. Can you spot me the mistake? I want to update on department field and year field. Also I'm using MultiSelectField from django-multiselectfield third party. The form shows up correctly except submit button's not working. here is my models.py class Teacher(models.Model): type_choice = (('Full Time', _('Full Time')), ('Part Time', _('Part Time'))) departments = ( ('TC', 'Foundation Year'), ('GIC', 'Software Engineering'), ('GEE', 'Electrical Engineering'), ('GIM', 'Mechanical Engineering'), ('OAC', 'Architecture'), ('OTR', 'Telecom'), ('GCI', 'Civil Engineering'), ('GGG', 'Geotechnical Engineering'), ('GRU', 'Rural Engineering') ) years = ( ('year1', 'Year1'), ('year2', 'Year2'), ('year3', 'Year3'), ('year4', 'Year4'), ('year5', 'Year5') ) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) teacher_type = models.CharField(max_length=50, choices=type_choice) department = MultiSelectField(choices=departments) year = MultiSelectField(choices=years) def __str__(self): return '%s %s' % (self.user.email, self.teacher_type) forms.py class TeacherForm(forms.ModelForm): class Meta: model = Teacher fields = ['teacher_type', 'department', 'year'] views.py @method_decorator(teacher_required, name="dispatch") class TeacherDepartEditView(LoginRequiredMixin, UpdateView): model = Teacher login_url = "/" form_class = TeacherForm template_name = "attendance/content/teacher/teacher_dep_edit.html" def get_success_url(self): return reverse('teacher_info') template <form method="POST"> {% csrf_token %} <div class="row mt-3"> <div class="col-md-6"> <label>Choose department ( can choose more than one )</label> {{ form.department}} </div> <div class="col-md-6"> <label>Choose Year ( can choose more than one )</label> {{ form.year }} … -
Creating Tags and filtering according to them in django
I'm creating a blog application to share interview experiences and i would like to filter the blog posts based on year, company of interview and job roles etc.. how do i take the above parameters as tags and when clicked on a certain tag, have to show all posts on that? My model looks like this class experience(models.Model): name=models.CharField(max_length=200) job_role=models.CharField(max_length=200) company=models.CharField(max_length=200) year=models.CharField(max_length=20) -
images are not showing in django
hi when i am saving images from my admin they are saved in project directory like this images/images/myimg.jpg.. but when i am trying to display them in my template like this <img src="{{About.image.url}}" alt="profile photo"> the image do not displays.. when i inspect the page in chrome... it shows image source unknown.. <img src="(unknown)" alt="profile photo"> please see the files .. settings.py STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR,'portfolio/static') ] STATIC_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL ='/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'images') project urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('home/', include("home.urls")), path('blog/', include("blog.urls")), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT ) the model having image is inside a app named 'home' models.py of home app from django.db import models import datetime # Create your models here. class About(models.Model): image = models.ImageField(upload_to = 'images') desc = models.TextField() home/views.py from django.shortcuts import render from home.models import * from django.views.generic import ListView # Create your views here. def index(request): abt = About.objects.all() return render(request,'home/index.html',{'abt': abt.first()}) def Experience(request): Exp = Experience.objects.all() return render(request,'home/Experience.html',{'Exp': Exp}) class MyView(ListView): context_object_name = 'name' template_name = 'home/index.html' queryset = About.objects.all() def get_context_data(self, **kwargs): context = super(MyView, self).get_context_data(**kwargs) context['Experience'] = … -
How to upload ebooks on dtabaseses
I recently started creating a website with angular and Django. This is to be an online bookstore or an ELibraby something like Amazon Kindle, my problem is that I found out that it's not advisable to store ebooks on a database but I need a way for users to get these ebooks from the database and for admins to be able to upload to some sort of file system since database is not possible, please is there anyway I can accomplish this on my site. I have checked the internet but I haven't seen anything helpful, maybe I am searching wrong or something but I will really appreciate any advice. And also I will like to know if there is any API that can help me add books to my website at least to fill in some space till actual ebooks are uploaded. Any advise will really help... -
Django get nearby objects based on locations (coordinates) in two models and serializers?
I'm struggling a little bit about how to get objects around a radius in Django Rest Framework. Basically, what I need is to get restaurants & promotions based on Point (coordinates - latitude and longitude), so for example if I have 2 restaurants and 4 promotions I just pass the location in coordinates and want to get only nearby ones from those 2 restaurants and promotions, from their respectively endpoint. (/restaurant and /promotion) I get it working for Restaurant, but not for Promotion since that model don't have location field but has a Foreign key with Restaurant I though it could work fine ... but nope. So I'm out of ideas ... I put what I have done below: Models.py from django.contrib.gis.db import models class Restaurant(models.Model): """Restaurant model""" restaurant_name = models.CharField(max_length=255) address = models.TextField() city = models.CharField(max_length=120) state = models.CharField(max_length=120) zip_code = models.CharField(max_length=10) location = models.PointField() # ... def __str__(self): return self.restaurant_name class Promotion(models.Model): """Promotion model""" promotion_name = models.CharField(max_length=100) # ... restaurant_name = models.ForeignKey(Restaurant, on_delete=models.CASCADE) def __str__(self): return self.promotion_name serializers.py class RestaurantSerializer(serializers.ModelSerializer): class Meta: model = Restaurant fields = '__all__' class PromotionSerializer(serializers.ModelSerializer): restaurant_name = serializers.StringRelatedField() # location = PointField(source='restaurant_name.location') class Meta: model = Promotion fields = '__all__' And finally my … -
How to Get Server Error Message in Debug=False
I am new to Django and made a custom handler500 page for when debug=False: def handler500(request, *args, **argv): // Send me a Slack message of the error return render(request, '500.html', status=500) As shown in the comment, I want to send myself a Slack message of the 500 error (as would be shown in debug=True. How can I access that error message? Thanks! -
Django Form - Getting last record value from database as dynamic default or initial value for form field
I'm new in Python/Django with basic understanding and moving my steps slowly. This is my first question in stackoverflow. I've learned a lot from the previously discussed posts. Thanks to all who asked questions and special thanks to all those who contributed to such helpful answers. I searched and read a lot and tried to understand but could not figure out my way ahead on the following issue. I have a form for Transaction entry with the following fields. ==> Date ==> Farmer_num ==> purchase_qty ==> tr_rate I need to enter many records (500+ for a date) with the same date and same price (tr_rate). Instead of selecting date from datepicker and writing price (tr_rate) on entry form every time, i want to get them as default/initial value when form loads for new entry. This will save my time as well as prevent from entering the wrong date and price. When the form loads, in the date field, I want the last entry date as initial/default date from Trans table. For example if the last entry date was 2020-08-08, form should load with this date. When that date's entry is finished, I select another date manually e.g. 2020-08-12 for another … -
Django Email Backend Failing when DEBUG = False
Has anyone experienced this issue where when DEBUG = True your applications can't send emails? I'm trying to set up a password reset email and a contact form and both work fine in development and in production as long as DEBUG = False, but as soon as it equals True the email backend breaks (this is especially frustrating because I can't use DEBUG to find the issue). My email config looks as follows: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.privateemail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'admin@programaticlearning.com' EMAIL_HOST_PASSWORD = 'CorrectPassword' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
Bootstrap tabpanel isn't showed with django url view
I am working with Django 3.1 and Bootstrap 4. I am trying to implement a tablist with href pointing to django view. However, when I click the second tab, nothing happens. The expected behavior is that the response from the view function is rended in the content of the tabpanel. This is my code: template.html <ul class="nav tab-switch" role="tablist" id="profile-tabs"> <li class="nav-item"> <a class="nav-link active" id="user-profile-info-tab" data-toggle="pill" href="#user-profile-info" role="tab" aria-controls="user-profile-info" aria-selected="true">Profile</a> </li> <li class="nav-item {% if active_tab == 'research2' %} active {% endif %}"> <a class="nav-link" id="user-profile-research-tab2" href="{% url 'app:research_profile' %}" role="tab" aria-controls="user-profile-research2" aria-selected="false">Research</a> </li> </ul> <div class="tab-pane fade show pr-3" id="user-profile-research2" role="tabpanel" aria-labelledby="user-profile-research-tab2"> <div class="table-responsive"> <div class="main-panel col-12"> <div class="content-wrapper"> {% include 'templates/_research_list.html' %} </div> </div> </div> </div> The view.py include in the response the variable "active_tab", but for some reason, the tab content never is showed. Any help would be very appreciated. -
Where to add Tinymce api key?
i downloaded the zip file form tinymce.cloud. and added the file in static folder everything is working fine, except now i'm getting this notification every time i want to create a post. I already have an account but as they suggested to add key in tinymce.js file the content is totally different in mine because i'm not using just single js file but bunch of files now i don't know where i should put my api key. so it stop giving me notification. script file i'm using in head file post_create.html where i added script. -
No apps folder on django lightsail
After creating a new lightsail django instance on AWS, I found that the folders /opt/bitnami/apps/ does not exist as referenced in the documentation https://aws.amazon.com/getting-started/hands-on/deploy-python-application/. I've created django instances before on AWS and have never encountered this issue. bitnami@ip-172-26-4-185:~$ ls bitnami_application_password bitnami_credentials htdocs stack bitnami@ip-172-26-4-185:~$ cd / bitnami@ip-172-26-4-185:/$ cd opt bitnami@ip-172-26-4-185:/opt$ cd bitnami bitnami@ip-172-26-4-185:/opt/bitnami$ cd apps -bash: cd: apps: No such file or directory bitnami@ip-172-26-4-185:/opt/bitnami$ ls apache bncert-tool bnsupport-tool git nami properties.ini stats apache2 bnsupport common gonit node python var bncert bnsupport-regex.ini ctlscript.sh mariadb postgresql scripts Additional info: 16 GB RAM, 4 vCPUs, 320 GB SSD Django Virginia, Zone A (us-east-1a) attached static ip address -
ImportError: path_to_venv/lib/python2.7/site-packages/PIL/_imaging.so: undefined symbol: PyString_FromStringAndSize
[Tue Sep 01 10:36:25.566741 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] Traceback (most recent call last): [Tue Sep 01 10:36:25.566824 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] File "/root/jielong/fairy/wsgi.py", line 19, in <module> [Tue Sep 01 10:36:25.566872 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] application = get_wsgi_application() [Tue Sep 01 10:36:25.566911 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] File "/root/jielong/jielong_env/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application [Tue Sep 01 10:36:25.566946 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] django.setup() [Tue Sep 01 10:36:25.566984 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] File "/root/jielong/jielong_env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup [Tue Sep 01 10:36:25.567019 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] apps.populate(settings.INSTALLED_APPS) [Tue Sep 01 10:36:25.567056 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] File "/root/jielong/jielong_env/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate [Tue Sep 01 10:36:25.567090 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] app_config.import_models(all_models) [Tue Sep 01 10:36:25.567128 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] File "/root/jielong/jielong_env/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models [Tue Sep 01 10:36:25.567184 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] self.models_module = import_module(models_module_name) [Tue Sep 01 10:36:25.567223 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module [Tue Sep 01 10:36:25.567257 2020] [wsgi:error] [pid 19181:tid 140458551392000] [remote 119.247.226.9:52728] return _bootstrap._gcd_import(name[level:], package, level) [Tue Sep 01 … -
listview objects are not redirecting to detailview when clicked
i am trying to create a blog , i am able to display list of objects in my blog model by class based list view.. but when trying to display them individually by function based detail view i am getting 404 error. (The current path, blog/1, didn't match any of these.) i tried class based views as well but unfortunately got no success.. please see.. models.py from django.db import models import datetime # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=500) writer = models.CharField(max_length=150,default='my dept') category =models.CharField(max_length=150) image = models.ImageField(upload_to='images') post = models.TextField(max_length=2000) Date = models.DateField( default=datetime.date.today) def __str__(self): return self.title views.py from django.views.generic import ListView , DetailView , UpdateView from.models import BlogPost class BlogList(ListView): model = BlogPost template_name = 'blog/bloglist.html' context_object_name = 'post' def detailview(request, id=None): blg = get_object_or_404(BlogPost, id=id) context = {'blg': blg, } return render(request, 'blog/blogdetail.html', context) urls.py from django.urls import path # importing views from views..py from .views import BlogList ,detailview urlpatterns = [ path('list', BlogList.as_view(), name='list'), path('(?P<id>\d+)/$', detailview, name='detail') ] bloglist.html <div class="post-body"> {% for p in posts %} <a href="/blog/{{ p.id }}"><blockquote>{{p}}</br></br>{{p.Date}}</blockquote> </a> {% endfor %} -
Sending Emails in Production Environment
I have a web app I'm hosting on Digital ocean using nginx and gunicorn. I recently tried to add password reset capabilities for my users as well as a contact form. When I ran and tested on my local machine everything worked fine, but now that I've moved to production I get a 500 error when I try to send a password reset email, and my contact form is not generating any email message. Is there some additional set up related to digital ocean, or nginx that needs to be done to allow emails to be sent? my settings.py is set up as follows: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.privateemail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'admin@programaticlearning.com' EMAIL_HOST_PASSWORD = 'CorrectPassword' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
How to getting results of bulk creating user without waiting for a long time?
I want to generate lots of users in admin system. But the question is make_password in Django is a time-consuming operation. So, i want to assign this operation to a thread. Thus, the admin can get the generated file immediately without waiting for a long time which including user id, password. Below is the code i wrote which have some issues. Cause for getting the new generated user id, I consider the lastest user id plus by one as the beginning id, and getting the end user id by adding the beginning id by the num to generate. Then, if someone is registering during the period of bulk creating by admin, errors like dulplicate entry will throw. How should i address this problem, pls give me some advice. Thx. def BatchCreateUser(self, request, context): """批量创建用户""" num = request.get('num') pwd = request.get('pwd') pwd_length = request.get('pwd_length') or 10 app = request.get('app') latest_user = UserAuthModel.objects.latest('id') start_user_id = latest_user.id + 1 # 起始学号 end_user_id = latest_user.id + num # 终止学号 user_id_list = [i for i in range(start_user_id, end_user_id + 1)] # 学号列表 if not pwd: raw_passwords = generate_cdkey(num, pwd_length, False) # 随机生成密码列表 Thread(target=batch_create_user, args=(user_id_list, raw_passwords, app)).start() else: raw_passwords = [pwd for _ in range(num)] Thread(target=batch_create_user, … -
Wagtail Admin: How to control where user is redirected after submitting changes for moderation
On a Wagtail site I've built, I have a model type that is editable by authenticated users who do not have full admin privileges. They can only save as a draft or submit the changes for moderation. The problem I'm having is that Wagtail is inconsistent about where it redirects after executing these two actions. Saving the Draft takes the user back to the edit screen they were just on, with a note saying the draft was saved (good). Submitting for Moderation returns the user to the admin browse view of the parent page, which shows all of the sibling nodes in a list. They can't edit the vast majority of items on that list, so I think this is confusing for a non-admin user. I would like to have the "Submit for Moderation" action detect whether the user belongs to a group other than admin (or, failing that, whether the page has unpublished changes, as in my code example below) and, if so, redirect them back to the edit screen just like "Save as Draft" does. I tried this in my model definition and it didn't work: def save(self, *args, **kwargs): #do some field value manipulations here before saving … -
Django: manage.py runserver fails with watchman exception
When I try running manage.py runserver on a completely new project, I get a watchman exception: (towngen) gru-mbp:towngenweb gru$ ./manage.py runserver Watching for file changes with WatchmanReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. September 01, 2020 - 01:07:15 Django version 3.1, using settings 'towngenweb.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 96, in handle self.run(**options) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 103, in run autoreload.run_with_reloader(self.inner_run, **options) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/utils/autoreload.py", line 613, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/utils/autoreload.py", line 598, in start_django reloader.run(django_main_thread) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/utils/autoreload.py", line 313, in run self.run_loop() File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/utils/autoreload.py", line 319, in run_loop next(ticker) File "/Users/gru/.venvs/towngen/lib/python3.8/site-packages/django/utils/autoreload.py", line 532, in tick self.update_watches() File … -
Django - Best Approach to query latest time series objects?
Long time lurker, first time poster, so beware! Let's say I'm modeling end of day stock prices, and have two Django models for this: Stock, and DailyPriceData (simplified for this question). In reality, Stock has additional metadata, and DailyPriceData has OHLC data, volume, etc.: class Stock(models.Model): ticker = models.CharField(max_length=10) class Meta: unique_together=['ticker'] class DailyPriceData(models.Model): stock= models.ForeignKey(Stock, on_delete=models.CASCADE) date = models.DateField() price = models.DecimalField(max_digits=30, decimal_places=6) class Meta: unique_together=['stock','date'] indexes = [ models.Index(fields=['stock','date']), ] Now, let's say there are 50k Stock objects, and each Stock object has ~10 years or more of DailyPriceData objects. What is the best way of extracting only the latest DailyPriceData objects of each Stock object for display on a frontend? Using PostgreSQL, I can accomplish the task with the .Distinct method, though this is very slow and not suitable for a frontend. Should I create another model object, shown below? Is this wasteful? Should I use a signal or management command to keep this updated?: class DailyPriceDataLatest(models.Model): stock= models.OneToOneField(Stock, on_delete=models.CASCADE) daily_price_data = models.OneToOneField(DailyPriceData, on_delete=models.CASCADE) class Meta: unique_together = ['stock'] Is there a better way to skin this cat, so that I can query the latest price data by Stock or group of Stock objects quickly? -
How can I to link my post creator page to the other pages in Python?
one of my html files about.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="{% static "all.css" %}"> <link rel="stylesheet" href="{% static "bootstrap.css" %}" > <link rel="stylesheet" href="{%static "style.css" %}"> <title>Online yuridik xizmatlar</title> </head> <body> <nav class="navbar navbar-expand-sm navbar-dark bg-dark"> <div class="container"> <a href="{% url 'home' %}" class="navbar-brand"><i class="fas fa-balance-scale"></i></a> <button class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a href="{% url 'home' %}" class="nav-link">Bosh sahifa</a> </li> <li class="nav-item"> <a href="{% url 'about' %}" class="nav-link">Biz haqimizda</a> </li> <li class="nav-item"> <a href="{% url 'index' %}" class="nav-link">Blog</a> </li> <li class="nav-item"> <a href="{% url 'contact' %}" class="nav-link">Biz bilan bog'laning</a> </li> </ul> </div> </div> </nav> <div class="about-banner"> <div class="container text-center py-5 text-white"> <h1>Bizning kompaniyamiz haqida</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis aut doloribus dolores minus</br> voluptatibus in?</p> </div> </div> <div class="about-content"> <div class="container"> <div class="row py-5"> <div class="col-md-6"> <h3>What we do</h3> <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Dolorem, doloremque quidem quasi sint reiciendis rem voluptas atque ab nam non, qui excepturi unde optio cum, omnis necessitatibus recusandae a repellat.</p> <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Dolorem, doloremque quidem … -
Allow download of entire contents of Amazon S3 folder in Django
I'm using Django and I have a S3 Account with files in a folder called media. I want to allow users to download the entire list of files as an archived zip folder to save them having to click on each individual link to get the file. I'm using Django, and Amazon S3 and Boto3. Links are like, https://mydomain.s3.amazonaws.com/media/filename1.txt https://mydomain.s3.amazonaws.com/media/filename2.txt https://mydomain.s3.amazonaws.com/media/filename3.txt https://mydomain.s3.amazonaws.com/media/filename4.txt https://mydomain.s3.amazonaws.com/media/filename5.txt So essential I want to bundle all files in another link that is a download to all files, as an archive. Any suggestions on how to do this with Django?