Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to manually test task retry in Celery?
I'm trying to implement task retry in my Django app using Celery and would like to test if the task will be properly restarted when an unexpected exception will be raised. To do this I manually rise an Exception in the task but it's doesn't work as expected. It throws a RecursionError saying that maximum recursion depth is exceeded while calling a Python object. So how can I know if my task will be retried in case an Exception is raised in production mode? This is how my task looks like: @celery.app.task() def download(client): return client.download('www.something.com/api') The same task with Celery retry options: @celery.app.task(bind=True, autoretry_for=(Exception,), exponential_backoff=2, retry_kwargs={'max_retries': 5}, retry_jitter=True) def download(self, client): print('test') try: raise Exception return client.download('www.something.com/api') except Exception as exc: print('exception !') download.(client).retry(exc=exc) And code execution output shows that retries are not controled by Celery: test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test … -
filter a query based on a value only if the value is not empty in django
I need to filter a query based on a variable but only if this var is not empty ... here is what I have tried : rows = Attendance.objects.filter(type= the_type if the_type != "" else '*') the problem is in the part else '*' I have tried to remove else, but it won't work as it is required to use an else after if in the ternary operator, also tried else pass but it gives me an error. -
django import with django-import-export
could anybody tell me what I did wrongly here as I am unable to see all the fields while importing data from db class UserResource(ModelResource): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'id') import_id_fields = ('id',) class UserAdmin(ImportMixin, admin.ModelAdmin): resource_class = UserResource As show below ss I can see only username field shows up and my csv file is shown below username, email, first_name, Last_name, id abc, abc@gmail.com, abd, de -
The 'django_comments' is in INSTALLED_APPS settings but the 'comments' is not recognizable template tag
I want to use django-comments-xtd for threaded comments in my app. This is a framework which extends original django-contrib-comments. So like the tutorial says, I included both django_comments_xtd and django_comments to installed apps. But when I load the tag comments it says 'comments' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache comments_xtd crispy_forms_field crispy_forms_filters crispy_forms_tags crispy_forms_utils django_simple_bulma i18n l10n log md2 posts_extras rest_framework static tz I am so confused. The traceback itself shows I have included django_comments to INSTALLED_APPS setting INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'crispy_forms', 'six', 'social_django', 'django_simple_bulma', 'django_comments_xtd', 'django_comments', 'rest_framework', 'django_markdown2', 'posts.apps.PostsConfig', 'users.apps.UsersConfig', 'core.apps.CoreConfig', ] No idea why is this happening. How comments_xtd is registered tag library, not comments? -
How to check if there is more than one environment variable set for running Python scripts in PATH
I am learning Django and in Comand Prompt I have already installed Django, then when I check django-admin --version it says 'django-admin' is not recognized as an internal or external command, operable program or batch file. Because of this I tried to install Django 3 times again but it still output the same. What is the cause of this problem? To test is my Django is working or not I have also tried to import django in my python interpreter. I have 2 python versions in my computer the first one is 3.8 and the second one is 3.8.6 ,which the CMD tells me to download. When I tried to import django in python3.8 it output No module named 'django', when I tried to import django in python3.8.6 it worked !! I hope my python 3.8 work because my Pycharm is using that. What is the cause of the problem ?? I have been suffering from this problem for 1 week😥😥, if you know the problem, solution or suggestions please write it below. 😄😄😄 -
PermissionError: [Errno 13] Permission denied when doing migrations in docker
Here is my dockerfile: FROM python:3.8-alpine ENV PATH="/scripts:${PATH}" COPY ./requirements.txt /requirements.txt RUN apk update RUN \ apk add --no-cache postgresql-libs && \ apk add --no-cache --virtual .build-deps gcc libc-dev make git libffi-dev openssl-dev python3-dev libxml2-dev libxslt-dev gcc musl-dev && \ apk add postgresql && \ apk add postgresql-dev && \ apk add jpeg-dev zlib-dev libjpeg &&\ python3 -m pip install -r requirements.txt && \ apk del .build-deps RUN mkdir /backend COPY ./backend /backend WORKDIR /backend COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/ RUN adduser -D user RUN chown -R user:user ./ RUN chown -R user:user /vol RUN chmod -R 666 /vol/web USER user CMD ["entry_point.sh"] and my docker compose: version: "3.7" services: backend: build: context: . ports: - "8000:8000" volumes: - ./backend/backend:/backend command: sh -c "python manage.py runserver 0.0.0.0:8000" environment: - DEBUG=1 depends_on: - db links: - db:db networks: - djangonetwork db: image: postgres restart: always expose: - "5432" environment: POSTGRES_USER: xxxx POSTGRES_PASSWORD: demodemo POSTGRES_DB: xxxx networks: - djangonetwork networks: djangonetwork: driver: bridge When i run the docker-compose run backend python manage.py makemigrations --noinput command i get the following error: Migrations for 'auth': /usr/local/lib/python3.8/site-packages/django/contrib/auth/migrations/0012_userloginactivity.py - Create model UserLoginActivity Traceback (most recent call … -
Django Admin, ManyToMany field getting Unknown field(s) (linked_sites) specified for Model error
I have two Django Models connected through ManyToMany relation. class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) account = models.ForeignKey(Account, related_name=RelatedNames.USERS, on_delete=models.CASCADE, null=True, blank=True) accessed_sites = models.ManyToManyField(Site, related_name=RelatedNames.USERS) class Site(models.Model): name = models.CharField(max_length=255) location = models.OneToOneField(GeoLocation, on_delete=models.PROTECT, related_name=RelatedNames.ADDRESS, blank=True, null=True) score = models.IntegerField(default=0) avg_spent_time = models.DurationField(default=timedelta(days=0)) _type = models.IntegerField(choices=SiteTypeChoices.CHOICES, max_length=20) primary_email = models.EmailField(null=True, blank=True) def __str__(self): return self.name def get_site_address(self): return str(self.location) I'm trying to display and modify the relation through the admin: class SitesAdmin(ModelAdmin): fields = [Fields.NAME, Fields.PRIMARY_EMAIL, Fields.TYPE, Fields.SCORE, Fields.LOCATION] list_display = fields class UsersAdmin(ModelAdmin): fields = [Fields.EMAIL, 'full_name', Fields.ACCOUNTS, 'linked_sites'] list_display = [Fields.EMAIL, 'full_name', Fields.ACCOUNTS, 'linked_sites'] readonly_fields = ('full_name',) def full_name(self, obj): return obj.get_full_name() def linked_sites(self, obj): return "\n".join([site.name for site in obj.accessed_sites.all()]) the list display works but when opening a User object I'm getting the following error: Unknown field(s) (linked_sites) specified for CustomUser. Check fields/fieldsets/exclude attributes of class UsersAdmin. -
Filter product Django "LATEST", "BEST SALE", "TOP RATED","ON SALE"
I need your help. I have 4 categories "LATEST", "BEST SALE", "TOP RATED" and "ON SALE". In the "LATEST", I want to show the 20 most recently added products. In the "BEST SALE", need to show products that have the best-selling status. In the "TOP RATED", need to show 20 products with a high rating. In the "ON SALE", need to show 20 products that have the sale status. How do I make a filter for these categories? Thanks a lot. Some examples Django, please. class Product(models.Model): StatusProduct=( (_(''), _('')), (_('best sale'), _('BEST SALE')), (_('on sale'), _('ON SALE')), ) name = models.CharField(_('Name'), max_length=150, blank=True, null=True, default=None, help_text=_('The maximum number of characters - 150')) price = models.DecimalField(_('Price'), max_digits=10, decimal_places=1, default=0) discount = models.IntegerField(_('Discount'), default=0) status = models.CharField(_('Status'), max_length=20, choices=StatusProduct, default='') parentcategory = models.ForeignKey(ParentCategory, verbose_name=_('Category'), on_delete=models.CASCADE, blank=True, null=True, default=None) category = models.ForeignKey(MenuBarProduct, verbose_name=_('Category'), on_delete=models.CASCADE, blank=True, null=True, default=None) subcategory = models.ForeignKey(CategoryProduct, verbose_name=_('Category'), on_delete=models.CASCADE, blank=True, null=True, default=None) short_description = CKEditor5Field(_('Short description'), config_name='extends', blank=True, null=True, default=None) description = CKEditor5Field(_('Description'),config_name='extends', blank=True, null=True, default=None) is_active = models.BooleanField(_('Active'), default=True, help_text=_('Activated, allow to publish')) created = models.DateTimeField(_('Created'), auto_now_add=True, auto_now=False) updated = models.DateTimeField(_('Updated'), auto_now_add=False, auto_now=True) created_by = models.ForeignKey(User, verbose_name=_('Created by'), on_delete=models.CASCADE, editable=False, null=True, blank=True) def __str__(self): return "%s" % (self.name) … -
celery add_periodic_task with multiple crontab
I'm using celery with django 3. Originally, I wanted to run my get_index function every minute from 9 to 12:30 in [sat,sun,mon,tue,wed]. After some research, I find out that it's not possible to handle my case with a single crontab (because of 12:30); So I end up using two crontabs, which seem to work: crontab(minute='*', hour='9-12', day_of_week='sat,sun,mon,tue,wed') crontab(minute='00-30', hour='12', day_of_week='sat,sun,mon,tue,wed') But when I try to use them, like: @app.on_after_finalize.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(crontab(minute='*', hour='9-12', day_of_week='sat,sun,mon,tue,wed'), get_index.s(), name='fetch index from tse every minute from 9 to 12 on workdays') sender.add_periodic_task(crontab(minute='00-30', hour='12', day_of_week='sat,sun,mon,tue,wed'), get_index.s(), name='fetch index from tse every minute from 12 to 12:30 on workdays') Only the second one will apply. If I change the name of the second task to something like `get_index2` and duplicate my function, it will work fine. I think the same function name (get_index) is causing the issue. Is there any way to add bind multiple crontab to a single add_periodic_task? or somehow using same function for multiple add_periodic_task? -
Python Django no items shows on cart
My main project shop works as expected. But I just added a cart to my project. when I click add item to cart on my main page I see this: [04/Oct/2020 07:14:56] "POST /cart/EEE-1249363/ HTTP/1.1" 302 0 [04/Oct/2020 07:14:56] "GET /cart/ HTTP/1.1" 200 964 which may say that the item got added to cart. But when I go to my cart I can't display any item. Here is my entire cart. Can you please tell me what I am doing wrong? here is my cart/templates/cart/detail.html {% extends 'base.html' %} {% block content %} <h1>HI there </h1> {% for product in product %} <p>{{ product.quantity }} </p> <p>{{ product.name }} </p> {% endfor %} {% endblock %} cart/apps.py: from django.apps import AppConfig class CartConfig(AppConfig): name = 'cart' cart/cart.py: from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): """ Initialize the cart """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, override_quantity=False): """ Add a product to the cart or update its quantity. """ product_PN = str(product.PN) if product_PN not in self.cart: self.cart[product_PN] … -
correct endpoint for fetching user's profile django rest framework
I have pretty simple models: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=32, unique=True) name = models.CharField(max_length=64, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=128, blank=True) about = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) And I have a /user endpoint. This endpoint is handled by a DRF ModelViewSet. Pretty straightforward. Now I need to also fetch user's profile to render in my React app. I need to be able to get, put/patch and maybe delete profiles. What is the correct implementation for this? For now I have following endpoing /user/int:pk/account. And a view: class ProfileView(RetrieveUpdateDestroyAPIView): serializer_class = serializers.AccountSerializer lookup_url_kwarg = 'pk' queryset = Account.objects.all() http_method_names = ['get', 'put', 'delete'] permission_classes = [IsAccountOwner] def get(self, request, *args, **kwargs): instance = get_object_or_404(Account, user=self.kwargs.get('pk')) serializer = self.get_serializer(instance) return Response(serializer.data) def put(self, request, *args, **kwargs): instance = get_object_or_404(Account, user=self.kwargs.get('pk')) self.check_object_permissions(self.request, instance) serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) def delete(self, request, *args, **kwargs): instance = get_object_or_404(Account, user=self.kwargs.get('pk')) self.check_object_permissions(self.request, instance) self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT) So I am overriding the logic to fetch or update profiles by user's id, not the … -
Using Django to retrieve values of an attribute based on user-selected values of another attribute
I have 3 tables which are item, shop and stock item table consists of item_id item_name item_price 1 drug AJG 32.00 2 drug BOLS 10.00 3 drug CPP 5.00 4 drug C77 55.00 5 drug CLIMO 13.00 shop table consists of shop_id shop_name shop_country 3 ABC Clinic Australia 4 FYZ Hospital New Zealand 5 HH Pharmacy Spain 22 SAJ Clinic Portugal 33 PO Pharmacy Portugal stock table consists of shop_id item_id stock_qty 3 1 22 4 2 45 5 3 11 22 4 39 33 5 66 I've built web app using Django to allow the user to input the item_name (i.e., Drug A) and shop_name (ABC Clinic) using the following code. So far, i have a function that is able to show the item names and shop names based on regex. However, the results rendered also show combinations where the shop does not have that particular item. For example, the results.html page will show ABC clinic with Drug CLIMO stock if the user keys in Climo for item and ABC for shop - even though ABC clinic does not have that drug. As such, is there some way Django can display the shops that only have stock of the … -
How to Save or Print the array field in Django using CreateView?
HTML Array of Input Field Model.py Models.py Image Forms.py Forms.py Image Views.py Views.py Image Please help me here. I want to convert this array field values into string with comma separated and then save in table. I hope I will get resolution. Thanks in Advance. -
Django using FTP for large files
I'm using Django admin to upload large files into another server ( A download host ). The files are usually 100mb. I'm using FTP currently based on this. It works fine with files less than 1mb but as it itself says in the documentation, it doesn't work with larger files and I get a 503 when the upload finishes in the Django admin. I really searched a lot about another way to to this but it seems there is no other way in Django. can you help me? -
Taking value of selected radio buttons from one page in Django
I want to take value of selected radio buttons in a single page. To explain this here is my code in models.py file class Quiz(models.Model): Description = models.CharField(max_length=200) def __str__(self): return str(self.Description) class Question(models.Model): Question_Text = models.CharField(max_length=500) Option1 = models.CharField(max_length=100) Option2 = models.CharField(max_length=100) Option3 = models.CharField(max_length=100, blank=True) Option4 = models.CharField(max_length=100, blank=True) Answer = models.CharField(max_length=100) QuizID = models.ForeignKey(Quiz, on_delete=models.CASCADE) def __str__(self): return str(self.Question_Text) I want user to choose one option from "Option1, Option2, Option3, Option4" fields and I want to get value of the selected radio button. Here's my try: disp.html <form action="" method="post"> {% csrf_token %} {% for q in question %} {{ q.Question_Text }} <br> <input type="radio" id="question_{{ q.Option1 }}" name="{{ q.id }}" value="{{ q.Option1 }}"> <label for="question_{{ q.Option1 }}">{{ q.Option1 }}</label> <br> <input type="radio" id="question_{{ q.Option2 }}" name="{{ q.id }}" value="{{ q.Option2 }}"> <label for="question_{{ q.Option2 }}">{{ q.Option2 }}</label> <br> {% if q.Option3 %} <input type="radio" id="question_{{ q.Option3 }}" name="{{ q.id }}" value="{{ q.Option3 }}"> <label for="question_{{ q.Option3 }}">{{ q.Option3 }}</label> <br> {% endif %} {% if q.Option4 %} <input type="radio" id="question_{{ q.Option4 }}" name="{{ q.id }}" value="{{ q.Option4 }}"> <label for="question_{{ q.Option4 }}">{{ q.Option4 }}</label> <br> {% endif %} {% endfor %} <br> <input type="submit" class="btn btn-primary" … -
Stream videos uploaded to digitalocean
I would like to create a website where users could upload some videos and Could set a time to play/stream it at a specific time, so that other logged in users could watch the stream at that time. I am using Django to build the website and using angular to serve the frontend. I have a digitalocean space and would like to know the best options to upload and stream the videos at specific time from the account. I am new to programming so please let me know if there is any way to achieve this, or if I should be making use of any other technologies or methods. -
Django CSRF missing or incorrect Ajax POST without jquery (Vanilla JavaScript)
when i got this error when i was using jquery i simple do: data: {'csrfmiddlewaretoken': "{{csrf_token}}"} Now I'm trying to move to vanilla JavaScript, here is my ajax call <script> document.addEventListener('DOMContentLoaded', function () { document.querySelector('#sendMessage').onclick = function (e) { e.preventDefault(); let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function (e) { if (this.readyState == 4 && this.status == 200) { alert('success') let response = this.responseText console.log(response) } else { console.log(this.status) console.log(this.readyState) } }; xhr.open("POST", "{% url 'chat:room' room.id %}", true); // Send data csrf_token, content, area xhr.setRequestHeader('Content-type', 'application/json'); data = { 'csrfmiddlewaretoken': '{{ csrf_token }}', 'content': document.querySelector('#id_content').value, 'area': parseInt(document.querySelector('#id_area').value), } console.log(data) xhr.send(JSON.stringify(data)); } }); </script> However i get this error: Forbidden (CSRF token missing or incorrect.): /chat/room/3/ [04/Oct/2020 05:25:16] "POST /chat/room/3/ HTTP/1.1" 403 2513 I have been searching for a while but all answers are solving it for jquery not vanilla js, Any help? -
TemplateDoesNotExist at /accounts/login/ login.html
Imm trying to use default django login system. It gives me error that my login.html templates does not exist. I have my login templates saved in a root directory..> templates>registration>login.html Imm using custom user models and token authentication.. Here's what i tried ..> account urls.py from django.contrib.auth import views as auth_views from django.conf.urls import url from django.urls import path urlpatterns = [ path("login/", auth_views.LoginView.as_view(template_name = "login.html"), name='login'), path("logout/", auth_views.LogoutView.as_view(), name='logout'), ] Main App Urls.py from django.contrib import admin from django.urls import path, include from rest_framework.urlpatterns import format_suffix_patterns from django.conf.urls.static import static from django.conf import settings from django.conf.urls import url from articles.views import ArticleDetail, ArticleList from account.views import AccountList from rest_framework.authtoken import views urlpatterns = [ path('admin/', admin.site.urls), path('article/', ArticleList.as_view()), path('article/<int:pk>/', ArticleDetail.as_view()), path('accounts/', AccountList.as_view()), path('accounts/', include('account.urls')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = format_suffix_patterns(urlpatterns) Templates dir in settings.py# TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Does using a custom user models and Token auth effects default login system ? -
'list' object has no attribute '_meta'
why my code is showing this error as my whole code is correct? 'list' object has no attribute '_meta' my views.py from django.shortcuts import render, redirect, get_list_or_404 from .models import Task from .forms import TaskForm def update_task(request, pk): up_task = get_list_or_404(Task, id=pk) if request.method == 'POST': up_form = TaskForm(request.POST, instance=up_task) if up_form.is_valid(): up_form.save() return redirect('tasks') else: up_form = TaskForm(instance=up_task) context = { 'update_task_form': up_form } return render(request, 'task/update_task.html', context) my urls.py from django.urls import path from . import views urlpatterns = [ path('', views.tasks, name='tasks'), path('task/<str:pk>/update/', views.update_task, name='update_task'), ] my error Internal Server Error: /task/3/update/ Traceback (most recent call last): File "C:\Users\Royal\AppData\Roaming\Python\Python38\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Royal\AppData\Roaming\Python\Python38\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Royal\PycharmProject\todoapp\todoapp\task\views.py", line 31, in update_task up_form = TaskForm(instance=up_task) File "C:\Users\Royal\AppData\Roaming\Python\Python38\site-packages\django\forms\models.py", line 294, in init object_data = model_to_dict(instance, opts.fields, opts.exclude) File "C:\Users\Royal\AppData\Roaming\Python\Python38\site-packages\django\forms\models.py", line 85, in model_to_dict opts = instance._meta AttributeError: 'list' object has no attribute '_meta' [04/Oct/2020 09:06:27] "GET /task/3/update/ HTTP/1.1" 500 71974 Internal Server Error: /task/3/update/ Traceback (most recent call last): File "C:\Users\Royal\AppData\Roaming\Python\Python38\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Royal\AppData\Roaming\Python\Python38\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Royal\PycharmProject\todoapp\todoapp\task\views.py", line 31, in update_task up_form = … -
How to get user instance in Model Serializer in django Rest Framework
I have 2 models CustomUser and Student. In CustomUserSerializer, whenever the user is created i also want to create Student instance inside CustomUserSerializer. How can I get the current user instance? # models.py class CustomUser(AbstractUser): is_student = models.BooleanField('student status', default=False) is_teacher = models.BooleanField('teacher status', default=False) email = models.EmailField(_('Email Address'), unique=True, blank=True) class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) # serializers.py class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = models.CustomUser fields = [ 'id', 'email', 'is_teacher', 'is_student',..] def create(self, validated_data): if validated_data.get('is_student') == True: Student.objects.create(user=...?) # what should I put here? return super(CustomUserSerializer, self).create(validated_data) [UPDATED] I have another question it's related to Student model. If I have models like below should I create serializer for Student? when I want to have serializer for Class. class Class(models.Model): student = models.ManyToManyField(Student) Thanks -
What a solution of with python 3.8.6 version in fatal python error: "initfencoding"
Fatal Python error: initfsencoding: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' -
How do I instantiate Django models using data from an API?
So at the moment, I've written the code to make calls to an API and write it to a file on my machine so I can go through it and figure out which values are located where, etc. I have also written the code to open the file and loop through the values. All I need to do now (as far as I'm aware) is write the piece of code that instantiates models using values provided by the data pulled from the API. The problem is, I have no idea where to put this code and how to call it. The code I've written is all in a separate python file located in the same directory as my Django app.I thought I could run the code from that file if I imported Django's models and the model I'm trying to create, so I added from django.db import models from models import MyModel to the beginning but was given the following error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I appreciate that the traceback is telling me exactly what to do, but I have no … -
TypeError at '' __init__() got an unexpected keyword argument ''
I am working through a project creating a simple Django auction site and I am having difficulty overriding the init method in a Django modelform when creating a new Bid from the 'Detail' view and passing a related object(auction) & user. I am trying to override the BidForm(forms.modelform) init method so i can pass the related 'Auction' object using kwargs.pop. I get the error 'TypeError: init() got an unexpected keyword argument 'auction'' Please suggest what i am doing wrong and point me in the right direction- Thank you in advance Model class Bid(TimeStampMixin): """ Model representing a bid in an auction """ auction = models.ForeignKey( Listing, on_delete=models.SET_NULL, related_name='offer', null=True) bidder = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='bid_user') amount = models.PositiveIntegerField() objects = BidQuerySet.as_manager() def get_absolute_url(self): return reverse('detail', args=[self.pk]) def __str__(self): return f"{self.amount} in Listing No: {self.auction.id}" class Meta: ordering = ['amount'] @staticmethod def high_bid(auction, bidder, bid_amount): """util method to ascertain highest bid in auction then update in related auction obj **auction---listing being bid on, bid__auction **bidder---user bidding **amount--- current highest bid """ ###error checks, is current bid less than start bid? etc if bid_amount < auction.start_bid: return if (auction.highest_offer and bid_amount < auction.highest_offer.amount): return if bidder.id is auction.user.id: raise PermissionDenied ##after … -
Reverse for 'wagtailadmin_explore' with arguments '('',)' not found
I have been trying to rebuild my Wagtail website as a docker container to be run on Fargate. For reasons, I started from scratch and rebuilt all my dependencies. After pip installing everything, the site works fine locally using venv. However, I get strange errors when launching the in the Docker container. Can anyone help me identify a fix for this? I get the following error at /admin: Error during template rendering In template /usr/local/lib/python3.8/site-packages/wagtail/admin/templates/wagtailadmin/home/site_summary_pages.html, error at line 4 Reverse for 'wagtailadmin_explore' with arguments '('',)' not found. 1 pattern(s) tried: ['admin/pages/(?P<parent_page_id>[0-9]+)/$'] 1 {% load i18n wagtailadmin_tags %} 2 3 <li class="icon icon-doc-empty-inverse"> 4 <a href="{% url 'wagtailadmin_explore' root_page.pk %}"> 5 {% blocktrans count counter=total_pages with total_pages|intcomma as total %} 6 <span>{{ total }}</span> Page <span class="visuallyhidden">created in {{ site_name }}</span> 7 {% plural %} 8 <span>{{ total }}</span> Pages <span class="visuallyhidden">created in {{ site_name }}</span> 9 {% endblocktrans %} 10 </a> 11 </li> 12 My base image for Docker is Python 3.8 Alpine. I've diffed a pip freeze for both local and Docker and the versions of the packages are the same. All migrations run on both docker and local. Here is my pip freeze from the Docker implementation: asgiref==3.2.10 … -
How to fit data from a jsonresponse to a live graph in Django?
I'm trying to implement a live graph using ajax and Django. I am using a function bellow that generating continuous data and a view returning this data as a json response. #Data Generation def DataGene(): while True: time.sleep(3) data = {'dp':randrange(10), 'dt':datetime.now().strftime('%Y-%m-%d %H:%M:%S')} #print (randrange(10), datetime.now().strftime('%Y-%m-%d %H:%M:%S')) return data if __name__ == "__main__": DataGene() How to fit this data into the live graph Live plot (https://canvasjs.com/html5-javascript-dynamic-chart/): <html> <head> <script> window.onload = function () { var dps = []; // dataPoints var chart = new CanvasJS.Chart("chartContainer", { title :{ text: "Dynamic Data" }, data: [{ type: "line", dataPoints: dps }] }); var xVal = 0; var yVal = 100; var updateInterval = 1000; var dataLength = 20; // number of dataPoints visible at any point var updateChart = function (count) { count = count || 1; for (var j = 0; j < count; j++) { yVal = yVal + Math.round(5 + Math.random() *(-5-5)); dps.push({ x: xVal, y: yVal }); xVal++; } if (dps.length > dataLength) { dps.shift(); } chart.render(); }; updateChart(dataLength); setInterval(function(){updateChart()}, updateInterval); } </script> </head> <body> <div id="chartContainer" style="height: 370px; width:100%;"></div> <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script> </body> </html> Django View: def fetch_values_ajax(request): data = ReturnData() return JsonResponse(data)