Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
gdstorage config is throwing error; Django
MySettings from decouple import config GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE = config("GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE_CONTENTS") I'm trying to setup gdstorage for my django project but was not given a json file according to the instruction in the docs so i copied the keys and placed it in my environmental variable yet it's still throwing this error. MyErrorMessage gd_storage = GoogleDriveStorage() File "C:\Users\username\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\gdstorage\storage.py", line 160, in __init__ credentials = Credentials.from_service_account_file( File "C:\Users\username.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\google\oauth2\service_account.py", line 238, in from_service_account_file info, signer = _service_account_info.from_filename( File "C:\Users\username.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\google\auth\_service_account_info.py", line 72, in from_filename with io.open(filename, "r", encoding="utf-8") as json_file: FileNotFoundError: [Errno 2] No such file or directory: '78a23bb0124ac97ec7404104ae37dccffe33846a' -
how to add a map to admin page django
i want to get coordinates using map on admin page(latitude and longitude) i added in models field from django.contrib.gis.db import models as gis point = gis.PointField(null=True, blank=True, srid=4326, verbose_name='location') but i'm getting an error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. I realized that I need to add GDAL_LIBRARY_PATH to settings, but I don't know what to put there or if there is another way to add a map to the admin page? -
django https for another host except localhost
I'm trying to install SSL certificate for local server. I found this tutorial and try to do step by step. Everything is working fine for 127.0.0.1:8000, but not for my another host. settings.py ALLOWED_HOSTS = ['127.0.0.1', '192.168.4.241'] What I tried: mkcert -cert-file cert.pem -key-file key.pem localhost 127.0.0.1 192.168.4.241 python manage.py runserver_plus 192.168.4.241:8000 --cert-file cert.pem --key-file key.pem Error: OSError: [WinError 10049] The requested address is not valid in its context How can I fix this? -
Inherinting Django SetUpTestData method called for each child
Inheriting a mother class make its classmethod setUpTestData called for each child class. This is what I excepted but not what I want. Here is a minimalist example from django.test import TestCase class ParentClass(TestCase): @classmethod def setUpTestData(cls): cls.parent_attr = "parent value" print("ParentClass.setUpTestData called") # this is called twice class TestChild1(ParentClass): @classmethod def setUpTestData(cls): super(TestChild1, cls).setUpTestData() cls.child_attr = "child value 1" def test_child(self): self.assertEqual(self.parent_attr, "parent value") self.assertEqual(self.child_attr, "child value 1") class TestChild2(ParentClass): @classmethod def setUpTestData(cls): super(TestChild2, cls).setUpTestData() cls.child_attr = "child value 2" def test_child(self): self.assertEqual(self.parent_attr, "parent value") self.assertEqual(self.child_attr, "child value 2") $ python manage.py test accounts.tests.test_test Creating test database for alias 'default'... System check identified no issues (0 silenced). ParentClass.setUpTestData called .ParentClass.setUpTestData called . ---------------------------------------------------------------------- Ran 2 tests in 0.006s OK Destroying test database for alias 'default'... I want to be able to make many child class where each child class would apply tiny modification to the common 'inherited' database. However I do not want to run many time the parent classmethod as it is very slow. How can I ensure parent database is generated only once and that every child class works on a copy of parent database instead of regenerating the entire database. -
Django how to print datetimefield with timezone
I'm trying to print my datetime fields with the time zone i.e like this 2022-03-28T00:00:00+05:30 My serializer like this class ChallengeReadSerializer(serializers.ModelSerializer): start_date = serializers.DateTimeField(format='iso-8601') class Meta: model = models.Challenge fields = [ "start_date", ] Prints this 2022-03-23T03:16:00Z When I modify the serializer like this class ChallengeReadSerializer(serializers.ModelSerializer): start_date = serializers.SerializerMethodField() class Meta: model = models.Challenge fields = [ "start_date", ] def get_start_date(self, obj): return obj.start_date.isoformat() It prints 2022-03-28T00:00:00+05:30, which is what I want. I don't understand how this is happening, and couldn't find any information except it being two formats, how does the .isoformat() print timezone and (format='iso-8601') not print TZ -
django pwa not working for another hosts except localhost
I have install django-pwa and everything is working fine on localhost (127.0.0.1). But I can't see a install app button on the other host. How can I fix that? settings.py ALLOWED_HOSTS = ['127.0.0.1', '192.168.4.241'] PWA_APP_NAME = 'QLNB' PWA_APP_DESCRIPTION = 'QLNB' PWA_APP_THEME_COLOR = '#016e38' PWA_APP_BACKGROUND_COLOR = '#f0ece2' PWA_APP_START_URL = '/' PWA_APP_DEBUG_MODE = False PWA_APP_ICONS = [ { 'src': '/static/images/TDF.png', 'sizes': '160x160' } ] PWA_SERVICE_WORKER_PATH = BASE_DIR / 'static/scripts/serviceworker.js' base.html {% load static %} {% load pwa %} <!doctype html> <html lang="cs" class="w-100 h-100 m-0 p-0 overflow-auto"> <head> {% progressive_web_app_meta %} -
Django Templates check if string is "\t"
I am extending a selection form for csv delimiters and wanted to add the option for the tab character. <option value="&#9;" {% if settings.csvImportDelimiter == '&#9;' %} selected {% endif %}>Tab</option> The part that is not working is {% if settings.csvImportDelimiter == '&#9;' %}. I tried putting '\t' instead of ' ' without success. Is there a different syntax to this? I looked at the both Jinja and Django template docs but did not find anything on these control symbols. -
Django cache isolation when running tests in parallel
When I run tests in parallel, I get random failures because one test interferes with the cache of another test. I can work around the problem with @override_settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "[random_string]", } }, ) Actually to make that smaller I created a @isolate_cache decorator that is a wrapper around override_settings. But still I need to go and decorate a large number of test cases. This is error prone, because, as I said, the failures are random. I might run the test suite 100 times without error and think that everything is OK, but I still might have forgotten to decorate a test case, and at some point it will fail randomly. I've also thought about creating my own TestCase subclass and use only that for all my test cases. This presents a similar problem: at some point someone would inherit from django.test.TestCase out of habit, and it might not fail for a long time. Besides, some of my tests inherit from rest_framework.test.APITestCase (or other classes), so there isn't a single test case subclass. Is there any way to tell Django to run each test case in an isolated section of the cache once and for all? -
Django: How to create some variable in model based on the foreign key data?
I am new to Django and right now I am working on my first project: sits reservation system for some cinema. For this I have created 3 models: Movie, Hall and Event. Hall generates sits map as array. class Hall(models.Model): HALL_NAME = ( ('A', 'Hall A'), ('B', 'Hall B'), ('C', 'Hall C') ) hall_name = models.CharField(choices=HALL_NAME, max_length=30) hall_structure = models.CharField(max_length=10000, default=generate_sits(hall_name)) @property def get_sits(self): if self.hall_name == 'A': return generate_sits('A') if self.hall_name == 'Hall B': return generate_sits('B') if self.hall_name == 'Hall C': return generate_sits('C') else: return "lol" def __str__(self): return f'{self.hall_name}' After that i would like to create a variable for Event model, which takes the array structure of the sits, turns it into dictionary (Example ['A1': 'empty', 'A2': 'empty', ...] ). I want this variable to be overwritten in the future, when someone should book a sit on the vebsite (['A1': 'reserved']). Here is my Event model: class Event(models.Model): EVENT_DAYS = ( ('mon', 'Monday'), ('tu', 'Tuesday'), ('we', 'Wednesday'), ('th', 'Thursday'), ('fr', 'Friday'), ) EVENT_TIME_SLOT = ( ('10', '10:00'), ('13', '13:30'), ('17', '17:00'), ('20', '20:30'), ('00', '00:00'), ) EVENT_TYPE = ( ('2d', '2D'), ('3d', '3D'), ) end_default = "for this Event was assigned yet" days_default = "No day " time_default … -
What is the best way to send and fetch data periodically from Django backend to React frontend?
I'm making a web visualization app that needs to display data in real-time. I have a Python SDK that only requests data (using request library from python) directly from our database using the API provided and returns a response in JSON format. I'm using Django version 3.2 and have created a Django app and a React app version 17.0.2 in the same directory. What I did was get the data in my views.py using the Python SDK and then using the Django Rest Framework, created an API from it without using serialization. Then in the front-end (React), I fetched the data in the DRF API using Axios. So far, it's working just fine. However, I noticed that I need to restart my local Django server and refresh the page first before the latest/updated data gets reflected in my visualization. What I need is for the back-end to send the latest data to the front-end in real-time or for the front-end to request/fetch the latest data periodically from the back-end - whichever is better in terms of performance. I'm new to using DRF in the backend and Django+React as the front-end. Someone suggested looking into promises in Python but I'm not … -
How to give access to different object of a model to different users in django
I am doing an online classroom project in Django where I created a model named course which is accessible by teachers. Now I am trying to add students in a particular class by inviting students or students can enroll using "clasroom_id"(a unique field I used in the model). I added the models and views of the course object below. models.py class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.course_name def is_valid(self): pass views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): course = form.save(commit=False) course.created_by = request.user course.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) def view_courses(request, *args, **kwargs): students = course.objects.filter(created_by=request.user) dict = {'course':students} return render(request, 'teacherhome.html',dict) -
How to prevent django migrations from running?
My team frequently uses the production DB for testing new changes and on more than one occasion migrations have been created and applied before being code reviewed, creating issues in production. There are so many things wrong with this situation, but I'm hoping to at least protect our prod DB by blocking migrations based on the state of an environment variable. Is this possible? -
How to know which django middlewares are asynchronous enabled and which are not?
To see what middleware Django has to adapt, you can turn on debug logging for the django. request logger and look for log messages about “Synchronous middleware … adapted” . I have been trying to do just the same but without any luck. This is my settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'DEBUG', }, 'loggers': { 'django.request': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, }, } Even though I have set up the LOGGING variable, I am not getting the output like mentioned in the documentation. Starting server at tcp:port=8000:interface=127.0.0.1 HTTP/2 support not enabled (install the http2 and tls Twisted extras) Configuring endpoint tcp:port=8000:interface=127.0.0.1 Listening on TCP address 127.0.0.1:8000 HTTP b'GET' request for ['127.0.0.1', 42684] HTTP 200 response started for ['127.0.0.1', 42684] HTTP close for ['127.0.0.1', 42684] HTTP response complete for ['127.0.0.1', 42684] 127.0.0.1:42684 - - [22/Mar/2022:12:11:47] "GET /admin/" 200 3550 HTTP b'GET' request for ['127.0.0.1', 42684] HTTP 200 response started for ['127.0.0.1', 42684] HTTP close for ['127.0.0.1', 42684] HTTP response complete for ['127.0.0.1', 42684] 127.0.0.1:42684 - - [22/Mar/2022:12:11:48] "GET /admin/core/user/" 200 9028 HTTP b'GET' request for ['127.0.0.1', 42684] HTTP 200 response started … -
Django error no such table: auth_group when running makemigrations
When i run python manage.py makemigrations it throws an error: File "/home/smoke/miniconda3/envs/testing/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/smoke/Documents/wsl_dev/testing/genelookup/apps/authentication/urls.py", line 7, in <module> from .views import login_view, register_user File "/home/smoke/Documents/wsl_dev/testing/genelookup/apps/authentication/views.py", line 14, in <module> compute, created = Group.objects.get_or_create(name='compute') File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 588, in get_or_create return self.get(**kwargs), False File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 435, in get num = len(clone) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 1354, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1202, in execute_sql cursor.execute(sql, params) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in … -
how to create a Dropdown in Django
how to create two Dropdown fields in Django. first is state, & second is city View.py file: def dropdown(request,state_slug): context={} stateO=State.objects.order_by('name') context['state']=stateO sO=State.objects.get(state_slug=state_slug) cityO=City.objects.filter(State=sO).order_by('name') context['city']=cityO context['my_state']=sO return render(request,'drop.html',context) Url.py: class State(models.Model): name = models.CharField(max_length=96) state_slug = models.SlugField(max_length=96, blank=True) def save(self, *args, **kwargs): # Saving The Modefied Changes if not self.state_slug: self.state_slug = slugify(self.name) super(State, self).save(*args, **kwargs) def __str__(self): # Dundar Method return self.name class City(models.Model): State = models.ForeignKey(State, on_delete=models.CASCADE) name = models.CharField(max_length=100) def __str__(self): return self.name html file: <body> <select> {% for i in state %} <option value="{% url 'dropdown' i.state_slug %}}">{{i}}</option> {% endfor %} </select> <select> {% for j in city %} <option value="{{ j }}">{{ j }}</option> {% endfor %} </select> </body> filter the citys name on the base of state name. without using Ajex. -
Creating Oauth callback function in python. I there is a webserver should sends me Token and I want to react to the token if it's correct by call back
I want to make the same function but in Python Django how can I do that because I want to make authentication for login using Oauth 2.0 public function callback(Request $request){ $response = Http::post('https://oauth.zid.sa' . '/oauth/token', [ 'grant_type' =>'authorization_code', 'client_id' => 48, 'client_secret' => 'LsswUNyWTjyKT9AsXnpsv3FnG4glSNZQ5SM3YRnD', 'redirect_uri' => 'http://client.test/oauth/callback', 'code' => $request->code // grant code]);} -
upload image in forms Django
I am trying to upload image from form but whenever I submit everything got saved in database other than image field.But when I try to do samething from admin panel it works. models.py class Post(models.Model): title = models.CharField(("Title"), max_length=100) title_image = models.ImageField( ("Title Image"), upload_to='static/Images/TitleImages/', max_length=None, blank = True,null = True) Forms.py class AddPostForm(ModelForm): class Meta: model = Post fields = ['title','title_image'] Views.py class AddPostView(LoginRequiredMixin,CreateView): model = Post template_name = 'MainSite/add_post.html' fields = '__all__' def dispatch(self, request, *args, **kwargs): if request.user.is_anonymous: messages.error(request,"You need to login to access this page") return redirect('/') elif request.user.is_superuser: if request.method == "POST": form = AddPostForm(request.POST) if form.is_valid(): form.save() messages.success(request,"POST added successfully") return redirect('/') else: print("error") else: print("method is not post") form = AddPostForm() return render(request,'MainSite/add_post.html',{'form':form}) else : messages.error(request,"You need to have superuser permission to access this page") return redirect('/') addpost.html <form action= "" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.media }} {{ form|crispy}} <button class="btn btn-primary profile-button" style = "width:150px;"type="submit" >Add Post</button></div> </form> my model have 2 things title and title_image but whenever I submit only title is saved and when I do through admin panel it works. I dont know what I am doing wrong here any advice will be helpful. Thanks in advance -
DJango unable to upload image on update
So basically django is unable to upload file after calling update function. It does work with create function. The path is getting updated in the database but the file isn't copying in the /media/ I'm not using the form for image (only for blog content), rather using froala editor. views.py def blog_update(request, pk): context = {} if not (request.user.is_authenticated): return redirect('/') else: try: blog_obj = Blog.objects.get(id = pk) if blog_obj.user != request.user: return redirect('/') initial_dict = {'content': blog_obj.content} form = BlogForms(initial = initial_dict) if request.method == 'POST': form = BlogForms(request.POST) image = request.FILES['image'] title = request.POST.get('title') gist = request.POST.get('gist') user = request.user if form.is_valid(): content = form.cleaned_data['content'] blog_obj = Blog.objects.filter(id = pk).update( user = user , title = title, gist = gist, content = content, image = image ) messages.success(request, f"Blog updated successfully!") return redirect('/my-blogs/') context['blog_obj'] = blog_obj context['form'] = form except Exception as e: print(e) return render(request, 'update-blog.html', context) forms.py class BlogForms(forms.ModelForm): class Meta: model = Blog fields = ['content'] I tried to print the path for existing file as well as the new selected file and it shows correct. Somehow the update function isn't copying the file to the media dir. I'm new to this, any help is … -
Django ChoiceField with custom forms
I am relatively new to Django and have been following up some tutorials on how to create registration forms with Django. **This is the html form code** <form action="{% url 'register' %}" method="post"> {% csrf_token %} <div class="form-row"> <div class="col form-group"> <label>First name</label> {{ form.first_name }} </div> <!-- form-group end.// --> <div class="col form-group"> <label>Last name</label> {{ form.last_name }} </div> <!-- form-group end.// --> </div> <!-- form-row end.// --> <div class="form-row"> <div class="col form-group"> <label>Email</label> {{ form.email }} </div> <!-- form-group end.// --> <div class="form-group col-md-6"> <label>Directorate</label> <select name="directorate" class="form-control" required> <option value="" disabled selected>Select</option> {% for i in form.directorate %} <option value=""></option> {% endfor %} </select> </div> <!-- form-group end.// --> </div> <!-- form-row end.// --> <div class="form-row"> <div class="form-group col-md-6"> <label>Create password</label> {{ form.password }} </div> <!-- form-group end.// --> <div class="form-group col-md-6"> <label>Repeat password</label> {{ form.confirm_password }} </div> <!-- form-group end.// --> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-block"> Register </button> </div> <!-- form-group// --> </form> **This is models.py code** class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) directorate = models.CharField(max_length=100) # required date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) … -
Date value in Django API response is one day lesser that actual value in database
I have a Django model which contain a date field. While I am calling a get API to get values from this model. The date value in response is one day lesser that what is there in the db. Please find a sample table id type created_date 1 test_type 2019-05-23 05:30:00 While I calling a get API I got response like this: {id":"1","type":"test_type","created_date":"2019-05-22T20:00:00-04:00"} Can you please help to fix this issue. And please give me an idea why this is happening. Thanks in advance -
Taking django application to https
I have a django application running perfectly fine in development server with http://localhost:8081 I need to take it to https. For which I tried 2 methods, but none of them is working. Method1: Using stunnel I installed stunnel and generated cert and key with openssl. openssl genrsa 2048 > ca.key openssl req -new -x509 -nodes -sha1 -days 365 -key ca.key > ca.cert cat ca.key ca.cert > ca.pem Defined dev_https as: pid= cert = certs/ca.pem sslVersion = all foreground = yes output = stunnel.log [https] accept=10443 connect=8081 and executed below commands: stunnel certs/dev_https & HTTPS=on /home/user/python3.9/bin/python3 /path/to/django/app/manage.py runserver localhost:8081 This is giving me error on console from stunnel as: connect_blocking: connect 127.0.0.1:8081: Connection refused (111) Connection reset: 0 byte(s) sent to SSL, 0 byte(s) sent to socket from django app gui: If I try to access the app over https://localhost:10443 This site can’t be reached If I try to access app over http://localhost:8081 ---> It works fine. But that's not required. Method2: Apache with mod_wsgi I installed mod_wsgi with rpm. Then modified httpd.conf as: LoadModule wsgi_module modules/mod_wsgi.so WSGIScriptAlias / /path/to/django/app/wsgi.py WSGIPythonHome /home/user/python3.9 WSGIPythonPath "/home/user/python3.9/lib;/home/user/python3.9/lib/python3.9/site-packages" <Directory /path/to/django/app> <Files wsgi.py> Require all granted </Files> </Directory> and restarted the httpd. On starting the django … -
django inspectdb non public schema
We only have 1 database with atleast 10 different schemas how can I generate an inspectdb. Let's say python manage.py inspectdb "schema9.table1" > models.py to generate models I found couple of answers saying that django dont support this kind of feature specifically postgresql but maybe since it's 2022 maybe there's a simple and short way to do this -
Writeable Serializer
I have the following viewsets and serializers setup to create a single action to post a schedule with it's steps but I receive the following error. class StepCreateSerializer(serializers.Serializer): start_time = serializers.TimeField() time = serializers.IntegerField() def update(self, instance, validated_data): pass def create(self, validated_data): print(validated_data) return validated_data class ScheduleCreateSerializer(serializers.Serializer): name = serializers.CharField(max_length=100) identifier = serializers.CharField(max_length=10) steps = StepCreateSerializer(many=True) def update(self, instance, validated_data): pass def create(self, validated_data): steps_data = validated_data.get('steps', []) schedule = Schedule.objects.create(**validated_data) for step_data in steps_data: Step.objects.create(schedule=schedule, **steps_data) return schedule class ScheduleViewSet(BaseViewSet): queryset = Schedule.objects.all() serializer_class = ScheduleSerializer def create(self, request, *args, **kwargs): ser = ScheduleCreateSerializer(data=request.data) ser.is_valid(raise_exception=True) ser.save() return Response() I call it with the following json payload with POST method: { "name": "Schedule123", "identifier": "S123", "steps": [ { "start_time": "07:21:00", "time": 5, "valve_actions": [ { "start_state": true, "end_state": false, "valve": 2 }, { "start_state": true, "end_state": false, "valve": 1 } ] } ] } It results in the following error when called with the payload TypeError: Direct assignment to the reverse side of a related set is prohibited. Use steps.set() instead. The models are as follows class Schedule(models.Model): identifier = models.CharField(max_length=10) name = models.CharField(max_length=100) class Step(models.Model): start_time = models.TimeField() time = models.IntegerField() schedule = models.ForeignKey("manager.Schedule", on_delete=models.CASCADE, related_name="steps", null=True) How do … -
Route53 DNS issue with Django Elastic Beanstalk app
Not sure what I am doing wrong here. My zone is public and I have simple routing for the A records pointing to the EB alias. I even tried a CNAME to no avail. I even did a test response within the console. Everything checks out but there is something funny happening between the Route53 -> EB handshake. The EB alias works just fine by itself. I would love some pointers. Perhaps I need to configure something within Django settings? -
Getting "_pickle.PicklingError: Can't pickle <function>: it's not the same object" for django-q async_task decorator
I'm trying to create a decorator that I can apply to any function, so I can make it a django-q async task. The decorator is written as bellow def django_async_task(func): """Django Q async task decorator.""" def wrapper(*args, task_name): return django_q.tasks.async_task(func, *args, task_name=task_name) return wrapper Then I can use the above decorator in any task as below @django_async_task def my_task(a): print(f'Hello {a}') task_id = my_task('Vidu', task_name='task1') However, I cannot get the above to work as I'm getting _pickle.PicklingError: Can't pickle <function my_task at 0x7f3dc084be50>: it's not the same object as tests.my_task I tried functools wraps as below but it didn't have any effect. def django_async_task(func): """Django Q async task decorator.""" @functools.wraps(func) def wrapper(*args, task_name): return django_q.tasks.async_task(func, *args, task_name=task_name) return wrapper I also tried a decorator class but it didn't solve the issue either.