Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. General design philosophy question: best way to implement "toggleable" separate features in a website
Let's say I want to create a blueprint of an online store that I can sell to potential clients. However, the idea is to make it so that the client chooses features that they want their store to have (from a pre-designated list) and pay only for those features, that way avoiding paying for something they don't need. So for example, one client wants to have and online store with a Cart, Purchase History, Graphs, Reports. Another one only wants simple registration and cart (but maybe in future they will want me to "enable" other features as well). My question is: what, in your opinion, is the best way to tackle this problem from a Django developer perspective? My thoughts: Create every feature as a separate app and deploy the whole thing commenting out the features that client did not pay for. And when a client wants additional features, I simply go to settings.py and uncomment the app they requested. Can I even make changes on the settings.py file on a live website without restarting it? Create an admin panel for myself (the superuser) that will have an ability to turn features on or off. So when the client pays … -
How to handle create/update on multiple nested serializers?
I've been able to make creating/updating happen on nested serializers, but I can't seem to get it to work when there are multiple many to many nest serializers. Models: class Brand(models.Model): name = models.CharField(max_length=500) class Incentive(models.Model): name = models.CharField(max_length=500) brands = models.ManyToManyField(Brand, related_name='incentives_brand') start_dt = models.DateTimeField(auto_now_add=False, blank=True, null=True) end_dt = models.DateTimeField(auto_now_add=False, blank=True, null=True) class Version(models.Model): name = models.CharField(max_length=1000) incentives = models.ManyToManyField(Incentive, related_name='versions_incentive', blank=True) brands = models.ManyToManyField(Brand, related_name='versions_brand') Serializers: class BrandSerializer(serializers.ModelSerializer): class Meta: model = Brand depth = 1 fields = ['id', 'name'] class IncentiveSerializer(serializers.ModelSerializer): brands = BrandSerializer(many=True) class Meta: model = Incentive # depth = 1 fields = ['id', 'name', 'brands', 'start_dt', 'end_dt'] class VersionSerializer(serializers.ModelSerializer): incentives = IncentiveSerializer(many=True) brands = BrandSerializer(many=True) class Meta: model = Version fields = ['id', 'name', 'incentives', 'brands'] def create(self, validated_data): brands = validated_data.pop('brands', []) incentives = validated_data.pop('incentives', []) instance = Version.objects.create(**validated_data) for brand_data in brands: brand = Brand.objects.get(**brand_data) instance.brands.add(brand) for incentive_data in incentives: incentive = Incentive.objects.get(**incentive_data) instance.incentives.add(incentive) return instance def update(self, instance, validated_data): brands = validated_data.pop('brands', []) incentives = validated_data.pop('incentives', []) instance = super().update(instance, validated_data) brand_objs = [] incentive_objs = [] for brand_data in brands: brand = Brand.objects.get(**brand_data) brand_objs.append(brand) instance.brands.set(brand_objs) for incentive_data in incentives: incentive = Incentive.objects.get(**incentive_data) incentive_objs.append(incentive) instance.incentives.set(incentive_objs) return instance I tried using the … -
How to filter queryset based on boolean value, then count in template
I want to count how many jobs are open vs closed. I don't understand why this isn't working, I have added {{ap.id}} and {{open.line_num_id }} after the forloop just to see what was rendered. I would think that if they match, then it's added to the count. This is not the case, all jobs are counted regardless of the "if" statement. Totally lost as to what is happening and why. Any help would be very appreciated . I have two models: class Airplane(models.Model): line_num = models.CharField(max_length=10, unique=True) vh_num = models.CharField(max_length=4, unique=True) vz_num = models.CharField(max_length=4, unique=True) stall = models.CharField(max_length=30, choices=stall_picker) status = models.CharField(max_length=30, choices=status_picker) owner = models.ForeignKey(User, on_delete=models.CASCADE) is_completed = models.BooleanField(default=False) pm = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.line_num class Job(models.Model): line_num = models.ForeignKey( Airplane, on_delete=models.CASCADE, related_name="ap_jobs") job_num = models.CharField(max_length=10, unique=True) description = models.CharField(max_length=200) status = models.CharField(max_length=30, choices=status_picker) category = models.CharField(max_length=30, choices=categories_picker) is_completed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class meta: ordering = ["category", "status"] def __str__(self): return (f"{self.job_num}: {self.description} : {self.is_completed}") My View: def Ap_linup(request): context = { 'ap_list': Airplane.objects.all().filter(is_completed=False), 'open_jobs': Job.objects.all().filter(is_completed=False), 'closed_jobs': Job.objects.all().filter(is_completed=True) } return render(request, 'airplane/airplane_list.html', context) Template: {% extends 'base.html' %} {% block title %} Airplane List {% endblock %} … -
Where does this (Django) CustomUser field come from?
My searches only turned up tips on how to add fields or add_fieldsets in admin.py when using Django's CustomUser. I need to find out where a field named admin comes from when the model form is rendered in the class-based CreateView. There is no error with the code, but the template automatically adds an admin choice field on top of the page-the drop-down choices are users (all 3 types) already created. But I want to create a new staff user. So how do I tell Django to leave the admin field out (at least until a user is saved)? # models.py class CustomUser(AbstractUser): user_type_data = ((1, "HOD"), (2, "Staff"), (3, "Student")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class Staff(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) email = models.EmailField() objects = models.Manager() # forms.py class StaffForm(forms.ModelForm): model = Staff first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) class Meta: model = Staff fields = '__all__' # views.py class StaffCreateView(CreateView): model = Staff form_class = StaffForm context_object_name = 'staff' success_url = reverse_lazy('staff_list') # staff_form.html <form method="post"> {{ form.as_p }} <input type="submit" value="Save"> </form> -
chartjs-plugin-annotation box in Django app
I have chartjs v2.9.3 in my Django app and it works great. Now I need to add a box to one of my charts using chartjs-plugin-annotation, and I've followed all the steps, but I can't get it to work. I've used chartjs-plugin-annotation v0.5.7 which is for v2.9.3. I get no errors in the console log. First, scripts with chart.js and plugins: <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@0.5.7/chartjs-plugin-annotation.min.js"></script> My code for chart (chart works, I just can't get box to appear): <canvas id="myChart" height="250"></canvas> <script> function setChart12(){ $('#myChart').remove(); $('#container_glavni').append('<canvas id="myChart" height="200"></canvas>'); var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: date, datasets: [{ label: 'Number of reports', data: data_nc }, { type: 'line', label: 'Median', data: [50], fill: false, borderColor: 'rgb(54, 162, 235)', }], }, options: { layout: { padding: { top: 30 } }, responsive: true, legend: { display: false }, plugins: { datalabels: { anchor: 'end', align: 'end', offset: 5, }, autocolors: false, annotation: { annotations: { box1: { type: 'box', xMin: 0, xMax: 1, yMin: 0, yMax: 30, backgroundColor: 'rgba(255, 99, 132, 0.25)'} } } }, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } });} </script> I've tried: … -
show aggragated data in admin changelist_view
I have an app where I am tracking user searches. The table currently looks like this: What I want to change is the view. I'd dlike to group/aggregate/annotate the view based on Search Term column and keep the latest date of each search term. The column User searches is being updated when user puts the same term in the search bar so there is no need for me to keep all records. I just need the latest one. I tried to update queryset using distinct() and annotate() in admin model but with no success. In other words I want to have 1 unique term in the table with the latest date (Searched on column). Below is my code: models.py class SearchQueryTracker(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, unique=False) total_results = models.IntegerField('Search results', default=0) total_searches = models.IntegerField('User searches', default=0) search_term = models.CharField(max_length=1000, blank=True, null=True) searched_on = models.DateTimeField('searched on', default=timezone.now) views.py @login_required def SearchViewFBV(request): query = request.GET.get('q') query_list = request.GET.get('q', None).split() query_list_count = len(query_list) user = User.objects.get(email=request.user.email) find_duplicate_results = SearchQueryTracker.objects.filter(search_term=query).update(total_searches=F('total_searches') + 1) .... search_tracker = SearchQueryTracker() search_tracker.total_searches = find_duplicate_results search_tracker.author = user search_tracker.search_term = query search_tracker.save() admin.py class SearchQueryTrackerAdmin(ImportExportModelAdmin): list_display = ('search_term', 'author', 'total_results', 'total_searches', 'searched_on') readonly_fields = list_display … -
apache2 permissions denied, django project
I have a linux server (ubuntu) and I uploaded a project, in my project, I try to generate a pdf with reportlab, using some fonts for the created pdf. I am having problems with permissions for reportlab. When I check out the error log in apache (/var/log/apache2/error.log), the error that appears is: reportlab.pdfbase.ttfonts.TTFError: Can't open file "recursos/fonts/Lato-Regular.ttf" I already gave full permissions (chmod 777) and also changed the owner to apache (chown :www-data) to the whole project, but the same error appears. In my local machine, works perfectly. -
Populating sql table with foreign keys using django
So im having some trouble inserting data into my sql database when using django. Setting up the tables aswell as populating them trough the admin page works perfectly fine but i have a scraper function that runts every 24h thats supposed to insert data. from datetime import datetime from .faceScraper import faceScraper as fc def Dbpopulator(): from ..models import Event [title_list, time_list, location_list, nation_list] = fc() print("scraped") for i in range(len(title_list)): e = Event() e.title = title_list[i] e.starttime = time_list[i][0] e.endtime = time_list[i][1] e.location = location_list[i] instance = e.save(commit=False) instance.nation = nation_list[i] instance.save() The problem arises when im trying to set the nation which is a foreign key from the models file below. from django.db import models # Create your models here. class Nation(models.Model): name = models.CharField(max_length=80, primary_key=True) description = models.TextField() Facebook = models.CharField(max_length=80, null=True, blank=True) def __str__(self): return self.name class Event(models.Model): title = models.CharField(max_length=80, unique=True) starttime = models.DateTimeField(null=True, blank=True) endtime = models.DateTimeField(null=True, blank=True) nation = models.ForeignKey( Nation, on_delete=models.CASCADE, default=None, null=True, blank=True) location = models.CharField(max_length=80, null=True, blank=True) def __str__(self): return self.title I have tried many different ways primarily just setting e.nation = nation_list[i] But it just wont work, i am also very certain that the database is already populated with … -
Django does not send cookies to my react app
Django backend app sends cookies in development but when I deploy it. It does not send cookies to my react application. My react application is served on Netlify and the Django app is served on Heroku. In the Django app, I have set CORS_ALLOWED_ORIGINS and CORS_ALLOW_CREDENTIALS = True. In the react app I have set withCredentials: true using Axios. The entire setup works well in development. -
django compressor error 'set' object has no attribute 'format'
Im trying to configure django compressor to work with the ifc.js library, it uses bundled js files, these arew my settings along the default from the django compressor toolkit COMPRESS_ES6_COMPILER_CMD = { 'export NODE_PATH="{paths}" && ' '{browserify_bin} "{infile}" -o "{outfile}" ' '-t [ "{node_modules}/babelify" --presets="{node_modules}/babel-preset- es2015" ]' } COMPRESS_ENABLED = True COMPRESS_OFFLINE = False when I load the page or if i try to compress, it gives me a "AttributeError: 'set' object has no attribute 'format'" with location in xxx/site-packages/compressor/filters/base.py in input, line 178, im not really sure if its a configuration error or a bug from the package, thanks -
Django Redirect by Name - No Reverse Match Error
My django project name is 'exercises' and the app name is 'practice'. This basic application allows a user can navigate to different pages with a button click. The reference to each page uses the following href: {% url 'practice:redirector' project.pk %} Where practice:redirector points to my app (practice) url path named redirector. It is parameterized with the primary key of the page which I am trying to redirect to. See below from django.urls import path from practice import views app_name = "practice" urlpatterns = [ path('', views.all_sites, name="all_sites"), path('<int:pk>', views.redirector, name='redirector'), path('clickToAddItems', views.clickToAddItems, name='clickToAddItems'), path('displayEvens', views.displayEvens, name='displayEvens'), path('displayMousePosition', views.displayMousePosition, name='displayMousePosition'), path('luckySevens', views.luckySevens, name='luckySevens'), ] This url points to the views within practice. There, I have a view set up for each page that corresponds to the name that the page will display. I also have a re director view that uses the pk passed in the url to pull the relevant page from my database and use the name as the argument in the redirect() shortcut: from django.shortcuts import render, redirect from practice.models import Project app_name = "practice" # Create your views here. # Main list of javascript sites def all_sites(request): # query my project model to return all site … -
How to properly update a many to many nested serializer?
I have been able to replicate the create method to add the correct nested serializers in a POST request. However, I'm still having issues updating in a PUT or PATCH. When using a PUT or PATCH request and I pass the entire object data or the "brands" data, it will only update in the position it is passed. So if I have an object with 3 values: "brands": [ { "id": 1, "name": "Brand 1 Test" }, { "id": 2, "name": "Brand 2 Test" }, { "id": 3, "name": "Brand 3 Test" } } If I pass: "brands": [ { "id": 1, "name": "Brand 1 Test" }, { "id": 2, "name": "Brand 2 Test" } It will give me the same list of 3 brands. But if I do that in reverse order it will update and add the 3rd brand. I'm not sure what's causing it. Here's the code I have: Models class Brand(models.Model): name = models.CharField(max_length=500) class Incentive(models.Model): name = models.CharField(max_length=500) brands = models.ManyToManyField(Brand, related_name='incentives_brand') start_dt = models.DateTimeField(auto_now_add=False, blank=True, null=True) end_dt = models.DateTimeField(auto_now_add=False, blank=True, null=True) Serializers class BrandSerializer(serializers.ModelSerializer): class Meta: model = Brand depth = 1 fields = ['id', 'name'] class IncentiveSerializer(serializers.ModelSerializer): brands = BrandSerializer(many=True) class Meta: model … -
How to Deploy Django app using OVH webhosting?
I am about to deploy my django app in OVHcloud, I bought the web hosting plan(shared web hosting platform) and it looks like I need to use a CMS. I am confused as I am not sure how to proceed, is Django CMS a solution? Moreover I am using django channels so my app is asgi would that be an issue or I should switch to VPS ? Any help/guidance is appreciated. -
Custom field - got multiple values for keyword argument 'related_name'
I'm working on a custom field that is just a shortcut to ForeignKey that points to addresses.Country model. When I run makemigrations it returns this error with I'm not sure: TypeError: Couldn't reconstruct field rsft_country on properties.Property: django.db.models.fields.related.ForeignKey.__init__() got multiple values for keyword argument 'to' I understand that there are two to arguments passed but I don't understand why. It looks like the field is initialized two times. Once with the kwargs I provided and then with all the kwargs. class RsftCountryField(models.ForeignKey): def __init__(self, verbose_name=None, **kwargs): print(kwargs) kwargs['verbose_name'] = verbose_name or 'Krajina' to = 'addresses.Country' on_delete = kwargs.pop('on_delete',None) or models.PROTECT related_name = kwargs.pop('related_name',None) or '+' super().__init__(to, on_delete, related_name=related_name, related_query_name=None, limit_choices_to=None, parent_link=False, to_field=None, db_constraint=True, **kwargs) Model: ... rsft_country = addresses_fields.RsftCountryField(null=True, blank=True) It prints kwargs two times: {'null': True, 'blank': True} {'blank': True, 'null': True, 'related_name': '+', 'on_delete': <function PROTECT at 0x7fa9fa277d00>, 'to': 'addresses.country'} Why does it do that and how to make it work? -
select_related().prefetch_related() returns invalid field
There is a class like: class SubCategories(models.Model): code = models.CharField(max_length=50) name = models.CharField(max_length=50) class Categories(models.Model): subcategory = models.ForeignKey( 'app.SubCategories', related_name='app_category_subcategory' ) I am going to do a query as follows: Cat = Categories() Cat.select_related('subcategory').prefetch_related('code').get_or_create(id=2, defaults={ 'subcategory__code':205610}) subcategory_id works but for subcategory__code (which I need) it raises an error that this is invalid field name for Categories. That would be nice if someone could tell me how can I access the code field from the ForeignKey -
Django migrate varchar [closed]
error Tengo un error al momento de hacer migrate... ¿Alguien podría darme una luz sobre como puedo avanzar en esta situación? Lo que más me preocupa es que en local me funciona perfecto, pero en el server ya me genera este error. -
How do I leverage react components from python email templates?
We have a django/react app that has a lot of work put into creating some react components that we want to reuse in some templated emails. Most of the components are in their own package outside of the actual react app. How should we incorporate these components into emails without having to rewrite them all? I'm assuming this will involve making a smaller react app hat only renders the content for the email then use that from some service to generate the python email template? I feel like this could be a large opened ended question but please add comments about how I could make it more specific and I will be happy to make changes. Also I feel like this has to be a common problem and wouldn't mind being pointed in the direction of some preexisting questions or articles as my googling must be lacking today. -
Django Foreign Keys connections
I have a model Field that has a OneToMany connections with TreeSensor and WeatherStation model. Im trying to pass over the queries of each treesensor/weatherstation model that match the id of each different field but get a Field 'id' expected a number but got <built-in function id>. .How do i fix that? Maybe change something on the filter ? class Field(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, default=None) friendly_name = models.CharField(max_length=24, blank=True) class TreeSensor(models.Model): field = models.ForeignKey(Field, on_delete=models.CASCADE) ... class WeatherStation(models.Model): field = models.ForeignKey(Field, on_delete=models.CASCADE) ... view def map(request): field_list = models.Field.objects.filter(user = request.user) tree_sensors = models.TreeSensor.objects.filter(field__pk = id) weather_stations = models.WeatherStation.objects.filter(field__pk = id) context = { "title": "Map", "field_list": field_list, "tree_sensors": tree_sensors, "weather_stations" : weather_stations, } template = 'agriculture/map.html' return render(request, template, context) -
How to Include JavaScript variable in Django URL in template?
I want to include mangaid variable in "{% url 'manga' mangaid %}". Neither ${mangaid} nor mangaid works. How can I do this? let input = document.querySelector("#search") input.addEventListener("keyup", () => { document.querySelector("#results").innerHTML = ""; let value = (input.value) fetch(`searchresponse/${value}`).then((response) => response.json()).then((results) => { results.forEach(function (result) { let mangaid = (result["id"]) document.querySelector("#results").insertAdjacentHTML('beforeend', `<a class="result" id="result${mangaid}">${result["title"]}</a>`); document.getElementById("result"+mangaid).addEventListener("click", (event) => { event.target.href = "{% url 'manga' mangaid %}" }) }) }) }) -
Compare two numbers from django rest framework model
New to django here. I want to compare two values from a model like the following inside an API made with django rest framework: class SalaryRangeModel(models.Model): salary_min = models.PositiveIntegerField salary_max = models.PositiveIntegerField I want to compare them. If salary_min is bigger than salary_max return a error. Should I code this on the model? On the serializer? On the front-end? Thanks! -
How to add None values in pandas?
I am reading xl file and xl file containing some data some rows are empty in date fields when i am uploading xl it is showing errors because empty fields so i need to add none or empty , null values to xl( in empty places)? projectid name reference jurisdiction_doctype shipping_datedue isthis_a_rush workflow allocated_date 0 CF805011 Calib 9802476632 Lien Release 03-31-2021 yes In DR 03-25-2021 1 CF80501 Calib 9802476632 Lien Release 03-31-2021 yes In DR 2 Calib 9802476632 Lien Release yes In DR 03-25-2021 3 CF80501yyy Calib Lien Release 03-31-2021 yes In DR 03-25-2021 4 CF8050 Calib 9802476632 Lien Release 03-31-2021 yes In DR 03-25-2021 -
Sharing static folder between backend and nginx containers
I have following Dockerfile FROM python:3.9 RUN adduser --disabled-password --gecos '' user WORKDIR /src COPY . ./ USER user and docker-compose.yml nginx: build: ./nginx volumes: - ./static:/static - ./nginx/etc:/etc/nginx/conf.d backoffice: ... container_name: backoffice command: bash -c "sh core/run_backoffice.sh" volumes: - ./core:/src - ./static:/static run_backoffice.sh #!/bin/bash python ./core/run.py collectstatic --no-input files structure total 56 drwxr-xr-x 9 root root 4096 Apr 11 12:53 . drwxr-xr-x 3 root root 4096 Apr 8 11:57 .. drwxr-xr-x 6 root root 4096 Apr 11 12:48 core drwxr-xr-x 5 root root 4096 Apr 11 12:54 core/. drwxr-xr-x 9 root root 4096 Apr 11 12:53 core/.. -rw-r--r-- 1 root root 384 Apr 11 12:48 core/Dockerfile -rw-r--r-- 1 root root 654 Apr 8 11:28 core/run.py -rw-r--r-- 1 root root 270 Apr 11 12:40 core/run_backoffice.sh -rw-r--r-- 1 root root 3099 Apr 11 12:53 docker-compose.yml drwxr-xr-x 3 root root 4096 Apr 8 11:28 nginx When I run collectstatic I get error backoffice | Traceback (most recent call last): backoffice | File "/src/./core/run.py", line 22, in <module> backoffice | main() backoffice | File "/src/./core/run.py", line 18, in main backoffice | execute_from_command_line(sys.argv) backoffice | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line backoffice | utility.execute() backoffice | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute backoffice | … -
Django-allauth login page is too simple
I have created a project in which I provided a login system. I also want to provide a login with the google option. I have installed Django-allath and made the necessary changes to log in and retrieve the necessary data. But when I click on login with google it sends me to the simple login page and after continuing it redirects me to the google login page. I want when I click on login with [ <a href="{% provider_login_url 'google' %}"> <img src="https://img.icons8.com/color/480/000000/google-logo.png" /> </a> ]1google, It automatically redirects me <a href="{% provider_login_url 'google' %}"> <img src="https://img.icons8.com/color/480/000000/google-logo.png" /> </a> to the google login page. Please help me. -
django model fields dropped in validated data while using nested serializers
I'm writing a post req view in my api, but when I try to create the object using validated_data in the overriden create method, django tells me that one of the required model fields are missing (the field exists in the request data before validation) models.py: class Workout(models.Model): owner = models.CharField(max_length=20) name = models.CharField(max_length=50) def __str__(self) -> str: return self.name class ExerciseData(models.Model): name = models.CharField(max_length=60) muscles_worked = models.CharField(max_length=15) def __str__(self) -> str: return self.name class ExerciseObject(models.Model): sets = models.IntegerField() reps = models.IntegerField() exercise_data = models.ForeignKey(ExerciseData,on_delete=models.CASCADE,related_name='exercise_instances') workout = models.ForeignKey(Workout,on_delete=models.CASCADE,related_name='workout_exercises') def __str__(self) -> str: return f"Exercise: {self.exercise_data.name} Workout: {self.workout.owner} {self.workout.name}" serializers.py class ExerciseDataSerializer(serializers.ModelSerializer): class Meta: model = ExerciseData fields = ('name','muscles_worked') class ExerciseObjectSerializer(serializers.ModelSerializer): exercise_data = ExerciseDataSerializer() class Meta: model = ExerciseObject fields = ('sets','reps','exercise_data','workout') #TODO: finish create function def create(self,validated_data): print("validated data", validated_data) return ExerciseObject(**validated_data) views.py: class ExerciseObjectView(APIView): def post(self,request): data = request.data.copy() # required: sets,reps,workout_id,exercise_id data['exercise_data'] = ExerciseData.objects.filter(id=data['exercise_id']).first() print("request data", data) s_data = ExerciseObjectSerializer(data=data) print(s_data) if s_data.is_valid(): print("valid") print(s_data.create(s_data.validated_data)) else: print(s_data.errors) return JsonResponse({'data':{}}) output from print("request data, data): request data <QueryDict: {'sets': ['2'], 'reps': ['15'], 'workout': ['2'], 'exercise_id': ['185'], 'exercise_data': [<ExerciseData: calf stretch hands against wall>]}> serializer error: {'exercise_data': [ErrorDetail(string='This field is required.', code='required')]} -
Unable to deploy django app with websockets and channels using daphne . Asgi application error
I am currently deploying my chat app on web with daphne using mobaxterm . This is the site -> http://139.59.6.41/ But the thing is asgi application error is being shown when I run the command sudo journalctl -u daphne.service I am unable to understand what is the error. here is the error log : root@ubuntu-s-1vcpu-1gb-blr1-01:~# sudo journalctl -u daphne.service -- Logs begin at Sat 2022-04-09 18:40:30 UTC, end at Mon 2022-04-11 12:26:26 UTC. -- Apr 09 19:09:46 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: Started WebSocket Daphne Service. Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: Traceback (most recent call last): Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: File "/home/django/Chatapp/venv/lib/python3.8/site-packages/channels/routing.py", line 32, in get_default_application Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: value = getattr(module, name) Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: AttributeError: partially initialized module 'Chatapp.asgi' has no attribute 'application' (most likely due to a circular import) Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: During handling of the above exception, another exception occurred: Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: Traceback (most recent call last): Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: File "/home/django/Chatapp/venv/bin/daphne", line 8, in <module> Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: sys.exit(CommandLineInterface.entrypoint()) Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: File "/home/django/Chatapp/venv/lib/python3.8/site-packages/daphne/cli.py", line 170, in entrypoint Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: cls().run(sys.argv[1:]) Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: File "/home/django/Chatapp/venv/lib/python3.8/site-packages/daphne/cli.py", line …