Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to join a table more than once when a table references different rows of that table
I have a table which can have up to 3 references to another table. here it is in my Django ORM class CreatorCategories(models.Model): name = models.CharField(max_length=100, unique=True) icon = models.CharField(max_length=200, unique=True) class ContentCreatorUsers(models.Model): creatorcategory1 = models.ForeignKey(CreatorCategories, related_name='creatorcategory1', on_delete=models.DO_NOTHING, null=True, blank=True) creatorcategory2 = models.ForeignKey(CreatorCategories, blank=True, related_name='creatorcategory2', null=True, on_delete=models.SET_NULL) creatorcategory3 = models.ForeignKey(CreatorCategories, blank=True, null=True, related_name='creatorcategory3', on_delete=models.SET_NULL) topbannerphotokey = models.CharField(max_length=100, null=True, blank=True) I am running a sql query in a aws lambda (I have not added the select statements that will get the values for a categories name and icon) SELECT id, creatordisplayname, contentcreatordisplaycardurl, creatorurlslug, currentmonitaryactioncount, isverifiedcontentcreator FROM users_contentcreatorusers INNER JOIN users_creatorcategories ON users_contentcreatorusers.creatorcategory1_id= users_creatorcategories.id INNER JOIN users_creatorcategories ON ISNULL(users_contentcreatorusers.creatorcategory2_id, NULL) = ISNULL(users_creatorcategories.id, NULL) INNER JOIN users_creatorcategories ON ISNULL(users_contentcreatorusers.creatorcategory3_id, NULL) = ISNULL(users_creatorcategories.id, NULL) WHERE approvedcreator = true ORDER BY currentmonitaryactioncount DESC LIMIT 12; this sql query keeps giving me the same error: Traceback (most recent call last): File "browsecontentcreatorstest.py", line 115, in <module> lambda_handler() File "browsecontentcreatorstest.py", line 57, in lambda_handler cur.execute(''' psycopg2.errors.DuplicateAlias: table name "users_creatorcategories" specified more than once I need to be able to grab the name and the icon of each of the categories a creator has. I'm not sure how to do this without joins. And the documents I have … -
Add script tag to all django templates
My Django app contains 100+ HTML templates (should've made a web app). I need to add a user feedback widget similar to Usersnap. One way is to add a script tag to all of the 100+ template files and make sure it's added in all future files as well. Is there a way to add the script tag without repeating the code 100+ times? -
Problem with static files in django heroku
I have sam problems this static files in django. I sucsesfull deploy django app to heroku and this site workin https://timon-webchat.herokuapp.com/, but how you can see without any styles or images. But if runing python manage.py runserver local all good and I can see styles, js-codes and images Please tell me what's wrong here is mine setings.py file: """ Django settings for web_chat project. Generated by 'django-admin startproject' using Django 3.1.7. For more information o n this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. from django.urls import reverse_lazy import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+*yv5wtriwzs91yk!gpu27r!p+b1063n26bpjf79+=236yu4%t' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_gravatar', 'app_chat', 'acounts', ] AUTH_USER_MODEL = 'acounts.User' LOGIN_REDIRECT_URL = reverse_lazy("main") LOGOUT_REDIRECT_URL = reverse_lazy("login") 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', ] MIDDLEWARE_CLASSES = … -
Python Skipping If Statement in Class
I have the following Django class view: class AddOrder(View): product_type = "BarZero Monolithic" template_name = "" def get(self, request): if not request.user.is_authenticated: return redirect("login") context = {} if (self.product_type == "Barzero Monolithic"): form = AddClearChoiceOrderForm(request.POST or None) elif (self.product_type == "AccuFrame 360 PMMA"): form = AddPMMAOrderForm(request.POST or None) elif (self.product_type == "AccuFrame 360 Zirconia"): form = AddZirconiaOrderForm(request.POST or None) if form.is_valid(): fs = form.save(commit=False) fs.clearchoice_center_name = request.user.prosthodontist.prosthodontist fs.email_for_design_approval = request.user.prosthodontist.email_ack fs.product_type = self.product_type fs.save() orders = WebOrder.objects.filter( Q(clearchoice_center_name = fs.clearchoice_center_name), Q(patient_identifier = fs.patient_identifier), Q(barzero_zirconia_options = fs.barzero_zirconia_options), Q(bar_type_options = fs.bar_type_options), Q(arch_type = fs.arch_type), Q(tooth_shade = fs.tooth_shade), Q(cagenix_gingiva_shade = fs.cagenix_gingiva_shade), Q(patient_scheduled_date = fs.patient_scheduled_date), Q(requested_delivery_date = fs.requested_delivery_date), Q(email_for_design_approval = fs.email_for_design_approval), Q(special_instructions = fs.special_instructions) ) order = orders[0] return HttpResponseRedirect(reverse('print_order_i', args=(order.id,))) context['form'] = form return render(request, self.template_name, context) and the following url code: path('addorder/BarZero', AddOrder.as_view(product_type="BarZero Monolithic", template_name="order/add_barzero_order.html"), name="create_barzero_order"), This pushes out the following error through the site debugger: UnboundLocalError at /order/addorder/BarZero local variable 'form' referenced before assignment if form.is_valid(): It seems that the code is skipping over my if statement for some reason, that I can not understand, so please educate me on how to fix this. -
Django: extended user with proxy model to add extra method, how to use the method in template?
I extend the default user model with a proxy model to add an extra method. from django.contrib.auth.models import User class Person(User): class Meta: proxy = True def custom_method(self): pass The main purpose is to use the method in templates. <div>{{ user.custom_method }}</div> But since the user is pointing to the default user model, it has no access to the custom_method. Is there any way to achieve this other than create a subclass of the User model? -
User-specific download file in django
i have an app in django that do some processes and build a file, in one section, i want to show the user that file to download that. (for example, user enter a name in front-end and the app give him a pdf file to download). the file building process is ok and it is in /app_dir/media/app/report/username/file.pdf here is my code, but it does not worked and i faced some problems. can you please help me, where is my problem? and how i can make that user-specefic? each user just can access to his files. views.py (my_main_function): views.py (download function): urls.py: simple testing download.html file: -
django.db.utils.IntegrityError: NOT NULL constraint failed: rango_category.super_cat_id
/*tests.py*/ def create_user(username, password): user = get_user_model().objects.create_user(username=username, password=password) return user #helper function to populat database def create_category(name, super, user): category = Category.objects.get_or_create(name=name)[0] category.super = super category.user = user category.save() return category def create_super_category(title): super = SuperCategories.objects.create(title=title) super.save() return super # The following test is for the save and deleting of # a page from the favorites list class TestFavoritesFeature(TestCase): def setUp(self): self.user = create_user("testUser", "testPassword") self.super = create_super_category('Frameworks') self.cat = create_category('python', self.super, self.user) /* Models */ class SuperCategories(models.Model): title = models.CharField(max_length=maxLength128) def __str__(self): return self.title class Category(models.Model): super_cat = models.ForeignKey(SuperCategories, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=maxLength128, unique=True) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name Both the object.create and object.get_or_create give an error for NOT NULL field. Above is the code , 2 models and both throw an error on only the id field that we do not even populate. It is the function's job to assign a unique id to it. The above is code from tests.py file. I am trying to populate DB for unit testing . In the actual code, these objects.get_or_create or objects.create do not give errors but are rather … -
How can I submit multiple forms using Django and JavaScript?
I'm working on an app that displays a form on the index page, into which you can enter information to eventually calculate a gross total and output other details based on the form inputs. My form inherits from form.Forms. A button, "Add row", creates as many copies of this row as needed. Each form contains a form with the ID "calc-form". My problem is that only one form is included in the POST method. I would like to process all forms with one click. How can I include all additional forms in the POST method when I click "Calculate"? index.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} {% load static %} <script type="text/javascript" src="{% static 'app.js' %}"></script> <table id="table-id"> <tr id='table-row'> <form id="calc-form" action="{% url 'result' %}" method="post"> {% csrf_token %} {% for field in form %} <td>{{ field|as_crispy_field }}</td> {% endfor %} </form> </tr> </table> <br> <input type="submit" value="Calculate" form="calc-form"> <button type="button" id="add-row-btn" onclick="addRow()">Add row</button> <button type="button" id="delete-row-btn" onclick="deleteRow()">Delete last row</button> {% endblock content %} views.py from django.shortcuts import render from .forms import TariffCalcForm def index(request): form = TariffCalcForm context = {'form': form} return render(request, 'clickapp/index.html', context) def result(request): context = {} if request.method … -
Not able to host the python application in docker
I'm trying to host the sample application in docker. But not able to host. run the application. I believe it should host in http://127.0.0.1:8001 I have exposed the port 8001 docker file FROM python:3.9-alpine3.13 EXPOSE 8001 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 COPY requirements.txt . RUN python -m pip install -r requirements.txt WORKDIR /app COPY . /app RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app USER appuser CMD ["gunicorn", "--bind", "0.0.0.0:8001", "pythonPath.to.wsgi"] docker-compose.yml version: '3.4' services: vscodedjangodocker: image: vscodedjangodocker build: context: . dockerfile: ./Dockerfile ports: - 8001:8001 -
Is it secure for Django to store the CSRF token in a cookie?
I'm using React and Django for my web application. As far as I know, Django uses a double submit pattern, where the CSRF token in the cookie and header/body are compared server side. I use the following code to extract the CSRF token from document.cookie as specified by Django docs: export function getToken() { let cookieValue = null; const name = "csrftoken"; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent( cookie.substring(name.length + 1) ); break; } } } return cookieValue; } I then use it like so: axios .post("/api/auth/login", { username: username, password: password, }, { withCredentials: true, headers: { "X-CSRFToken": getToken(), } } So my question is, I've heard that an attacker can't access a user's cookies and thus can't extract the CSRF token to place in the request header/body. But why can't the attacker execute a script running the getToken function and place the result in a header like I did? (Say we ignore CORS for the sake of argument) Example: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" … -
Getting False value for a key in self.data even when it is not present in the request
I have 2 radio buttons in the UI, one for setting a variable (ng-model) say selected as true (ng-value=true) and other one for setting it as false (ng-value=false). Now, when none of them is selected it results in the variable selected being absent from the outgoing request (as expected). However, when that is dealt with Django Forms, the self.data dictionary in the clean() method gives False on accessing self.data.get('selected') / self.data['selected'] why is that so? Shouldn't it be None or at least give a key-error when it was not even present in the actual request? Note that the variable 'selected' is actually a field in a Django Model with default=False, is that thing responsible for this behaviour? How can I circumvent this situation considering that altering the Django Model field isn't an option? -
Why images on Cloudinary doesn't show up? I've tried many times but nothing
I have a profile's model and a post model. When debug mode is set to False, images don't appear. Here is my settings.py from pathlib import Path import os import dj_database_url import cloudinary_storage BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY', '...') DEBUG = os.environ.get('DEBUG', False) ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django.contrib.sitemaps', 'cloudinary_storage', 'taggit', 'tinymce', 'ckeditor', 'sweetify', 'hitcount', 'storages', 'notifications', 'django_resized', 'django_countries', 'post', 'website', 'comment', 'announce', 'superadmin', 'commissions', 'sitemanagement', 'profil.apps.ProfilConfig', ] CLOUDINARY_STORAGE = { 'CLOUD_NAME': os.environ.get('CLOUD_NAME', 'name'), 'API_KEY' : os.environ.get('API_KEY', 'key'), 'API_SECRET' : os.environ.get('API_SECRET', 'secret'), } DEFAULT_FILE_STORAGE = os.environ.get('DEFAULT_FILE_STORAGE', 'cloudinary_storage.storage.MediaCloudinaryStorage') MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'club.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] WSGI_APPLICATION = 'club.wsgi.application' # Database DATABASES = { 'default': { 'ENGINE': os.environ.get('ENGINE', 'django.db.backends.postgresql'), 'NAME': os.environ.get('NAME', 'name'), 'USER': os.environ.get('USER', 'user'), 'HOST': os.environ.get('HOST', 'host'), 'PASSWORD': os.environ.get('PASSWORD', 'password'), 'PORT': os.environ.get('PORT', 'port'), } } db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) """ # EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_LOCALTIME = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', 'email_address') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_USER', 'email_password') AUTH_PASSWORD_VALIDATORS = [ … -
Cannot connect django container to postgres on a linux host machine
After going through all of the Stackoverflow threads on this topic, I still could not solve the problem. This happens only on my Fedora laptop, on my Macbook, the docker containers work perfectly fine. My docker-compose.yml file is very standard: version: "3.8" services: app: container_name: data-management restart: always build: ./ ports: - '3000:3000' links: - 'postgresdb' volumes: - ./:/usr/local/share/src/app env_file: - .dev.env postgresdb: container_name: be-postgres restart: always image: postgres:12.7-alpine ports: - '5432:5432' volumes: - postgres-db:/var/lib/postgresql/data env_file: - .dev.env volumes: postgres-db: As you can see the environment variables are read in both containers from a file: POSTGRES_PASSWORD=devpassword123 POSTGRES_USER=devuser POSTGRES_SERVICE=postgresdb POSTGRES_PORT=5432 These env variables are also used in the settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ['POSTGRES_SERVICE'], 'NAME': os.environ['POSTGRES_USER'], 'PORT': os.environ['POSTGRES_PORT'], 'USER': os.environ['POSTGRES_USER'], 'PASSWORD': os.environ['POSTGRES_PASSWORD'], } } The problem that I am having is that the django application cannot connect to the postgresDB: django.db.utils.OperationalError: could not connect to server: Host is unreachable Is the server running on host "postgresdb" (172.xx.x.x) and accepting TCP/IP connections on port 5432? I also checked if the port in the postgres container is opened and it is: / # netstat -tuplen Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program … -
SQL - How to split values in field with commas in multiple rows
I have a field in a MySQL table with '3,4,7,16' in it. These values are store in another table id - value 1 - name1 2 - name2 ... 16 - name16 I would like to get then in 4 rows 3 4 7 16 I have seen many answer but they need temporary table, function, loop or procedure. I am using Django ORM and can not do that in the query. Can you help to solve this issue ? -
Can't load django-sortedm2m
I downloaded the Django package django-sortedm2m and I added it to settings.py as sortedm2m but when I tried to load the package in models.py with: from sortedm2m.fields import SortedManyToManyField And Django didn't recognize it. Is it possible that the package is deprecated? I'm using Django version 3.1.7 and Python 3.8.10. If this can't be solved, is there any similar package? -
How to create serializer with nested data DRF?
I have seen many tutorials about nested serializer, but unfortunately I can`t solve this task. Please, give me some tips. I need to create this JSON { "external_id": "11", "details": [ { "amount": 7, "price": "12.00", "product": { "name": "Car" } } ] } My models consist the next relative: from django.db import models class Order(models.Model): NEW = 'new' ACCEPTED = 'accepted' FAILED = 'failed' order_status = [ (NEW, 'new'), (ACCEPTED, 'accepted'), (FAILED, 'failed'), ] status = models.CharField(max_length=12, choices=order_status, default='new', blank=False) created_at = models.DateTimeField(auto_now_add=True) external_id = models.CharField(max_length=128) def __str__(self): return f'Order № {self.external_id}' class Product(models.Model): name = models.CharField(max_length=64) def __str__(self): return self.name class OrderDetail(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='details', null=True, blank=True) amount = models.IntegerField(null=True, blank=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product', null=True) price = models.DecimalField(decimal_places=2, max_digits=6, null=True, blank=True) def __str__(self): return f'Detail for {self.order}, detail for product {self.product}' My view class ProductViewSet(ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer class OrderViewSet(ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer pagination_class = ContentRangeHeaderPagination class OrderDetailViewSet(ModelViewSet): queryset = OrderDetail.objects.all() serializer_class = OrderDetailSerializer My serializer class OrderDetailSerializer(serializers.ModelSerializer): class Meta: model = OrderDetail fields = ['id', 'amount', 'price'] depth = 1 class ProductSerializer(serializers.ModelSerializer): product = OrderDetailSerializer(many=True) class Meta: model = Product fields = ['id', 'name', 'product'] class OrderSerializer(serializers.ModelSerializer): … -
netlify build failure: npm ERR! path /opt/build/repo/package.json
I have a django 1.10 app which I have deployed to netlify but is failing to build. I'm using the django distill app to generate the static files. and I have pushed these to https://github.com/kc1/static1 . The netlify build log has; 1:12:57 PM: $ npm run-script build 1:12:57 PM: npm ERR! code ENOENT 1:12:57 PM: npm ERR! syscall open 1:12:57 PM: npm ERR! path /opt/build/repo/package.json 1:12:57 PM: npm ERR! errno -2 1:12:57 PM: npm ERR! enoent ENOENT: no such file or directory, open '/opt/build/repo/package.json' 1:12:57 PM: npm ERR! enoent This is related to npm not being able to find a file. 1:12:57 PM: npm ERR! enoent 1:12:57 PM: npm ERR! A complete log of this run can be found in: 1:12:57 PM: npm ERR! /opt/buildhome/.npm/_logs/2021-08-05T17_12_57_910Z-debug.log 1:12:57 PM: 1:12:57 PM: ──────────────────────────────────────────────────────────────── 1:12:57 PM: "build.command" failed 1:12:57 PM: ──────────────────────────────────────────────────────────────── 1:12:57 PM: 1:12:57 PM: Error message 1:12:57 PM: Command failed with exit code 254: npm run-script build As you can see in the repo I don't have a package.json ( this came from python ). Do I need to create one? How do I get this working? -
Django + Uvicorn times out on super() save function
I'm using Django running on Gunicorn and Uvicorn to run an ASGI web app. Whenever a super().save() function is called (super(Message, self).save(*args, **kwargs)) the app completely times out. Anybody else having this issue or understand what is going on here? Thanks -
Value Error saying The QuerySet value for an exact lookup must be limited to one result using slicing
I am working on a project and i am trying to add products in the cart, but i am facing an issue : ValueError at /onlineshopping/add-to-cart/p1/, this is the location. The logic also checks whether the item is current present in the order or not to not create duplicate items. I am not getting where am i wrong. Please help me out. Here is urls.py: path('cart/', views.cart, name='cart'), path('add-to-cart/<str:slug>/', add_to_cart, name='add-to-cart'), Here is models.py: class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(AffProduct, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username Here is views.py: @login_required def add_to_cart(request, slug): item = AffProduct.objects.filter(slug=slug) order_item = OrderItem.objects.get( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("cart") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("cart") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("cart") This is my cart.html: {% block … -
Django Models Relationship and Creation Flow - How to link all models to the user's parent
I’me new to software development, and I'm struggling with a basic design problem. I’m building a SaaS platform where the user Admin signs up and creates and Organization. Every user should belong to an organization. The user can add abstract users Workers and Hubs, and every worker belongs to a hub. Any model that is created should belong to an organization. I’m trying to figure out the best practice to associate all the models to their respective organizations and how the signup flow should be with both Admin and Organization. Should I create the user first or the organization? Does it matter? Also I'm a bit confused on how to use created_by.organization or request.user.organization to assign the created Worker to the creator's organization in the worker creation form (the same concept will apply to all other forms). User Model class CustomUser(AbstractUser): ... organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="organization", null=False) ... Organization Model class Organization(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200, blank=False, validators=[MinLengthValidator(3)]) email = models.EmailField(max_length=70, blank=False, unique=True, validators=[ MinLengthValidator(3)]) image = models.ImageField( upload_to='organizations-images/', blank=True, null=True) timezone = TimeZoneField(default='Europe/London', choices_display='WITH_GMT_OFFSET') def __str__(self): return self.name Worker Model class Worker(CustomUser, TimeStampedModel): hub = models.ForeignKey( Hub, on_delete=models.RESTRICT, related_name='hub_workers' ) def __str__(self): return … -
How can update field by overriding save method which is in another models
I have two models PaymentModel and MeterModel. PaymentModel have this fields: payment_id = models.CharField(max_length = 100,primary_key=True, blank=True, editable=False, unique=True, default=create_new_payment_id) meter_serial_number = models.ForeignKey(MeterModel, on_delete = SET_NULL,null=True) payment_amount = MoneyField(max_digits = 14, decimal_places = 2, null = False, blank = True, default_currency = 'INR') payment_timestamp = models.DateTimeField(auto_now_add = True) payment_type = models.CharField(max_length = 20, choices = payment_mode_choises, default = '1') payment_mode = models.CharField(max_length = 20, choices = payment_type_choises, default = '1') # PAyment mode transaction_id = models.CharField(max_length = 25) transaction_details = models.CharField(max_length = 100) and MeterModel have this fields: tarrif_id = models.ForeignKey(TarrifMasterModel,on_delete=models.RESTRICT) ca_number = models.ForeignKey(CustomerDetailModel, on_delete=models.RESTRICT) meter_model_number = models.CharField(max_length=100, blank=True) calibration_certificate_number = models.CharField(max_length=100, blank=True) bill_date = models.PositiveSmallIntegerField(null=True, blank=False, validators=[MinValueValidator(0), MaxValueValidator(31)]) current_outstanding = MoneyField(max_digits=10, decimal_places=2, default_currency='INR', default=0.0) last_bill_number = models.ForeignKey(BillDetailModel,on_delete=SET_NULL, null=True, blank=True) I want to update_field current outstanding in meter_detail after by overriding save method in PaymentModel when payment is post. assume it payment amount is 60 and current outstanding is 10 then payment amount total is 70. If user only pay Rs. 40 then remaining Rs.20 want to be get update in current outstanding of meter_detail I tried this but doesn't work def save(self,*args, **kwargs): print(self.payment_amount) print(self.meter_serial_number.meter_serial_number) print(self.meter_serial_number.current_outstanding) new_outstanding = self.payment_amount - self.meter_serial_number.current_outstanding print("new_outstanding : ",new_outstanding) meter_detail = MeterDetailModel.objects.filter(meter_serial_number=self.meter_serial_number).first() print("meter_detail : … -
Is conditional rendering good in django?
I dont know if conditional rendering a whole html template is good or bad ? I understand that we can do this on templates but just wanna know if this is okay? In my view, if profile.exists(): return render(request, 'index.html') else: return render(request, 'nodata_index.html') Is this good, or shall i do if template condition on templates ? Is there any problem using the above method or shall go with template formats -
Django, xlsxwriter and images
I have django site where I am trying to create an excel file with an image in it. The image is on a AWS: https://unord-tools-django-project-static.s3.eu-central-1.amazonaws.com/media/public/10e8f47bb84901d20ff435071577c58b_TFxmjcV.jpg I am using: xlsxwriter==1.4.5 and trying to write it with: worksheet_s.insert_image(5, thisColumn, str('https://unord-tools-django-project-static.s3.eu-central-1.amazonaws.com/media/public/'+image)) My model looks like this: class Room(models.Model): # Relationships location = models.ForeignKey("asset_app.Locations", on_delete=models.SET_NULL, blank=True, null=True) room_type = models.ForeignKey("asset_app.Room_type", on_delete=models.SET_NULL, blank=True, null=True) # Fields name = models.CharField(max_length=30) image = models.ImageField(storage=PublicMediaStorage(), null=True, blank=True ) The error I am getting is this: worksheet_s.insert_image(5, thisColumn, str('https://unord-tools-django-project-static.s3.eu-central-1.amazonaws.com/media/public/'+image)) TypeError: can only concatenate str (not "ImageFieldFile") to str -
Django Rest Framework Bad Request with Image - "submitted data was not an image"
I am having an extremely similar problem to this stack overflow question: Django REST Framework upload image: "The submitted data was not a file" I am trying to submit an image to DRF, and getting this error: {"image":["The submitted data was not a file. Check the encoding type on the form."]} Except, I'm trying to follow the advice in that question, and while it worked for one model, it is absolutely not working for another. Here's my serializer: from rest_framework import serializers from .models import Blog from article.serializers import Base64ImageField class BlogSerializer(serializers.ModelSerializer): class Meta: image = Base64ImageField(max_length=None, use_url=True) model = Blog fields = ['date', 'body', "id", "title", "image", "published"] The Base64ImageField function is exactly the same as listed on that other question My Blog model looks like this: from django.db import models def imageFile(instance, filename): return '/'.join(['images', filename]) class Blog(models.Model): date = models.DateField("Post date") title = models.CharField(max_length=255) body = models.TextField(blank=True) image = models.ImageField(upload_to=imageFile, null=True, blank=True, max_length=255) published = models.BooleanField() This is working for the Article model, but no matter what I try, I cannot make it save for Blog. Here is the API View class I call: class BlogCreateView(generics.CreateAPIView): queryset = Blog.objects.all() serializer_class = BlogSerializer Why is this error happening? … -
Django how to list and update object in same page?
I am using two different views and html template for update and show my objects. First template for list all objects and second template for update each object. Right now when I am clicking any objects in list page then it's taking me to update page. is it possible to update and show all objects in same page? here is my code: #Here I am listing all objects def ListProjectView(request): project = CustomerProject.objects.all() context = {"project":project} return render(request,'members/clientproject.html',context) #this view for update object def UpdateList(request,pk=None): obj = get_object_or_404(CustomerProject, pk=pk) form = CustomerProjectFroms(request.POST or None, instance=obj) if request.method == "POST": if form.is_valid: form.save() context = {'form':form} return render(request,'members/projectupdate.html',context) urls.py path('reviewproject/', views.ListProjectView, name='list-project-view'), path('<int:pk>', views.UpdateList, name='update-list'), #list_html #here I am showing all objects {%for i in project %} <a href="{%url 'members:update-list' i.pk %}">{{i.project_title}}</a> {%endfor%} #update_html <form method="POST"> {% csrf_token %} {{form}} <button type="submit">SUBMIT</button> </form>