Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Merge two models with one-to-one relationship into one model serializer (Django)
In Django Rest, I have a model named User which is used as AUTH_USER_MODEL. In order to expand this model and separate authentication-related fields with additional information, I have created another model named Profile. Profile contains unrelated data like age, height, country, zip_code, and so on. These two models have one-to-one relationship. I need a special endpoint which is only accessed by admin and used for creating a user and its profile in one request. For this purpose, I need a flat serailizer like this: { "username": "something", "password": "1234", "email": "user@domain.com", "age": 43, "country": "USA" } I tried creating a class inheriting serailizers.Serializer and create fields manually, but this seems very unengineered. Also imagine what happens if later on I add new fields to these models. Also, I could include ProfileSerializer inside UserSerializer and I would have: { "username": "something", "password": "1234", "email": "user@domain.com", "profile": { "country": "USA", // and rest of fields } } I need a flat serializer combining two (or even more) models that have one-to-one relationship.The serializer must contain all required fields of these two models. What should I do? -
Mobile Browser stripping out 10 digit numbers
I have a Django app that takes user text and relays it to another user. In some cases the text includes 10 digit phone numbers or 10 digit authorizations. On mobile devices our users are reporting that any 10 digit number is being removed from the input field. Base.html <!DOCTYPE HTML> <html lang="en"> <head> {% load static tags bootstrap4 %} <!-- <link rel="icon" type="image/png" sizes="96x96" href="{% static 'invoiceManager/images/favicon-96x96.png'%}"> --> {% appName as name %} <title>{{name}} Job Manager</title> <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate"> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="format-detection" content="telephone=no" /> <!-- <meta name="description" content="Use this HTML basic website two percentage column layout template where the navigation menu and the extra stuff are at the same width on the left column, the main content is on the right column."> <meta name="generator" content="HAPedit 3.1"> <link rel="canonical" href="https://www.w3docs.com/snippets/html/layout_templates/26.html" /> <meta property="og:type" content="website" /> <meta property="og:title" content="{{name}}" /> <meta property="og:description" content="Generic ERP system" /> <meta property="og:image" content="https://www.w3docs.com/build/images/logo-amp.png" /> <meta property="og:image:type" content="image/jpeg" /> <meta property="og:image:width" content="192" /> <meta property="og:image:height" content="192" /> <meta property="og:image:alt" content="W3dcos" /> --> {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <script … -
Setting initial form field value for superuser in Django
I have form for writing comments and I want "author" field to be "admin" for default if the logged user is superuser. I also want to hide the "author" field form for the superuser. model: class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) author = models.CharField(max_length=20) text = models.TextField() publication_date = models.DateTimeField() def ___str___(self): return self.text form: class CreateComment(forms.ModelForm): class Meta: model = Comment fields = ["author", "text"] def __init__(self, *args, **kwargs): super(CreateComment, self).__init__(*args, **kwargs) ChatGPT suggested me to add this to the form: if kwargs.get("user").is_superuser: self.fields["author"].widget = forms.HiddenInput() self.fields["author"].initial = "admin" but I got this error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/14/ Django Version: 4.1.7 Python Version: 3.9.7 Installed Applications: ['mainapp.apps.MainappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Tomasz\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "C:\Users\Tomasz\anaconda3\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Tomasz\Desktop\myblog\mainapp\views.py", line 41, in article_view form = CreateComment() File "C:\Users\Tomasz\Desktop\myblog\mainapp\forms.py", line 23, in init if kwargs.get("user").is_superuser: Exception Type: AttributeError at /14/ Exception Value: 'NoneType' object has no attribute 'is_superuser' I appreciate any help, thanks. -
Django ModelForm doesnt show up
/*I made a website before and ı exactly copy paste modelform part what was before but ı m getting error on my current website */ /*This is my model, */ from django.db import models class AppModel(models.Model): name = models.CharField(max_length=50,verbose_name='Name') email = models.CharField(max_length=100,verbose_name='E-mail') subject = models.CharField(max_length=50,verbose_name='Subject') message = models.TextField(verbose_name='Message') /This is my form,/ from django import forms from App.models import AppModel class UserForm(forms.ModelForm): class Meta: model = AppModel fields = '__all__' /* This is my view, */ from django.shortcuts import render,redirect from .forms import UserForm def SupportForm(request): form = UserForm(request.POST or None) context = dict( form = form ) if form.is_valid(): newForm = form.save() return redirect('support') return render(request,'support.html',context) /* And This is my html, */ {% extends 'layout.html' %} {% load crispy_forms_tags %} {% block container %} {% load static %} <div class="container" style="height: 100vh; display: flex; justify-content: center; align-items: center;"> <div> <h2>Communicate</h2> <hr> <form method="post" action="{% url 'support' %}"> {% csrf_token %} {{ form|crispy }} <!-- {{ form.as_p }} --> <button type = "submit" value = "Submit" class = "btn btn-warning">Ekle</button> </form> </div> </div> {% endblock %} -
django rest framework simple post method with two related objects
I am trying to create a simple Django Rest Framework application storing a listening history, which consists of a ListeningHistory, a Track and an Artist model. Each ListeningHistory record is related to one track, and each track is related to one or multiple artists. If a track or an artist already exists, it should re-use that record and not try to create a new one. models.py: class Artist(models.Model): name = models.CharField(max_length=255, unique=True) #TODO: should be unique in combination w/ probably some other stuff class Track(models.Model): title = models.CharField(max_length=255, unique=True) #TODO: should be unique in combination w/ artists and album artists = models.ManyToManyField(Artist) album = models.CharField(max_length=255, null=True) class ListeningHistory(models.Model): class Meta: ordering = ['-played_at'] played_at = models.DateTimeField(unique=True) track = models.ForeignKey(Track, on_delete=models.PROTECT) serializers.py: class ArtistSerializer(serializers.ModelSerializer): class Meta: model = Artist fields = '__all__' class TrackSerializer(serializers.ModelSerializer): artists = ArtistSerializer(many=True) class Meta: model = Track fields = '__all__' def create(self, validated_data): artists_data = validated_data.pop('artists') track, created = Track.objects.get_or_create(**validated_data) artists = [Artist.objects.get_or_create(name=artist_data['name'])[0] for artist_data in artists_data] track.artists.set(artists) return track class ListeningHistorySerializer(serializers.ModelSerializer): track = TrackSerializer() class Meta: model = ListeningHistory fields = '__all__' def create(self, validated_data): track_data = validated_data.pop('track') artists_data = track_data.pop('artists') track, created = Track.objects.get_or_create(**track_data) artists = [Artist.objects.get_or_create(name=artist_data['name'])[0] for artist_data in artists_data] track.artists.set(artists) listening_history = … -
Django cannot open downloaded zip file
I want to download a note with all attached files to a zip file in Django by clicking a button. That's the view: def download_note(request, pk): note = get_object_or_404(Note, pk=pk) file_path = f'notes/media/downloaded_notes/note{note.id}.txt' notefiles = NoteFile.objects.filter(note=note) urls = [f.file.url for f in notefiles] if get_language() == 'en': content = f'Title: {note.title}, Author: {note.user}, Date: {note.add_date.strftime("%d-%m-%Y %H:%M:%S")}\n' \ f'Category: {note.category}\n' \ f'Note:\n{note.note_text}' else: content = f'Tytuł: {note.title}, Autor: {note.user}, Data: {note.add_date.strftime("%d-%m-%Y %H:%M:%S")}\n' \ f'Kategoria: {note.category}\n' \ f'Notatka:\n{note.note_text}' with open(file_path, 'w', encoding='utf-8') as f: f.write(content) zip_file_path = f'notes/media/downloaded_notes/note{note.id}.zip' with zipfile.ZipFile(zip_file_path, 'w') as zipf: zipf.write(file_path, os.path.basename(file_path)) media_root = settings.MEDIA_ROOT.replace('\\', '/') print(media_root) for url in urls: print(f'{media_root}{url[6:]}') #file_url = os.path.join(media_root, url[6:]) #zipf.write(file_url, os.path.basename(url[6:])) file_name = os.path.basename(url) zipf.write(f'{media_root}{url[6:]}', file_name) with open(zip_file_path, 'rb') as f: response = FileResponse(f.read(), content_type='application/zip') response['Content-Disposition'] = f'attachment; filename="note{note.id}.zip"' return response When I click download button Chrome hangs for few seconds and then file is downloaded. But zip file in Downloads directory is not working. When I am trying to open it there is a message saying that the file's format is invalid or file is broken. But when I go to django project and to media/downloaded_notes/note70.zip everything works fine. So I think an issue is in this fragment: with open(zip_file_path, 'rb') … -
How can I add or do some multiplcations and let my user change their CharField values in Django Application
I need an Explanation and Advice to make my small project like I would given my users "money, not real money just some numbers" and let them spend on my items and I need a way to know how can I make the money usable on the money they have like addition the money amount and subtraction on the amount of their money, I need an Advice and Explanation please. I've tried to do these things and they are not working, my mind is blowing and I need help -
How to filter an item in one queryset from appearing in another queryset in django
I have a Django view where I am getting the first queryset of 'top_posts' by just fetching all the Posts from database and cutting it in the first four. Within the same view, I want to get "politics_posts" by filtering Posts whose category is "politics". But I want a post appearing in 'top_posts', not to appear in 'politics_posts'. I have tried using exclude but it seems like it`s not working. Below is my view which is currently not working: def homepage(request): top_posts = Post.objects.all()[:4] politics_posts = Post.objects.filter(category='news').exclude(pk__in=top_posts) context={"top_posts":top_posts, "politics_posts":politics_posts} return render(request, 'posts/homepage.html', context) Any help will be highly apprecuiated. Thanks. -
how to do dependent drop down in Django
how to do dependent drop down in Django, showing errors anyone [enter image description here] (https://i.stack.imgur.com/vMzmb.png) how to get output like branches corresponding to states [enter image description here] (https://i.stack.imgur.com/fR5lj.png) is it possible without Django forms, only with views -
How can I store the response from a third party API as instance in a Django model
I am building a web API in DRF. And there's this third party API whose response returns fields like ip_address, latitude, longitude, etc. I have a user model(which is basically inherited from an AbstractBaseUser) that contains fields like email, username, first_name and last_name. Creating an instance of this user model works. But what I want to do is save response from this third party API as an instance of a model called Artist that has a OneToOneField with the user model whenever an instance of this user model is saved. How can I do this? Note: I am letting Djoser, a third party library for handling authentication, take care of the authentication endpoints on my user model. So no views involved in this project so far yet it works. -
grouping is giving wrong data if order_by is added
I have a model Lead. It has column deal_value. I want to get the count of leads for the given buckets for deal_value. Buckets are from 0 to 1000 --> '<=1000' from 10001 to 100000 --> '<=100000' So I annotate the queryset with 'bucket' and group by bucket and perform aggregation on it. below is the code: import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'design_studio_app.settings') django.setup() from dashboard.utils import get_accessible_objects_for_a_user from accounts.models import User from dashboard.qfilters import get_q_created_at from django.db.models import Case, When, CharField, Value from django.db.models import Count user = User.objects.get(pk=1529) # get the queryset queryset = get_accessible_objects_for_a_user( 'Leads', user) # get the leads which are created this month queryset = queryset.filter(get_q_created_at('this_month')) queryset = queryset.order_by('deal_value') measure_group_metric = 'deal_value' min_value = 0 max_value = 100000 queryset = queryset.filter( **{measure_group_metric+"__gte": min_value, measure_group_metric+"__lte": max_value}) case_conditions = [ When(**{measure_group_metric+"__gte": 0, measure_group_metric+"__lte": 1000}, then=Value('<=1000')), When(**{measure_group_metric+"__gte": 10001, measure_group_metric+"__lte": 100000}, then=Value('<=100000')) ] queryset = queryset.annotate( bucket=Case( *case_conditions, default=None, output_field=CharField(), ) ) annotated_data = queryset.values('bucket').annotate(count=Count('id',allow_distinct=True)) print(annotated_data) The annotated_data is <SoftDeleteQuerySet [{'bucket': '<=1000', 'count': 26}, {'bucket': None, 'count': 1}, {'bucket': '<=100000', 'count': 8}, {'bucket': '<=100000', 'count': 1}, {'bucket': '<=100000', 'count': 1}]> So the count is wrong. we can see that bucket bucket': '<=100000' is repeated. However if I remove order_by('deal_value'). … -
Problem in Django Testing with Selenium ( TypeError : expected str, bytes or os.PathLike object, not NoneType )
I am currently running a testing to check whether if there is any problem with client-side rendering in Django. Therefore, I am running a loop to visit every route available in the Django project and record the browser console. The code is as follows : class SeleniumTest2(LiveServerTestCase): def setUp(self) -> None: super(MySeleniumTests, self).setUp() User = get_user_model() self.superuser = User.objects.create_superuser('superuser', 'superuser@example.com', 'password') self.client.login(username='superuser', password='password') models = apps.get_models() factories = generate_dynamic_factories_2(models) for model_name, factory_class in factories.items(): instances = factory_class.create_batch(10) for instance in instances : instance.save() def tearDown(self): self.selenium.quit() super(MySeleniumTests, self).tearDown() if(check_library_selenium()): def test_client_side(self): urls = get_urls() driver = webdriver.Edge() live_server = self.live_server_url for url in urls: driver.get( str(live_server) + url) # Print or use the console output as needed logs = driver.get_log('browser') print(url, logs) driver.quit() else : print(RED+'Client-side checker skipped'+RESET) And the error are as follows : Traceback (most recent call last): File "/Users/zulfathihanafi/.pyenv/versions/3.9.16/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/test/testcases.py", line 1723, in __call__ return super().__call__(environ, start_response) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 124, in __call__ response = self.get_response(request) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/test/testcases.py", line 1706, in get_response return self.serve(request) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/test/testcases.py", line 1718, in serve return serve(request, final_rel_path, document_root=self.get_base_dir()) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/views/static.py", line 34, in serve fullpath = Path(safe_join(document_root, path)) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/utils/_os.py", line 17, … -
Django Installation on Windows 10
I'm a newbie when it comes to Django framework, just want to ask if what drive is it recommended to install Django, should I follow YT vids that installs on desktop or should I put it in more specific path. Thanks As for now I haven't tried to install it, I'm still gathering opinions from experts to reduce flaws and errors in the future. :) -
django.db.utils.OperationalError: (2002, "Can't connect to server on 'mysql' (115)")
I did find some related questions, but the answers don't work. I think the problem might be the configuration problem. When I run sudo docker-compose up, it create 4 images. But the error occurs like that: rest | Performing system checks... rest | rest | System check identified no issues (0 silenced). rest | Exception in thread django-main-thread: rest | Traceback (most recent call last): rest | File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection rest | self.connect() rest | File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner rest | return func(*args, **kwargs) rest | File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 270, in connect rest | self.connection = self.get_new_connection(conn_params) rest | File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner rest | return func(*args, **kwargs) rest | File "/usr/local/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 247, in get_new_connection rest | connection = Database.connect(**conn_params) rest | File "/usr/local/lib/python3.10/site-packages/MySQLdb/__init__.py", line 121, in Connect rest | return Connection(*args, **kwargs) rest | File "/usr/local/lib/python3.10/site-packages/MySQLdb/connections.py", line 193, in __init__ rest | super().__init__(*args, **kwargs2) rest | MySQLdb.OperationalError: (2002, "Can't connect to server on 'mysql' (115)") rest | rest | The above exception was the direct cause of the following exception: rest | rest | Traceback (most recent call last): rest | File "/usr/local/lib/python3.10/threading.py", line 1016, in _bootstrap_inner rest | self.run() rest … -
Is there a way to use chain and group with celery?
Im building a solution using python, django rest framework, celery and rabbitmq to run some tasks in my api project. However some tasks may be done in parallel and others not. I tried this solution using chord and group, but in these two ways the last task(task_9) never is executed, all the others previous tasks are executed with success. When i tried chord i put task_9 as a callback function, but even this doesn't work. Here is an example of my code. chain(task_1.si(registry_id, name) | task_2.si(registry_id, name) | task_3.si(registry_id, name) | group(task_4.s(task_3_result), task_5.s(task_3_result), task_6.s(task_3_result), task_7.s(task_3_result), task_8.s(task_3_result), ) | task_9.si(registry_id, name) ).apply_async() -
Django settings.py can't import my local module
My Django tree looks like this git/src ├── myproject │ ├── settings.py │ ├── mysharedlib.py │ └── urls.py └── www ├── urls.py └── views.py It works except that in settings.py I have import mysharedlib But this raises an exception ModuleNotFoundError: No module named 'mysharedlib' Why isn't this working? -
Forbidden: /api/v1/token/logout/ "POST /api/v1/token/logout/ HTTP/1.1" 403 58
I am experiencing this problem following a tutorial and I can't identify the error in my "MyAccountView.vue" page. I tried changing to re_path and it did not work. Forbidden: /api/v1/token/logout/ [16/Oct/2023 19:01:35] "POST /api/v1/token/logout/ HTTP/1.1" 403 58 CODE: URLS.PY from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')) ] SETTING.PY REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSESS':( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSESS':( 'rest_framework.permissions.IsAuthenticated', ) } ERROR IMAGES Getting this error in browser's console MyAccountView.vue If it works i'm supposed to forward on "/" or home page of my site. methods: { logout() { axios .post("/api/v1/token/logout/") .then(response => { axios.defaults.headers.common["Authorization"] = "" localStorage.removeItem("token") this.$store.commit('removeToken') this.$router.push('/') }) .catch(error => { if (error.response) { console.log(JSON.stringify(error.response.data)) } else if (error.message) { console.log(JSON.stringify(error.message)) } else { console.log(JSON.stringify(error)) } }) } } -
How can I serialize the Transaction model in django rest framework
There are two reasons why the Transaction model should have a sender and receiver and assign them to the CustomUser model with different related names. It could help answer questions like: Who initiated the Transaction? Who received the funds? We want to serialize this model because our company intends to use React.js as the frontend of the application. I would like to know how to validate the serialization to ensure that the sender can send funds from their account to another. As you can see this view, I created it based on django template: def transfer(request): if request.method == 'POST': account_number = request.POST['account_number'] amount = Decimal(request.POST['amount']) superuser_account = Account.objects.get(user='superuser username') # set this username to the admin username or your preferred account. sender_account = Account.objects.get(user=request.user) receiver_account = Account.objects.get(account_number=account_number) interest_rate = 0.02 deduction = amount * interest_rate if sender_account.account_balance >= amount: sender_account.account_balance -= amount sender_account.save() receiver_account.account_balance += amount receiver_account.save() superuser_account.account_balance += deduction superuser_account.save() Transaction.objects.create( sender=request.user, receiver=receiver_account.user, amount=amount, account_number=account_number ) return redirect ('Transfer') else: messages.error(request, 'Insufficient Funds') return redirect ('Transfer') return render(request, 'transfer.html') This view checks if the sender account balance is greater than or equal to the specified transfer amount. If the sender doesn't have enough funds, it sets an error … -
Regex for username allows for more than one special character
The regex I have is not working as I intend it to. It should not allow for more than one special character and the special character should not be the starting character of the username. The below regex allows for more than one special character and it also for the special character to be the starting character. regex=r'^(?=.{6,15})(?=.*[a-z])(?=.*[@-_]).*$', Valid Input : user@site Invalid Inputs, user@@site, @usersite I tried to alter the Regex it mulitple ways, but not able to achieve the desired output -
How to assign user and user.profile to the request object using a single database query in django?
Django assign user to request in the django.contrib.auth.middleware.py by calling request.user = SimpleLazyObject(lambda: get_user(request)) The get_user function is in the init.py file which in turns calls another get_user function in the backends.py def get_user(self, user_id): try: user = UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None Here it is making a database call to get user by id. How can I get the user profile(related to user by a one to one field) in the same query and propagate it back so I can assign it to request.profile? -
Follow up to https://stackoverflow.com/questions/77300502/django-turn-off-on-pagination-for-one-filter-request/77300948#77300948
As mentioned in the question from title, I have 2 models, 1 Product and 1 for ProductImages. class Product(models.Model): title = models.CharField(max_length=200) details = models.TextField(null = True) slug = models.CharField(max_length=300, unique=True, null=True) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_imgs') image = models.ImageField(upload_to='product_imgs/', null=True) def __str__(self): return self.image.url My view for fetching list of products is, def get_queryset(self): qs = super().get_queryset() if self.request.method == 'GET': if 'category' in self.request.GET: category = self.request.GET['category'] category = models.ProductCategory.objects.get(id=category) qs = qs.filter(category=category) if 'owner' in self.request.GET: print('get_queryset Owner') owner = self.request.GET['owner'] qs = qs.filter(owner=owner) if 'available' in self.request.GET: available = self.request.GET['available'] == 'true' qs = qs.filter(available=available) results = [] for product in qs: images = models.ProductImages.objects.filter(product=product.id) results.append({'product': product, 'images': images}) return JsonResponse({ 'status': 'success', 'result': results, }) I am getting an error saying TypeError: Object of type Product is not JSON serializable on line return JsonResponse({ I couldn't find a solution for returning response which is combination of 2 different models. Can anybody please help me solving this issue? PS: I don't want to get the list of products in frontend and then make network call/calls to get images associated with them. -
DRF spectacular creates tags, can't figure out where to remove(
class EquipmentViewSet(ReadOnlyModelViewSet): queryset = Equipment.objects.all() serializer_class = EquipmentSerializer @extend_schema( summary='Получение списка всех объектов класса "Оборудование"', tags=['Equipment'], description=""" Получение списка всех оборудования. В ответе будет получен полный список объектов класса "Оборудование". """, request=EquipmentSerializer, responses=equipment_status_codes ) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) In the swager, in addition to tags=['Equipment'], tag = v1 is created where /api/v1/equipment/{id}/ is located. I tried everything, I want to cry, extend_schema_view doesn't help in any way -
How to get rid of this extra gap in my Django website?
I deployed this website, which can be seen by pasting the URL in the browser. RFP Website If you see the homepage, you can see that on the right, it seems to scroll infinitely and I am getting a huge gap, which is not in other pages. How to get rid of this? -
How can I properly Query data from a django model without
im trying to create a simple django app for buying and selling shares but im having trouble querying my data properly specifically the amount of available shares. These are my models: from django.db import models from accounts.models import CustomUser class Share(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) quantity_available = models.PositiveIntegerField() def __str__(self): return self.name class Transaction(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) share = models.ForeignKey(Share, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() total_price = models.DecimalField(max_digits=10, decimal_places=2) transaction_date = models.DateTimeField(auto_now_add=True) is_purchase = models.BooleanField() then these are my views: from django.shortcuts import render, redirect from .models import Share, Transaction from .forms import BuyShareForm, SellShareForm def buy_share(request): share = Share.objects.filter(quantity_available__gt=100) form = BuyShareForm(request.POST or None) if request.method == 'POST' and form.is_valid(): quantity = form.cleaned_data['quantity'] if quantity <= share.quantity_available: transaction = Transaction(user=request.user, share=share, quantity=quantity, total_price=quantity * share.price, is_purchase=True) transaction.save() share.quantity_available -= quantity share.save() return redirect('shares:buy-success') else: form.add_error('quantity', 'Insufficient shares available') context = { 'share': share, 'form': form, } return render(request, 'shares/buy_share.html', context) def sell_share(request): share = Share.objects.all() form = SellShareForm(request.POST or None) if request.method == 'POST' and form.is_valid(): quantity = form.cleaned_data['quantity'] transaction = Transaction(user=request.user, share=share, quantity=quantity, total_price=quantity * share.price, is_purchase=False) transaction.save() share.quantity_available += quantity share.save() return redirect('shares:sell_success') return render(request, 'shares:sell_share.html', {'form': form}) when i try to get the … -
Cannot redirect with forwardauth Traefik middleware
How to actually switch(redirect) to another page (login page) with Traefik ForwardAuth ? I'm using the following docker labels: 'traefik.http.routers.my-route.rule=Host("main.int")' 'traefik.http.routers.my-route.entrypoints=https443' 'traefik.http.routers.my-route.tls=true' 'traefik.http.routers.my-route.middlewares=my-test-auth@docker 'traefik.http.middlewares.my-test-auth.forwardauth.address=https://auth.page.int/login/' 'traefik.http.middlewares.my-test-auth.forwardauth.tls.insecureSkipVerify=true' Traefik logs shows that is accessing the auth.page.int/login page: GET /accounts/login/ HTTP/2.0" 200 3459 but browser stays on the main page. BTW redirect works with RedirectRegex middleware for the same example. Documentation: https://doc.traefik.io/traefik/middlewares/overview/