Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django models and views not rendering images
I am trying to use django to build a music streaming website.I used a models.integer field in my models.py and called it in views.py.But when i try to load the template using the live server the images just wont show up.Instead just the file name is being rendered. my models.py:- from django.db import models # Create your models here. class song_thumb(models.Model): artist=models.CharField(max_length=100,null=True) song_title=models.CharField(max_length=100,null=True) album=models.CharField(max_length=100,null=True) song_duration=models.FloatField(null=True) img=models.ImageField(upload_to='pics',null=True) my views.py:- from django.shortcuts import render from .models import song_thumb # Create your views here. def songs(request): artist1=song_thumb() artist1.artist='Alcest' artist1.song_title='Kodama' artist1.album='Kodama' artist1.song_duration='9.10' artist1.img='kodama.jpg' artist2=song_thumb() artist2.artist='Tash Sultana' artist2.song_title='Jungle' artist2.album='Jungle' artist2.song_duration='5.17' artist2.img='jungle.jpg' artist3=song_thumb() artist3.artist='Animals as leaders' artist3.song_title='Cafo' artist3.album='Cafo' artist3.song_duration='6.56' artist3.img='cafo.jpg' artists=[artist1,artist2,artist3] return render(request, 'home.html', {'artists':artists}) my homepage.html which is used to render all the data:- {% load static %} {% static "images" as baseurl %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Home Page</title> <script src=" https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src= " https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <link rel="stylesheet" href= 'https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css' integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src= 'https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js' integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <link rel="stylesheet" href="{% static 'home.css' %}"> <script src= 'https://kit.fontawesome.com/b99e675b6e.js'></script> </head> <body> <!--sidebar--> <div class="wrapper"> <div class="sidebar"> <h2>Sidebar</h2> <ul> <li><a href="#"><i class="fas fa-home"></i>Home</a></li> <li><a href="#"><i class="fas fa-user"></i>Register</a></li> <li><a href="#"><i class="fas fa-address-card"></i>About</a></li> <li><a href="#"><i class="fas fa-project-diagram"></i>Sign in</a></li> <li><a href="#"><i class="fas fa-address-book"></i>Contact</a></li> … -
Heroku app shows Server Error (500) Django website
I launched my Django app on Heroku a while ago. Everything was running smoothly all this time. But now when I try to access the app, it shows this single line only : Server Error (500) Here are the logs: 2020-04-14T09:36:48.786258+00:00 app[web.1]: 10.69.178.208 - - [14/Apr/2020:09:36:48 +0000] "GET / HTTP/1.1" 500 145 "https://ncovidweb.herokuapp.com/preventive-measures/" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" 2020-04-14T09:36:48.787091+00:00 heroku[router]: at=info method=GET path="/" host=ncovidweb.herokuapp.com request_id=d33234a9-222e-4ea8-9d4c-e93dbba0aa86 fwd="103.133.206.226" dyno=web.1 connect=0ms service=386ms status=500 bytes=380 protocol=https 2020-04-14T09:37:01.510013+00:00 app[web.1]: 10.109.140.73 - - [14/Apr/2020:09:37:01 +0000] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" 2020-04-14T09:37:01.514397+00:00 heroku[router]: at=info method=GET path="/" host=ncovidweb.herokuapp.com request_id=d179af23-8844-4aea-9b0a-c7f8dbf08b97 fwd="103.133.206.226" dyno=web.1 connect=0ms service=577ms status=500 bytes=380 protocol=https 2020-04-14T09:38:45.470752+00:00 heroku[router]: at=info method=GET path="/" host=ncovidweb.herokuapp.com request_id=4490976c-4df6-49ba-8eab-a92e527a3b08 fwd="103.133.206.226" dyno=web.1 connect=0ms service=446ms status=500 bytes=380 protocol=https 2020-04-14T09:38:45.471354+00:00 app[web.1]: 10.30.61.206 - - [14/Apr/2020:09:38:45 +0000] "GET / HTTP/1.1" 500 145 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" 2020-04-14T09:43:02.887254+00:00 heroku[router]: at=info method=GET path="/" host=ncovidweb.herokuapp.com request_id=8a378105-bd9c-476c-b9d0-7b58929e16c7 fwd="103.133.206.226" dyno=web.1 connect=1ms service=220ms status=500 bytes=380 protocol=https 2020-04-14T09:43:02.885109+00:00 app[web.1]: 10.150.193.19 - - [14/Apr/2020:09:43:02 +0000] "GET / HTTP/1.1" 500 145 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" 2020-04-14T09:45:12.066183+00:00 heroku[router]: at=info method=GET path="/" host=ncovidweb.herokuapp.com request_id=96142b52-d016-466d-adb7-80a970cde6a2 fwd="103.133.206.226" dyno=web.1 connect=1ms service=414ms status=500 … -
Django REST Framework: AttributeError: 'DeferredAttribute' object has no attribute 'isoformat'
This is my first time using Django REST FRAMEWORK, I'm facing an issue with a registration api, on the first try the api worked properly, but on the following tries it started throwing this error AttributeError: 'DeferredAttribute' object has no attribute 'isoformat' first here is my code: serializers.py: class UserSerializer(serializers.ModelSerializer): def create(self, validated_data): user = User.objects.create(**validated_data) user.set_password(validated_data['password']) user.save() # return dict(status=True, code=1) return User class Meta: model = User fields = ['phone', 'email', 'first_name', 'last_name', 'birth_date', 'gender', 'user_type', 'password', 'username'] extra_kwargs = { "password": {"write_only": True} } apis.py: class RegisterApi(CreateAPIView): model = get_user_model() permission_classes = [permissions.AllowAny] serializer_class = UserSerializer models.py: class User(AbstractUser): notification_token = models.CharField(max_length=255, unique=True, blank=True, null=True) phone = models.CharField( _("Phone Number"), max_length=50, validators=[phone_validator], unique=True, ) is_active = models.BooleanField( _('active'), default=False, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) photo = models.ImageField( _('Profile Picture'), upload_to='profile/', help_text=_( "the user's profile picture." ), blank=True, null=True ) address = models.CharField(_("Address"), max_length=255) lives_in = models.ForeignKey('City', on_delete=do_nothing, null=True, blank=True) user_type = models.CharField( _("Type"), max_length=3, choices=USER_TYPES, help_text=_("The user's type can be one of the available choices, " "refer to the Model class for the detailed list."), ) birth_date = models.DateField(_('Birth Date'), blank=True, null=True) gender … -
Child process was not spawned error with Django application and Gunicorn
I'm following this tutorial to deploy my Django application to a Linux server. My problem is that, when i type sudo supervisorctl status MYAPP i'm getting the following status: MYAPP FATAL Exited too quickly (process log may have details) I've chedk my logs and i only found this: supervisor: couldn't exec /home/hst/bin/gunicorn_start: EACCES supervisor: child process was not spawned This error is quite generic, so i 'm struggling to find what's wrong, here is my gunicorn_start: #!/bin/bash NAME="MYAPP" DIR=/home/hst/MYAPP USER=hst GROUP=hst WORKERS=3 BIND=unix:/home/hst/run/gunicorn.sock DJANGO_SETTINGS_MODULE=myproj.settings DJANGO_WSGI_MODULE=myproj.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- Can anyone help me with this? -
VS Python attach remote. Starts running for a couple seconds then stops
So I have this Django app inside of Docker running and I'm trying to attach VS code to it so I can debug here is my launch file { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Remote Attach", "type": "python", "request": "attach", "port": 8800, "host": "192.168.99.100", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "." } ] } ] } The host 192.168.99.100 is the IP that Docker runs on(I'm using Docker Toolbox). For some reason it runs for like 5 seconds then cancels itself. Any suggestions? -
Django Group By not working with multiple joins
I'm facing a problem grouping the records with queryset having multiple joins in Django ORM. It works fine when running a sql raw query. Please find below the models, sql raw query and my try on Django ORM for the respective query. model.py class Merchants(models.Model): id = models.IntegerField(primary_key=True) prospectId = models.CharField(max_length=50, default=None) merchantAmount = models.FloatField(null=True, blank=True, default=None) lenderName = models.CharField(max_length=10, default=None) requestedLoanAmount = models.FloatField(blank=True, default=None) createdDate = models.DateTimeField(default=None) storeId = models.IntegerField(unique=True, default=None) eStatus = models.CharField(max_length=10, default=None) loanBookingDate = models.DateField(default=None) dueLoanAmount = models.FloatField(default=None) totalRepayAmount = models.FloatField(default=None) los_loanApplicationId = models.CharField(max_length=50, default=None) modifiedDate = models.DateTimeField(default=None) loanStatus = models.CharField(max_length=20, default=None) LLA_LLMM = models.ForeignKey(LOS_Loan_Application, on_delete=models.CASCADE, db_column='los_loanApplicationId', to_field='loanApplicationId', default=None) class Meta: db_table = "loan_lending_mca_merchants" verbose_name_plural = "Merchants" class Agent_Task_Log(models.Model): iVisitId = models.IntegerField(primary_key=True) iTaskId = models.IntegerField(default=None) ePaymentMode = models.CharField(max_length=30, default=None) iAmount = models.IntegerField(default=None) iStoreId = models.IntegerField(unique=True, default=None) dupdation_date = models.DateTimeField(default=None) store = models.ForeignKey('trx_insight.Store', on_delete=models.CASCADE, db_column='iStoreId', default=None) collection_dpd = models.ForeignKey(Collection_DPD, on_delete=models.CASCADE, db_column='iStoreId', to_field='iStoreId') class Meta: db_table = "agent_task_log" verbose_name = "Agent Task Log" class Agents_Task(models.Model): iAgentTaskId = models.IntegerField(primary_key=True) iStoreId = models.IntegerField(unique=True, default=None) iAgentId = models.IntegerField(default=None) iTaskTypeId = models.IntegerField(unique=True, default=None) iAssignedBy = models.IntegerField(default=None) tCreationDate = models.DateTimeField(default=None) tUpdationDate = models.DateTimeField(default=None) tasksLog = models.ForeignKey(Agent_Task_Log, on_delete=models.CASCADE, db_column="iStoreId", to_field="iStoreId", default=None) class Meta: db_table = "agents_task" verbose_name_plural = "Agents Task" class Tasks_Master(models.Model): iTaskMasterId = … -
Django queryset using select_related and prefetch_related
models.py class Question(Model): pass class Topic(Model): question = models.Foreignkey(Question) class Syllabus(Model): topic = models.Foreignkey(Topic) #The Bridge Model class Test_Syllabus(Model): test = models.Foreignkey(Test) syllabus = models.Foreignkey(Syllabus) class Test (Model): pass I have a test object as follows: test = Test.objects.get(id=pk) Using the test object, I want to get the related queryset of questions. So, I tried the following code: questions = test.test_syllabus_set.all() #don't know how to go further from here I think it has something to do with select_related and prefetch_related. Please help me out with a perfect query for this use case. -
Django installation issue & ERROR: Exception
Since last months I had worked properly on some django project but those I when I try to work on new project I meet issue in the Django in installation. [enter image description here][1] [1]: https://i.stack.imgur.com/kMZKF.jpg This code Erro appears when I type pip install Django in the prompt command please could anyone help me out to fix that issue? -
Waypoints Infinite Scroll not rendering script tag content
Currently using Wapypoints Infinite in a Django framework. I am trying to place a Jquery script tag into the infinite item generated to report back to django that it loaded. Unfortunately the script tag is loading, however nothing contained inside it is loading (as checked with google dev inspect). Please find the HTML below. Thanks for your help! <div class="infinite-container"> {% for post in posts %} <div class="infinite-item"> <div class="content-section"> <div class="media-body"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ post.user.username }}</h2> <h3 class="text-secondary">{{ post.highlight.quality }}</h3> <video src="{{ post.highlight.highlight.url }}" type='video/mp4' controls> Program is incompatable with your browser, please update it. </video> <script type="text/javascript"> $.post('/feed/submitview/', {id: {{ post.highlight_id }}}) </script> </div> </div> </div> {% endfor %} </div> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); -
Eror in configuring allauth at AUTHENTICATION_BACKENDS
settings.py """ Django settings for classproject project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 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/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '%__uki0du$y1bwf)m!#!(9%k*9$^u%gtbye*283&2mwtj(vh0g' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'mainapp', ] 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', ] ROOT_URLCONF = 'classproject.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', 'django.template.context_processors.request', ], }, }, ] WSGI_APPLICATION = 'classproject.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' … -
Serial file upload VS Parallel file upload
Scenario: There's a frontend (an iOS application) and a backend (a server). Frontend needs to upload a set of images ranging from 1 - 10 (Nos. may vary) with some image data, to the backend. Question: 1) Do I upload the images in parallel (One network request per image) or in serial (all images in a network request). Which method method would be better in terms of speed and other factors? 2) If serial upload is best suited, to my knowledge, multipart form-data is used. Considering the below details of the image, how to create the body to accommodate multiple records? { "picture" : "@/Users/userName/Desktop/picture.png", "model" : "the model name to which the image is linked", "record_id" : "the record, to which the image is linked" } I use Swift and Python (Django). For testing purposes I use postman and curl. Thank you -
login_required decorator not redirecting to the following view
I want to render the specified template only when the admin got logged in so I used login_required decorator but it is redirecting to admin rather than rendering and displaying the specified template @login_required(login_url='/admin/') def employeesignupview(request): return render(request,'todoapp/employeesignup.html') -
Why does my html not render in my Django app home page?
I am new to to using Django I am making a pet gallery app, I am using bootstrap for my front-end and i want to create pet card in my home page, my problem is the html i write in my index.htm doesn't render in the home page. My index.htm: <!DOCTYPE html> <html lang="en"> <head> <title> The Pet Gallery </title> {% load static %} <link rel="stylesheet" href="{% static 'pet_gallery/style.css' %} " /> <link rel="stylesheet" href="https://bootswatch.com/4/litera/bootstrap.min.css"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> {% include 'nav_bar.htm' %} <div class="card_container"> <div class="card_image"> <img src="" alt=""> </div> <h4 class="card_title"></h4> <div class="card_body"> </div> </div> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html> style.css: .card_container{ width: 200px; height: 700px; background-color: grey; } I really need help i have been at this for days, if you need any additional information to be of help I will gladly provide. -
Attach Multiple Instances of A Single Object Type To Multiple Parent Objects Types in Django
I have these models: class Organization(models.Model): name = models.CharField(verbose_name="Orgainzation Name", max_length=100, unique=True) ein = models.CharField(verbose_name="Entity Identification Number", max_length=10, unique=True) address = models.ForeignKey(Address, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL) updated = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL) class User(AbstractUser): address = models.ForeignKey(Address, models.SET_NULL) birth_date = models.DateField() phone = models.CharField(max_length=15)``` I want to be able to attach multiple files to each object type Organization and User. I created these models to do so: class OrgFile(models.Model): file = models.FileField() parent = models.ForeignKey(Organization, models.SET_NULL) class UserFile(models.Model): file = models.FileField() parent = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL) It seems like there should be a way to use one File model and attach it to different types of objects. Is this possible or do I need to make a class for each parent type? -
Relationship between 2 models in Django
I have two models- Order and Expense. The expense is a crud list respective to the particular Order. How can I make such a relationship between these two models? models.py - Order class Order(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="order",blank=True,null=True) client_name = models.CharField(max_length=100) event_name = models.CharField(max_length=100) contact = models.CharField(max_length=15) event_date = models.DateField(auto_now_add=False,auto_now=False) expenses = models.IntegerField(default=0,null=True,blank=True) Models.py - Expense class ProjectExpense(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="project_expense",null=True,blank=True) order_id = models.IntegerField(default='0') exp = models.CharField(max_length=100) exp_desc = models.TextField(null=True,blank=True) amount = models.IntegerField(default='0') def __str__(self): return self.exp Thoughts - I tried assigning the field Order ID with the current Order. But how will I able to pass the current Order.I'm really stuck in here, Thanks in advance! -
How to control Django model form
Assume that I have this model. class Text(models.Model): name = models.TextField(default="") changed_name = models.TextField(default="") data = JSONField(default=dict) Now I want use django model form to: 1. create input in template, only input for name and file. 2. validate file, extract it (inside is json) and send to model field, best if content can be validate separately for model field, like def clean_ method. 3. validate name, then process it and send to two fields, one original and one after changes. Now I did this all in view with custom template and only send corrected post to form, but I like to move all of it to form if it can be done. -
HTML/CSS input field shrinking
Hi I'm trying to develop a website for an online store using Django. In my checkout form, input fields like address,country, zipcode, phone are shrinking. However, the field for state (which is a field with choices is not shrinking). Even in my login and register forms, the input fields are shrinking. Can anyone please tell me why this is happening? My checkout.html: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <!-- Custom styles for this template --> <link href="./css/form-validation.css" rel="stylesheet" /> </head> <div class="container"> <div class="row"> <body class="bg-white"> <div class="container"> <div class="py-5 text-center"> <img class="d-block mx-auto mb-4" src="https://getbootstrap.com/assets/brand/bootstrap-solid.svg" alt="" width="" height="" /> <h2>Checkout</h2> </div> <div class="row"> <div class="col-md-4 order-md-2 mb-4"> <h4 class="d-flex justify-content-between align-items-center mb-3"> <span class="text-muted">Your cart</span> <span class="badge badge-secondary badge-pill">{{ request.session.items_total }}</span> </h4> <ul class="list-group mb-3"> {% for item in cart.cartitem_set.all %} <li class="list-group-item d-flex justify-content-between lh-condensed" > <div> <h6 class="my-0">{{ item.product.name }}</h6> <small class="text-muted">Brief description</small> </div> <span class="text-muted">${{ item.product.price }}</span> </li> {% endfor %} <li class="list-group-item d-flex justify-content-between bg-light"> <div class="text-success"> <h6 class="my-0">Promo code</h6> … -
How to add foreign key to a serializer manually in django rest framework?
while creating a branch, I want to add the id of a company(foreign key) according to the company of requested user. Basically I want to add company id at serializer level only. Here is my create function of branchViewset: def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, context=context) if serializer.is_valid(raise_exception=True): serializer.save(company=request.user.owner) and here is my serializer: class CreateBranchSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) def validate(self, attrs): try: user = self.context['request'].user except: raise CustomAPIException(status_code=status.HTTP_401_UNAUTHORIZED, error_code='1006') return attrs But while creating branch I get the error: company: field is required How can i solve this? -
Django admin, how to restrict a user to insert records only within his country?
I have this Model title= country = models.CharField(max_length=25) country = models.ForeignKey(Country) city = models.ForeignKey(City) user = country = models.ForeignKey(User) Using the (Add Case +)page in the default Django admin, is there anyway to customise the country and city dropdown lists options depending on the current user? For example: if the current logged in user is from USA, then the country dropdown list will show only one option (USA), and the city dropdown list will show only the cities in USA.Then, this user would be allowed only to add cases related to his/her country. -
Recommended way to provide configuration files to Docker containers
I am moving our web application to docker-compose deployment (Django, DRF, AngularJS). Docker looks solid now and things are going well. I want to: confirm with you that I am following best practices regarding application configuration files know if "volume files" are actually bind mounts, which are not recommended I've managed to use environment variables and docker-compose secrets read from the Django settings.py file and it works. The downside is that environment variables are limited to simple strings and can pose some escape challenges when sending Python lists, dictionaries etc. We also have to define and maintain a lot of environment variables since our web app is installed in many place and it's highly configurable. On frontend side (AngularJS) we have two constants.js files and the nginx conf. I've used a CMD ["/start.sh"] in Dockerfile and have some sed commands. But this looks really hackish and it also means that we have to define and maintain quite a few environment variables. Are Docker volumes a good idea for to use for these configuration files? Does such thing as "volume file" actually exist (briefly mentioned here) or is it actually a bind mount? And bind mounts are less recommendable since they … -
How can I have statistics in django admin panel on User with date filter on related field?
Related model class AbstractTask(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) issued_at = models.DateTimeField(auto_now_add=True) Problem I need to show some User statistics per days the admin panel. Lets say just number of tasks issued for users, being able to filter it by issue date (how many were issued yesterday, the day before yesterday, etc). How I do it I use User proxy models to register ModelAdmin for different statistics pages. I use slightly modified (changed date ranges) DateFieldListFilter on task__issued_at field: list_filter = [ ('task__issued_at', DateFieldListFilter), 'username', ] Filters don't work Filters don't work because they end up generating query similar to this: (queryset = User.objects .annotate( # Different statistics. num_tasks=Count('task'), ) .filter( # DateFieldListFilter. task__issued_at__gte='2020-01-01', task__issued_at__lt='2020-01-02, ) .values('id', 'num_tasks') ) SQL: SELECT "auth_user"."id", COUNT("task"."id") AS "num_tasks" FROM "auth_user" LEFT OUTER JOIN "task" ON ("auth_user"."id" = "task"."user_id") INNER JOIN "task" T3 ON ("auth_user"."id" = T3."user_id") WHERE (T3."issued_at" >= 2020-01-01 00:00:00+03:00 AND T3."issued_at" < 2020-01-02 00:00:00+03:00) GROUP BY "auth_user"."id" The problem is that filter adds second join on table "task" when I need just one. Forcing first inner join by adding .filter(task__isnull=False) doesn't help. It just keeps performing two identical inner joins. It is the same behavior in django 2 and 3. Can It … -
Test POST request for multipart/form-data in Pyresttest
I need to test API for multipart/form-data using pyresttest. I have tried https://github.com/svanoort/pyresttest/issues/158 for my API but it's not working. I have created formdata.txt: ----WebKitFormBoundary7MA4YWxkTrZu0gW Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW ----WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="data"; filename="/D:/File-Upload/movie.json" Content-Type: application/json (data) ----WebKitFormBoundary7MA4YWxkTrZu0gW and my yaml file look like: - test: - group: "Group test" - name: "Test name" - url: "/post_movie/" - method: "POST" - headers: {'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'} - body: {'file':'D:/File-Upload/formdata.txt'} - expected_status: [200] but i'm getting error: UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 156-157: truncated\UXXXXXXXX escape How can I test multipart/form-data in pyresttest ? -
Django ModelForm - Using ForeignKey for Choices
I'm attempting to build out a rather large "Patient Onboarding" form using ModelForms. I'm having trouble getting the choices within the foreign keys to appear in the admin area or to the rendered form without manually adding them to the Postgres database. There has got to be a more efficient way to be doing this...thanks in advance! #models.py from django.db import models from django.forms import ModelForm from django import forms class Patient(models.Model): first_name = models.CharField(max_length=30, verbose_name='First Name', blank=False) middle_name = models.CharField(max_length=30, verbose_name='Middle Name', blank=False) last_name = models.CharField(max_length=30, verbose_name='Last Name', blank=False) gender = models.ForeignKey('GenderChoices', on_delete=models.CASCADE, verbose_name='Gender', blank=False) date_of_birth = models.DateField(verbose_name='Date of Birth', blank=False) medications = models.ForeignKey('MedicationsYesNo', on_delete=models.CASCADE, verbose_name='Do you currently take any medications?', blank=False) class MedicationsYesNo(models.Model): medications_yes_no = models.CharField( max_length=100, choices = [ ('Yes', 'Yes'), ('No', 'No') ] ) def __str__(self): return self.medications_yes_no class OnboardingForm(ModelForm): class Meta: model = Patient fields = '__all__' -
How do I parse more than 2 argument in my URL Path function in Django
Please Assist me. I have this in my url Pattern of my blog app app_name = 'webpages' path('articles/<int:pk>/<slug:slug>', views.blog_detail, name='articles_detail'), How do I code this in the template? I have tried this <a href="{% url 'webpages:articles_detail' post.pk post.slug %}">{{post.title}}</a> I was able to do this for just one argument. but ran into trouble doing for two arguments. -
passing query to html page as linkes ? django / postgresql
I am trying to pass query to HTML page . I tried (request / loader ) to pass the query but it gives No unit are available but there is 3 unit in the database views.pay. from django.shortcuts import render from django.http import HttpResponse from .models import uints from django.template import loader def index(request): latest_uint = uints.objects.order_by('-listing_date')[:5] context = {'latest_unit' : latest_uint ,} return render(request, 'realstate/index.html', context) models.py. from django.db import models import datetime from django.utils import timezone class uints(models.Model): uint_text = models.CharField(max_length = 200) num_of_room = models.IntegerField(default=2) num_of_bathroom = models.IntegerField( default=1) listing_date = models.DateTimeField('listing date') HTML page. {% if latest_uint %} <ul> {% for uint in latest_uint %} <li><a href="/realstate/{{ uint.id }}/">{{ uint.uint_text }}</a></li> {% endfor %} </ul> {% else %} <p>No unit are available.</p> {% endif %}