Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Upload multiple images from a single button using forms
Have been doing a lot of research but I cant seem to find much information on this. I have a simple blog app where users are able to create a blog post via a model form. I would like users to be able to upload multiple images to their blog from a SINGLE button. Most of the solutions I have found are using the admin panel or are just creating multiple buttons. None are using forms along with a button. I figure the best way to go about this would be to create a new model with a FK to the blog model but I cannot seems to come up with a proper implementation. If you could please point me in the right direction it would be greatly appreciated. -
Persisting Selected Option In Django Template Post-Refresh
I looked at multiple examples in stackoverflow on preserving the selected option in a dropdown after a page refresh. However, the dropdown continues to reflect the first item (CSS) in LANGUAGE_CHOICES. Here is what I have in api.py LANGUAGE_CHOICES = [ {'display_name': 'CSS', 'value': 'css'}, {'display_name': 'Go', 'value': 'go'}, {'display_name': 'Java', 'value': 'java'}, {'display_name': 'Javascript', 'value': 'javascript'}, {'display_name': 'Python', 'value': 'python'}, {'display_name': 'Ruby', 'value': 'ruby'}, ] Django Template file: example.html, iterating on LANGUAGE_CHOICES <label class="label setting-label"for="language">Language</label> <select id="language" name="language"> {% for lang in self.LANGUAGE_CHOICES %} <option value="{{lang.value}}" {%if lang.value == language.value%} selected {% endif %}> {{lang.display_name}} </option> {% endfor %} </select> The iteration on LANGUAGE_CHOICES creates the dropdown correctly, but it is not preserving the selected value after Save button is clicked. Resources: How do I iterate over the options of a SelectField in a template? Django Select Option selected issue -
How do I avoid duplicate queries in Django admin for a get_queryset() overwrite in a ModelAdmin page
I overwrote get_queryset and get the results I require. The problem is however that the page takes quite long to load. Upon checking the SQL debugger, it became apparent that two the same queries are executed and a third similar query. Does anyone have a reason why and how this could be avoided? Thank you kindly in advance. SQL: QUERY TIMELINE TIME (MS) ACTION + SELECT ••• FROM "django_session" WHERE ("django_session"."expire_date" > '''2021-07-13 20:49:27.015683''' AND "django_session"."session_key" = '''26huoisce3p4p3ef0f37vysjzo55uu3h''') LIMIT 21 1.18 Sel Expl + SELECT ••• FROM "auth_user" WHERE "auth_user"."id" = '1' LIMIT 21 0.58 Sel Expl + SELECT ••• FROM "inventory_product" LEFT OUTER JOIN "bolData_invoice_line" ON ("inventory_product"."id" = "bolData_invoice_line"."product_id") GROUP BY "inventory_product"."id") subquery 2 similar queries. Duplicated 2 times. 1625.29 Sel Expl + SELECT ••• FROM "inventory_product" LEFT OUTER JOIN "bolData_invoice_line" ON ("inventory_product"."id" = "bolData_invoice_line"."product_id") GROUP BY "inventory_product"."id") subquery 2 similar queries. Duplicated 2 times. 1449.67 Sel Expl + SELECT ••• FROM "inventory_product" LEFT OUTER JOIN "bolData_invoice_line" ON ("inventory_product"."id" = "bolData_invoice_line"."product_id") GROUP BY "inventory_product"."id", "inventory_product"."ean", "inventory_product"."hscode_id" ORDER BY "return_rate" DESC, "inventory_product"."id" DESC LIMIT 100 1387.94 Sel Expl``` PYTHON/DJANGO: ```@admin.register(ProductProxy) class ProductProxyAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(ProductProxyAdmin, self).get_queryset(request) qs = qs.annotate( total_sales=Coalesce(Sum('invoice_line__invoiced_quantity', filter=Q(invoice_line__invoice_linetype__id=3)),0.0), total_returns=Coalesce(Sum('invoice_line__invoiced_quantity', filter=Q(invoice_line__invoice_linetype__id=7)), 0.0)) \ .annotate( return_rate=ExpressionWrapper(F('total_returns')* … -
Why is DRF serializer returning errors with required fields?
When I make a post request to register a user, the data sent is complete and in order, but the RegisterationSerializer serializer returns an error for the username and password fields. The error reads This field is required. for both fields. My first guess was that the serializer is not receiving the data sent but that's false but the serializer receives the data. What am I doing wrong? Could the validated_data parameter in the create method not be populated. I tested it by printing it out on the terminal when making a request but it didn't print. For the model, I'm using the built-in user model. Serializer from django.contrib.auth.models import User from rest_framework import serializers class RegisterationSerializer(serializers.ModelSerializer): """Registeration serializer""" class Meta: model = User fields = ["id", "username", "first_name", "last_name", "email", "password"] extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): username = validated_data["username"] first_name = validated_data["first_name"] last_name = validated_data["last_name"] email = validated_data["email"] password = validated_data["password"] user = User.objects.create_user( username=username, first_name=first_name, last_name=last_name, email=email, password=password, ) return user Views from authentication.serializers import RegisterationSerializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.authtoken.models import Token class RegisterationView(APIView): """Registeration View""" def post(self, request): serializer = RegisterationSerializer(data=request.data) # Generate tokens … -
Re-saving a model instance in Django not working, but update() does work
Going a bit crazy with something that stopped working in my Django app (Django 3.2.5, Python 3.9.6) - here's a simplified version: class MyModel(models.Model): attribute_1 = models.CharField(max_length=1, default='0') myModel = MyModel() myModel.save() print(myModel.attribute_1) # OUTPUTS '0' myModel(attribute_1='1') myModel.save() print(myModel.attribute_1) # OUTPUTS '1' The second save() is not being saved, if I retrieve myModel from the database elsewhere I get attribute_1 equal to 0. This, however, does work as I expect it to: myModel = MyModel() myModel.save() MyModel.filter(pk=myModel.pk).update(attribute_1='1') Am I missing something incredibly obvious here? -
Django Model Bidirectional Many to Many Declaration?
I have two models, article and publication, in which I declare a manytomany field within Article. However, I also want to have a reference from publication to articles as well. Is the best way to just declare another ManyToManyField, i.e. Articles = models.ManyToManyField('Article'), and if so, how do I make it so that it's linked to that linking table? class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField('Publication') class Publication(models.Model): title = models.CharField(max_length=30) articles = ??? -
Django Rest Framework (DRF) Refuses to Validate Data with Foreign Keys in Update (PUT) Request
Using Django REST Framework (DRF), I am trying to follow the DRF documentation for nested serializers provided by this link. For the moment, let's assume that my code looks like the following: models.py class PvlEntry(models.Model): pvl_project = models.OneToOneField("review.ProjectList", on_delete=models.CASCADE, related_name='pvl_project') pvl_reviewer = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='+') pvl_worktype_is_correct = models.BooleanField(blank=False, null=False) pvl_hw_description = models.TextField(blank=False, null=False) class ProjectList(models.Model): """ """ project_number = models.IntegerField(blank=False, null=False, unique=True) project_manager = models.CharField(blank=False, max_length=255, null=False) project_name = models.CharField(blank=False, max_length=255, null=False) project_description = models.CharField(blank=True, max_length=1024, null=True) views.py class PvlEntryListCreateAPIView(ListCreateAPIView): """ This view is leveraged for jsGrid so that we can have jsGrid produce a JavaScript enabled view for actions like editing and filtering of the project vetting list. """ queryset = PvlEntry.objects.all() serializer_class = PvlEntrySerializer name = 'listcreate-pvlentry' def get_queryset(self): qs = self.queryset.all() return qs class PvlEntryRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView): """ Leveraged for jsGrid """ queryset = PvlEntry.objects.all() serializer_class = PvlEntrySerializer name = 'rud-pvlentry' serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'first_name', 'last_name', 'email' ] class ProjectListSerializer(serializers.ModelSerializer): class Meta: model = ProjectList fields = '__all__' class PvlEntrySerializer(serializers.ModelSerializer): pvl_project = ProjectListSerializer() pvl_reviewer = UserSerializer() def update(self, instance, validated_data): print(validated_data) return super(PvlEntrySerializer, self).update(self, instance, validated_data) class Meta: model = PvlEntry fields = '__all__' Now, I understand that as this … -
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]: …