Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django displaying a static image through a variable from models that is in a JSON object
I have been trying to display an image using Django in my HTML. Normally do display a static file somebody would do: <img src="{% static 'user_profile_pics/pfp_2.jpg' %}" > This image static file has been stored in the variable picture in my models.py. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) picture = models.TextField(max_length=500) The user selects the image they want to choose as their profile image. The views.py file is below with the profile definition having the request JSON dictionary with the variable picture being assigned to the model profile.picture. @login_required def profile(request): profile = Profile.objects.get(user = request.user) return render (request, "profile.html", {"userinfo": {'bio': profile.bio, 'picture': profile.picture}}) def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] confirm_password = request.POST['confirm_password'] bio = request.POST['bio'] picture = request.POST['picture'] if password==confirm_password: if User.objects.filter(username=username).exists(): messages.info(request, 'Username is already taken') return redirect(register) elif User.objects.filter(email=email).exists(): messages.info(request, 'Email is already taken') return redirect(register) else: user = User.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name) user.save() profile = Profile(bio=bio, picture=picture, user=user) profile.save() return redirect('login_user') else: messages.info(request, 'Both passwords are not matching') return redirect(register) else: return render(request, 'registration.html') Next up, displaying the bio and picture within the profile html … -
How to include the JSON Schema definition of a JSONField inside the OpenAPI schema generated by drf-spectacular?
By default, when using drf-spectacular to generate the OpenAPI schema, the JSONField will be typed as object or array. However, I have a JSON Field which is validated against a JSON Schema and I'd like this JSON Schema to be included on the OpenAPI schema. I couldn't find this specific scenario described on the docs of drf-spectacular, but however, I tried modifying it using @extend_schema but with no success. The model looks like this: Car(models.Model): name = models.CharField() data = models.JSONField("Car Data", validators=[JSONSchemaValidator(limit_value=my_schema)]) On the generated OpenAPI schema, this is represented as: data: type: object additionalProperties: {} nullable: true title: Car Data I'm not including a sample on how it should look because I'm seeking answers where this is possible in some pre-defined way. -
base.html only showing the context data in the home page
I have a ListView for my homepage that displays extra data using the get_context_data method. It works, but only in the url of the HomeView, the homepage, not in other templates after I extend the base.html file. Everything else in base appears, the only thing that doesn't is the context data. HomeView class HomeView(ListView): model = Product context_object_name='products' template_name = 'main/home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) news = News.objects.all() ... context.update({ 'news' : news, ... }) return context base.html {% load static %} <body> <div class="navbar"> <a id="title" href="{% url 'home' %}">home</a> </div> ... <div class="side-bar"> <div class="article"> <h3>News</h3> {% for new in news %} <p>{{ new.title }}</p> {% endfor %} <a href="{% url 'news' %}"><p>See more</p></a> </div> </div> {% block content %}{% endblock %} ... </body> home.html {% extends 'main/base.html' %} {% block content %} <div> {% for product in products %} <p>Some text..</p> {% endfor %} {% endblock content %} Does this mean that I have to add a get_context_data method to every single view I have? Isn't that too repetitive and hard to change? -
Django models relation
The idea is that there are two models: Group and Player. My objective is that there are different Groups and each group has players. Each player can belong to one or more groups. Inside a group, each player has some points accumulated, but the same player can have different points accumulated in another group. 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) I am confused because I don't know how to make that a player has "x" points in group A (for example) and also has "y" points in group B. I want to be able to show the data of a group, for each group, show its members and their points. -
Django with docker compose can not open file '/code/manage.py
i am deploying to docker compose django with postgrest but the problem i have is when trying to deploy an app to django as i get the following output. [+] Running 1/0 ⠿ Container proyecto-db-1 Running 0.0s python: can't open file '/code/manage.py': [Errno 2] No such file or directory asterisk@localhost:~/Documentos/Programacion/django/Proyecto> I get this output by implementing the following code: docker compose run web python manage.py startapp aplicacion docker compose run web django-admin startproject proyecto the docker-compose.yml is: version: '3.9' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db The Dockerfile is: # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ requirements.txt: Django>=3.0,<4.0 djangorestframework==3.13.1 psycopg2>=2.8 and .env is: ## do not put this file under version control! SECRET_KEY='c_r-e8v1divj8y+hu@-w=n#$xj#ciuejybd3_(k2h789(mcv8$' DEBUG=False ## Super-User Credentials SUPER_USER_NAME = 'root' SUPER_USER_PASSWORD = 'root' SUPER_USER_EMAIL = 'admin@email.com' -
Setting an initial value of an extra field on a ModelForm from an UpdateView
I have a form which is a modelform with two extra fields. In my model, it includes a PointField which is made up of an easting and northing (the X & Y components of the Point). On my modelform, I do not display the PointField and instead display two DecimalFields for the easting and northing: class QuoteForm(forms.ModelForm): easting = forms.DecimalField() northing = forms.DecimalField() class Meta: model = Quote fields = ('desc', 'client', 'contact', 'amount', 'easting', 'northing', 'note') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['note'].required = True self.helper = FormHelper() self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Save Quote') ) For my CreateView I include a form_valid that takes the easting and northing and turns them into a point and updates the PointField record. For my UpdateView, I want to go backwards from the PointField and populate the Easting and Northing DecimalFields on my form. I am stuck on how to "pass" this information to my form. I tried a get_form in my UpdateView like this, but it fails: class QuoteUpdateView(PermissionRequiredMixin, UpdateView): permission_required = 'jobs.update_quote' redirect_field_name = 'dashboard' model = Quote form_class = QuoteForm template_name = "jobs/quote_form.html" template_name_suffix = '_form' def get_form(self, form_class=None): form = super().get_form(form_class) quote = self.object pt = quote.ptgeom pt.transform(2953) form.fields['easting'] … -
How do I redirect to the created page after I submitted the form Django
I'm trying to redirect to the created page after I've filled out and submitted a form. I have gotten it to work on the update form but not the create form. How do i do this? Here's what I have so far. Let me know if you need more details and code views.py @login_required(login_url='login') def createRoom(request): form = RoomForm() topics = Topic.objects.all() if request.method == 'POST': topic_name = request.POST.get('topic') topic, created = Topic.objects.get_or_create(name=topic_name) Room.objects.create( host=request.user, topic=topic, name=request.POST.get('name'), assigned=request.user, status=request.POST.get('status'), priority=request.POST.get('priority'), type=request.POST.get('type'), description=request.POST.get('description'), ) return render('room', pk=room.id) context = {'form': form, 'topics': topics, 'room': room} return render(request, 'room/room_form.html', context) But this throws this error 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\issue_env\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\mikha\issuetracker\base\views.py", line 68, in createRoom return render('room', pk=room.id) Exception Type: AttributeError at /create-room/ Exception Value: 'function' object has no attribute 'id' -
Join two queryset in Django ORM
I'm writing a view that returns this: [ { "field_id" : 1, "stock" : [ { "size" : "M", "total" : 3 } ], "reserved" : [ { "size" : "M", "total" : 1 } ] }, { "field_id" : 2, "stock" : [ { "size" : "M", "total" : 2 }, { "size" : "PP", "total" : 2 } ], "reserved" : [ { "size" : "PP", "total" : 1 }, { "size" : "M", "total" : 2 } ] } ] For this result, I used values and annotation(django orm): reserved = Reserved.objects.all().values("size").annotate(total=Count("size")).order_by("total") stock = Stock.objects.filter(amount=0).values('size').annotate(total=Count('size')).order_by('total')) It's ok for me, but I would like put the reserved queryset inside stock. Like this: [ { "field_id" : 1, "stock" : [ { "size" : "M", "total" : 3, "reserved": 1 } ], }, { "field_id" : 2, "stock" : [ { "size" : "M", "total" : 2, "reserved": 1 }, { "size" : "PP", "total" : 2, "reserved": 0 } ], } ] It's possibile? Reserved and Stock doesn't relationship. -
AAC/ADTS to WAV in Flutter/Django
My Team and I are building a speech-to-text application for a specific purpose. The frontend is in Flutter and the backend is in Django I am using the flutter_sound package for Flutter and the only Codec it supports for recording audio is Codec.aacADTS and I am able to save the file using .aac or .adts On the backend (Django), we're using the Speech Recognition Library and when using the .aac or .adts file with this, it gives an error: ValueError("Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format") We tried using another .wav file and speech recognition works. So, do I need to convert the .aac/.adts file to a .wav file? How should I do it, and should it be on the frontend or the backend? Any library/code snippets to help me with that? Frontend Code (Flutter) Future startRecord() async { setState(() { isRecording = true; }); Directory? dir = await getExternalStorageDirectory(); await recorder.startRecorder( toFile: "${dir!.path}/audio.aac", codec: Codec.aacADTS); } Future stopRecorder() async { final filePath = await recorder.stopRecorder(); final file = File(filePath!); uploadAudio(file); print('Recorded file path: $filePath'); setState(() { isRecording = false; audioFile = file; }); } … -
django - different save methods for user actions and admin action
I have some items connected to users. When every item is added, timestamp is created through inheritance of BaseModel on auto_now field. By mistake when i added new field and populated i updated timestamps. I resolved timestamps with some custom migrations and copy data methods in django. What i wonder - is there possibility to override save method on admin to do only update_fields (so in other words with that i would not update update_at timestamp), while on user actions i want to retain original django save method which would update timestamp. So basically is it possible to have two different save methods? I know that i can override save method - but i don't know if i can have two save methods at the same time. -
How to bind field in django model and celery worker result
The question is theoretical and I just want to understand in which direction to move. I have the model below. The user fills in the form (word, translation) and at the moment the form is saved, celery worker is launched to create an mp3 file of the "word" field. How to link created mp3 file and Word model? How to organize the storage of these files? Thank you very much for your attention. class Word(models.Model): word = models.CharField(max_length=50) translate = models.CharField(max_length=50) audio = models.FileField(upload_to='uploads/') def save(self, *args, **kwargs): #start the celery worker to generate mp3 self.word = self.word.lower() super().save(*args, **kwargs) How to link created mp3 file and Word model? How to organize the storage of these files? -
comparing two (same) functions with same id <function ... at 0x7f490f225900> returns False in Django Middleware
I've created a middleware that modifies one argument for a view in process_view method. As this should do that to one particular view only, I'm comparing callback argument with the view function like this: from third_party_app import view_func class ModifyCodeKwargForViewFuncMiddleware(MiddlewareMixin): def process_view(self, request, callback, callback_args, callback_kwargs): if callback is view_func: raw_code = callback_kwargs["code"] normalized_code = utils.normalize_code(raw_code) return view_func(request, normalized_code) return None This works correctly on my development server; callback is view_func is True But it doesn't work on the server on heroku. I've logged callback and view_func right before comparing it and I noticed that their identifiers are the same (also on the heroku server), which is even weirder: class ModifyCodeKwargForViewFuncMiddleware(MiddlewareMixin): def process_view(self, request, callback, callback_args, callback_kwargs): logging.warning(f"callback is `{callback}`") logging.warning(f"imported view_func is `{view_func}`") logging.warning(f"callback is view_func {callback is view_func}") if callback is view_func: raw_code = callback_kwargs["code"] normalized_code = utils.normalize_code(raw_code) return view_func(request, normalized_code) return None The log entries look like this: callback is `<function view_func at 0x7f490f225900>` imported view_func is `<function view_func at 0x7f490f225900>` callback is view_func False How is this possible and how can I make it work? -
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?