Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - problem with concat in F expression
I have a query that gives the number of matched options. I managed to use annotate with Count and F expressions however Django is dividing my products into matched filters on the page. What I want is to have a product that will contain the product title, the number of matched filters, and a list of matched filters. product_list = product_list.annotate(client_type_product_count=Count('client_type', filter=Q(client_type__title__in=client_type)), client_type_title=F('client_type__title')).exclude(client_type_product_count__exact=0).distinct() Right now a page with results looks like on the screenshot below. The first value is the name of the product, the second (numeric value) is the number of matched options (so how many checkboxes user selected and are matching to this product) and the third is the option(s) name: But what I want is this: How can I achieve something like this? -
Is there a way to save a query in django and use it later?
I have a service that prints the incoming data to excel. This service works exactly as follows. I'm building the query but not running it. I dump and save the query with the help of "pickle", load and use it again with pickle in the celery task. This has worked on all my models so far. But in the model below, the pickle gives an error. django version=3.2 The Money Field I used in the model is here. django-money==3.0.0 class PaymentStatus: WAIT = 1 SUCCESS = 2 FAIL = 3 CANCEL = 4 types = ( (WAIT, _('Waiting')), (SUCCESS, _('Success')), (FAIL, _('Fail')), (CANCEL, _('Cancel')) ) class PaymentModel(models.Model): class Meta: app_label = 'betik_app_payment' indexes = [ models.Index(fields=['dt', 'user_email']) ] provider = models.PositiveIntegerField(choices=PaymentProviderTypeEnum.types) is_test = models.BooleanField(default=True) payment_status = models.PositiveIntegerField(choices=PaymentStatus.types, default=PaymentStatus.WAIT) price = MoneyField(max_digits=20, decimal_places=2, help_text=_('amount paid excluding tax and discount')) paid_price = MoneyField(max_digits=20, decimal_places=2, help_text=_('amount paid including tax and discount')) dt = models.DateTimeField() user_email = models.EmailField(null=True, blank=True) token = models.CharField(max_length=255, null=True, blank=True, help_text=_('This token comes from the payment system. With this token, inquiries are made in the payment system')) locale = models.CharField(max_length=10, default="en") pickle error: _pickle.PicklingError: Can't pickle <function QuerySet.distinct at 0x7faf69912430>: it's not the same object as django.db.models.query.QuerySet.distinct qs=PaymentModel.objects.filter(dt__date__lte="2030-01-01") pickle.dumps(qs) #raise … -
If it possible to filter out names of objects returned in Django Admin
For my Django CMS Admin I would like to prevent it returning a specific object to the CMS. What is the best way to do this? I would like to do something like class MyModuleAdmin(admin.ModelAdmin): list_display = ['name'] list_filter = ('my_module__name__is_not=moduleidontwant',) -
Django Rest Framework : how to specify a serializer to use different fields to create, update and get
I have a doubt with the serializers and so far I have not been able to solve it. I explain the doubt with the following example: I have a User model and this model has the following attributes: username, password, first_name, last_name, age, gender. I also have a serializer, which is called UserSerializer. The UserSerializer should do the following: When inserting information into the database, UserSerializer should only take into account the fields: username, password, first_name, last_name. When retrieving information from the database, UserSerializer should only take into account the fields: age, gender. When updating the database information, UserSerializer should only take into account the fields: password. My solution: class UserSerializer: class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password', 'first_name', 'last_name'] class UserGetSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['age', 'gender'] class UserUpdateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['password'] Question: The question: is there any way to synthesize the three serializers into one, or what is the best solution for this problem? Thank you very much. -
javastript get input element by checkbox
I have a table with 2 columns: checkbox and quantity. <form action="{% url 'create-order' %}" method="POST"> {% csrf_token %} <table class="table table-responsive table-borderless"> <thead> <th>&nbsp;</th> <th>Quantity</th> </thead> <tbody> {% for item in items %} <tr class="align-middle alert border-bottom"> <td> <input type="checkbox" id="check" name="item" value="{{ item.id }}" onclick={changeQuantityState(this)}> </td> <td> <input class="input" min="1" value=1 type="number" name="quantity"> </td> </tr> {% endfor %} </tbody> </table> <div class="submitButton"> <button type="submit" class="lgbtn green">Go to order</button> </div> </form> I have a handler for the checkbox: if checkbox is checked, then I can select the quantity. Otherwise, the quantity disabled. function changeQuantityState(checkbox) { checkbox.addEventListener('change', function(event) { var quantity = document.getElementById('qnt'); if (event.currentTarget.checked) { quantity.disabled = false; quantity.value = 1; } else { quantity.disabled = true; quantity.value = 0; } }); } I need change this line: var quantity = document.getElementById('qnt'); because I need the quantity for the current row in the table, for the current checkbox, but this code line return first quantity. -
How to fix the timezone in django while filtering datas from database
views.py: def index(request): if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date, '%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) global roles roles = Scrapper.objects.all() # for i in roles: # print(i.description) global find_description # find_description = Scrapper.objects.all().filter(created_at=f_date,updated_at=t_date) find_description = Scrapper.objects.all().filter(created_at=f_date,updated_at=t_date) print(find_description) models.py from django.db import models from django.db import connections from django.utils import timezone # Create your models here. class Scrapper(models.Model): id = models.IntegerField(primary_key=True) full_name = models.CharField(max_length=100) slug = models.CharField(max_length=100) description = models.TextField(max_length=100) created_at = models.DateTimeField(default=True) updated_at = models.DateTimeField(default=True) class Meta: db_table = "test_table_1" When I pass the data as filter to the database to get value there occurs error RuntimeWarning: DateTimeField Scrapper.created_at received a naive datetime (2022-11-09 00:00:00) while time zone support is active. My f_date= "2022-11-09 00:00:00" . Is there any solution for removing error -
Django celery results does not store task results
The problem speaks for itself - django-celery-results does not store any task results. I did everything as it was described in 'getting started' section in documentation, but still no results. I'm using django 4.1.2 and django-celery-results 2.4.0 Here is related variables from settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://redis:6379', } } CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://redis:6379") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BACKEND", "django-db") CELERY_CACHE_BACKEND = "django-cache" CELERY_RESULT_EXTENDED = True I also tried database cache - nothing changed. How can I get this to work? -
django - Createview add error message when none of checkboxes is checked
I'm struggling with adding error message when none of checkboxes is selected in my template. Now in my CreateView I've got following code to get value of checkboxes: def form_valid(self,form): box1=form.cleaned_data['box1'] box2=form.cleaned_data['box2'] How to produce an error when user doesn't click any of them? -
Cache form data against page refresh
I have certain forms in my Django project and I want to get a different data with a button on this form with a pop-up window and save it to the database. But here, how can I make the previously entered data come back when the page is reloaded so that my background data is not lost? Thanks in advance to everyone who helps. -
How to get the values from the table based on dates from datetime field django
views.py from django.shortcuts import render import pymysql from django.http import HttpResponseRedirect from facligo_app.models import Scrapper from django.utils import timezone import datetime import pytz find_description = "" def index(request): if request.method == "POST": from_date = request.POST.get("from_date") print(from_date) to_date = request.POST.get("to_date") print(to_date) roles = Scrapper.objects.all() # for i in roles: # print(i.description) global find_description find_description = Scrapper.objects.all().filter(created_at=from_date,updated_at=to_date) print(find_description) return render(request, "home.html", {"scrappers": find_description}) models.py from django.db import models from django.db import connections # Create your models here. class Scrapper(models.Model): id = models.IntegerField(primary_key=True) full_name = models.CharField(max_length=100) slug = models.CharField(max_length=100) description = models.TextField(max_length=100) created_at = models.DateTimeField(default=True) updated_at = models.DateTimeField(default=True) class Meta: db_table = "test_table_1" From my form I will post data where my from_date = "2022-11-09" and to_date = "2022-11-09". But my table column has time with date. Is there any solution to get the data based on only date I post. But my table should not make any alter. -
celery periodic task with view function
I have created periodic tasks to send mails only once as per the given time as below using post save signals class MailTask(models.Model): name = models.CharField(max_length=100, blank=True) subject = models.CharField(max_length=100) message = models.TextField() from_email = models.EmailField() recipient = models.EmailField() sent = models.BooleanField(default=False) time_to_send = models.DateTimeField() def create_periodic_task(sender, instance, created, **kwargs): if created: time_to_send = instance.time_to_send clocked_schedule, created = ClockedSchedule.objects.get_or_create( clocked_time=time_to_send ) periodic_task = PeriodicTask.objects.create( clocked=clocked_schedule, name=instance.name, task='core.tasks.send_mail_func', one_off=True, ) post_save.connect(create_periodic_task, sender=MailTask) the function to be called is as below @shared_task def send_mail_func(): mail_task = MailTask.objects.last() send_mail( mail_task.subject, mail_task.message, mail_task.from_email, [mail_task.recipient], fail_silently=False, ) This will run only the last instance of the email task, how I can loop through all the instance and send mail, or how I can connect the periodic task id the corresponding mail function -
PostgresSQL connection refused on docker container in same server
I have postgresSQL database running docker on server when i spin up another container for django app and trying to connect postgress getting connection error. any idea? django.db.utils.OperationalError: connection to server at "localhost" (127.0.0.1), port 6545 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (::1), port 6545 failed: Cannot assign requested address Is the server running on that host and accepting TCP/IP connections? -
How to call AsyncWebsocketConsumer functions from different files in Django
this is consumers.py class ChatConsumer(AsyncWebsocketConsumer): async def receive(self, text_data): pass this is my view.py class CreateChatMessageView(APIView): ... message_obj = ChatMessage.objects.create(chat_room=chat_room_obj, sender_id=sender_id, receiver_id=receiver_id, message_text=message_text, message_attachment=message_attachment) # here I want to call the 'receive' function from 'ChatConsumer(AsyncWebsocketConsumer):' message_obj.save() ... I want to call the receive function from ChatConsumer(AsyncWebsocketConsumer):. How can I have done? -
FILTERING AN ARRAY IRREGARDLESS OF THE ARRANGEMNT (Python)
Am trying to save this data from a callback url but the arrangement keeps changing, how do I fetch the data without use of index {"Body":{ "stkCallback":{ "MerchantRequestID":"106225-49293961-1", "CheckoutRequestID":"ws_CO_041120220958559137xxxxx768", "ResultCode":0, "ResultDesc":"The service request is processed successfully.", "CallbackMetadata":{ "Item":[ {"Name":"Amount","Value":1.00}, {"Name":"MpesaReceiptNumber","Value":"QK438EQIOX"}, {"Name":"TransactionDate","Value":20221104095914}, {"Name":"PhoneNumber","Value":2547xxxxx178} ] } } } } This is what I have done merchant_requestID = mpesa_body["Body"]["stkCallback"]["MerchantRequestID"] print(merchant_requestID) checkout_requestID = mpesa_body["Body"]["stkCallback"]["CheckoutRequestID"] print(checkout_requestID) result_code = mpesa_body["Body"]["stkCallback"]["ResultCode"] print(result_code) result_desc = mpesa_body["Body"]["stkCallback"]["ResultDesc"] print(result_desc) amount = mpesa_body["Body"]["stkCallback"]["CallbackMetadata"]["Item"][0]["Value"] print(amount) mpesa_receipt_number = mpesa_body["Body"]["stkCallback"]["CallbackMetadata"]["Item"][1]["Value"] print(mpesa_receipt_number) transaction_date = mpesa_body["Body"]["stkCallback"]["CallbackMetadata"]["Item"][2]["Value"] print(transaction_date) phone_number = mpesa_body["Body"]["stkCallback"]["CallbackMetadata"]["Item"][3]["Value"] print(phone_number) balance = '' Some transaction will have balance other will not have and that is where the error comes in because of fetching the data using index. Advice on how to save the data, more so the Item list without use of index. -
Calculate %-deviation with values from a pandas Dataframe
I am fairly new to python and I have the following dataframe setting_id subject_id seconds result_id owner_id average duration_id 0 7 1 0 1680.5 2.0 24.000 1.0 1 7 1 3600 1690.5 2.0 46.000 2.0 2 7 1 10800 1700.5 2.0 101.000 4.0 3 7 2 0 1682.5 2.0 12.500 1.0 4 7 2 3600 1692.5 2.0 33.500 2.0 5 7 2 10800 1702.5 2.0 86.500 4.0 6 7 3 0 1684.5 2.0 8.500 1.0 7 7 3 3600 1694.5 2.0 15.000 2.0 8 7 3 10800 1704.5 2.0 34.000 4.0 What I need to do is Calculate the deviation (%) from averages with a "seconds"-value not equal to 0 from those averages with a seconds value of zero, where the subject_id and Setting_id are the same i.e. setting_id ==7 & subject_id ==1 would be: (result/baseline)*100 ------> for 3600 seconds: (46/24)*100 = +192% ------> for 10800 seconds: (101/24)*100 = +421% .... baseline = average-result with a seconds value of 0 .... result = average-result with a seconds value other than 0 The resulting df should look like this setting_id subject_id seconds owner_id average deviation duration_id 0 7 1 0 2 24 0 1 1 7 1 3600 2 46 192 … -
populating multiple forms at once in django
I want to populate 'n' forms with my data. Some data will be from database and some from session. 'with this i get the info from session and have it in my view. store/view.py class AddProductToCartView(View): def get(self, request, pk): cart = request.session.get("cart") if cart: for item in cart: if item["id"] == pk: item["quantity"] += 1 break else: cart.append({"id": pk, "quantity": 1}) request.session["cart"] = cart else: request.session["cart"] = [{"id": pk, "quantity": 1}] return redirect("store:cart_view") class CartView(View): def get(self, request): in_cart = [] overall_price = 0 overall_tax = 0 if "cart" in request.session: overall_price = 0 for item in request.session["cart"]: product = Product.objects.select_related("category").get(id=item["id"]) total_price = product.price * item["quantity"] tax = (total_price * product.tax) in_cart.append({ "product": product, "quantity": item["quantity"], "total_price": total_price, "tax": tax }) overall_price += total_price overall_tax += tax part of data will be from a form checkout/forms.py class AddOrderInfoForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['order_by'].disabled = True self.fields['created'].disabled = True class Meta: model = Order fields = '__all__' and checkout/view.py class OrderView(CreateView): template_name = 'order/order_view.html' form_class = AddOrderInfoForm success_url = reverse_lazy('checkout_view') def get_initial(self): return {'order_by': self.request.user} and i want to populate my model several times (depending on the length of my 'cart' dictionary i guess..) model.py class Order(models.Model): order_by … -
Using postgresql with Django
I keep getting this error in the web page Using postgresql. pgadmin 4 Unauthorized The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env('DB_NAME'), 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': env('DB_HOST'), 'PORT': env('DB_PORT'), } } What can i do to fix this issue -
Getting TransactionManagementError on bulk_create with mysql db
I'm trying to create a few objects using Django's bulk_create but I'm getting TransactionManagementError. Django is on django-2.2.24 Mysql is running via docker and I'm using mariadb:10.10.2. Traceback (most recent call last): File "/Users/xyz/Documents/dev/django-proj/sliphy/manage.py", line 21, in <module> main() File "/Users/xyz/Documents/dev/django-proj/sliphy/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/xyz/Documents/dev/django-proj/sliphy/generator/management/commands/generate_backup.py", line 31, in handle self.bulk_create_into_user_trans() File "/Users/xyz/Documents/dev/django-proj/sliphy/generator/management/commands/generate_backup.py", line 78, in bulk_create_trans Transactions.objects.bulk_create(objs, batch_size=100) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/cacheops/query.py", line 411, in bulk_create objs = self._no_monkey.bulk_create(self, objs, *args, **kwargs) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 474, in bulk_create ids = self._batched_insert(objs_without_pk, fields, batch_size, ignore_conflicts=ignore_conflicts) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 1211, in _batched_insert self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1377, in execute_sql cursor.execute(sql, params) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/cacheops/transaction.py", line 99, in execute result = self._no_monkey.execute(self, sql, params) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 79, in … -
fetch data from parent model using the foreign key
How can the user access all client details (client model) when the user checks the invoice details(from invoice model) which has a foreign key client model class Clients(models.Model): company_name = models.CharField(max_length=200, blank=True, null=True) clients_name = models.CharField(max_length=200, blank=True, null=True,) phone_number = models.IntegerField(blank=True, null=True ) email = models.EmailField(blank=True, null=True ) invoice model class Invoice(models.Model): clients_name = models.ForeignKey(Clients, on_delete=models.CASCADE, blank=True, null=True) invoice_number = models.CharField(max_length=200, blank=True, null=True) slug = models.SlugField(unique =True) due_date = models.DateField() cost = models.CharField(max_length=200, blank=True, null=True) This is where i get stuck I have a view to fetch details about the invoice. But now i would the user to also view all client details from client model based on the clients_name (the foreign key) def single_invoice_details(request, slug): try: invoice_details = Invoice.objects.get(slug=invoice_number) except: return HttpResponse('cannot be found') return render(request, 'invoices/invoice_details.html', {'invoice_details': invoice_details}) What i tried def single_invoice_details(request, slug): try: invoice_details = Invoice.objects.get(slug=invoice_number) except: return HttpResponse('cannot be found') clients_details = Clients.objects.filter(clients_name=invoice_details) return render(request, 'invoices/invoice_details.html', {'invoice_details': invoice_details,'clients_details':clients_details}) -
djangoPDF: FileNotFoundError: [WinError 2] The system cannot find the file specified
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable hi; I want to display a PDF file in the navigator; knowing that I installed wkhtmltox-0.12.6-1.msvc2015-win64; but it gives me the following error message in browser: DoesNotExist at /scolar/Prise_en_chargeS2_PDFView/1/ Engagement matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/scolar/Prise_en_chargeS2_PDFView/1/ Django Version: 2.2.10 Exception Type: DoesNotExist Exception Value: Engagement matching query does not exist. Exception Location: C:\Users\LENOVO\workspace\budgetenv\lib\site-packages\django\db\models\query.py in get, line 406 Python Executable: C:\Users\LENOVO\workspace\budgetenv\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\Users\LENOVO\workspace\Project_GFC_Remote', 'C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\LENOVO\AppData\Local\Programs\Python\Python38', 'C:\Users\LENOVO\workspace\budgetenv', in eclipse: File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable need help emergency -
How to use different Pydantic Model in a view to create and respond
Im currently trying to understand the Pydantic FastAPI setup within my Django app and have the following issue: When I create a new Order object, I want to return the newly created object using a different Pydantic model as I use for the creation (as after the creation I now have the ID of the order that I can also return). # routes # Create a new Order @router.post("/create/", response_model=schemas.OrderResponse) def create_orders(order: schemas.OrderResponse): return views.create_order(order=order) # views.py from uuid import UUID from . import models, schemas # Create a new order def create_order(order: schemas.OrderResponse): new_order = models.Order.objects.get_or_create(order) return new_order # schemas.py # pydantic models from uuid import UUID from pydantic import BaseModel # Base Class for Model "Order" class OrderBase(BaseModel): product: str period: str power: int side: str class Config: orm_mode = True class OrderResponse(OrderBase): id: UUID When I now send an API request with this body: { "product": "Base", "period": "Hour", "power": 10, "side": "Buy" } I get this error -- how to set it up such that when creating the instance it doesnt validate for the UUID and after creation and when returning the instance it includes the UUID in the response? { "detail": [ { "loc": [ … -
Docker Image works with docker-compose up but not on Amazon ECS or Heroku
I am trying to host a Django project with a Postgres database in a Docker container. The project is a practice e-commerce site with a database for product info. I was able to get it working with docker-compose up and accessed the site running in the container at localhost:8000 but when I tried hosting it on AWS it didn't work. I uploaded the image to ECR and started a cluster. When I tried running a task with the image, it showed PENDING but as soon as I tried to refresh, the task was gone. I tried setting up cloudwatch logs but they were empty since the task was stopping immediately after starting. After that I tried hosting on Heroku. I was able to deploy the image but when I tried to open the app it showed an error (shown below). It feels like the image is just failing immediately whenever I try hosting it anywhere, but it works fine when I use docker-compose up. I think I'm making a very basic mistake (I'm a total beginner at all this) but not sure what it is. Thanks for taking the time to help. I'll also add my Dockerfile and docker-compose.yml Error … -
Cannot edit user profile and change password of the custom user in django
I have a custom user model in my django project. I can create users using the form based on this model but I'm unable to edit and change the passwords. How can I make this possible? Created the custom user models as shown below. from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): class Role(models.TextChoices): ADMIN = 'ADMIN', 'Admin' DEVELOPER = 'DEVELOPER', 'Developer' TESTER = 'TESTER', 'Tester' base_role = Role.ADMIN role = models.CharField(max_length=20, choices= Role.choices) def save(self, *args,**kwargs): if not self.pk: self.role = self.base_role return super().save(*args, **kwargs) I tried to edit the user the profile and change password using this form. from django.contrib.auth.forms import UserCreationForm from .models import User from django import forms class RegisterUserForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=50) last_name = forms.CharField(max_length=50) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email','role', 'password1', 'password2') class EditUserForm(forms.ModelForm): email = forms.EmailField() first_name = forms.CharField(max_length=50) last_name = forms.CharField(max_length=50) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') corresponding views.py file from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.views.decorators.cache import never_cache from .forms import RegisterUserForm, EditUserForm from django.views import generic from django.urls import reverse_lazy from django.contrib.auth.views import PasswordChangeView from … -
Sent an extra field to serializers -DRF
I have a ModelSerializer with fields from the table SubscriptionsPlans. serializer.py class SubscriptionSerializer(serializers.ModelSerializer): class Meta: model = SubscriptionsPlans fields = { 'id', 'name', 'plan_type', 'plan_details', 'price' } I want to sent an extra field name sub_id into this serializer from views. This sub_id will be True or False depending on a table SubscriptionsOrder. If SubscriptionsOrder has rows then the sub_id will be a True else False. SubscriptionsOrder for a specific user is looked here. views.py class SubscriptionView(APIView): def get(self, request): get_sub_id = SubscriptionsOrder.objects.filter(id=request.user).first() sub_id = get_sub_id.plan_selected subscription_details = SubscriptionsPlans.objects.filter(is_deleted=False) user_serializer = SubscriptionSerializer(subscription_details) return Response(user_serializer.data) I want to sent sub_id along with the user_serializer. models.py class SubscriptionsPlans(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) plan_type = models.CharField(max_length=255) plan_details = models.TextField(max_length=1000) request_per_month = models.IntegerField() price = models.FloatField() is_deleted = models.BooleanField(default=False) created_at = models.DateTimeField() updated_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Subscription Plans' verbose_name_plural = 'Subscription Plans' class SubscriptionsOrder(models.Model): id = models.IntegerField(primary_key=True) user_id = models.ForeignKey( AppUser, null=True, on_delete=models.SET_NULL ) plan_selected = models.ForeignKey(SubscriptionsPlans, null=True,on_delete=models.SET_NULL) billing_info = models.IntegerField() payment_info = models.IntegerField() class Meta: verbose_name = 'Subscription Order' verbose_name_plural = 'Subscription Order' before sending sub_id the output looks like this { "id": 1, "name": "Professional", "plan_type": "MONTHLY", "plan_details": "{'Details'}", "price": 50.0 }, { "id": 2, "name": "Business", … -
Getting product items from Products table with id's saved in CartItems table (django, sqlite)
I'm new to django and in backend development in general, as well as databases. I have a CartItems and Products models in django. In the CartItems there's only id and product_id columns. How can I get all the products saved in CartItems using the product_id? What I did so far was to use a for loop in CartItems and used the product_id as a parameter to do Products.objects.get(id=id) and append() it to an empty list. And It works. cart_details = [] for item in cart_items: cart_details.append(Products.objects.get(id=item.product_id)) Is this the way to do it? If there's a better way please let me know. Thank you!