Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
self.assertEqual(response.status_code, 200) AssertionError: 302 != 200 in django
Here i am creating a Login api and if login is success then redirect to csv_import view I am not write in my unit test as i am new to django here is my urls.py urlpatterns = [ path('', LoginAPIView.as_view(), name='login_api'), path('register/',views.register, name="register"), path('books/details/',login_required(views.csv_import),name="csv_import"), path('logout/',views.logout,name="logout"), ] Here is my views.py class LoginAPIView(View): def get(self, request): return render(request, 'login.html') def post(self, request): email = request.POST.get('email') password = request.POST.get('password') user = authenticate(request, email=email, password=password) print("USERRR",user) if user is not None: print("USERR") login(request, user) print("CREATED") return redirect('csv_import') else: messages.info(request,'Invalid credentials..') return redirect('login_api') def csv_import(request): print("CSV IMPORT") csv_file = os.path.join('static','books.csv') with open(csv_file,'r') as f: reader = csv.DictReader(f) for row in reader: title = row['title'] author = row['author'] authors = row['authors'] isbn13 = int(row['isbn13']) isbn10 = row['isbn10'] try: price = float(row['price'].replace('$','')) except: price = None publisher = row['publisher'] pubyear = row['pubyear'] subjects = row['subjects'] try: pages = int(row['pages']) except ValueError: pages = None dimensions = row['dimensions'], x, books = BooksDetails.objects.get_or_create(title=title,author=author,authors=authors,isbn13=isbn13, isbn10=isbn10,price=price,pages=pages, publisher=publisher,pubyear=pubyear,subjects=subjects, dimensions=dimensions) books_list = BooksDetails.objects.get_queryset().order_by('-id') flag = request.POST.get('flag_value') if flag == '1': try: rows = int(request.POST.get('row','')) print("ROWS",rows) if rows is not None: books_list = books_list[:rows] else: books_list = books_list except ValueError: books_list = books_list else: books_list = books_list print("HERE") paginator = Paginator(books_list, 30) print("NEAR") … -
MultipleObjectsReturned at /rants/first-rant/ get() returned more than one Rant -- it returned 2
I'm getting the error because I have two first-rant slug's on the database. I expected this to come. I have a solution in mind to add random numbers at the end of the url. Can anyone help me implement this using the RandomCharField of https://django-extensions.readthedocs.io/en/latest/field_extensions.html. Here are my models: class Category(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Category, self).save(*args, **kwargs) return self.slug def get_context_data(self, **kwargs): context = super(self).get_context_data(**kwargs) context['rants'] = Rant.objects.filter('category') return class Rant(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(max_length=150) categories = models.ManyToManyField( Category, related_name='rants_categories') user = models.ForeignKey(User, default='', null=True, related_name='users_rant', on_delete=models.PROTECT) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateField(auto_now=True) class Meta: verbose_name = "rant" verbose_name_plural = 'rants' def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Rant, self).save(*args, **kwargs) return self.slug def get_absolute_url(self): from django.urls import reverse return reverse('main:detail', kwargs={'slug': self.slug}) Here are my views: class RantListView(ListView): model = Rant template_name = 'rants/list.html' context_object_name = 'rants' class RantDetailView(DetailView): model = Rant template_name = 'rants/detail.html' def rant_category(request, slug): rants = Rant.objects.filter( categories__slug__contains=slug ) context = { "slug": slug, "rants": rants } return render(request, "rants/category_list.html", context) And finally my urls path('', RantListView.as_view(), name='list'), path('<slug:slug>/', RantDetailView.as_view(), name='detail'), path('category/<slug:slug>/', rant_category, name='categories'), My … -
'NoneType' object has no attribute 'id'
Added a form to the DetailView, I'm trying to create an entry through the form, I get an error My views I don’t even know why this problem got out, it seems that I did everything according to the dock class CardDetailView(SuccessMessageMixin, ModelFormMixin, DetailView): model = Card template_name = 'cards/detail.html' success_message = 'Ваше сообщение об ошибке получено. Мы обязательно займемся этим.' form_class = WrongCardsForm def get_success_url(self): return reverse_lazy('detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(CardDetailView, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): form = form.save(commit=False) form.author = self.request.user form.card = self.get_object() form.save() super(CardDetailView, self).form_valid(form) else: return super(CardDetailView, self).form_valid(form) My forms class WrongCardsForm(ModelForm): class Meta: model = WrongCards fields = ['mistake_in', 'error_text',] # fields = '__all__' My urls urlpatterns = [ path('', views.CardsListView.as_view(), name='index'), path('<int:pk>/', views.CardDetailView.as_view(), name='detail'), ] My models class WrongCards(models.Model): """Карточки с ошибками""" CHOICE = ((None, 'Выберите в чем ошибка'), ('a', 'терминe'), ('b', 'определение'), ('c', 'произношение')) mistake_in = models.CharField('Ошибка в', choices=CHOICE, max_length=3) card = models.ForeignKey('Card', on_delete=models.CASCADE, verbose_name='Ошибка', related_name='wrong_cards') error_text = models.TextField('Подробнее об ошибки') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Автор') def __str__(self): return self.mistake_in class Card(models.Model): """Карточки слов""" term = models.CharField('Термин', max_length=100) transcription = models.CharField('Транскрипция', max_length=100) definition = … -
Djanog Filter by field values of the reverse reference model of 1:N relationship
The Branch and Subsidy models have a 1:N relationship, In the Subsidy model, the 'related_name' of the branch field is set to 'subsidy'. I'm trying to filter the Branch query set with the 'price' field value of Subsidy, but I get the following error. Branch.objects.filter(subsidy__price__gt=0) Cannot resolve keyword 'subsidy' into field. Choices are: brand_idx, idx, is_active, name, order, province_idx, sido, sido_id As shown below, individual instances seem to have good access to the related_name called 'subsidy', but I don't know why I couldn't find the field "subsidy" when filtering the query set. Branch.objects.get(idx=1).subsidy.all() my models.py class Branch(models.Model): idx = models.AutoField(primary_key=True) name = models.CharField(max_length=128, null=True, blank=True) province_idx = models.IntegerField(default=0, null=True, blank=True) sido = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name='sigungu') brand_idx = models.IntegerField(default=0, null=True, blank=True) order = models.IntegerField(default=0, null=True, blank=True) is_active = models.IntegerField(default=1, null=True, blank=True) def save(self, *args, **kwargs): if self.province_idx: self.sido_id = self.province_idx else: self.sido_id = 0 super().save(*args, **kwargs) class Meta: managed = False db_table = 'branch' class Subsidy(models.Model): idx = models.AutoField(primary_key=True) car = models.ForeignKey(Car, on_delete=models.CASCADE, blank=True, null=True, db_column='car_idx', related_name='car_subs') lineup = models.ForeignKey(Lineup, on_delete=models.CASCADE, blank=True, null=True, db_column='lineup_idx', related_name='lineup_subs') trim = models.ForeignKey(Trim, on_delete=models.CASCADE, blank=True, null=True, db_column='trim_idx', related_name='trim_subs') branch = models.ForeignKey(Branch, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name='subsidy') price = models.IntegerField(default=0, blank=True, null=True) is_state = models.IntegerField(default=0, … -
How to architecture a Python Backend with constant Background Taks
i would like to design a Python Backend where i have one Task that is running the whole time logging data from several Serial ports. Also there should be other background tasks running when there are certain request and they would accedd the data from the constant background task (maybe over an db). So there are some questions: I have a little experience in Flask so i would like to use it, but i stumbled across FastAPI which has backgroundjobs already implemented. So which Framework would you recommend? For the background tasks or threads what is the best Solution? Celery? Or should i outsource the constant background task to its own standalone python app? Thanks for your help! -
Django - How to import a model from another app into another app's views
I am working in an app called 'lineup', and I have another app called 'market' that has a model called 'Inventory' which I need to import into the lineup app's views.py How can I do that? -
TypeError: unsupported type for timedelta hours component: NoneType
I am getting this error in production (heroku/postgres) but not in local(sqlite). class ModelC(models.Model): model_c_field_1 = models.ForeignKey(Venue, null = True, blank= True, on_delete=models.CASCADE) class ModelB(models.Model): model_c_field_2 = models.ForeignKey(ModelA, blank=True, null=True, on_delete=models.CASCADE) model_c_field_1= models.ForeignKey(Venue, blank=True, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) def function(request, userprofile_id): latest_model_object = ModelB.objects.filter(user=userprofile_id).order_by('-id')[:1] time_delta = () for ModelB in latest_model_object: time_delta = timezone.now() - modelb.created_at time_delta_rule = ModelC.objects.filter(venue=request.user.userprofile.venue) timedelta_test=timedelta() for ModelC in time_delta_rule: timedelta_test = timedelta(hours = ModelC.timeframe) print(timedelta_test) examples of print result: 0:00:00 or 1 day, 0:00:00 Giving the below error. 2023-04-14T04:26:40.379344+00:00 app[web.1]: timedelta_test = timedelta(hours = modelc.timeframe) 2023-04-14T04:26:40.379344+00:00 app[web.1]: TypeError: unsupported type for timedelta hours component: NoneType -
How to use a dictionary with annotate in django?
I have a model: class Hero(models.Model): # ... name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) benevolence_factor = models.PositiveSmallIntegerField( help_text="How benevolent this hero is?", default=50 ) and a dictionary: sample_dict = { 1: 'A', 2: 'B', 3: 'C' } I tried to use annotate like below: hero = Hero.objects.annotate(sample_id=Value(sample_dict[F('id)], output_field=CharField())) but there is an key error <django.db.models.expressions.Subquery object at 0xffff8d014438> I want to use value of field 'id' of Hero model as a key of sample_dict. but Subquery does not return a value. -
Email verification error in Django registration
I am creating an application using Django. The user registration page includes email verification, but I am encountering an error here. When a user registers for the application by providing their email address and password, an email verification is triggered, and a verification code URL is sent to the user's email from the Django application. However, when the user clicks on this URL, an ERR_CONNECTION_TIMED_OUT error occurs. I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Displaying nested dictionary data without known key names in html table using Django
Using Django 3.0.6 I am trying to display this dictionary in a html table. data = { 'Exception': { 'business': { 'Renewed': 73, 'Manual': 15, 'Automatic': 3}, 'Aviation Sector': { 'Automatic': 6, 'Renewed': 6, 'Manual': 2} } } The names of these values (for easier understanding) are: Task is 'Exception' Products are 'Business', 'Aviation Sector' Classifications are 'Renewed', 'Manual', 'Automatic' And the numbers are how many times that classification occurred for that Product. I need the table to look like the attached image WITHOUT hardcoding any of the values as the values will change every time the function pulls new data. I can modify the dict if needs be before sending to the html page. The code that creates the initial dict is set up so if a different type of 'Task' were pulled in the query it would be the main key for another set of key values so the table html code would create a second table under the first with the same format just different task name. I cannot upgrade my version of django and I cannot use template filters that are not standard with Django. Here is what the table should look like Ive tried too … -
Page not found 404 Django The current path , didn’t match
I tried to run Django for the first time and got this Request Method: GET Request URL: http://127.0.0.1:8000/hello/new Using the URLconf defined in test.urls, Django tried these URL patterns, in this order: hello/ [name='index'] hello/ [name='new'] admin/ The current path, hello/new, didn’t match any of these. hello/views.py from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse("hello, 1") def new(request): return HttpResponse("hello, 2") hello/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('', views.new, name='new') ] urls.py in my project directory urlpatterns = [ path('hello/', include('hello.urls')), path('admin/', admin.site.urls) ] -
How to login with multiple email addresses when using django-allauth
I have a django project with the django-allauth app. I want to authenticate by username or emailA or emailB. I set ACCOUNT_AUTHENTICATION_METHOD to username_email and I confirmed that I can authenticate by username or email address. Reading the documentation, it looks like I can use ACCOUNT_MAX_EMAIL_ADDRESSES, but I don't know how to use it. the documentation django-allauth: ACCOUNT_MAX_EMAIL_ADDRESSES(=None) The maximum amount of email addresses a user can associate to his account. It is safe to change this setting for an already running project – it will not negatively affect users that already exceed the allowed amount. Note that if you set the maximum to 1, users will not be able to change their email address as they are unable to add the new address, followed by removing the old address. I am new to django and am struggling with this. Can someone provide an example? -
django - Load template and add a load spinner while Django data is loading
When I open my Django project, I want first to load body.html and then dashboard.html. dashboard.html is a heavy file as its working with python dataframes in the script tag. So first I want to display body.html and once body.html is render, add a load spinner while dashboard.html and its python Django data are loading This actual code is not showing the Highcharts data as the body Class (DashboardGraphs) does not contain the Django data so there's no data for show in body.html So, the question is how can I load first body.html AND then dashboard.html which Is inside body.html (dashboard-container). With the code I showed, that Is happening but the charts are not showing data. Thanks. # urls.py ########################################## path('dashboard_graphs', DashboardViewFinal.as_view() , name='dashboard_graphs'), path('dashboard', DashboardGraphs.as_view() , name='dashboard'), # views.py ########################################## class DashboardViewFinal(LoginRequiredMixin, TemplateView): def __init__(self): self.dashboard_view_23 = DashboardView(2023,'2023') self.year_int_2023 = 2023 self.year_str_2023 = str(2023) self.dashboard_view_22 = DashboardView(2022, '2022') self.year_int_2022 = 2022 self.year_str_2022 = str(2022) template_name = 'dashboard.html' @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) # ----------------------------------------------- # Conexion con HTML # ----------------------------------------------- def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['panel'] = 'Panel de administrador' context['month_total_2022'] = self.dashboard_view_22.get_graph_month_total() context['alumnos_mens_total_valor_2022'] = self.dashboard_view_22.get_graph_alumnos_mensual() context['month_total_2022'] = self.dashboard_view_22.get_graph_month_total() context['ingresos_total_2022'] = self.dashboard_view_22.get_ingresos_total()[0] context['egresos_total_2022'] … -
Django dictionary key value access
I got the below response via api to a text field, how can I access the pin and reference no.. I tried separating it but it's not looking safe I want to be able to access the pin with key "pin" Thanks in anticipation { "success":"true", "message":"E-pin was Successful", "pin":"1211ggg3322", "amount":775, "transaction_date":"29-03-2023 12:18:33 pm", "reference_no":"I11767", "status":"Successful" } -
Django: how to generate random number inside a slug field
I have a model called Product, when the user create an objects inside a Product model, I want to generate some random number inside a Product model field Slug like this: https://stackoverflow.com/questions/76010275/cryptography-python-installation-error-with-rush-airgapped-installation Take a look at this Stack Overflow question, you may see the domain name at first, and some path name called questions, and some random number at the end of the questions, I think it should look like this in django path: path('question/random_number/<slug:slug>/', views.some_views_name, name='Redirect-name') All the examples i found in the internet does not do something like this, so how can i do this in django? model: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) image = models.ImageField(upload_to='product-image') price = models.FloatField(max_length=11) category = models.ForeignKey(Category, on_delete=models.CASCADE) slug = models.SlugField(max_length=100, unique=True) def get_user_public_url(self): return reverse('Public-Profile', kwargs={'slug': self.user.profile.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return str(self.user) -
Nested Relationships in DRF Serializers
AttributeError at /api/register/ Got AttributeError when attempting to get a value for field user_profile on serializer UserRegistrationSerializer. The serializer field might be named incorrectly and not match any attribute or key on the UserProfile instance. Original exception text was: 'UserProfile' object has no attribute 'user_profile'. UserProfile model looks like this from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, models.CASCADE) date_of_birth = models.DateField() phone_number = models.CharField(max_length=20, blank=False) is_phone_verified = models.BooleanField(default=False) is_email_verified = models.BooleanField(default=False) phone_code = models.CharField(max_length=20, blank=False) email_code = models.CharField(max_length=20, blank=False) serializers.py file looks like this from django.contrib.auth.models import User from .models import UserProfile from django.core.exceptions import ValidationError from datetime import datetime from rest_framework.validators import UniqueValidator from rest_framework import serializers from django.core import validators class UserModelSerializer(serializers.ModelSerializer): first_name = serializers.CharField( required=True, max_length=50, error_messages={ 'required': 'Please enter your name.', 'max_length': 'Please enter a valid name.' } ) last_name = serializers.CharField( required=True, max_length=50, error_messages={ 'required': 'Please enter your name.', 'max_length': 'Please enter a valid name.' } ) username = serializers.CharField( required=True, max_length=30, validators=[UniqueValidator(queryset=User.objects.all())], error_messages={ 'required': 'Please enter a username.', 'max_length': 'Username should be no more than 30 characters.', 'unique': 'This username is already taken. Please choose a different one.', } ) email = serializers.EmailField( … -
Using dynamic select2 field within formsets in Django
I use django-formset-js-improved which works nicely to add, delete and reoreder my formsets. However, I would like to have a dynamic select2 formfield. I looked into different packages (i.e. django-autocomplete, django-select2), but they seem to work with forms. I was thinking of getting the form fields id, by listening on the trigger 'formAdded' and working from there. However, this seems not to be fired (see: django-formset-js-improved not firing 'formAdded' event). Any idea on how to solve this? -
Can't find sqlite version 3.9 or greater for djano install
I tried installing Django on my AWS linux AMI machine. Right off the bat, I got errors that the current version of Django required sqlite version 3.9 or greater. So I went about trying to install a version of sqlite that matched the requirements, but had no luck. So, to get around the issue, I downgraded the Django version to 2.15 which was compatible with the version of sqlite and everything worked just peachy. Then I wanted to add bootstrap to the project, so I installed with the following command: pip install django-bootstrap3 That package required a later version of Django, so it uninstalled 2.15 and installed Django 3.2.18. When I try to run the server, I get the that incompatiblity message with the Django version and sqlite. (By the way, the exact version of bootstrap was 3-23.1) I am able to install sqlite via pip: pip install db-sqlite3 But that gives me something earlier than 3.9 which is needed. So, I could either find an earlier version of bootstrap that works with Django 2.15, or find a later version of sqlite. Obviously the best fix would be to get a more current version of sqlite. Any suggestions? Thanks -
django-formset-js-improved not firing 'formAdded' event
I use django-formset-js-improved to dynamically add, delete and reorder formsets. All works fine, except for the event 'formAdded' appears not to be triggered. I copied the script from the GitHub repo (https://github.com/pretix/django-formset-js/blob/master/example/example/templates/formset.html): <script> jQuery(function($) { $('#formset').formset({ 'animateForms': true, 'reorderMode': 'animate' }).on('formAdded', function() { console.log("Form added", this, arguments); }).on('formDeleted', function() { console.log("Form deleted", this, arguments); }); }); </script> However, nothing is logged to the console on 'add' or 'delete'. Am I missing something? -
Python Django templates not found
I'm having trouble with connecting django templates. django.template.loaders.filesystem.Loader: E:\CS\Udemy\Python and Django Full Stack\Django\charity\templates\posts\post_base.html (Source does not exist) Actually it has to be charity\posts\templates\post_base.html In my settings.py # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = os.path.join(BASE_DIR, "templates") STATIC_DIR = os.path.join(BASE_DIR, "static") MEDIA_DIR = os.path.join(BASE_DIR, 'media') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'posts', 'comments', 'rest_framework', 'bootstrap4', 'django.contrib.humanize', ] 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', 'django.contrib.sessions.middleware.SessionMiddleware', # 'django_session_timeout.middleware.SessionTimeoutMiddleware', # 'charity.middleware.SessionExpiredMiddleware', ] ROOT_URLCONF = 'charity.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], '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', ], }, }, ] What I expected is django loads templates in a separate app. -
Image in HTML isn't displayed using Flask
So I tried to display all images in my directory with flask on a website but all I get is the raw HTML code () This is a cut down version of my code import flask import os import sqlite3 app = flask.Flask(__name__) @app.route("/") def pic(): base_path = "uploads/" image_extensions = ['.jpg', '.jpeg', '.png', '.gif'] images = [] for file_name in os.listdir(os.path.join(base_path)): if file_name.lower().endswith(tuple(image_extensions)): file_path = os.path.join(base_path, file_name) images.append(f'<img src="{file_path}" width="150" height="150">') #<a href="{file_path}" target="_blank"> return flask.render_template('x.html', images=images) app.run(port=8000, debug=True) and this the html part <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> </head> <body> <table> <tr> {% for image in images %} <td>{{ image }}</td> {% endfor %} </tr> </table> </body> </html>``` -
How to reference a Many to Many field in django that takes various Users
Im building a Django model for creating Polls with various users where they can invite each other. Models.py class Participant(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) class DateTimeRange(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField() class AvailabilityPoll(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True) duration = models.TimeField() datetime_ranges = models.ManyToManyField(DateTimeRange, related_name='datetime_ranges') deadline = models.DateTimeField() participants = models.ManyToManyField(Participant, related_name='participants') def is_expired(self): return self.deadline <= timezone.now() def get_participant_count(self): return self.participants.count() I made a view and a serializer for a POST api using Django Rest Framework to create this view: Views.py class AvailabilityPollView(APIView): permission_classes = (IsAuthenticated, ) serializer_class = AvailabilityPollSerializer @swagger_auto_schema(request_body=serializer_class, responses={201: serializer_class}) def post(self, request): poll = request.data serializer = self.serializer_class(data=poll) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializers.py from rest_framework import serializers from django.contrib.auth import get_user_model from polls.models import AvailabilityPoll, DateTimeRange User = get_user_model() class ParticipantsSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['email'] class DateTimeRangeSerializer(serializers.ModelSerializer): class Meta: model = DateTimeRange fields = '__all__' def create(self, validated_data): range = DateTimeRange.objects.create(start_time=validated_data['start_time'], end_time=validated_data['end_time']) range.save() return range class AvailabilityPollSerializer(serializers.ModelSerializer): datetime_ranges = DateTimeRangeSerializer(many=True) participants = ParticipantsSerializer(many=True) class Meta: model = AvailabilityPoll fields = '__all__' def create(self, validated_data): datetime_ranges_data = validated_data.pop('datetime_ranges') participants_data = validated_data.pop('participants') poll = AvailabilityPoll.objects.create(**validated_data) for range in datetime_ranges_data: poll.datetime_ranges.add(DateTimeRangeSerializer.create(self, validated_data=range)) for participant in participants_data: user = … -
What does the DJANGO_TEST_RANDOM_STATE environment variable do?
I'm not able to find anything on the DJANGO_TEST_RANDOM_STATE environment variable in Django's official docs. What is this environment variable used for? -
Basic conceptual question about ending a chatbot function/process with python / django
I'm creating a chatbot in django (using django for frontend and backend). My frontend calls this django function (in views.py, views.start_convo) to start the chatbot. This works fine. However, I also want to be able to send a request to STOP the chatbot. I'm not sure the best way to implement this functionality. Also, Latency is also very important to me, so I don't want the loop to waste much time checking something. Thoughts on the best way to approach / re-architect for this? Some ideas I've thought through / have: Use a global variable for start/stop, so instead of 'while True:', change to 'while_my_global_variable is True:'. Send a request from my frontend javascript that edits the global variable. This seems back because it is not thread safe for multiple users. Have the start_convo and stop_convo requests update a database with a boolean on whether to continue or not, and change 'while True:' to check that database row for whether the conversation should stop. Something with async / await, but I couldn't figure out how to set that up to do what I wanted. Ideally, send some time of signal to kill the function immediately (as opposed to the function … -
Django + Vite + Vue with Router does not work
I am trying to run the basic Vite default app with router to run a vue 3 front end along with Django. However I am receiving the following error which generally doesn't come when running only a Vite with vue router app. Uncaught SyntaxError: Unexpected token 'export' (at index-2331cb67.js:5:33627) Uncaught SyntaxError: Cannot use import statement outside a module (at AboutView-d0a85a00.js:1:1) I have updated the code here. Please guide.