Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Railway app production isnt working: Csrf post error when i try to sign in when it works perfectly locally
On a local server, my webapp was working perfectly, but in production i get a csrf post error whenever I try to sign in or register. In settings i have 'django.middleware.csrf.CsrfViewMiddleware' in my settings.py file, and i have these: {% csrf_token %} In my HTMLs. I have tried pretty much every suggestion I have seen and cannot seem to get it working. Any thoughts? I tried adding all of these suggested by other posts i have seen : ALLOWED_HOSTS = ["*"] CSRF_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_DOMAIN = 'mydomainname' CSRF_COOKIE_NAME = "csrftoken_custom" SESSION_COOKIE_SAMESITE = 'Lax' CSRF_COOKIE_SAMESITE = 'Lax' CSRF_TRUSTED_ORIGINS = ['*'] and the same error kept coming. -
multiple models to one manytomanyfield table
I have two apps Levels, Classes with Many To Many Relationships, Levels can have many Classes, and Classes can have many Levels. How can I do that? I tried: levels/models.py class Level(models.Model): name = models.CharField(max_length=50) classes = models.ManyToManyField(ChildClass, related_name='childclass', blank=True,db_table='level_class', primary_key=False) child_class/models.py class ChildClass(models.Model): name = models.CharField(max_length=50) levels = models.ManyToManyField('level.Level', related_name='childclass',db_table='level_class') Returns (Error) child_class.ChildClass.levels: (fields.E340) The field's intermediary table 'level_class' clashes with the table name of 'level.Level.classes'. level.Level.classes: (fields.E340) The field's intermediary table 'level_class' clashes with the table name of 'child_class.ChildClass.levels'. -
White screen after installing django-unfold
I got a problem, it's with JS which we got with the package or with me, which made a mistake on django-side, i'm not sure. I have installed the django-unfold package using "pip install django-unfold" and added it to my INSTALLED_APPS list as follows: INSTALLED_APPS = [ "unfold", "unfold.contrib.filters", "unfold.contrib.forms", # "nested_admin", 'django.contrib.admin', # base 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # project apps 'work', # third-party-apps 'rest_framework', 'djoser', # 'corsheaders', 'django_filters', ] I have also made some changes to my admin.py as shown below: from unfold.admin import ModelAdmin @admin.register(Genre) class GenreAdmin(ModelAdmin): pass However, when I try to access the admin page at /admin/, I am presented with a white screen. Upon checking the console, I found the error message "Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data" in the alpine.persist.js file. I am not proficient in JS but I find the code in this file difficult to understand. Therefore, I asked ChatGPT to make the code in alpine.persist.js more descriptive. The updated code is shown below: (() => { function persistPlugin(alpineInstance) { let createPersistInterceptor = () => { let key, storage = localStorage; return alpineInstance.interceptor( (componentState, getState, setState, propName, uid) => { let stateKey … -
Django unit testing imagefield error using SimpleUploadedFile
This is the tests.py class ArticleModelTestCase(TestCase): def setUp(self): self.article = Article.objects.create( title = 'Title test.', content = 'Content test.', date_posted = timezone.localtime(), image = SimpleUploadedFile( name = 'test_image.jpg', content = b'', content_type = 'image/jpeg' ) ) def test_title(self): self.assertEqual(self.article.title, 'Title test.') def test_content(self): self.assertEqual(self.article.content, 'Content test.') def test_image_field(self): self.assertEqual(self.article.image.name, 'test_image.jpg') and I got this error Creating test database for alias 'default'... System check identified no issues (0 silenced). .F. ====================================================================== FAIL: test_image_field (articles.tests.ArticleModelTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/xxx/projects/xxxx/backend/articles/tests.py", line 27, in test_image_field self.assertEqual(self.article.image.name, 'test_image.jpg') AssertionError: 'article_images/test_image_7U9qlax.jpg' != 'test_image.jpg' article_images/test_image_7U9qlax.jpg test_image.jpg ---------------------------------------------------------------------- Ran 3 tests in 0.004s FAILED (failures=1) Destroying test database for alias 'default'... What happen is that the SimpleUploadedFile not only created a 'test_image.jpg' but it created 3 files of: test_image.jpg test_image_CWK5SDf.jpg test_image_7U9qlax Everytime I ran the test it will always created 3 image files with a random words and number as the suffix after 'test_image' Why does this happen? and how to fix this? Thanks -
How do I fix the return type of a Django model manager's method?
I'm using Django 4.1.7 with django-stubs 1.16.0, and mypy 1.1.1. I have code that looks like this: class ProductQuerySet(QuerySet): ... class ProductManager(Manager): def create_red_product(self, **kwargs) -> "Product": return self.model(color=Product.Color.RED, **kwargs) _product_manager = ProductManager.from_queryset(ProductQuerySet) class Product(Model): ... objects = _product_manager() When mypy looks at this, it says: models/product.py:46: error: Incompatible return value type (got "_T", expected "Product") [return-value] It seems like the type of self.model in a model manager method is _T, which from what I understand is a generic type bound to the model, which in my case should be "Product". Why isn't this working? How can I fix it? -
How do I type a custom User model manager for mypy in Django?
I'm using Django 4.1.7 with django-stubs 1.16.0. I created a custom user manager for my User model like this: from django.contrib.auth.models import UserManager class MyUserManager(UserManager): def delete_test_data(self): return self.filter(test_data=True).delete() class User(AbstractUser): test_data = models.BooleanField() ... objects = MyUserManager() Everything works as expected, but when I run mypy on this, it complains with: models.py:32: error: Incompatible types in assignment (expression has type "MyUserManager[User]", base class "AbstractUser" defined the type as "UserManager[AbstractUser]") [assignment] Am I doing something wrong? Is this a mypy bug? Bad types defined in django-stubs? Is there a way to type this without forcing mypy to ignore it? -
How to make bootstrap navlink active in dynamically generated for loop in django template
I am trying to make a tag navlink active in for loop django template. Every link is passing id, base on id matching i would like make nav-link active. This is my Template html page, this is for loop and here i am checking condition to make nav-link active. I am not able to highlight the nav-link. <ul class="nav nav-pills" role="tablist"> <li class="nav-item"> <a class="nav-link"href="{% url 'core_app:store' 'all' %}">All</a> </li> {% for type in store_type %} {% if type.id == typeid %} <li class="nav-item"> <a class="nav-link active" href="{% url 'core_app:store' type.id %}">{{type.name}}</a> </li> {% else %} <li class="nav-item"> <a class="nav-link"href="{% url 'core_app:store' type.id %}">{{type.name}}</a> </li> {% endif %} {% endfor %} </ul> This is my View code Here i am getting all store_type and base on link click and passing id and i am extracting type of store. Then i would like to highlight my nav-link active base on conditional matching def store(request, id): if id == "all": store_list = Store.objects.all().order_by('id') else: store_list = Store.objects.all().filter(store_type=int(id)).order_by('id') return render(request, 'core_app/store/all_store.html', {'stores': store_list, 'typeid': id, "store": "active", 'store_list': 'active', 'store_type': StoreType.objects.all()}) Model (Store has StoreType) class StoreType(models.Model): name = models.CharField(max_length=255, blank=True, null=True) ... def __str__(self): return self.name class Store(model.Model): store_type = models.ForeignKey(...) name … -
Failed to compute cache key
A error is showing in my code: [+] Building 10.0s (7/9) => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 518B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 218B 0.0s => [internal] load metadata for docker.io/library/python:3.9-alpine3.13 9.9s => CANCELED [1/5] FROM docker.io/library/python:3.9-alpine3.13@sha256:a7 0.0s => => resolve docker.io/library/python:3.9-alpine3.13@sha256:a7cbd1e7784 0.0s => => sha256:a7cbd1e7784a35a098cedbc8681b790d35ff6030a5e 1.65kB / 1.65kB 0.0s => => sha256:ec5c85c9adb18db9c7204b674ee8ec4ae5268a7996c 1.37kB / 1.37kB 0.0s => => sha256:77dca58f10dd82e74ddf80f3382c327a4b61c7dee3a 7.43kB / 7.43kB 0.0s => [internal] load build context 0.0s => => transferring context: 74B 0.0s => CACHED [2/5] COPY ./requirements.txt /tmp/requirements.txt 0.0s => ERROR [3/5] COPY ./app /app 0.0s ------ > [3/5] COPY ./app /app: ------ failed to solve: failed to compute cache key: "/app" not found: not found How to resolve this error while running docker-compose build on terminal on macOS? This is my Docker file: FROM python:3.9-alpine3.13 LABEL maintainer="DV" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./app /app WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="/py/bin:$PATH" USER django-user This is my docker-compose.yml file: version: "3.9" services: app: … -
Need recommendation Python stack for a web application
Here is a short description a web application: Users will be able to authorize to app through social media accounts. The web app will get users' posts from social media platforms by API. It will look like a table with users' posts with different data. Users will be able to choose posts and remove them in bulk. Features: search posts by keyword, filter by date and media type, and sort new and old. Happy to hear any suggestions. I don't know what stack is best for my web application. -
X.MultipleObjectsReturned: get() returned more than one X -- it returned X
I have a model, Chapter, linked to the Book model through a ForeignKey. One of it's fields, the integer field, number, is "slugified" to make the slug field, chapter_slug. The problem is my DetailView. When I call it the error "raise self.model.MultipleObjectsReturned(books.models.Chapter.MultipleObjectsReturned: get() returned more than one Chapter -- it returned 2!" That happens when I have more than one chapter 1, in this case, in two different books. class Chapter(models.Model): book = models.ForeignKey(Book, on_delete=models.PROTECT) number = models.IntegerField(default=1) name = models.CharField(max_length=200, blank=True) chapter_slug = models.SlugField(null=True) ... def get_absolute_url(self): return reverse('chapter', kwargs={'book_slug': self.book.book_slug, 'chapter_slug': self.chapter_slug}) def save(self, *args, **kwargs): if not self.chapter_slug: self.chapter_slug = slugify(self.number) return super().save(*args, **kwargs) ... path('book/<slug:book_slug>/chapter/<slug:chapter_slug>/', views.ChapterView.as_view(), name='chapter'), class ChapterView(DetailView): model = Chapter template_name = books/chapter.html' context_object_name = 'chapter' slug_field = 'chapter_slug' slug_url_kwarg = 'chapter_slug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) chapter = self.get_object() context['book_slug'] = chapter.book.book_slug context['chapter_slug'] = chapter.chapter_slug ... [08/Apr/2023 15:43:03] "GET / HTTP/1.1" 200 79 Not Found: /favicon.ico [08/Apr/2023 15:43:03] "GET /favicon.ico HTTP/1.1" 404 9214 [08/Apr/2023 15:43:14] "GET /book/example/chapter/1 HTTP/1.1" 301 0 Internal Server Error: /book/example/chapter/1/ Traceback (most recent call last): File "/home/user/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/user/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/.local/lib/python3.10/site-packages/django/views/generic/base.py", line … -
How to increase the loading speed of database in django?
I've build this website https://hanjaba.com/ using django and supabase as the database. However the loading speed website seems to be very slow when it have to retrieve data from the database and loads the static pages quite fast. How can I increase the loading speed of the database? -
Why my code for displaying user profile in Django isn't working?
I'm learning Django and I'm making a website that includes registering and creating your own profile. When you're logged in you can view other users profiles and by clicking on their picture it redirects you to their profile site. The problem is: the picture redirects you to the right url but it shows base template rather than the one that I want I checked some websites and even chat gpt for help but it wasn't successful I'll only show important parts of my code but if sth missing just let me know and I'll add it. Here's the code for 'urls.py': from django.urls import path from . import views from django.views.generic.base import RedirectView from django.templatetags.static import static app_name = 'app' urlpatterns = [ path('', views.index, name='index'), path('profile/', views.profile, name='profile'), path('profile_list/', views.profile_list, name='profile_list'), path('user_profile/<int:user_id>/', views.user_profile, name='user_profile'), ] 'views.py' from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import login, logout, authenticate from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.decorators import login_required from django.urls import reverse from django.contrib import messages from .forms import RegisterForm, UserProfileForm, MessageForm from .models import UserProfile, Message from django.contrib.auth.models import User def index(request): return render(request, 'base.html') @login_required def profile(request): user_profile = UserProfile.objects.get(user=request.user) if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES, instance=user_profile) … -
Django login - Preserve the 'next' parameter in the URL when the login form submission fails
I am using Django LoginView to render login form and handle the login action. Sometimes the login url has a next parameter. If the user enters wrong username and password, then it is again redirected to the login page but the url should preserve the next parameter. But I am not able to achieve it. class CustomLoginView(LoginView): ''' After successful login, django auth view should redirect the user to the next GET param Ref: python - Django built in login view not redirecting to next https://stackoverflow.com/questions/50542035/python-django-built-in-login-view-not-redirecting-to-next ''' def get_success_url(self): next_page = self.request.POST['next'] if next_page == '': next_page = '/' # if next param is not available, then redirect the user to the homepage after login. return next_page def form_invalid(self, form): response = super().form_invalid(form) next_url = self.request.GET.get('next') or self.request.POST.get('next') if next_url: response['Location'] = f"{self.request.path}?next={next_url}" return response I was expecting the form_invalid method to preserve the next param in the url but it's not happening. I think setting response['Location'] variable in the form_invalid method is not the right way. Looking forward towards some help. -
Django: How to create "Published" and "Last edited" fields?
I'm writing a blog for my portfolio and I wanna compare (in the Django template) the date I published an article with the date I edited it in order to display the "Edit date" only if it was edited before. The problem is: I don't wanna test for every single date field, like year, month, day, hour, minute, etc., but if I simply compare the two values, it'll always display both values, since the time precision goes beyond seconds, making the dates different even though I never edited that particular post. TL;DR How to compare dates when their values will always differ, given the precision Django takes time, without using an iffor every value (year, month, day, hour, minute, second)? What I tried: I successfully accomplished solving my main problem, but my code looks something like if this == that and if this == that etc.. It doesn't look pretty and I don't wanna code this for every website I build. It looks like there's a better way to solve it. -
custom domain from godaddy through cloudflare to ec2 instance
im trying to set up my first propper custom domain. heres what ive done. on godaddy i have deleted all of my dns records and pointed to cloudflares name servers on cloudflare i have set up an a record to my ec2 instance with my custom domain i bought on godaddy i still cant connect to my ec2 instance with my custom domain but can with my ec2's ip address all of the tutorials i find about this stuff involve route 53 rather than cloudflare. must i use route 53? what am i doing wrong/ what else should i try / investigate? how could i make this work? below is some evidence for what ive done. -
Django github git add . does nothing on new project
I did add already few project to github. Now I created another one in django. I follow procedure: I create repo on github. then in CMD: git clone https://github.com/my_name/repo_name.git Then I paste my project there. Then I follow procedure described here: https://docs.github.com/en/migrations/importing-source-code/using-the-command-line-to-import-source-code/adding-locally-hosted-code-to-github With other project after: git add . I saw all (not sure if all but many of them) files processed on the window. Now after I type git add . it does nothing. There results is that for example it deos not add and does not push static folder at all. I do evrything the same way as before. When I try to push my old project to github it works. I have problem with new project in django. -
When I runserver I get this error: Django 405 error
Django 405 error-page not found. when I runserver I get this error.Anybody have any clue how to fix this error? I use Windows 10, python, django. [08/Apr/2023 19:54:11] "GET / HTTP/1.1" 200 3710 Not Found: /favicon.ico [08/Apr/2023 19:54:13] "GET /favicon.ico HTTP/1.1" 404 4697 [08/Apr/2023 19:54:40] "POST / HTTP/1.1" 200 3959 [08/Apr/2023 19:55:17] "GET /password/reset/ HTTP/1.1" 200 3402 [08/Apr/2023 19:55:25] "POST /password/reset/ HTTP/1.1" 302 0 [08/Apr/2023 19:55:25] "GET /password/reset/done/ HTTP/1.1" 200 3135 Method Not Allowed (POST): /password/reset/done/ Method Not Allowed: /password/reset/done/ [08/Apr/2023 19:55:28] "POST /password/reset/done/ HTTP/1.1" 405 0 My settings.py file looks like this import os from pathlib import Path from dotenv import load_dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent env_path = BASE_DIR / '.env' load_dotenv(dotenv_path=env_path) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY', "error") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv("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', 'django_crontab', 'service', 'base', 'blog', 'users', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES … -
How to stop page from refreshing when a POST request is sent using Django and AJAX
I have a browse and upload file button. I also have a Start Task button. I want to browse and select a file. After doing so, I want to click Start Task which sends a POST request and NOT have the page reload. At the moment, when I click Start Task, the selected file gets cleared out. I am new to Django and Ajax so any help is appreciated. Here is my index.html with my buttons: <div class="container-fluid px-4"> <h3 class="mt-4">Intrusion Detection System</h3> <form action="{% url 'upload' %}" class="row gy-1 gx-2 align-items-center" id='startIDS' method="post" enctype="multipart/form-data" style="margin-bottom: 10px;"> <div class='col-auto'> <input class="form-control" type="file" name="file"> </div> <div class='col-auto'> {% csrf_token %} <button type="submit" class="btn btn-primary btn-sm" style="float: right;" onclick="wait()" id="button2">Upload File</button> <script> function wait() { //go_to_sleep.delay(5); alert("Click Ok and then please wait for upload to finish"); } </script> </div> <div class='progress-wrapper'> <div id='progress-bar' class='progress-bar' style="background-color: #68a9ef; width: 0%;">&nbsp;</div> </div> <div id="progress-bar-message">Waiting for progress to start...</div> <div id="celery-result"></div> <script src="{% static 'celery_progress/celery_progress.js' %}"></script> <!--CELERY--> </form> <form method="post" id="post-form"> {% csrf_token %} <button id="ajax-button" type="submit">Start task</button> </form> {% if task_id %} <script> $(document).ready(function() { $("#ajax-button").click(function(e) { e.preventDefault(); // STOP PAGE FROM REFRESHING $.ajax({ type: 'POST', url: '{% url "upload" %}', data: { csrfmiddlewaretoken: '{{ … -
I have been developing a web app in django. But whenever i make any changes to the css, it doesnt get applied
Currentlt creating a web app using Django when i ecnountered a problem. Whenever i make any changes to the css file, the webpage does not show any change. However, if i copy the contents from the css file and create a new css file and paste it there, it works perfectly. I dont know what is happening, please help. I am trying to change the css of to make some changes in the webpage but the changes are not getting applied. I have to create a new file and paste the contents from the previous css file if i want to make any changes. This new file works perfectly for sometime, then it will stop responding. Then i have to create a new css file. -
Add validation for auto populated field in django admin based on some condition
There is one model form, in which there are various fields, so all fields are filled except name field(name field can be kept blank), once we can hit submit button that name field should be auto-populated based on following code, name field length is restricted to 100, so if it exceeds that length, it gives Internal Server Error, I want to handle that ISE, instead of ISE I want to raise error(BadRequest) based on if condition mentioned in the code, but I am not able to raise it. Even I have tried with try Except, but not able to raise error, can not able to do with clean method because in this class where save_model method is defined at there NestedModelAdmin in inherited. def save_model(self, request, obj, form, change): if not obj.name: obj.name = '{}_{}'.format( obj.id, obj.model_name, ) if len(obj.name) > 100: raise BadRequest('Name cannot be longer than 100 characters.') super().save_model(request, obj, form, change) -
Django Use ModelForm to Filter database and return objects to Folium Map and table
I am trying to create a page with a Model Form, a Folium map, and a table. I want the users to be able to query the Django Model through the Model Form and have the results appear on the map and table. I am stuck trying to figure out how to use the form to query the model and how to pass the data to the map and table views. Here is my code so far. views.py import folium from django.shortcuts import render from .models import StLouisCityLandTax from .forms import StLouisCityLandTaxForm def formViewPage(request): if request.method == 'GET': form = StLouisCityLandTaxForm(request.get) if form.is_valid(): sale = form.cleaned_data['sale'] neighborho = form.cleaned_data['neighborho'] properties = StLouisCityLandTax.objects.filter(sale=sale, neighborho=neighborho) else: properties = StLouisCityLandTax.objects.all() else: form = StLouisCityLandTaxForm() properties = StLouisCityLandTax.objects.all() context = {'form': form, 'properties': properties} return render(request, 'maps/partials/_form.html', context) def allObjectsMap(request): properties = StLouisCityLandTax.objects.all() # create a Folium map centered on St Louis m = folium.Map(location=[38.627003, -90.199402], zoom_start=11) # add tile layer control and tile layer folium.TileLayer( tiles='https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', attr='Esri', name='Esri Satellite', overlay=False, control=True ).add_to(m) folium.LayerControl().add_to(m) # add markers to the map for each station for i in properties: coordinates = (i.point_y, i.point_x) # folium.Marker(coordinates).add_to(m) iframe = folium.IFrame( f"Land tax ID: {i.land_id}" + '<br>' + f"Owner: … -
I have three QuerySets from one table. 'asiento' and create lista1, lista2 and lista3
lista1 = asiento.objects.all().annotate(grupo= Substr("cuenta__codigo",1,1)).values('grupo').annotate(sum_debe=Sum("debe"),sum_haber=Sum("haber")) lista2 = asiento.objects.all().annotate(grupo = Substr("cuenta__codigo",1,3)).values('grupo').annotate(sum_debe=Sum("debe"),sum_haber=Sum("haber")) lista3 = asiento.objects.all().annotate(grupo = Substr("cuenta__codigo",1,6)).values('grupo').annotate(sum_debe=Sum("debe"),sum_haber=Sum("haber")) Chain then three QuerySets: listan = chain(lista1,lista2,lista3) The result of the chain in the variable listan is: {'grupo': '1', 'sum_debe': Decimal('251.680000000000'), 'sum_haber': Decimal('0')} {'grupo': '2', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('251.680000000000')} {'grupo': '1.0', 'sum_debe': Decimal('194.120000000000'), 'sum_haber': Decimal('0')} {'grupo': '1.2', 'sum_debe': Decimal('37.5600000000000'), 'sum_haber': Decimal('0')} {'grupo': '1.3', 'sum_debe': Decimal('20'), 'sum_haber': Decimal('0')} {'grupo': '2.1', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('143.450000000000')} {'grupo': '2.3', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('22.5600000000000')} {'grupo': '2.4', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('85.6700000000000')} {'grupo': '1.0.80', 'sum_debe': Decimal('128.450000000000'), 'sum_haber': Decimal('0')} {'grupo': '1.0.90', 'sum_debe': Decimal('65.6700000000000'), 'sum_haber': Decimal('0')} {'grupo': '1.2.00', 'sum_debe': Decimal('27.5600000000000'), 'sum_haber': Decimal('0')} {'grupo': '1.2.40', 'sum_debe': Decimal('10'), 'sum_haber': Decimal('0')} {'grupo': '1.3.20', 'sum_debe': Decimal('20'), 'sum_haber': Decimal('0')} {'grupo': '2.1.00', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('123.450000000000')} {'grupo': '2.1.50', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('20')} {'grupo': '2.3.70', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('22.5600000000000')} {'grupo': '2.4.00', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('45.6700000000000')} {'grupo': '2.4.45', 'sum_debe': Decimal('0'), 'sum_haber': Decimal('40')} i need to order by a new field 'grupo' created in every query sets with annotate. When I sort (listan) with the chain result using the new 'grupo' field. listan = sorted(chain(lista1,lista2,lista3),key=attrgetter('grupo')) I receive the error: 'dict' object has no attribute 'grupo'. Thanks for your help. -
Select 3 random items and exclude the one already selected
I'm trying to display three random drinks in my template, selected from a database of drinks. I currently have the random selection working but also noticed theres a chance of a drink showing up twice. How do I prevent this from happening? Is there a smarter way of doing this? import random def testview(request): drink1 = random.choice(DrinkRecipe.objects.all()) drink2 = random.choice(DrinkRecipe.objects.all()) drink3 = random.choice(DrinkRecipe.objects.all()) context ={ 'drink1' : drink1, 'drink2' : drink2, 'drink3' : drink3, } return render(request,'drinks/test.html', context=context) -
Django use same object for multiple views
In django im making my first app. I'm trying to find a way to share an object between multiple view methods. e.g. In my views.py I have def lights_on(request): hue_connector = HueConnector() print(hue_connector.turn_all_lights_on()) return redirect('/') def lights_off(request): hue_connector = HueConnector() print(hue_connector.turn_all_lights_off()) return redirect('/') def light_on(request, light_id): hue_connector = HueConnector() hue_connector.set_light_on_state(light_id, "true") html = "<html><body>" + light_id + "</body></html>" return redirect('/') Lets say I want 10 more views in my views.py that need a HueConnector. How should I create one that can be used by all methods? -
why is my django app not working on browser after running python manage.py runserver 0.0.0.0:8080
while running on vagrant i try to test my django app using the command python manage.py runserver 0.0.0.0:8080 but it seems running on my device but when trying it on chrome on 127.0.0.1:8080 is not working. (profile_api) vagrant@ubuntu-bionic:/vagrant/src/profiles_project$ python manage.py runserver 0.0.0.0:8080 Performing system checks... System check identified no issues (0 silenced). April 08, 2023 - 14:43:56 Django version 1.11, using settings 'profiles_project.settings' Starting development server at http://0.0.0.0:8080/ Quit the server with CONTROL-C. 127.0.0.1 refused to connect.