Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where does the smartselect URLS belong?
I'm trying to set op SmartSelect in my django project so I can chain dropdown menu's. I do not understand how/where the urls belongs for the installation? urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^chaining/', include('smart_selects.urls')), ) This is what their official installation guide says. Though this is either and old version of Django or i'm doing something wrong as I have not seen any URLS file written this way before and VScode does not recognize it. What am I doing wrong? -
ModuleNotFoundError: No module named 'Authentication.apps' ( Only On Hosting)
All my Django apps are working perfectly on a local server, and when I host it and build it every other app/Module is being found except for Authentications.apps List of Installed Apps INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Appointments.apps.AppointmentsConfig', 'Chattings.apps.ChattingsConfig', 'Finance.apps.FinanceConfig', 'Authentication.apps.AuthenticationConfig', 'Feedbacks.apps.FeedbacksConfig', 'Inventory.apps.InventoryConfig', 'Settings.apps.SettingsConfig', 'rest_framework', 'corsheaders', 'fcm_django', 'cloudinary_storage', 'cloudinary', ] All other apps e.g. Appointments.apps, Chattings.apps, Inventory.apps are being loaded and all of them are on the same directory level. And the thing to be noted is that the same code/app is working on local env If I remove the Authentication.apps part then the app is getting hosted perfectly [2022-11-29 19:24:54 +0000] [1] [INFO] Starting gunicorn 20.1.0 [2022-11-29 19:24:54 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) [2022-11-29 19:24:54 +0000] [1] [INFO] Using worker: sync [2022-11-29 19:24:54 +0000] [16] [INFO] Booting worker with pid: 16 BASE_DIR in this APP = /workspace/DigiLabBackEnd [2022-11-29 19:25:00 +0000] [16] [ERROR] Exception in worker process Traceback (most recent call last): File "/workspace/.heroku/python/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/workspace/.heroku/python/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/workspace/.heroku/python/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/workspace/.heroku/python/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/workspace/.heroku/python/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File … -
Assign a verbose_name in django admin
Is there any way to change verbose_name of a field in django admin ? For example, I have a Model A with field example_1. In django admin I want to associate any verbose_name to this field class ModelA(models.Model): example_1 = models.CharField(max_length=50, verbose_name='foo') -
Cannot connect .js files with html files in django
I am unable to connect my index.js file with Django and index.html Django is connected to index.html fine but not to index.js. I have attached my settings.py, urls.py, index.html, webpack.config.js, and index.js files below. settings.py: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent STATICFILES_DIR = os.path.join(BASE_DIR, 'static') TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = 'static/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [STATICFILES_DIR,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', ], }, }, ] In settings.py DEBUG=True urls.py: from django.contrib import admin from django.urls import path from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('hello/', TemplateView.as_view(template_name='index.html')) ] index.html: {% load static %} <!doctype html> <html> <head> <title>NEPTUNE Analytics</title> </head> <body> <script src="{% static 'index-bundle.js' %}"></script> </body> </html> webpack.config.js: const path = require('path'); module.exports = { entry: './js/index.js', // path to our input file output: { path: path.resolve(__dirname, './static'), // path to our Django static directory filename: 'index-bundle.js', // output bundle file name }, }; index.js: function component() { const element = document.createElement('div'); element.innerHTML = 'Hello World'; return element; } document.body.appendChild(component()) I have tried changing DIRS in settings.py … -
Django project on AWS not updating code after git pull
stackoverflowers. I am a Django newbie and I am having an issue. It's my first time ever deploying a Django project on AWS. I am running Postgres, Redis, Nginx as well as my project on Docker there. So everything is working fine, but when I change something on my local machine, push changes to git and then pull them on the AWS instance, the code is not refreshing at all. Only the static files are updating automatically (I guess because of Nginx). Here is my docker-compose config: version: '3.9' services: redis: image: redis command: redis-server ports: - "6379:6379" postgres: image: postgres environment: - POSTGRES_USER= - POSTGRES_PASSWORD= - POSTGRES_DB= ports: - "5432:5432" web: image: image_name build: . restart: always command: gunicorn project.wsgi:application --bind 0.0.0.0:8000 env_file: - envs/.env.prod ports: - "8000:8000" volumes: - ./staticfiles/:/tmp/project/staticfiles depends_on: - postgres - redis nginx: image: nginx ports: - "80:80" - "443:443" volumes: - ./staticfiles:/home/app/web/staticfiles - ./nginx/conf.d:/etc/nginx/conf.d - ./nginx/logs:/var/log/nginx - ./certbot/www:/var/www/certbot/:ro - ./certbot/conf/:/etc/nginx/ssl/:ro depends_on: - web Can you please tell me what to do? Please keep in mind I really am a newbie so if you would be kind to explain it I would be forever grateful! Thanks in advance! I tried deleting everything from docker and … -
Django model gives "TypeError: Object of type UUID is not JSON serializable" error on object create [closed]
I have created a django model as below : class ProjectHistory(models.Model): uuid = models.UUIDField(default=uuid4, editable=False) history = JSONField(default=dict, blank=True, null=True) version = models.PositiveIntegerField(default=0) sequence = models.PositiveIntegerField(default=0) project = models.ForeignKey(Project, related_name='projecthistory', on_delete=models.CASCADE) def Meta(self): unique_together = ("sequence", "project") def save(self, *args, **kwargs): sequence_list = ProjectHistory.objects.filter(project=self.project) self.sequence = sequence_list.count() + 1 super(ProjectHistory, self).save(*args, **kwargs) When I create the object for ProjectHistory model as below : sequence_list = ProjectHistory.objects.filter(project=project) projecthistory = ProjectHistory.objects.create(project=project, history=old_manifest) I see the following error : [29/Nov/2022 18:40:34] INFO [views.py:30] ProjectManifest GET begin [29/Nov/2022 18:40:34] INFO [views.py:203] Subtitle GET success 8 [29/Nov/2022 18:40:34] INFO [views.py:88] ProjectManifest GET end [29/Nov/2022 18:40:34] "GET /project/6e4f263f-3ed3-472c-8311-9202d29a4c4f/ HTTP/1.1" 200 8281 [29/Nov/2022 18:40:39] INFO [views.py:97] ProjectManifest POST begin: 6e4f263f-3ed3-472c-8311-9202d29a4c4f USER DATA : None [29/Nov/2022 18:40:39] INFO [views.py:133] ProjectManifest POST get project [29/Nov/2022 18:40:39] INFO [views.py:143] Project POST has a workspace : 119d535e-1bb0-4e95-b946-4d3ac4d16e0f but no workspacemember [29/Nov/2022 18:40:39] INFO [views.py:147] False - Workspace object (2) - None - None The history : {'fps': 24, 'text': {}, 'asset': {}, 'title': 'Your Video - 6e4f263f3ed3472c83119202d29a4c4f', 'width': 1080, 'height': 1920, 'images': {}, 'videos': {}, 'effects': {}, 'filters': {'preset': ''}, 'version': 1.0, 'bg_color': '00000000', 'duration': 0, 'elements': {}, 'subtitles': {}, 'user_uuid': None, 'audio_only': False, 'created_at': '2022-11-29 16:24:06', 'updated_at': '2022-11-29 16:24:06', 'subtitle_url': … -
Celery 4.4 + Redis - long ETA tasks, default_timeout
We are using Celery (celery==4.4.7) along with Redis broker We have some long ETA tasks with some tasks having ETA of now + 7 days. We were getting issues of the celery tasks being executed multiple times and during debugging we found that the reason is because default_timeout is 1 hour I looked here: celery tasks with long eta (8+ hours) are executed multiple times in a row when eta is reached and https://docs.celeryq.dev/en/4.4.0/getting-started/brokers/redis.html#visibility-timeout We want to increase the default_timeout to 7 days or a bit longer to 8 days. app.conf.broker_transport_options = {"visibility_timeout": 864000} Are there any negative consequences of doing this? -
Modelos Django. Relaciones [closed]
La idea es que hayan dos modelos, Grupo y Jugador. Mi objetivo es que hayan distintos Grupos y que cada grupo tenga jugadores, cada jugador puede pertenecer a más de un grupo. Dentro de un grupo, el jugador tiene cierto puntaje, pero dentro de otro grupo, el jugador puede tener otro puntaje distinto. class Player(models.Model): username = models.CharField(max_length = 200) won_games = models.IntegerField(default=0) class Point(models.Model): player = models.ForeignKey(Player, on_delete=models.PROTECT, related_name='points') val = models.IntegerField() group = models.ForeignKey(Group, on_delete=models.PROTECT, related_name='points') class Group(models.Model): id = models.CharField(max_length = 200) players = models.ManyToManyField(Player,related_name="groups") points = models.ManyToManyField(Point) Lo que me está costando es cómo aclarar que el jugador tiene una cantidad x de partidas ganadas en el grupo A y también tiene una cantidad "y" de partidas ganadas en el grupo B. -
Django - Loop and Return in JS or in Python?
In general, if making a Post call from JS to the backend, how to best handle a loop while keeping the UI interactive? For example, if I have a function to update multiple files, should I loop the Ajax calls in Javascript, and wait for each file edit function return at once to display on the web page? Wouldn't this risk losing data/interrupting the process if the web page is closed? On the flip side, sending all the data to the backend would remove that risk, but since only 1 Return can happen, the UI wouldn't be ideal/dynamic. Are database writes/reads the solution to this conundrum, or am I missing something? Cheers. -
How to set lookup_field of GenericViewSet with JSONfield key?
How do I set the lookup_field with a key in JSONField model? The model: exchange = models.ForeignKey(StockExchange, on_delete=models.CASCADE, related_name='tickers') fundamentals = models.JSONField(null=True, blank=True) The viewset: class StockCardsV2ViewSet(BaseGetViewSet): search_fields = ('^fundamentals__General__Name', '^fundamentals__General__Code') filter_backends = (filters.SearchFilter,) queryset = Ticker.objects.all() serializer_class = StockCardsV2Serializer lookup_value_regex = '[0-9a-zA-Z_.]+' lookup_field = 'fundamentals__General__Code' The Serializer: class Meta: model = Ticker fields = ('id', 'url', 'name', 'ticker', 'logo_url', 'currency_symbol', 'sector', 'industry', 'esg_rating', 'weekly_prices', 'monthly_prices', 'yearly_prices', 'two_yearly_prices', 'ad', 'in_watchlist') lookup_field = 'fundamentals__General__Code' extra_kwargs = { 'url': {'lookup_field': 'fundamentals__General__Code'}, } There are no problems with search_fields but I get this error for the lookup_field. 'Ticker' object has no attribute 'fundamentals__General__Code' Example fundamentals: "fundamentals": { "General": { "CIK": null, "LEI": null, "Code": "SATX-WTA", "ISIN": null, "Name": "Satixfy Communications Ltd.", } }, -
AttributeError at /profile/1/ 'User' object has no attribute 'room_set
I created profile page and out of nowhere it just broke. Everything was working fine but then it just broke outta nowhere. I have no clue what's wrong Here is my code and traceback. Let me know if more detail and code is needed. views.py def userProfile(request, pk): user = User.objects.get(id=pk) rooms = user.room_set.all() room_messages = user.message_set.all() topics = Topic.objects.all() context = {'user': user, 'rooms': rooms, 'room_messages': room_messages, 'topics': topics} return render(request, 'authentication/profile.html', context) traceback Traceback (most recent call last): File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mikha\issuetracker\users\views.py", line 59, in userProfile rooms = user.room_set.all() Exception Type: AttributeError at /profile/1/ Exception Value: 'User' object has no attribute 'room_set' -
DRF - Upload a valid image
Hope someone would be able to help me out here. I am trying to update an image on a table called MyCards, when updating this image the system should then look to see if this image contains certain word, if so then the field points would be increased by one. But, when trying to update the image I get the following error { "image": [ "Upload a valid image. The file you uploaded was either not an image or a corrupted image." ] } Not sure how to solve this issue, if anyone could help on it, would be great. please find here my model, viewset and serializer MODEL: class MyCards(models.Model): profile = models.ForeignKey(AppUserProfile, on_delete=models.CASCADE) card = models.ForeignKey(Cards, on_delete=models.CASCADE) points = models.IntegerField(default=0) image = models.ImageField(upload_to=f'media/app_user/', blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.card.business.business_name VIEWSET class MyCardsViewSet(ModelViewSet): serializer_class = UpdateMyCardsSerializer queryset = MyCards.objects.all() def update(self, request, pk=None, *args, **kwargs): super().update(request, *args, **kwargs) x = self.get_object() img = f"media/{x.image}" result = pytesseract.image_to_string(img) if "Petel Chang" in result: x.points += 1 return self.update(request, *args, **kwargs) SERIALIZER class UpdateMyCardsSerializer(serializers.ModelSerializer): class Meta: model = MyCards fields = ('profile', 'card', 'points', 'created', 'updated', 'image') -
DRF: Overwrite inculded default endpoints to custom views
So I am using dj-rest-auth with Simple-JWT. My urls.py is: urlpatterns = [ path('dj-rest-auth/', include('dj_rest_auth.urls')), ] But I want to update a specific endpoint of dj-rest-auth.urls to a custom view: path('dj-rest-auth/login/', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair') Simply adding both the lines together ain't doing the job. dj-rest-auth/login/ gives the default view only. How shall I overwrite it? -
Django lookup by JSONField array value
Let's say I have MySQL database records with this structure { "id": 44207, "actors": [ { "id": "9c88bd9c-f41b-59fa-bfb6-427b1755ea64", "name": "APT41", "scope": "confirmed" }, { "id": "6f82bd9c-f31b-59fa-bf26-427b1355ea64", "name": "APT67", "scope": "confirmed" } ], }, { "id": 44208, "actors": [ { "id": "427b1355ea64-bfb6-59fa-bfb6-427b1755ea64", "name": "APT21", "scope": "confirmed" }, { "id": "9c88bd9c-f31b-59fa-bf26-427b1355ea64", "name": "APT22", "scope": "confirmed" } ], }, ... Any way I can filter all of the objects who's actors name contains '67', for example? Closest variant I have is that I got it working like that: queryset.filter(actors__contains=[{"name":"APT67"}]) But this query matches by exact actor.name value, while I want to to accept 'contains' operator. I also have it working by quering with strict array index, like this: queryset.filter(actors__0__name__icontains='67') But it only matches if first element in array matches my request. And I need that object shall be returned in any of his actors matches my query, so I was expecting something like queryset.filter(actors__name__icontains='67') to work, but it's not working :( So far I have to use models.Q and multiple ORs to support my needs, like this - search_query = models.Q(actors__0__name__icontains='67') | models.Q(actors__1__name__icontains='67') | models.Q(actors__2__name__icontains='67') | models.Q(actors__3__name__icontains='67') queryset.filter(search_query) but this looks horrible and supports only 4 elements lookup(or I have to include more … -
Project with django,docker,celery,redis giving error/mainprocess] cannot connect to amqp://guest:**@127.0.0.1:5672//: [errno 111] connection refused
I'm trying to create a Django project with celery and redis for the messaging service using docker-compose. I'm getting Cannot connect to amqp://guest:**@127.0.0.1:5672. I'm not using guest as a user anywhere or 127.0.0.1:5672 and amqp is for RabbitMQ but I'm not using RabbitMQ. So, I don't know if my docker-compose volumes are not set correctly for celery to get the settings, where is it getting amqp from, or is the broker miss configured. docker-compose.yml: version: '3' network networks: data: management: volumes: postgres-data: redis-data: services: nginx: image: nginx ports: - "7001:80" volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro - ../static:/static command: [nginx-debug, '-g', 'daemon off;'] networks: - management depends_on: - web db: image: postgres:14 restart: always volumes: - postgres-data:/var/lib/postgresql/data/ - ../data:/docker-entrypoint-initdb.d # import SQL dump environment: - POSTGRES_DB=link_checker_db - POSTGRES_USER=link_checker - POSTGRES_PASSWORD=passw0rd networks: - data ports: - "5432:5432" web: image: link_checker_backend build: context: . dockerfile: Dockerfile environment: - DJANGO_LOG_LEVEL=ERROR - INITIAL_YAML=/code/initial.yaml volumes: - ../:/code - ../link_checker:/code/link_checker - ../link_checker_django/:/code/link_checker_django - ./settings.py:/code/link_checker_django/settings.py working_dir: /code command: > sh -c " python manage.py migrate --noinput && python manage.py collectstatic --no-input && python manage.py runserver 0.0.0.0:7000 " networks: - data - management depends_on: - db redis: image: redis volumes: - redis-data:/data networks: - data celery-default: image: link_checker_backend volumes: - ../:/code … -
DRF - Unable to log in with provided credentials
I tried to get a token from django rest framework. bigissue@vmi995554:/opt/ftusbrdp/sbin$ http POST http://172.18.0.1:7000/api-token-auth/ username='nicola' password="Password12345" HTTP/1.1 400 Bad Request Allow: POST, OPTIONS Content-Length: 68 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Tue, 29 Nov 2022 14:19:40 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.9.15 X-Content-Type-Options: nosniff X-Frame-Options: DENY { "non_field_errors": [ "Unable to log in with provided credentials." ] } I have create superuser and also a normal user from admin web gui. All users are active. What I'm missing? Here down is my configuration. I have import module app like rest_framework and rest_framework.authtoken, I set REST_FRAMEWORK variable for token use. Then I call views.obtain_auth_token methods to get string token. The settings.py file. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appjud', 'rest_framework', 'rest_framework.authtoken' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', ), } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbjud', 'USER': 'root', 'PASSWORD': 'Password19', 'HOST':'localhost', 'PORT':'3306', } } The router.py file from appjud.viewsets import userviewsets from rest_framework import routers router = routers.DefaultRouter() router.register('user', userviewsets, basename ='user_api') The serialiers.py file class userSerializers(serializers.ModelSerializer): class Meta: model = User fields = '__all__' The viewsets.py file from rest_framework import viewsets from .serializers import userSerializers from django.contrib.auth.models import User class userviewsets(viewsets.ModelViewSet): queryset … -
Django- Template not found
I can't seem to get my delete, edit and add review functionality working. The errors come as soon as I try to navigate to the urls I have set up. When I try and add a new review using my link on the reviews page I get the below message: TemplateDoesNotExist at /reviews/add I don't understand why because I have linked the url above to the template, which I have created. The issue I have with my edit/delete views is that the url it searches for when I click the button is just /edit/ or /delete/ rather than reviews/edit/int:pk or reviews/delete/int:pk as per my urls. I have pasted my code below, any help would be much appreciated! I have the feeling I am going to kick myself when I realise! reviews.html: {% extends "base.html" %} {% load static %} {% block content %} <div class="container-fluid home-container"> <div class="row align-items-center"> <div class="col-sm-12 text-center mt-4"> <h2><strong>Reviews</strong></h2> </div> </div> {% for review in reviews %} <hr class="hr-1"> <div class="row featurette"> <div class="col-sm-12"> <h2 class="featurette-heading">{{ review.title }}</h2> <p class="lead">{{ review.content }}</p> <div class="row justify-content-between mx-1"> <p>By: {{ review.user }}</p> <p>Created on: {{ review.created }}</p> <p>Last Updated: {{ review.updated }}</p> </div> <!-- Add user authentication … -
Getting Datefield after Today and Before another date not returning the expected object
I am writing an app in Django where I have created a PayPeriods model as such: class PayPeriods(models.Model): first_day = models.DateField(default=date.today) last_day = models.DateField(default=date.today) pay_day = models.DateField(default=date.today) I've created a small function that allows me to get the current PP through my app, def get_pp(): _pp = PayPeriods.objects.filter(first_day__gte=datetime.today())[0] return _pp but its not returning as expected. What am I missing? Current day today is 11/29/2022, so I am expecting to return Obj #4, as the code is written. PP Object #3: first_day = 11/13/22, last_day = 11/26/22 PP Ojbect #4: first_day = 11/17/22, last_day = 12/10/22 PP Ojbect #5: first_day = 12/11/22, last_day = 12/24/22 I have verified that my dates are formatted the same way, (stored data & datetime.today(), and my timezone settings are correct.). -
How to set a logic that only event attendant can give review regarding an event in drf?
i'm new in drf i'm managing event management system, i tried to count event attendees and only event attendees can review about event. i facing issue to in review model. i manage attendees in Event model with ManyToManyField. here my models , class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="event_user") attendees = models.ManyToManyField(User, blank=True, related_name='attendees_user') venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='venue_user') event_type = models.CharField(max_length=50, choices=event_type) event_name = models.CharField(max_length=25) start_time = models.DateTimeField(blank=False, null=True) end_time = models.DateTimeField(blank=False, null=True) def __str__(self): return f'{self.venue} - {self.event_name}' class Reviews(models.Model): reviewer = models.ForeignKey(User, on_delete=models.CASCADE, related_name="reviewer_user") event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name="event") review = models.TextField() class Meta: verbose_name_plural = "Reviews" def __str__(self): return f'{self.reviewer} -- {self.review} -- {self.event}' here my serializers class EventSerializer(serializers.ModelSerializer): images = serializers.ListField( child=serializers.FileField(allow_empty_file=True, use_url=True, ), required=False) class Meta: model = Event fields = ( 'id', 'user', 'attendees', 'venue', 'event_type', 'event_name', 'start_time', 'end_time', 'images') def create(self, validated_data): uploaded_data = validated_data.pop('images') attendees = validated_data.pop('attendees') instance = Event.objects.create(**validated_data) instance.attendees.set(attendees) instance.save() for pics in uploaded_data: EventImages.objects.create(event=instance, event_pics=pics) return instance def to_representation(self, instance): response = super(EventSerializer, self).to_representation(instance) response["venue_name"] = instance.venue.venue_name response["start_time"] = instance.start_time.strftime("%d/%m/%Y, %H:%M:%S") response["end_time"] = instance.end_time.strftime("%d/%m/%Y, %H:%M:%S") return response def validate(self, data): if data.get("start_time") > data.get("end_time"): raise serializers.ValidationError("'End time' must be after 'Start time'.") else: pass if Event.objects.filter( (Q(venue=data['venue']) & … -
How do I test views in Django Rest Framework that make calls to other apis/ google earth engine
A lot of views on my project makes http requests to other services, and one of the views makes a call to google earth engine service. How do I go about testing these components? Should I just let them make the calls and make my tests depend on an internet connection? Is there a design structure in which I can choose to mock the request data? -
Update is creating new entry rather than updating it
I have a model where users save their details. I am able to save user details through the template I have created. But whenever I edit the data to update it, a new entry is created in database models.py class User(AbstractUser): pass def __str__(self): return self.username class Detail(models.Model): """ This is the one for model.py """ username = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default="") matricno = models.CharField(max_length=9, default="") email = models.EmailField(default="") first_name = models.CharField(max_length=200, default="") last_name = models.CharField(max_length=255, default="") class Meta: verbose_name_plural = "Detail" def __str__(self): return self.first_name+ " "+self.last_name views.py @login_required(login_url="signin") def details(request): form = Details() if request.method == "POST": form = Details(request.POST) if form.is_valid(): detail = form.save(commit=False) detail.username = request.user detail.save() return redirect(success, pk=detail.pk) else: form = Details(initial={"matricno":request.user.username}) return render(request, "details.html", {"form":form}) def success(request,pk): return render(request, "success.html", {"pk":pk}) def updatedetails(request, pk): detail = Detail.objects.get(id=pk) form = Details(instance=detail) if request.method == "POST": form = Details(request.POST, instance=detail) if form.is_valid(): form.save() return redirect(success, pk=detail.pk) return render(request, "details.html", {"form":form}) urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("details/", views.details, name="details"), path("success/<int:pk>/", views.success, name="success"), path("edit/<int:pk>/", views.updatedetails, name="updatedetails"), ] The template used for rendering out the form to input user details goes as follows <!DOCTYPE html> <html lang="en"> <head> … -
Get values of Enum fields from Django Queryset
I have a model with an enum column, e.g. from django_enum_choices.fields import EnumChoiceField class Service(Enum) MOBILE: "MOBILE" LAPTOP: "LAPTOP" class Device(models.Model): service = EnumChoiceField(Service) ... Is it possible to get get the query results with the enumerated column being the value of the enum? For example: If I do: query = Device.objects.values("service") print(query) I get: <QuerySet [{'service': <Service.MOBILE: 'MOBILE'>}, {'service': <Service.MOBILE: 'MOBILE'>}, {'service': <Service.LAPTOP: 'LAPTOP'>}]> I wish to get: <QuerySet [{'service': 'MOBILE'}, {'service': 'MOBILE'}, {'service': 'LAPTOP'}]> I get errors when I run: query = Device.objects.values("service__value") or query = Device.objects.values("service.value") I want to something like how we can get value of an enum field by saying mobile_service = Service.MOBILE # <Service.MOBILE: "MOBILE"> mobile_service_as_string = mobile_service.value # "MOBILE" The errors: django.core.exceptions.FieldError: Cannot resolve keyword 'value' into field. Join on 'service' not permitted. django.core.exceptions.FieldError: Cannot resolve keyword 'service.value' into field. Choices are: service, .. -
Django Selenium Parsing Data
How can return WebDriver=auth in function parameters? I have a task.py file in which, first, in the login function, I use Selenium to log in to my personal account, then the form_fill function receives the Url parameters in which the form is filled, and the WebDriver and returns the data and the driver. I'm trying in views.py to first call the login function for authorization and return the WebDriver to another form_fill function. task.py def login(url): driver = webdriver.Chrome(service=service,options=options) driver.maximize_window() driver.get(url) driver.find_element(By.ID,"login").send_keys(LOGIN) driver.find_element(By.ID,"password").send_keys(PASSWORD) driver.find_element(By.ID,'bind').click() return driver def form_fill(url_pars,driver,name_flat): driver.get(url_pars) driver.find_element(By.ID,"epd_field").click() codplat=driver.find_element(By.CLASS_NAME,"home_right").text driver.find_element(By.XPATH,'//span[contains(text(),"name_flat}")]'.format(name_flat)).click() driver.find_element(By.CLASS_NAME,"js-find-btn").click() driver.find_element(By.CLASS_NAME,"js-more-btn").click() driver.find_element(By.CLASS_NAME,"btn-close-pop").click() return [driver,codplat] views.py class AuthView(TemplateView): template_name="mos_sel/login.html" def get_context_data(self, **kwargs) : context=super().get_context_data(**kwargs) # login(URL_LOGIN) return WebDriver in auth auth=login(URL_LOGIN) return context views.py class PaymentListView(AuthView,ListView): template_name='mos_sel/parse_list.html' model=Flat context_object_name='fields' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['name_flat']=Flat.objects.get(pk=self.kwargs['pk']).name_flat # How get WebDriver in parameters call form_fill function forma_fill=form_fill(GET_USLUGA_URL,auth,context['name_flat'].upper()) return context login.html {% extends "base.html" %} {% block content %} <h3>Enter for authorization</h3> <a href="{% url 'AuthView' %}"><button type="button" class="btn btn-success">Enter</button></a> {% endblock content %} parse_list.html {% extends "base.html" %} {% block sidebar %} <h5>{{name_flat}}</h5> {% for field in fields %} {{field.cod_platelshika}} {{field.period_oplaty}} {{field.summa}} {% endfor %} {% endblock sidebar %} I want get WebDriver in function fill_form parameters -
Render multiple models with pk in a single view
I'm trying to pass lesson.price, and lesson.invoice_id from Lesson model and student.student_id from Student Model into the single view so that I can display them in a template. However, Lesson model has a field "student" which has a foreign key to User, not to Student model. You will see my code for view class is wrong since I have no clue how to get a proper student object with a primary which is used for lesson object. How could I get a proper student object with lesson_id primary key in view class? class User(AbstractUser): '''User model for authentication and lessons authoring.''' class Role(models.TextChoices): ADMIN="ADMIN",'Admin' STUDENT="STUDENT",'Student' TEACHER="TEACHER",'Teacher' id = models.AutoField(primary_key=True) username = models.CharField( max_length=30, unique=True, validators=[RegexValidator( regex=r'^@\w{3,}$', message='Username must consist of @ followed by at least three alphanumericals.' )] ) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True, blank=False) gender = models.CharField(max_length=255) address = models.TextField(default='') baseRole = Role.ADMIN role = models.CharField(max_length=50, choices=Role.choices) created_at = models.DateTimeField(default=timezone.now, blank=True) updated_at = models.DateTimeField(default=timezone.now, blank=True) def save(self, *args, **kwargs): self.role = self.baseRole return super().save(*args, **kwargs) def __str__(self): return self.first_name+" "+self.last_name class Student(User): student_id = models.CharField(max_length=10, default=uuid.uuid4) baseRole = User.Role.STUDENT student = StudentManager() class Lesson(models.Model): lesson_id = models.AutoField(primary_key=True) lesson_name = models.CharField(max_length=255) student = models.ForeignKey(User,on_delete=models.DO_NOTHING,related_name='studying', unique=True) teacher … -
Is it possible to pass command line arguments to a decorator in Django?
I have a decorator that is supposed to use a parameter that's passed in from the commandline e.g @deco(name) def handle(self, *_args, **options): name = options["name"] def deco(name): // The name should come from commandline pass class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( "--name", type=str, required=True, ) @deco(//How can I pass the name here?) def handle(self, *_args, **options): name = options["name"] any suggestions on this?