Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Manage.py runserver Failed
I have virtual environment of window 10 of company laptop. I am trying to execute python manage.py or python manage.py runserver Not getting error and it just shows output like this- enter image description here I expect the runserver start in my virtual environment. -
when running server, django always displays error
im only learnin python and django, i tried running server but only it shows error that says Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\theta\AppData\Local\Programs\Python\Python39\lib\site- packages\django\urls\resolvers.py", line 717, in url_patterns iter(patterns) TypeError: 'module' object is not iterable django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'app_advertisements' from ' C:\\Users\\theta\\PycharmProjects\\advertisements\\app_advertisements\\__init__.py' >' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app_advertisements')), ] and an app\urls.py from django.urls import path from .views import index urlpatterns = [ path('user/', index), ] -
I was trying to build an django project, it shows ```got an unexpected keyword argument 'chunked got an unexpected keyword argument 'chunked'```
The project when I previously build on my laptop it works but when I was trying to build this project on my pc it shows docker.errors.DockerException: Error while fetching server API version: HTTPConnection.request() got an unexpected keyword argument 'chunked'. My docker-compose.yml file looks like version: "3.3" services: db: image: postgres:14.0-alpine3.14 restart: always environment: POSTGRES_DB: ${DB_NAME} POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} volumes: - korean_mbc_appointment:/var/lib/postgresql/data web: build: ./ restart: always command: "python manage.py runserver 0.0.0.0:8000" volumes: - ./:/code expose: - 421 # ports: # - "420:8000" depends_on: - db nginx: build: ./nginx restart: always volumes: - ./static:/code/static - ./media:/code/media ports: - "420:80" depends_on: - web volumes: korean_mbc_appointment: The issue when I was trying to build the project looks like sudo docker-compose -f docker-compose.yml up -d --build Traceback (most recent call last): File "/usr/lib/python3/dist-packages/docker/api/client.py", line 214, in _retrieve_server_version return self.version(api_version=False)["ApiVersion"] File "/usr/lib/python3/dist-packages/docker/api/daemon.py", line 181, in version return self._result(self._get(url), json=True) File "/usr/lib/python3/dist-packages/docker/utils/decorators.py", line 46, in inner return f(self, *args, **kwargs) File "/usr/lib/python3/dist-packages/docker/api/client.py", line 237, in _get return self.get(url, **self._set_request_timeout(kwargs)) File "/usr/local/lib/python3.10/dist-packages/requests/sessions.py", line 602, in get return self.request("GET", url, **kwargs) File "/usr/local/lib/python3.10/dist-packages/requests/sessions.py", line 589, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python3.10/dist-packages/requests/sessions.py", line 703, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python3.10/dist-packages/requests/adapters.py", line 486, in send … -
How to set interaction endpoint on discord
I'm trying to set a interaction endpoint and the verification isn't working. @csrf_exempt def discord_endpoint(request): return JsonResponse({'type':1}) I'm getting: Validation errors: interactions_endpoint_url: The specified interactions endpoint url could not be verified. and as a post response from discord in my django app: b'{"application_id":"...","entitlements":[],"id":"...","token":"...","type":1,"user":{"avatar":"...","avatar_decoration":null,"discriminator":"0","global_name":"...","id":"...","public_flags":0,"username":"nickname"},"version":1}' -
Django How to add new user_id row in django admin, by number or name in another table with same user_id, like works ForeignKey, but without in models
I have Model Users with User_id and Model Subcribes with User_id, but without ForeignKey, How can I add new rows in Subscribes with hints of Users number or name in table Users, like if it would with ForeignKey? Is it possibe, to connect 2 tables like this in django admin? -
Wagtail and Django
I'm experienced with Django and I've just started looking into wagtail integration in order to provide a better UX to the content management. Let's say I have an existing Django app and I would like to keep the same structure but this time the contents can be managed from the wagtail admin panel instead of the Django one. Is there a way to let's say created a parallel Model which mirrors the existing Django Model. So I add contents from wagtail admin and it will add those content to the same DB schema . I know you can created a 1 to 1 relation to the existing django model, that might be one way of approaching it I think. Not sure what the best way to do so ?? Also it seems like you will have to provide an html template for each Model correct ? When does it make sense to use it ? Do you actually save time instead of crating you own UI ? What are the alternatives there ? Thank you in advance -
Djoser reset password flow to javascript frontend (Vue)
I've got most of this reset password flow done using djoser in django. I get the email successfully. The last part where I redirect back to Vue.js frontend after the user follows the link in the email is the only thing I'm missing. For clarity I expect to be redirected to my Vue frontent url with uid and token present. From there I can finish this off. My django files are: backend/settings.py (look at DJOSER setup): """ Django settings for backend project. Generated by 'django-admin startproject' using Django 4.2.1. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path from django.urls import reverse # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent BASE_URL = 'http://127.0.0.1:8080' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-1z1=&mfysp%pklgh@x+^_j3+p5)x+zm@va36wc9eq0z=7r3u7z' STRIPE_SECRET_KEY = 'sk_test_51NH4LnIIOIhiNEiGlcpsukLE5pi6Me9zYOhTf1uVP4ux7WgCXyR5QG9b6Yzfgm6qB4Agl8ZcQwZ7RN2rKIex04nk00kF97Aeok' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = [ 'http://127.0.0.1:8080', ] CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:8080', ] CSRF_COOKIE_HTTPONLY = False # SESSION_COOKIE_SAMESITE = 'None' # … -
Migrating wagtail snippet model into page model
I'm wanting to convert an existing snippet model into a page model, along with migrating all existing data from the snippet model. Is there a way to do this without having to manually convert the data/ create a script to generate pages from the existing models? I've updated the model, ran the migrations etc. and can create new pages for this type in the wagtail UI, but the existing data hasn't been migrated over and there's no new page models for it. References/links to the old snippet models are still intact, but there's nowhere to view/edit the model as it no longer appears as a snippet and hasn't been migrated over to a page. -
Django Flowbite dropdown doesn't work when I'm looping it in template for loop
Fowbite dropdown works when I write it out of for loop, but when I'm moving it into the for loop it stops working. And reason is not html id. I wrote 3 dropdowns out of for loop with same id and it worked. {% for comment in comments %} <div> <button id="dropdown-comments-{{ comment.id }}" data-dropdown-toggle="comment-options-{{ comment.id }}" class="text-primary-900"> <i class="w-6 h-6 fa-solid fa-ellipsis-vertical hidden sm:block"></i> <i class="w-6 h-6 fa-solid fa-ellipsis sm:hidden"></i> </button> </div> <div id="comment-options-{{ comment.id }}" class="z-10 hidden bg-white divide-y divide-primary-100 rounded-lg shadow w-44 dark:bg-primary-700"> <ul class="py-2 text-sm text-primary-700 dark:text-primary-200" aria-labelledby="comment-options-button"> <li> <a href="" class="block px-4 py-2 hover:bg-primary-100 dark:hover:bg-primary-600 dark:hover:text-white"> <i class="fa-solid fa-pen mr-3"></i> {% trans "Edit" %} </a> </li> <li> <button data-modal-toggle="delete-confirm-{{ comment.id }}" class="block text-start text-red-600 w-full px-4 py-2 hover:bg-primary-100 dark:hover:bg-primary-600 dark:hover:text-white"> <i class="fa-solid fa-trash mr-3"></i> {% trans "Delete" %} </button> </li> </ul> </div> {% endfor %} -
Prevent Prettier from breaking Python code
I am writing some conditions in my django html file and upon every save, vs code Prettier rearranges my code but it's doing it the wrong way hence creating errors. Here's an example of what it is doing. {% if messages %} {% for message in messages %} {% if message.tags == 'error' %} <div class="error-message">{{ message }}</div> {% elif message.tags == 'success' %} <div class="success-message">{{ message }}</div> {% else %} <div class="text-center mb-3">{{ message }}</div> {% endif %} {% endfor %} {% endif %} I tried modifying the settings.json with the following "git.confirmSync": false, "editor.formatOnPaste": true, "python.formatting.provider": "autopep8", "explorer.confirmDelete": false, "python.showStartPage": false, "explorer.confirmDragAndDrop": false, "python.linting.pylintArgs": ["--load-plugins=pylint_django"], "[python]": { "editor.defaultFormatter": "ms-python.python" } But it's still doing the same thing -
How to style the CSS bootstrap 'col' elements?
I'm trying to style bootstrap CSS columns col-xl so that I'll be able to have 5 or 6 cards/tiles on my page instead of 4 (page image attached) without touching the other grid layouts. However at this point I've no idea on how to achieve that. Below is my code: {% extends 'base.html' %} {% load static %} {% block content %} <h2>My Meals</h2> <div class='py-4 mt-auto'> <div class='container px-4'> <div class="row meal-tiles"> {% for meal in meals %} <div class="col-sm-12 col-md-12 col-lg-4 col-xl-3 d-flex align-items-stretch meal-tile"> <div class="card mb-3 meal-tile-border"> {% if meal.image %} <img src="{{ meal.image.url }}" alt="{{ meal.name }}" class="img-fluid" style="height: 200px;"> {% else %} <img src="{% static 'images/mealdefault.png' %}" alt="Default Image" class="img-fluid" style="height: 200px;"> {% endif %} <div class="card-body"> <h4 class='card-title'> <strong>{{ meal.name }}</strong></h4> {% with macros=meal.calculate_total_macros %} <p>Kcal in 100g: {{ macros.total_kcal_per_100g }}</p> <p>Carbohydrates in 100g: {{ macros.total_carbohydrates_per_100g }}</p> <p>Fats in 100g: {{ macros.total_fats_per_100g }}</p> <p>Proteins in 100g: {{ macros.total_proteins_per_100g }}</p> <p>Glycemic Load in 100g: {{ macros.total_glycemic_load_per_100g }}</p> <p>Glycemic Index: {{ macros.average_glycemic_index }}</p> {% endwith %} </div> </div> </div> {% empty %} <div class="col-12"> <p>No meals found.</p> </div> {% endfor %} </div> </div> </div> {% endblock %} I've tried styling the css for the .col-xl … -
No 'Access-Control-Allow-Origin' header is present on the requested resource React Django issue
I used django-cors-headers for managing CORS in my Django app. INSTALLED_APPS = [ ..., 'core', 'corsheaders', 'rest_framework', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] CORS_ALLOW_HEADERS = ("x-requested-with", "content-type", "accept", "origin", "authorization", "x-csrftoken") And my React look likes the following: React.useEffect(() => { // Make an API call to the backend axios.get('http://127.0.0.1:8000/core') .then((response) => { const namesArray = response.data.map(item => item.title); setNames(namesArray); }) .catch((error) => { console.log(error); }); }; I also include the following in package.json in my react app. "proxy": "http://localhost:8000/core", It's still throwing error Access to XMLHttpRequest at 'http://127.0.0.1:8000/core' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Please help, thank you!! -
my django project was displaying images but doesnt display images anymore after i deployed it to render
my Django project was working fine but after me deploying it using the render server the images do not display anymore like the logo what could be the cause and how can I solve it I tried using AWS S3 buckets but that failed and other than that failed its too complex I guess but is their some sort of easier way of doing this -
Django migrate error on first migration due to forms Meta class using User
I am getting the auth_user does not exist error on manage.py migrate when I try to migrate my app for the first time. This is due to the following part in one of my forms: class MyForm(ModelForm): def __init__(self, *args, **kwargs): ***dothings and super init*** def clean(self): ***dothings**** # This is where it goes wrong: class Meta: owner_choices_base = User.objects.values_list('username', flat=True) owner_choices = [(c, c,) for c in owner_choices_base] owner_choices.insert(0, (None, None,)) model = SomeModel widgets = { 'owner': forms.Select(choices=owner_choices), 'concerned_business_lines': forms.SelectMultiple() } It seems this executes before any of the migrations are done and it will see that User related things actually don't exist yet. It works nicely when I delete the Meta part and after that recreate it. Now I would like to have an app that works without having to comment out code for the first time you create it, but I have no idea how to get around this issue while still being able to populate my "special" owner field with users and I hope someone here will have an idea. For more information on why the Meta class is there: The owner field in the form is just a charfield, but I want to make … -
How can I automatically delete a field value in my Django model?
I want to delete the value of my model in Django which automatically: verify_code = models.IntegerField(blank=True, null=True) verification_timestamp = models.DateTimeField(blank=True, null=True) def save(self, *args, **kwargs): if self.verify_code is not None: self.verification_timestamp = timezone.now() super().save(*args, **kwargs) here I save the time in verification_timestamp if verify_code is not set to None, then I want to delete the value of verify_code after 1 min (for example save the value to None after 1 min), now what should I do? -
improve django queryset performance
I have a set of products that I need to fetch from my API, along with their respective discounts. Initially, I used the subqueries approach to achieve this, but it has led to significant performance issues as the dataset has grown. I'm looking for suggestions on how to refactor the queryset to improve the performance. Any ideas or alternative methods to efficiently retrieve product discounts would be greatly appreciated. This is the QuerySet: active_vouchers = Voucher.dal.get_active_vouchers( voucher_kind=VoucherKindChoices.Static_based ).prefetch_related('voucher_ranges__packs__expense') is_discounted_subquery = active_vouchers.filter( voucher_ranges__packs__product__id=OuterRef('pk'), min_basket_value=0 ) voucher_type = is_discounted_subquery.filter(voucher_ranges__packs__product__id=OuterRef('pk')).\ values('voucher_type')[:1] voucher_kind = is_discounted_subquery.filter(voucher_ranges__packs__product__id=OuterRef('pk')).\ values('voucher_kind')[:1] voucher_fixed_amount = Voucher.bll.convert_voucher_fixed_price_currency(active_vouchers, currency.code).\ filter(voucher_ranges__packs__product__id=OuterRef('pk'), ).values('converted_fixed_price')[:1] voucher_percent_amount = is_discounted_subquery.filter( voucher_ranges__packs__product__id=OuterRef('pk'), ).values('value_percentage_based')[:1] qs = self.annotate( is_discounted=Case( When( Q(Exists(is_discounted_subquery)), then=True, ), default=False ), voucher_kind=Case( When( Q(is_discounted=True), then=Subquery(voucher_kind) ), default=Value('no_voucher') ), voucher_type=Case( When( Q(is_discounted=True), then=Subquery(voucher_type) ), default=Value('no_voucher') ), fixed_static_discount=Case( When(Q( is_discounted=True, voucher_kind=VoucherKindChoices.Static_based, voucher_type=VoucherTypeChoices.Fixed_price_based ), then=Subquery(voucher_fixed_amount) ), default=0, output_field=MoneyCurrencyOutput(currency) ), percentage_static_discount=Case( When(Q( is_discounted=True, voucher_kind=VoucherKindChoices.Static_based, voucher_type=VoucherTypeChoices.Percentage_based ), then=Subquery(voucher_percent_amount) ), default=0, ), price_after_static_discount=Case( When( Q( is_discounted=True, voucher_kind=VoucherKindChoices.Static_based, voucher_type=VoucherTypeChoices.Fixed_price_based), then=ExpressionWrapper( F('default_pack_price') - F('fixed_static_discount'), output_field=MoneyCurrencyOutput(currency), ) ), When( Q( is_discounted=True, voucher_kind=VoucherKindChoices.Static_based, voucher_type=VoucherTypeChoices.Percentage_based), then=ExpressionWrapper( F('default_pack_price') * (100 - F('percentage_static_discount')) / 100, output_field=MoneyCurrencyOutput(currency), ) ), default=0, output_field=MoneyCurrencyOutput(currency) ), ) return qs This the QuerySet explain and the query in SQL: https://explain.depesz.com/s/xIgD#source Im not sure why planning time is … -
Design approach for quiz application with different types of questions and response types
I am trying to implement this functionality along with the ability of a user to select if the question is a multiple choice question with options, a short answer question stem with an answer field, and an image video question where the stem can be an image with fields to respond. So far: class Question(models.Model): QUESTION_TYPE_CHOICES = [ ('MCQ', 'MultipleChoiceQuestion'), ('SAQ', 'ShortAnswerQuestion'), ('IVQ', 'ImageVideoQuestion'), ] id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) paper = models.ForeignKey(Paper, on_delete=models.CASCADE, null=True) question_type = models.CharField(max_length=200,choices=QUESTION_TYPE_CHOICES, null=True) # MultipleChoiceQuestion, ShortAnswerQuestion, EssayQuestion, ImageVideoQuestion question_text = models.CharField(max_length=200) def __str__(self): return self.question_text class Meta: abstract = True class MultipleChoiceQuestion(Question): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) paper = models.ForeignKey(Paper, on_delete=models.CASCADE, null=True) # multiple_choice_question_text = models.CharField(max_length=200) multiple_choice_option_text = models.CharField(max_length=200, default=None) def __str__(self): return self.question_text class MultipleChoiceOption(models.Model): multiple_choice_question = models.ForeignKey(MultipleChoiceQuestion, on_delete=models.CASCADE, null=True) multiple_choice_option_text = models.CharField(max_length=200, default=None) is_correct = models.BooleanField(default=False) def __str__(self): return self.multiple_choice_option_text # applies to short answer questions and essays class ShortAnswerQuestion(Question): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) paper = models.ForeignKey(Paper, on_delete=models.CASCADE, null=True) # short_answer_question_text = models.TextField() # Text of the question answer_text = models.TextField() # Answer to the question discussion = models.TextField(blank=True) # Discussion or additional information about the question (optional) def __str__(self): return self.question_text # applies to OSCEs, POTS or other question with … -
how to perform the validation on django html form
View def Checkout(request): amount_str = request.POST.get('amount') amount = int(float(amount_str) * 100) cart = request.session.get('cart') tax = sum(i.get('tax', 0) for i in cart.values() if i) payment = client.order.create( { "amount": amount, "currency": "INR", "payment_capture" : "1" } ) order_id = payment['id'] context = { 'tax' : tax, 'order_id' : order_id, 'payment' : payment, } return render(request, 'checkout/checkout.html', context) html <div class="container"> <form method="post" action="{% url 'placeorder' %}"> {% csrf_token %} <div class="row"> <div class="col-lg-6"> <div class="checkbox-form mt-30"> <h3>Billing Details</h3> <div class="row"> <div class="col-md-6"> <div class="checkout-form-list"> <label>First Name <span class="required">*</span></label> <input type="text" value="{{user.first_name}}" name="first_name" placeholder="" readonly> <input type="text" value="{{order_id}}" name="order_id" placeholder="" hidden> <input type="text" value="{{payment}}" name="payment" placeholder="" hidden> </div> </div> <div class="col-md-6"> <div class="checkout-form-list"> <label>Last Name <span class="required">*</span></label> <input type="text" value="{{user.last_name}}" name="last_name" placeholder="" readonly> </div> </div> <div class="col-md-12"> <div class="checkout-form-list"> <label>Address <span class="required">*</span></label> <input type="text" name="address" placeholder="Street address"> </div> </div> </form> </div> Not adding all the fields this is my checkout page. if I click the continue button I want to perform the validation like all the fields are required. but in this case, I did not add any validation so I got the page error how can I add the validation in this code -
how does django oscar register the user model in the admin?
my custom User rom django.db import models from oscar.apps.customer.abstract_models import AbstractUser class User(AbstractUser): phone = models.CharField(max_length=32, blank=True, null=True) # new class Meta: db_table = 'auth_user' my extra settings 'users.apps.UsersConfig' AUTH_USER_MODEL = 'users.User' The model works correctly in the dashboard, but I didn't find the code that register user and user groups in admin panel. How oscar do that? -
Python Django from channels.generic.websocket import WebsocketConsumer
Python Django WebSocket connection to 'ws://192.168.3.12:8000/room/74b38da601c8d3bce0dcfd269d72fc4c0c5c63d7abe0d74599a6c0cc39a110f9/' failed:enter image description here [20/Jul/2023 11:13:34] "GET /room/0ab774881c5b30fc126ad1a0acc4d4202228982ddbbeb44cfaf92f2cc952e141/ HTTP/1.1" 404 6463 I checked the urls,find there don't have /room; But,routing.py: websocket_urlpatterns = [re_path(r'room/(?P<group>\w+)/$',consumers.ChatConsumer.as_asgi()),re_path(r'enroom/(?P<group>\w+)/$',consumers.ChatEnConsumer.as_asgi()),re_path(r'chart/(?P<group>\w+)/$',consumers.ChartConsumer.as_asgi()),re_path(r'user_actual_line/(?P<group>\w+)/$', consumers.UserActualLineConsumer.as_asgi()),] So I suspect something is wrong with websocketconsumer -
Command line not recognizing 'djstripe_sync_plans_from_stripe' or 'djstripe_sync_plans'
Has anyone else encountered / solved this issue? We've found no insight into this from the web. But as far as we can tell, I have to run at least one of these commands to sync our Stripe account with our Django database models. The CLI command that's worked for all our other teammates has been: python3 manage.py djstripe_sync_plans_from_stripe The expectation, as I understand, is that this command should sync Django models from relevant data on the Stripe account, however my terminal doesn't recognize this command. This is the first time the team has experienced this while onboarding a new collaborator. One command that is recognized is: python3 manage.py djstripe_sync_models This command produces a number of funky errors which may or may not be related to the issue at hand, but it does run. This illustrates that some of these "djstripe" commands are recognized, just not the one that we need. Bottom line, we need to find a fix or a workaround. -
Django form image field mandatory error even when filled
I have a form that works both for when creating a new instance or editing one, on django. The problem is that no matter what scenario, even when I fill the input file fields, it always returns error that fields are mandatory. The models.py: class Images(models.Model): background_image = models.ImageField(upload_to='images/') user_image = models.ImageField(upload_to='images/user/') other_model = models.OneToOneField( "OtherModel", on_delete=models.CASCADE ) forms.py file: class ImagesForm(forms.ModelForm): background_image = forms.ImageField( widget=CustomImageInputWidget(attrs={"id": "background_input", "title": _("Background")}) ) user_image = forms.ImageField( widget=CustomImageInputWidget(attrs={"id": "logo_input", "title": _("Logo")}) ) class Meta: model = Images fields = "_all_" views.py file: if request.POST: images_form = ImagesForms(request.POST, request.FILES, instance=image_forms_instance) else: images_form = ImagesForms(initial={"other_model": other_model}, instance=customizable_instance) template file: <form method="POST" enctype="multipart/form-data" id="my-form"> {{ csrf_input }} {{images_form.as_p()}} {{images_form.errors}} <div class="tools-card-footer"> <span class="tools-icon-share"> <input type="submit" name="custom" value="Start"> </span> </div> </form> custom widget file: {% if widget.is_initial %}{{ widget.initial_text }}: <a href="{{ widget.value.url }}">{{ widget.value }}</a>{% if not widget.required %} <input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}"{% if widget.attrs.disabled %} disabled{% endif %}> <label for="{{ widget.checkbox_id }}">{{ widget.clear_checkbox_label }}</label>{% endif %}<br> {{ widget.input_text }}:{% endif %} <input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}> <div class="dropzone" id="{{widget.attrs.id}}-div"> <input accept="image/png, image/gif, image/jpeg" type="file" name="file" id="{{widget.checkbox_id}}" {% for name, value in widget.attrs.items() %}{% if value is not … -
Can't import django_heroku
I'm currently trying to deploy a django-react application to heroku, I'm following a guide and it tells me to install django-heroku package (as well as psycopg2, psycopg2-binary, whitenoise, etc). All of those are installed on my virtual environment (env) requirements.txt asgiref==3.7.2 botocore==1.31.5 cachetools==5.3.1 certifi==2023.5.7 cffi==1.15.1 charset-normalizer==3.1.0 colorama==0.4.6 cors==1.0.1 dj-database-url==2.0.0 Django==4.2.2 django-cors-headers==4.1.0 django-heroku==0.3.1 django-storages==1.13.2 djangorestframework==3.14.0 djangorestframework-simplejwt==5.2.2 filelock==3.12.2 future==0.18.3 gcloud==0.18.3 gevent==22.10.2 googleapis-common-protos==1.59.1 greenlet==2.0.2 gunicorn==21.2.0 httplib2==0.22.0 idna==3.4 jmespath==1.0.1 jws==0.1.3 oauth2client==4.1.3 oauthlib==3.2.2 packaging==23.1 Pillow==9.5.0 protobuf==4.23.4 psycopg2==2.9.6 psycopg2-binary==2.9.6 pyasn1==0.5.0 pyasn1-modules==0.3.0 pycparser==2.21 pycryptodome==3.18.0 PyJWT==2.7.0 pyparsing==3.1.0 Pyrebase4==4.7.1 PySocks==1.7.1 python-dateutil==2.8.2 python-dotenv==1.0.0 python-jwt==2.0.1 pytz==2023.3 requests==2.29.0 requests-file==1.5.1 requests-oauthlib==1.3.1 requests-toolbelt==0.10.1 rsa==4.9 s3transfer==0.6.1 six==1.16.0 sqlparse==0.4.4 tldextract==3.4.4 typing_extensions==4.7.1 tzdata==2023.3 uritemplate==4.1.1 urllib3==1.26.16 whitenoise==6.5.0 zope.event==5.0 zope.interface==6.0 But when I try to import django-heroku it says "Import "django_heroku" could not be resolved".Issue. File structure: image. What should I try? I want the installed packages to work (dj_database_url doesn't work too). I tried reinstalling the necessary packages (also the whole environment), but it simply doesn't work. I'm sure I'm using my virtual environment (env) -
PostgreSQL/Django: target >2 Billion (2.000.000.000) Limit/Advice
I developed an R&D database to store machine time data. From this raw time I calculate/extract statistics. Suggestions/advice is needed regarding data size limits. Setup: Django (Python) backend with PostgreSQL database. Concept: Every machine: stores about 300.000 records split over two tables: index_table and data_table. An index_table contains machine info (setting, labels, operator). The data_table has 7 fields (index*, step*, datetime, value, setpoint, comment, active) where index* is an foreign key to index table and step* an foreign key to measurement settings. Comment field (text) about 30 chars. Workflow: Normally raw data (300.000 records) is uploaded to data_table and statistics are calculated/extracted. Typical user: Zero: Upload and extract datafile to database (index_table, data_table). Every time about 300.000 records in data_table. After that user "initiates calculate statistics". First: "production" report request is to collect statistics (no problems relative small tables). Second: "R&D" report request raw data (300.000 records) and server make some transformations and plots (Plotly) over HTML Status: Currently I uploaded 400 machines. The data_table has 30.000.000 (30 million) records and the database size is: 10Gb. The server is running on a low end workstation. Performance is fine and smooth. And above my expectation (last large database experience 20 years … -
How do I create multiple different types of POST requests in Django that can each be handled in a different way?
In my django project, I have a page which allows users to add a task through clicking a button and entering the details of the task(in a modal window). Users are also able to edit/delete tasks by clicking a button next to each respective task. I've run into the issue of not being able to submit different types of post requests that can handle each operation individually. Here is an image of the page for clarity: User interface I'm not sure how to create two different "types" of POST requests that can handle these two cases. One "type" of POST request for adding a task and another for editing/deleting it. Just for reference, this is what the modal window would look like to add a task: add task Right now this is the URL I want both of them to redirect to when the form is submitted(which is just the original page after the modal window is removed after submission) is: path('team/<str:team>/', views.team_view) This is the team_view function currently: def team_view(request, team): connection.connect() team_url = team[4:] if(team[4] == '1'): team_num = team[4:] else: team_num = team[5] tasks = Task.objects.filter(team_id=team_num) context = { 'task_list' : tasks, 'team_id' : team_num, 'team_id_url': team_url …