Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to include a `@cached_property` in a Pandas DataFrame built from a Django Queryset?
I have a django queryset that includes 3 "columns" of type @cached_property. I would like to be able to convert that queryset to a pandas dataframe so that I can do some cool stuff like, allow it to be downloaded in excel format, etc. But, unless I comment out the cached properties from the field list supplied to .values(), I get an exception like: django.core.exceptions.FieldError: Cannot resolve keyword 'enrichment_fraction' into field. Choices are: compounds, formula, id, msrun, msrun_id, name, peak_data, peak_group_set, peak_group_set_id Here's the relevant snippet of code: res = PeakGroup.objects.filter(q_exp).prefetch_related( "msrun__sample__animal__studies", "msrun__sample__animal", "msrun__sample", "msrun__sample__tissue", "msrun__sample__animal__tracer_compound", ) fieldsforpandas = [ "name", "msrun__sample__id", # Used in link "msrun__sample__name", "msrun__sample__tissue__name", "msrun__sample__animal__tracer_labeled_atom", "msrun__sample__animal__id", # Used in link "msrun__sample__animal__name", "msrun__sample__animal__feeding_status", "msrun__sample__animal__tracer_infusion_rate", "msrun__sample__animal__tracer_infusion_concentration", "msrun__sample__animal__tracer_compound__name", "msrun__sample__animal__studies__id", # Used in link "msrun__sample__animal__studies__name", # Cached properties... "enrichment_fraction", "total_abundance", "normalized_labeling", ] forpandas = res.values(*fieldsforpandas) df = pandas.DataFrame.from_records(forpandas) print(df) If I comment out those last 3 cached properties, there's no exception and the df prints to the log just fine. Here's an example of one of the cached properties in the model: @cached_property def total_abundance(self): return self.peak_data.all().aggregate( total_abundance=Sum("corrected_abundance") )["total_abundance"] That one's one of the simpler ones. Is there a way to include the cached properties in the dataframe or am … -
Django update same model in different view
i have a book model, where author is many to many field: class Book(models.Model): title = models.CharField(max_length=255, verbose_name="Title") author = models.ManyToManyField(User, related_name="Task") content = models.TextField(blank=True, null=True) author model: class User(AbstractUser): introduction = models.CharField() job_title = models.CharField() In the app of Book, i created an updateview using modelform and UpdateView, this part is easy to do. # example.com/book/1/edit path('<int:pk>/edit', views.BookEditView.as_view(), name='book-edit') However, in the app of user, i'd like user to be able to edit their own books as well: # example.com/user1/book/1/edit path('<username>/book/<int:pk>/edit', views.UserEditBookView.as_view(), name='editbook') Question: if i use generic view, can it take two parameters? Afterall, only one parameter(primary key) needed to let Django know which one needs to be updated. if i need to use class based view, how should i do that? -
Nginx Open Socket Left Connection Error Django
when I first published my Django project, the index page was showing, but when I clicked anywhere, it did not redirect to the page. The error I'm getting against the request is Server Error(500) I reset the system, I restarted nginxi, this time the index page started not to come. nginx error.log is error 2094#2094: *19 open socket #10 left in connection 4 I couldn't find many resources about this problem on the internet. Can anyone help me? /etc/nginx/sites-available/lordplus GNU nano 4.8 /etc/nginx/sites-available/lordplus server { listen 80; server_name www.domain.com; root /var/www/lordplus; # Projenin kök dizini location /static/ { } location /media/ { } location / { include proxy_params; proxy_pass http://unix:/var/www/lordplus/lordplus.sock; } } And here Gunicorn Service /etc/systemd/system/gunicorn.service GNU nano 4.8 /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=runadmingen Group=www-data WorkingDirectory=/var/www/lordplus ExecStart=/var/www/lordplus/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/var/www/lordplus/lordplus.sock lordplus.wsgi:application [Install] WantedBy=multi-user.target -
Django is not able to find static files
I've started a new Django project and run into issue at the very begining. I have created a "core" app and inside I have prepared a simple html page using bootstrap. Instead of using CDN I have downloaded bootstrap files and put it under static directory. The problem is Django can't find those static files. I am using the latest version of Django >>> django.VERSION (3, 2, 5, 'final', 0) Snippet from my base.html file: {% load static %} <!-- Bootstrap core CSS --> <link href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'headers.css' %}" rel="stylesheet"> settings.py STATIC_URL = '/static/' STATICFILES_DIR = [ BASE_DIR / 'static' ] and my directory structure: . ├── apps │ └── core │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ ├── models.py │ ├── templates │ │ └── core │ │ ├── base.html │ │ └── index.html │ ├── tests.py │ └── views.py ├── db.sqlite3 ├── manage.py ├── ref_manager │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── static │ ├── assets │ │ └── bootstrap │ │ ├── css | | … -
Server Error (500) Django/Heroku While loading homepage, but working fine with django/admin
When I got to https://secure-brook-21764.herokuapp.com/admin/ then site works fine but Homescreen https://secure-brook-21764.herokuapp.com/ It's giving me server error 500, Is there any problem loading static files ? I guess there's something wrong in my settings.py How to solve that problem I checked django deploy to Heroku : Server Error(500) This question too but it's very old and not helping me to solve that issue. settings.py """ Django settings for backend project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os import environ #import environ env = environ.Env() # Initialise environment variables environ.Env.read_env() from datetime import timedelta from pathlib import Path import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'storages', 'base.apps.BaseConfig', 'blog.apps.BlogConfig', 'panel.apps.PanelConfig', 'sitebranding.apps.SitebrandingConfig', ] REST_FRAMEWORK = { … -
contador continuo de um for dentro do outro for em template django
Tenho o seguinte código no template django: {% for materia in materias %} {% for aluno in materia.alunos %} <tr class="center"> <td>{{ forloop.counter }}</td> <td>{{ aluno.nome }}</td> <td colspan="3">{{ aluno.matricula }}</td> </tr> {% endfor %} {% endfor %} E gostaria de listar todos os alunos com um contador que fosse continuo e não reiniciasse a cada iteração do for externo. Ou seja, se há 2 matérias e cada matéria tem 2 alunos, o contador deveria ficar: 1, 2, 3 e 4. Com forloop.counter e forloop.parentloop não funciona. Alguém pode dar uma ajuda? -
Display the items related to a foreign key
What i want is to display a the name and age of employees here with its department. For like a department header and a list of employee names and age EG: (department name1) name1 age1 name2 age2 (department name2) name3 age3 I am new to django i used One to Many key i dont get what do i do with in my views and url/ html. My Models.py class Department(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Employee(models.Model): name = models.CharField(max_length=200) age = models.CharField(max_length=200) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return self.name My views.py: def index(request: HttpRequest) -> HttpResponse: context = { 'categories': Employee.objects.all() } return render(request, 'index.html', context) My urls.py: path('', views.index), My html: {% for item in categories.all %} {{ item.name }} {{ item.age }} </br> {% endfor %} -
Passing context variable from template to JavaScript file
This thread here discussed using variables in inline JavaScript in templates. If I have a separate .js files containing scripts, sitting in static folder, such as following: utils.js const createButton = (buttonCount) => { containerId = "myContainerId" container = document.getElementById(containerId) for (var i = 0; i < buttonCount; i++) {} newButton = document.createElement("button") newButton.value = "Test" newButton.id = "testButton" + i container.appendChild(newButton) } } createButton(buttonCount) mytemplate.html {% extends "base.html" %} {% load static %} {% block title %}Testpage{% endblock %} {% block content-main %} <link href="{% static "css/mycss.css" %}" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" /> <div id="myContainerId"></div> <script src="{% static 'js/utils.js' %}"> </script> {% endblock %} If I have a variable buttonCount passed into this template via a view function's context, how do I pass it to the utils.js file to be called by function createButton()? views.py def button_view(request): ... buttonCount = 5 return render(request, 'mytemplate.html', {'buttonCount': buttonCount}) -
Catch-all view break URL patterns in Django
def get_urls(self): urls = super().get_urls() url_patterns = [path("admin_profile", self.admin_view(self.profile_view))] return urls + url_patterns The above method cause the catch-all view to break URL patterns which I route after the admin URLs and cause the following error/exception: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/admin_profile/ Raised by: django.contrib.admin.sites.catch_all_view But this only happen when final_catch_all_view = True in django.contrib.admin.sites.catch_all_view When setting final_catch_all_view = False No error or exception is made, everything went fine. Now my question is how can make the function work when final_catch_all_view = True And this is what docs say about catch_all view: > The new admin catch-all view will break URL patterns routed after the > admin URLs and matching the admin URL prefix. You can either adjust > your URL ordering or, if necessary, set AdminSite.final_catch_all_view > to False, disabling the catch-all view. See What’s new in Django 3.2 > for more details. -
deploy django-app to heroku - Application error
I am trying to deploy my Django app to Heroku. I am following all the steps mentioned on Heroku dev center https://devcenter.heroku.com/articles/django-app-configuration. The app deploys successfully but when I run heroku open or manually visit the link it shows Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail My Logs: 2021-07-13T18:26:37.515968+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-07-13T18:26:37.515969+00:00 app[web.1]: self.callable = self.load() 2021-07-13T18:26:37.515969+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-07-13T18:26:37.515970+00:00 app[web.1]: return self.load_wsgiapp() 2021-07-13T18:26:37.515970+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-07-13T18:26:37.515970+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-07-13T18:26:37.515970+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2021-07-13T18:26:37.515971+00:00 app[web.1]: mod = importlib.import_module(module) 2021-07-13T18:26:37.515971+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-07-13T18:26:37.515972+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-07-13T18:26:37.515972+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-07-13T18:26:37.515973+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-07-13T18:26:37.515973+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked 2021-07-13T18:26:37.515973+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-07-13T18:26:37.515974+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-07-13T18:26:37.515974+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-07-13T18:26:37.515974+00:00 … -
Getting a "'str' object has no attribute 'get'" error in Django Python
Some context: I am trying to create an email verification system in Django. I have already made the register/sign-in/log-out views and they work but I have added the verification system to them. I am getting the error after submitting the registration form. I think that the error is happening after the form submission where I am sending the email. The error I am getting is: 'str' object has no attribute 'get' Here is the relevant code: Views: def register(request): if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): inst = form.save() uidb64 = urlsafe_base64_encode(force_bytes(inst.id)) domain = get_current_site(request).domain link = reverse('verify_email', kwargs={'uidb64': uidb64, 'token': token_generator.make_token(inst)}) activate_url = 'http://' + domain + link print(activate_url) #prints the correct link email_subject = 'Verify Your Email' email_body = 'Hello ' + inst.username + '\nClick the link to verify your email\n' + activate_url email = EmailMessage( email_subject, email_body, settings.EMAIL_HOST_USER, [inst.email], ) return reverse('verify_email_intro', kwargs={'user_id': inst.id}) else: form = CreateUserForm() return render(request, 'users/register.html', {'title_page': 'Register', 'form': form}) @csrf_exempt def verify_email_intro(request, user_id): context = { 'user_id': user_id, } return render(request, 'users/verify_email.html', context) def verify_email(request, uidb64, token): try: pk = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(id=pk) if user.is_active: return redirect('login') else: user.is_active = True user.save() except Exception as ex: pass return … -
Django many to many serializers circular dependency work around?
I have two models, publications and articles, that are connected to each other by a ManyToManyField. Models shown below class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField('Publication') class Publication(models.Model): title = models.CharField(max_length=30) I want to reference articles to publication and publications to articles in both model serializers. class PublicationSerializer(serializers.ModelSerializer): title = serializers.CharField() articles = ??? class Meta: model = Publication fields = ['title', 'articles'] class ArticleSerializer(serializers.ModelSerializer): headline = serializers.CharField() publications = PublicationSerializer(many=True) class Meta: model = Article fields = ['headline', 'publications'] I have been looking up various solutions, many refer to using Relational Fields, such as StringRelatedField, and saw a different solution using SerializerMethodField(), but there doesn't appear to be much documentation on them. Any examples or solutions to this issue? -
Adding custom QuerySet to UserModel causes makemigrations exception
I would like to create a custom queryset for my User model. However, I cannot simply use objects = UserQuerySet.as_manager() since the standard Django User model already has a custom UserManager. My code is simply : class UserQuerySet(MyBaseQuerySet): def opted_out_method(self): return class User(AbstractUser): objects = UserManager.from_queryset(UserQuerySet)() # etc... This code works, except when I do this: $manage.py makemigrations --dry-run File "./manage.py", line 49, in <module> execute_from_command_line(sys.argv) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 164, in handle changes = autodetector.changes( File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/autodetector.py", line 43, in changes changes = self._detect_changes(convert_apps, graph) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/autodetector.py", line 129, in _detect_changes self.new_apps = self.to_state.apps File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 210, in apps return StateApps(self.real_apps, self.models) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 273, in __init__ self.render_multiple([*models.values(), *self.real_models]) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 308, in render_multiple model.render(self) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 577, in render body.update(self.construct_managers()) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 536, in construct_managers as_manager, manager_path, qs_path, args, kwargs = manager.deconstruct() File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 61, in deconstruct raise ValueError( The … -
How can I add my custom model function's value in my API
So trying to build my own poll app and the models have a lot of relation with each other and I need to count how many objects are in relation with some other objects so I need these custom function for it here's the model with the costume functions class Poll(models.Model): title = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_available = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title @property def total_votes(self): votes = 0 for o in self.option_set.all(): votes = votes + o.how_much_vote return votes @property def users_involved(self): list = [] for o in self.option_set.all(): for v in o.vote: list.append(v.user) return list @property def users_involved(self): users = [] for o in self.option_set.all(): for v in o.who_voted: users.append(v) return users @property def total_votes_each_option(self): dct = {} for o in self.option_set.all(): dct[o.title]= o.how_much_vote return dct My question is how do you include all of those custom functions total_votes, users_involved, etc to my api? because right now my api looks something like this: { "id": 1, "title": "Which is the best frontend framework?", "is_active": true, "is_available": true, "date_created": "2021-07-13T14:08:17.709054Z" } which is expected but I want to know how do I add those extra value to make it look like this { "id": 1, … -
Can saving a model fail after pre_save?
I have a pre_save signal set up for my User model that does something before a User is saved. My question is, will a User.save() function ever fail after the pre_save has already been executed? Basically I'm doing something in the pre_save that I wouldn't want to do if the User.save() fails. Should I be worried about this corner case? NOTE: I cannot use post_save because I need the pre_save instance object. -
How to get data from mysql reverse foreign key without using the prefetch concept?
I have two models, Like, class User(models.Model): fname = models.CharField(max_length=32, blank=True, null=True) class Meta: managed = True db_table = 'u_users' class Email(models.Model): usr_id = models.ForeignKey(User, db_column='usr_id', related_name='emails', on_delete=models.CASCADE) email = models.EmailField(max_length=64) class Meta: managed = True db_table = 'u_email' Now i'would like to get list of users with list of email each users have Sample output. [ { "id":1, "fname":"Test User", "emails":[ { "id":1, "email":"masstmp+2ffj7@gmail.com" }, { "id":2, "email":"masstmp+2ffj8@gmail.com" } ] }, { "id":2, "fname":"Test User2", "emails":[ { "id":3, "email":"masstmp+2ffj9@gmail.com" }, { "id":4, "email":"masstmp+2ffj10@gmail.com" } ] } ] But i need to get this output using single query. In raw query i able to write the query and get the output easy. But i want to know about how to do this in ORM. Please, Thank you. -
Django: Call a function in views.py on HTML form submit
I am building a geospatial web app and am currently trying to implement a date form input to display data from different dates. Each data point is an Object stored in the database, and my frontend uses OpenLayers in javascript. Data is passed from views.py to javascript as a geojson file. Since it's a map, I would effectively like everything to stay in the same view and URL (asides from some GET parameters in the URL). The flow that I'm thinking of goes like: 'Submit' button is clicked on GET form Function in views.py (or somewhere else) is called with parameters from the GET form A query is made to the database to filter by date, and creates a geojson file of the points Geojson is given to javascript to display All the posts I've seen about this problem include calling a different view, can I do all this in the same view? Thank you! -
Hello DevOps, I m getting Application error on Heroku after successful push. Need your help to fix that
I Followed heroku Docs https://devcenter.heroku.com/articles/getting-started-with-python#deploy-the-app to push my app directly from terminal. But after successful deployment on https://secure-brook-21764.herokuapp.com/ but there is application error. these are heroku logs --tail $ heroku logs --tail » Warning: heroku update available from 7.53.0 to 7.54.1. 2021-07-13T17:41:57.282928+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/os.py", line 675, in __getitem__ 2021-07-13T17:41:57.282929+00:00 app[web.1]: raise KeyError(key) from None 2021-07-13T17:41:57.282929+00:00 app[web.1]: KeyError: 'DATABASE_ENGINE' 2021-07-13T17:41:57.282930+00:00 app[web.1]: 2021-07-13T17:41:57.282930+00:00 app[web.1]: During handling of the above exception, another exception occurred: 2021-07-13T17:41:57.282931+00:00 app[web.1]: 2021-07-13T17:41:57.282931+00:00 app[web.1]: Traceback (most recent call last): 2021-07-13T17:41:57.282932+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-07-13T17:41:57.282932+00:00 app[web.1]: worker.init_process() 2021-07-13T17:41:57.282932+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process 2021-07-13T17:41:57.282933+00:00 app[web.1]: self.load_wsgi() 2021-07-13T17:41:57.282933+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-07-13T17:41:57.282934+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-07-13T17:41:57.282934+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-07-13T17:41:57.282935+00:00 app[web.1]: self.callable = self.load() 2021-07-13T17:41:57.282935+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-07-13T17:41:57.282936+00:00 app[web.1]: return self.load_wsgiapp() 2021-07-13T17:41:57.282936+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-07-13T17:41:57.282936+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-07-13T17:41:57.282937+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app 2021-07-13T17:41:57.282937+00:00 app[web.1]: mod = importlib.import_module(module) 2021-07-13T17:41:57.282938+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2021-07-13T17:41:57.282942+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-07-13T17:41:57.282942+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-07-13T17:41:57.282943+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-07-13T17:41:57.282943+00:00 app[web.1]: … -
What is most optimal way to include data science visualizations and/or simple charts in django?
I am new in django, I have achieved to built a simple website up running in my local sever, but now I have reached that part where I want to add some cool and nice looking graphs to my project, but I see many options that are not that simple, if I could choose, I would use some python-based library or something, but it needs to load very fast. I am looking for guidance and suggestions. Thank you in advance. -
Travis Cl builds failing Python/Django
New dev here and am working on a course that has me using Docker and Travis Cl to build a restful API. My builds started off fine, but am now currently getting constant build failures (possible note of relevance, did have a small power outage and after ran docker-compose build again). I've looked and cannot for the life of me figure out what I'm missing at this point. Any advice appreciated. Please let me know if you need any other info. TIA Worker information 0.17s0.00s0.01s0.00s0.01s system_info Build system information 0.02s0.01s0.46s0.23s0.05s0.00s0.04s0.00s0.01s0.01s0.01s0.01s0.01s0.00s0.00s0.03s0.00s0.01s0.36s0.00s0.00s0.00s0.01s0.01s0.10s0.01s0.82s0.00s0.12s6.03s0.00s2.79s0.00s2.61s docker_mtu_and_registry_mirrors resolvconf services 3.02s$ sudo systemctl start docker git.checkout 0.41s$ git clone --depth=50 --branch=main https://github.com/Ash-Renee/Recipe-App-API.git Ash-Renee/Recipe-App-API 0.01s Setting environment variables from repository settings $ export DOCKER_USERNAME=[secure] $ export DOCKER_PASSWORD=[secure] 0.01s$ source ~/virtualenv/python3.6/bin/activate $ python --version Python 3.6.7 $ pip --version pip 20.1.1 from /home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pip (python 3.6) before_install 0.61s$ echo $DOCKER_PASSWORD | docker login --username $DOCKER_USERNAME --password-stdin Pip version 20.3 introduces changes to the dependency resolver that may affect your software. We advise you to consider testing the upcoming changes, which may be introduced in a future Travis CI build image update. See https://pip.pypa.io/en/latest/user_guide/#changes-to-the-pip-dependency-resolver-in-20-2-2020 for more information. install 6.66s$ pip install -r requirements.txt before_script 7.59s$ pip install docker-compose 17.50s$ docker-compose run … -
want to load models content in html django
i have a model name section connected with other model name subject with foreign key what i want to do is i want to load half of it content in other page and half of it content on other html my models.py class Section(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='section') sub_section = models.CharField(max_length=500, blank=True) title = models.CharField(max_length=5000, blank=False) teacher = models.CharField(max_length=500, blank=False) file = models.FileField(upload_to='section_vedios', blank=False) about_section = models.TextField(blank=False, default=None) price = models.FloatField(blank=False) content_duration = models.DurationField(blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject.name i mean i want to load {{section.title }} in one page and {{section.file }} on other when a person click on the {{ section.title }} here is my html <ul> {% for section in section_list %} <div class="card"> <div class="card-header"> {{ subject.name}} </div> <div class="card-body"> <h5 class="card-title">{{ section.title }}</h5> <p class="card-text"></p> <a href="#" class="btn btn-primary">CLick Here</a> </div> </div> {% endfor %} so when a person click on click here a another load up and in that i want to load {{section.file.url}} -
Django form working with bound and unbound form
In django I have the following form for a toy wikipedia website, used when a page is created class WikiSubmitForm(forms.Form): Title = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'placeholder': "Title of wiki page"}), label="") Body = forms.CharField(widget=forms.Textarea(attrs={'placeholder': "Content of wiki page"}), label="") When I allow a user to edit a page, I want to set an input value, so that the initial Body variable in the form is set to the actual content on the page. Confusingly, if I use: form = WikiSubmitForm(initial = {'Title': Title, 'Body': mkdown_file}) The form is created with the preset values, but it looks different to the form as on the create page part of the website, despite them using the same form (see picture at bottom), whereas if I do what I did on the create page but add initial values form = WikiSubmitForm(request.POST, initial = {'Title': Title, 'Body': mkdown_file}) It looks normal, but the initial values don't load. This seems to be because the form is now 'bound'. I found a workaround solution, but out of curiosity was wondering (1) Is there a way to fix the different look of the form when request.POST isn't passed in as an argument (2) Is there a way to pass in … -
Formset Not Saving on UpdateView Django
I'm having problem on formset not saving on UpdateView. This has been discussed in several SO post, and so far I can summarized them to following Make sure to pass an instance. Hence. Reference context['formset'] = journal_entry_formset(self.request.POST, instance=self.object) Override the POST method. Reference Another One My UpdateView is an exact replica of my CreateView except for two changes above. Here is my CreateView: class JournalEntryUpdateView(UpdateView): model = JournalEntry template_name = 'add-journal-entry.html' success_url = reverse_lazy('index') form_class = JournalEntryForm def get_context_data(self, *args, **kwargs): context = super(JournalEntryUpdateView, self).get_context_data(*args, **kwargs) if self.request.POST: context['formset'] = journal_entry_formset(self.request.POST, instance=self.object) else: context['formset'] = journal_entry_formset(instance=self.object) return context def form_valid(self, form): context = self.get_context_data(form=form) formset = context['formset'] if formset.is_valid(): response = super().form_valid(form) formset.instance = self.object formset.save() return response else: return super().form_invalid(form) def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) formset = journal_entry_formset(self.request.POST, instance=self.object) print ("form:", form.is_valid() ) # True print ("formset:", formset.is_valid() ) # False print(formset.non_form_errors()) # No Entry print(formset.errors) # {'id': ['This field is required.']} if (form.is_valid() and formset.is_valid()): return self.form_valid(form) else: return self.form_invalid(form) When I click submit, the page just refreshes and nothing happens. (i.e. I don't have that typical yellow error debug screen page). I check the value in the database … -
Django mail sending in very slow
I have implemented a password reset view and it sends a link to an e-mail account. But it takes more time to send. How can I make send faster e-mail using multi-threading class ResetPasswordView(SuccessMessageMixin, PasswordResetView): email_template_name = 'accounts/password_reset_email.html' form_class = CustomPasswordResetForm template_name = 'accounts/password_reset.html' success_message = mark_safe( """<li>We emailed you instructions for setting new password.</li> <br> <li>if an account exists with the email you entered. You should receive them shortly.</li> <br> <li>If you don’t receive an email, please make sure you’ve entered the address you registered with, and check your spam</li> """ ) success_url = reverse_lazy('accounts:reset_password') -
Checkboxes are not the same height as input boxes - Bootstrap
I want the checkboxes on the left side to be the same height as the text input boxes on the right. Not set to proper height HTML: {% block content %} <h1>{{ls.name}}</h1> <form method="post" action="#"> {% csrf_token %} {% for item in ls.item_set.all %} <div class="input-group mb-3"> <div class="input-group-prepend"> <div class="input-group-text"> {% if item.complete == True %} <input type="checkbox", value="clicked", name="c{{item.id}}" checked> {% else %} <input type="checkbox", value="clicked", name="c{{item.id}}"> {% endif %} </div> </div> <input type="text", value="{{item.text}}" class="form-control"> </div> {% endfor %} <div class="input-group mb-3"> <div class="input-group-prepend"> <button type="submit", name = "newItem", value="newItem" class="btn btn-primary">Add Item</button> </div> <input type="text", name="new"> </div> <button type="submit", name = "save", value="save" class="btn btn-primary">Save</button> </form> {% endblock %}