Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is this the right way to get item of specific status in django?
I'm doing a to-do list in Django, I gave a model 'Todo' 3 status, which are 'todo''in_progress' and 'done', now I want to change a task's status from 'todo' to 'in_progress' and render this task, below codes seems not to work, any help would be appreciated. views.py ''' def add_to_progress(request, todo_id, project_id): todo = Todo.objects.get(id=todo_id) project = Project.objects.get(id=project_id) if request.method != 'POST': form = dragTodoForm() else: form = dragTodoForm(request.POST) if form.is_valid(): form.save() Todo.objects.filter(id=todo_id).update(status='in_progress') progress = Todo.objects.filter(status='in_progress') context = {'form', form, 'todo', todo, 'project', project, 'progress', progress} return render(request, 'todo_lists/new_progress.html', context) ''' project.html ''' </div> <form method="post" action="{% url 'todo_lists: add_to_progress' todo.id project.id %}"> {% csrf_token %} {{ form.as_p }} <button type="submit">Doing</button> </form> </div> ''' -
Save date to db with difference timezone
faced with a problem, that Django save a datetime with difference time: my local time and time from Django settings. My current timezone + 3 hours ahead, than utc time. And for example i tried save date to Django: 2021-01-01 08:00, but to database will be saved like 2021-01-01 11:00. After receive date from db, DateTime field will be serialized, and will be showed like 2021-01-01 08:00. But there is one bigger problem. With one database, can work two Django app, where local timezone on VPS can has a different value: +6 time, ahead utc. And after serialization, we will has different time in Django apps, but we use one DB and has same TZ in Django settings. How can solve this moment? Thanks -
False commit | Django
my code is working perfectly but I'd like to make some changes and NOT save anymore the uploaded filename in SQLite database. My code: # false commit to get upload file name upload = form.save(commit=False) upload.save() uploadFile = upload.file.name.split('/')[-1] As I said, I don't need right now to save this form in database. I tried to comment out the line upload.save() but the code is not working, displaying the error message below: Exception Type: com_error Exception Value: it's possible that the file may be removed, renamed or trashed. Thank you! -
Pytest hangs indefinitely running tests after Selenium image update
A day ago selenium updated their standalone-images (https://hub.docker.com/search?q=selenium&type=image) and at the same time selenium 4.0.0 was released on pypi (https://pypi.org/project/selenium/#history) I am using pytest and selenium to test my frontend of my django app and everything was working perfectly fine until yesterday when the release came out. What happens now is that when I run pytest (in PyCharm) the test just runs indefinitely without throwing an error or anything. It just never stops running. I very sure that the release is the problem, because when I pull the chrome-debug image, which was updated 15 days ago (in comparison to the chrome-standalone yesterday), my test-suite runs just fine again. I also tried pulling the standalone-firefox image to check if it may be a problem with only the standalone-chrome image, but I get the same result. Now, an intermediate solution is of course to use the chrome-debug image, but I am afraid that they will update this one soon too which will break my test-suite yet again, plus the standalone images are more lightweight. I have absolutely no clue what's going on. A minimal example of my test suite: Docker-compose: selenium: image: selenium/standalone-chrome ports: - 4444:4444 - 5900:5900 Docker-file; FROM python:3.9-alpine3.14 .... … -
Django+Postgres DB constraint errof
I have 2 models: class YouTubeCurrentChannelStat(models.Model): blogger = models.ForeignKey( BloggerProfile, on_delete=models.CASCADE, related_name='youtube_channel_stat' ) channel_id = models.CharField(primary_key=True, max_length=100) blog_theme = models.TextField(max_length=150, blank=True) channel_title = models.CharField(max_length=200, default='') subscribers = models.PositiveIntegerField() views = models.PositiveIntegerField() videos_count = models.PositiveIntegerField(null=True) description = models.TextField(max_length=5000) published_date = models.DateTimeField() last_updated = models.DateTimeField(blank=True, null=True, default='') and: class YouTubeVideoItemsCurrentStat(models.Model): channel = models.ForeignKey(YouTubeCurrentChannelStat, on_delete=models.CASCADE, related_name='videos_data') video_id = models.CharField(primary_key=True, max_length=100) stat_data = models.JSONField() # Updated daily with a Celery Task last_updated = models.DateTimeField(blank=True, null=True, default='') Second is related to first as FK. I use create_or_update method of Django ORM. When i create Postgres DB record for the first time - it creates without any issues. But when I want to update it I get this error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "socials_youtubecurrentchannelstat_pkey" DETAIL: Key (channel_id)=(UCd3rBmH-OiF7tp3pye9LJIg) already exists My create task looks like: def update_videos_db_records(channel_id, response, video_id): YouTubeVideoItemsCurrentStat.objects.update_or_create( video_id=video_id, channel_id=channel_id, stat_data=dict( title=response.get('title', ''), likes=response.get('likes', 0), views=response.get('views', 0), thumbnail=response.get('thumb_url', ''), comments=response.get('comments', 0), dislikes=response.get('dislikes', 0), favourites=response.get('favourite', 0) ), last_updated=datetime.datetime.now() ) Also I tried it this way: def update_videos_db_records(channel_id, response, video_id): YouTubeVideoItemsCurrentStat.objects.filter( video_id=video_id, channel_id=channel_id).update( stat_data=dict( title=response.get('title', ''), likes=response.get('likes', 0), views=response.get('views', 0), thumbnail=response.get('thumb_url', ''), comments=response.get('comments', 0), dislikes=response.get('dislikes', 0), favourites=response.get('favourite', 0) ), last_updated=datetime.datetime.now() ) But it raised the same error. Method description on Django docs says: Like … -
NameError SERVER is not Defined Django
I am getting an error I don't understand with django: NameError at / name 'SERVER' is not defined My View: class RobotDetail(UpdateView): model = models.Robot form_class = RobotUpdateForm template_name = 'dashboard-home/robotdetail.html' robo = Robot.objects.get(pk=pk) PORT = robo.port SERVER = robo.server My Model: port = models.IntegerField() server = models.CharField(max_length=200, default='10.10.19', blank=True, null=True) -
Extension of an issue about Uploading multiple files from the Django admin
folks! I'm beginner in Django and I've seen this answer How to upload multiple files from the Django admin? about uploading multiple files from django admin, but I'd like to know how to validate a such field in admin main form based only if the upload field located at its child Inline form has a file selected already? Thanks in advance. -
New Written Django Manager is not working in the template
I have a simple todolist app where each task has a Booleanfield called is_deleted. in my list template, I only want to show the tasks with is_deleted=False . I know I can use Task.objects.all().filter(is_deleted=False) in my view; but I want to do it with managers in my template. here is my manager: class TaskManager(models.Manager): def available(self): return self.filter(is_deleted=False) . . objects = TaskManager() here is my view: class TaskList(ListView): model = models.Task context_object_name="tasks" template_name = "home/list.html" paginate_by=5 and here is the the condition in my template: {% if tasks.available%} ... -
Model Field with only year or full date using Django
how can i get ModelField in which i would once add full date in format like "2016-07-04" and once only a year like 1997, so i would have two items one with only a year, and one with full date, and then i could sort them by year? -
Celery consumes all queues
I'm trying to achieve a following configuration: Send a message to RabbitMQ. Copy this message to 2 different queues. Run 2 consumers, where each of them would consume from its own queue. So, I have this to send messages: def publish_message(): with app.producer_pool.acquire(block=True) as producer: producer.publish( body={"TEST": "OK"}, exchange='myexchange', routing_key='mykey', ) I create my consumers this way: with app.pool.acquire(block=True) as conn: exchange = kombu.Exchange( name="myexchange", type="direct", durable=True, channel=conn, ) exchange.declare() queue1 = kombu.Queue( name="myqueue", exchange=exchange, routing_key="mykey", channel=conn, # message_ttl=600, # queue_arguments={ # "x-queue-type": "classic" # }, durable=True ) queue1.declare() queue2 = kombu.Queue( name="myotherqueue", exchange=exchange, routing_key="mykey", channel=conn, # message_ttl=600, # queue_arguments={ # "x-queue-type": "classic" # }, durable=True ) queue2.declare() class MyConsumer1(bootsteps.ConsumerStep): def get_consumers(self, channel): return [ kombu.Consumer( channel, queues=[queue1], callbacks=[self.handle], accept=["json"] ) ] def handle(self, body, message): print(f"\n### 1 ###\nBODY: {body}\nCONS: {self.consumers}\n#########\n") message.ack() class MyConsumer2(bootsteps.ConsumerStep): def get_consumers(self, channel): return [ kombu.Consumer( channel, queues=[queue2], callbacks=[self.handle], accept=["json"] ) ] def handle(self, body, message): print(f"\n### 2 ###\nBODY: {body}\nCONS: {self.consumers}\n#########\n") message.ack() app.steps["consumer"].add(MyConsumer1) app.steps["consumer"].add(MyConsumer2) But when I run worker passing -Q myqueue I get this: (venv) ➜ src git:(rabbitmq-experiment) ✗ celery -A settings worker -X myotherqueue --hostname 1@%h -------------- 1@gonczor v5.0.5 (singularity) --- ***** ----- -- ******* ---- Linux-5.11.0-37-generic-x86_64-with-glibc2.31 2021-10-14 19:37:26 - *** --- * --- … -
How can I run a bot in loop 24 hours a day in Django?
I have developed a bot which needs to be 24 hours online and I set the website up in namecheap (Just a hosting) and it kills my process when it has been running for 2 hours or something like that. [UID:3232][2228262] Killing runaway process PID: 2228339 with SIGTERM [UID:3232][2228262] Child process with pid: 2228339 was killed by signal: 15, core dump: 0 This is what it returns and I would like to avoid this, I have been reading about django-background-tasks but I'm not sure if I can make it run for the whole day. -
django.db.utils.OperationalError: no such table: Recruiter_jobs table not found error?
I Am doing a project in Django and I have created some models in my project and after migrating it gives me something error like Django.db.utils.OperationalError: no such table: Recruiter_jobs, but I think I have all the tables registered in admin also. but still, it showing an error... here's my models.py class empDetail(models.Model): cmpName=models.CharField("Company Name ",max_length=30) role=models.CharField("role ",max_length=20) def __str__(self): return self.empEmail class jobs(models.Model): location=models.CharField("Location ",max_length=30) desc=models.CharField("Descriptions ",max_length=3000) role=models.CharField("role ",max_length=10) sal=models.CharField("salary ",max_length=20) def __str__(self): return self.desc class candetail(models.Model): location=models.CharField("Locations ",max_length=30,default="") role=models.CharField("Role ",max_length=100,default="") cv=models.FileField(upload_to="media/canDetails/") def __str__(self): return self.location class availablejob(models.Model): cmpny=models.CharField("Company Name",max_length=100,default="") location=models.CharField("Location ",max_length=30) desc=models.CharField("Descriptions ",max_length=3000) role=models.CharField("Role ",max_length=100) sal=models.CharField("Salary ",max_length=20) def __str__(self): return self.role class empDetails(models.Model): cmpName=models.CharField("Company Name ",max_length=30) role=models.CharField("role ",max_length=20) cv=models.FileField(upload_to="media/empDetails/") def __str__(self): return self.empEmail heres the logs below (env) PS C:\Users\ashwi\Documents\GitHub\AMCH\AMCH_Recruiter> python manage.py migrate Operations to perform: Apply all migrations: Recruiter, admin, auth, contenttypes, sessions Running migrations: Applying Recruiter.0008_delete_jobs...Traceback (most recent call last): File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: Recruiter_jobs The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\ashwi\Documents\GitHub\AMCH\AMCH_Recruiter\manage.py", line 22, in <module> main() File "C:\Users\ashwi\Documents\GitHub\AMCH\AMCH_Recruiter\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\__init__.py", … -
502 Bad Gateway on Nginx When Trying to Deploy two different services on same url but different ports
I am trying to deploy a build version of React JS and Django Server on different ports. React JS serves on port 3000 and Django Server should serve on 8000. React JS works perfectly fine however URL to Django server says 502 bad gateway. Here is error logs of nginx. 2021/10/14 23:47:31 [error] 4250#4250: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: example.com, request: "GET / HTTP/1.1", upstream: "uwsgi://127.0.0.1:8001", host: "localhost:8000" Here is my localhost file present in /etc/nginx/sites-available # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name example.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /var/www/runbackend/backend/media; # your Django project's media files - amend as required } location /static { alias /var/www/runbackend/backend/static; # your Django project's static files - amend as … -
ImportError: No module named django.core.wsgi for Apachein CentOS 7
I am deploying a Django app on Apache in CentOS 7. My project is within a virtual environment created with pipenv shell. Django is installed in that virtual environment only and not globally. Below is the location of this virtual environment (as in where I run pipenv shell): /home/centos/proj/my_app And my app folder structure which contains wsgi.py is as following: /home/centos/proj/my_app/my_app/my_app/wsgi.py When I deployed, I see the following error in Apache log file: [Thu Oct 14 18:02:47.599843 2021] [:error] [pid 2999] [remote xx.x.xx.xx:116] mod_wsgi (pid=2999): Target WSGI script '/home/centos/proj/my_app/my_app/my_app/wsgi.py' cannot be loaded as Python module. [Thu Oct 14 18:02:47.600490 2021] [:error] [pid 2999] [remote xx.x.xx.xx:116] mod_wsgi (pid=2999): Exception occurred processing WSGI script '/home/centos/proj/my_app/my_app/my_app/wsgi.py'. [Thu Oct 14 18:02:47.600510 2021] [:error] [pid 2999] [remote xx.x.xx.xx:116] Traceback (most recent call last): [Thu Oct 14 18:02:47.600528 2021] [:error] [pid 2999] [remote xx.x.xx.xx:116] File "/home/centos/proj/my_app/my_app/my_app/wsgi.py", line 15, in <module> [Thu Oct 14 18:02:47.600610 2021] [:error] [pid 2999] [remote xx.x.xx.xx:116] from django.core.wsgi import get_wsgi_application [Thu Oct 14 18:02:47.600626 2021] [:error] [pid 2999] [remote xx.x.xx.xx:116] ImportError: No module named django.core.wsgi This thread here described a similar issue, but for uwsgi. It said that because Django is installed locally in the virtual environment, the PYTHONPATH is therefore incorrect … -
Trying to open a new template with django queryset data and show just one entry
I have a dashboard for a manufacturer that lists a snapshot of the products info based on if that product is made by their company. I want to be able to open the product snapshot into another html page so that updates can be made to it. I can filter the products in the dashboard and it clicks through and opens up the correct info on the new html page, but the problem is that it opens up all of the products on the page and lists them as well. My View: def product_info(request): manufacturer = Manufacturer.objects.get(user) company = manufacturer.company products = Products.objects.filter(manufacturer=company).all return render(request, 'My_app/product-expanded.html', {'products': products}) The HTML {% for product in products %} <div class="product-name"> <h3 style="text-decoration: underline;">{{ product.name|default:'Product'}}</h3> </div> {% if product %} <div class="product-expanded"> <ul> <li class="product-card"><br> <div id="product-price"> Community: {{ product.price }} </div> </li> </ul> </div> {% else %} <div class="no-products"> <h2>You have no current products.</h2> </div> {% endif %} {% endfor %} Any help would be greatly appreciated. Thank you. -
Annotate only returns specified grouping values - Django
I'm trying to sum column values of some rows with the a specific column value (currency_id) using annotate. My rows look like this: id | amount | currency_id | info1 | info2 1 | 14 | 1 | xxx | xxx 2 | 25 | 1 | xxx | xxx 3 | 92 | 2 | yyy | yyy And I want to get this: id | amount | currency_id | info1 | info2 1 | 39 | 1 | xxx | xxx 3 | 92 | 2 | xxx | xxx Here is my code: items = Item.objects.values('currency_id').annotate( Sum('amount'), ) Which works but I only get the column currency_id and the amount sum in the result: <QuerySet [{'currency_id': 1, 'amount__sum': 39}, {'currency_id': 2, 'amount__sum':92] This is because I use values() to specify the column to group. How can I get all other columns values? -
PermissionError: [Errno 13] Permission denied on Windows with WSL2 and Docker
I have a Docker dev setup that works fine on Mac and Windows with Hyper-V but not on Windows with WSL2. When Python attempts to execute a makedirs command, we get a PermissionError: [Errno 13] Permission denied error. For example, when attempting to make /code/static, we get: PermissionError: [Errno 13] Permission denied: '/code/static' Similarly for Django's makemigrations command, which attempts to make a migrations directory at /code/website/migrations we get: PermissionError: [Errno 13] Permission denied: '/code/website/migrations' But our Dockerfile clearly gives the apache user permission to the /code/ folder. Here's the full Dockerfile: # All Dockerfiles must start with a 'FROM' instruction, which specifies a base image # See: https://docs.docker.com/engine/reference/builder/#format # Note, some online sources say that you should put FROM django here (e.g., https://runnable.com/docker/python/dockerize-your-django-application) # but, in fact, you should NOT do this according to the official docs (as this approach has been deprecated). # See: https://hub.docker.com/_/django/ FROM python:3.8 # Sometimes we get warnings about old pip, so take care of that here RUN pip install --upgrade pip # See: https://www.quora.com/How-does-one-install-pip-in-a-Docker-container-using-a-Dockerfile RUN apt-get update && apt-get --assume-yes install imagemagick ghostscript sqlite3 # The ENV instruction sets the environment variable <key> to the <value> in ENV <key> <value>. # See: https://docs.docker.com/engine/reference/builder/#environment-replacement … -
how to show posts for a specific hour from its publishing time
I'm trying to show my posts for a specific time here is my models.py class Booking(models.Model): check_in = models.DateTimeField(default=timezone.now) check_out = models.DateTimeField(blank=True,null=True) i want display object for 12 hours after check out for example if we have an object its check out is 14/10/2021 10AM then show that post till 10PM ! i tried it , but didnt work Booking.objects.filter(check_out__hour=12) is it possible please ? thank you in advance -
No suggestion (autocomplete) for relation filed (1-to-many) in Django Model
For example two models: from django.db import models from datetime import datetime class Account(models.Model): date_field = models.CharField( max_length=255, verbose_name='Дата', help_text='Поле даты в BigQuery' ) class Lead(models.Model): account = models.ForeignKey( Account, on_delete=models.CASCADE, default=None, verbose_name='ID аккаунта BigQuery', ) def __str__(self): iso = self.data.get(f'{self.account.date_field}') date = datetime.fromisoformat(iso).strftime('%d-%m-%Y, %H:%M') return f'Lead by «{self.account}», created at {date}' VS Code doesn't see date_field in Lead.account. I have installed the Django, Python and Intellisense VS Code extension. Can i fit ix? -
Why static files giving not found error in django app?
I am creating a django app and everything going good so far, but I am having trouble with the static files. I have: STATIC_URL = '/static/' STATICFILES_DIRS = [ # Tell Django where to look for React's static files (css, js) os.path.join(BASE_DIR, "frontend/static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' When I am on home page then it is working fine, all static files are loaded perfectly but problem starts when I try to go to /dashboard Then I get Not Found error, when I debugged then the path for static files are like /dashoard/static/styles.css but it should be /static/styles.css. Why it is changing path for the static files? -
Django + Nginx corsheaders not visible for random endpoints
I am developing a web application with Django, Vue and Docker. For a while, I started to face the issue of CORS policy error. The weird thing is that the error sometimes appears and sometimes it does not appear - I can not detect what does it depend on. Usually there are some changes after rebuilding the whole project with command docker-compose up --build, however, I can not distinguish a single reason why am I getting CORS error on the server and localhost as well. The error message is as the following: Access to XMLHttpRequest at 'https://api.mywebsite.com/profile/' from origin 'https://mywebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I did setup CORS for Django, here's the configuration: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] # ... CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ 'https://mywebsite.com', # Here's where the web application is 'https://api.mywebsite.com', # Here's Django API ] Here's nginx.conf file: server { listen 80 default_server; client_max_body_size 20M; location / { autoindex on; if ($request_method = OPTIONS) { return 204; } add_header Access-Control-Allow-Origin "https://mywebsite.com"; add_header Access-Control-Allow-Origin "https://api.mywebsite.com"; add_header Access-Control-Max-Age 3600; add_header Access-Control-Expose-Headers Content-Length; add_header Access-Control-Allow-Headers Range; } location /static/ { autoindex on; alias /static/; } … -
Django Rest Framework - process result of serializer in another serializer
I have the following two views at my django api views.py: @api_view(['GET',]) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([AllowAny]) def user(request): if request.method == 'GET': serializer = UserSerializer(request.user) return JsonResponse(serializer.data, safe=False) @api_view(['POST']) @permission_classes([AllowAny]) def user_create(request): exception_handler = UserUnavailable success_handler = UserCreated if request.method == 'POST': serializer = CreateUserSerializer(data=request.data) try: if serializer.is_valid(raise_exception=True): serializer.save() return JsonResponse({"status_code": success_handler.status_code, "default_detail": success_handler.default_detail, "default_code": success_handler.default_code, "user_object": UserSerializer(serializer.instance) }, safe=False) except APIException: return JsonResponse({"status_code": exception_handler.status_code, "default_detail": exception_handler.default_detail, "default_code": exception_handler.default_code }, safe=False) What I want to do is that after the user has been created, I would like to show the user object in the API response, thats why I have UserSerializer(serializer.instance) in place but it seems that this statement is simply wrong. Can somebody help? -
Read value of an html script element in Angular, which is of type json
In the html page, there will be a script element which is a static content ( generated from a Django backend) with an ID. <script id="hello-data" type="application/json">{"hello": "world\\u003C/script\\u003E\\u0026amp;"}</script> I wanted to get that data in an angular service ( or even component) which would have a simple getElementById is javascript. const value = JSON.parse(document.getElementById('hello-data').textContent); I did a lot of searches, found answers pointing to "ViewChild", "@Inject(DOCUMENT)", but none of these works on a 'script' tag. Any pointers to solution would be really appreciated :) -
Object of type '' is not JSON serializable in DRF
I have this code in Django using the REST framework. Here are my models, serializer, views: model: class Car(AbstractTimeTrackable, models.Model): production_type = models.ForeignKey( 'cars.CarProductionType', on_delete=models.PROTECT, related_name='cars', verbose_name=_('production_type') ) warehouse = models.ForeignKey( 'warehouses.Warehouse', on_delete=models.SET_NULL, verbose_name=_('warehouse'), related_name='cars', blank=True, null=True, ) class Meta: verbose_name = _('Auto') verbose_name_plural = _('Auto') def __str__(self): return str(self.id) class Reservation(AbstractTimeTrackable, models.Model): is_active = models.BooleanField( default=False, verbose_name=_('is_active') ) cars = models.ManyToManyField( 'cars.Car', verbose_name=_('ID cars') ) class Meta: verbose_name = _('Reservation') verbose_name_plural = _('Reservation') def __str__(self): return str(self.id) serializer: class ReservationSerializer(serializers.ModelSerializer): days_count = serializers.IntegerField(required=True) cars = serializers.PrimaryKeyRelatedField(queryset=Car.objects.all(), many=True) class Meta: model = Reservation fields = [ 'id', 'is_active', 'cars' ] extra_kwargs = { 'id': {'read_only': True} } def create(self, validated_data): cars = validated_data.pop('cars') instance = super().create(validated_data) if cars: instance.cars.add(*cars) return instance view: class ReservationViewSet(CreateModelMixin, GenericViewSet): serializer_class = ReservationSerializer queryset = Reservation.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(status=status.HTTP_201_CREATED, data=serializer.validated_data) I am getting this error message: TypeError at /api/v1/reservations/ Object of type Car is not JSON serializable I need only PrimaryKey of Cars; that's why I use PrimaryKeyRelatedField. How can I resolve this error? -
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable
I had to reinstall my pycharm and now when I try to run my Django server I get the following error: (card_companion_venv) PS N:\My Drive\Projects\Card Companion\card_companion> python website/manage.py runserver 0.0.0.0:8000 --settings=website.settings.base Traceback (most recent call last): File "N:\My Drive\Projects\Card Companion\card_companion\website\manage.py", line 9, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "N:\My Drive\Projects\Card Companion\card_companion\website\manage.py", line 20, in <module> main() File "N:\My Drive\Projects\Card Companion\card_companion\website\manage.py", line 11, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The interpreter has the correct packages installed: and the terminal is using the virtual environment: (card_companion_venv) PS N:\My Drive\Projects\Card Companion\card_companion>