Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Do I Incorporate Ajax into a CreateView?
I have a CreateView...and it works fine in the traditional sense. I'm trying to convert it essentially to an AJAX for submit because the user can attach files to the form, and I'm trying to avoid a form submission failure based on the user's mistakes. Here is my CreateView... class CreateProcedureView(LoginRequiredMixin,CreateView): model = NewProcedure form_class = CreateProcedureForm template_name = 'create_procedure.html' def form_valid(self, form): instance = form.save() def post(self, request, *args, **kwargs): if "cancel" in request.POST: return HttpResponseRedirect(reverse('Procedures:procedure_main_menu')) else: self.object = None user = request.user form_class = self.get_form_class() form = self.get_form(form_class) file_form = NewProcedureFilesForm(request.POST, request.FILES) files = request.FILES.getlist('file[]') if form.is_valid() and file_form.is_valid(): procedure_instance = form.save(commit=False) procedure_instance.user = user procedure_instance.save() list=[] for f in files: procedure_file_instance = NewProcedureFiles(attachments=f, new_procedure=procedure_instance) procedure_file_instance.save() return self.form_valid(form) else: form_class = self.get_form_class() form = self.get_form(form_class) file_form = NewProcedureFilesForm(request.POST, request.FILES) return self.form_invalid(form) As stated it works just fine the way it is. What I'm trying to figure out is how can I best convert this to an AJAX type of approach? Here's what I have so far... Here's my AJAX... $(document).ready(function (){ $("#forms").on('submit', function(event) { event.preventDefault(); var newprocedure = '{{ newprocedure }}'; $.ajax({ type: "POST", url: "{% url 'Procedures:ajax_posting' %}", data:{ newprocedure:newprocedure, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(data) { … -
Serving Django App with Apache 2 on Virtual Host
I am learning the Django framework and can run my first app on the development server using: python3 manage.py runserver However, what I really want to do is serve my app with Apache so it can be access from the web. My Apache Virtual Host is: <VirtualHost *:443> ServerName django.example.com DocumentRoot /var/www/django/hello_world/mysite WSGIScriptAlias / /var/www/django/hello_world/mysite/mysite/wsgi.py Include /etc/letsencrypt/options-ssl-apache.conf SSLEngine On SSLCertificateFile /etc/letsencrypt/live/django.example.com/cert.pem SSLCertificateKeyFile /etc/letsencrypt/live/django.example.com/privkey.pem SSLCertificateChainFile /etc/letsencrypt/live/django.example.com/chain.pem WSGIDaemonProcess django.sample.com processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/django/hello_world/mysite/venv/lib/python3.6 WSGIProcessGroup django.sample.com <directory /var/www/django/hello_world/mysite> AllowOverride all Require all granted Options FollowSymlinks </directory> </VirtualHost> I'm getting: My settings.py file is: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-3b^iz&pognt=yt5m&(!w@keo&*@a9zb&)$n@32v!yj4w%c!k-4' DEBUG = True ALLOWED_HOSTS = [ 'django.sample.com' ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'mysite.wsgi.application' 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', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' I'm running … -
What should be my main direction with django?
Heey django masters. I have some questions becouse I don't know which direction to go further. I mastered django on an average/medium level. I want ask you, what is the most important in django and what should I pay attention to. Maybe have you and good tips or tutorials for me? Last my question, when should i learn ajax? Javascript should be first? -
Dictionary not rendering in page
in my view im trying to pass in a dictionary like so rooms = [ {'id': 1, 'name': 'designign'}, {'id': 2, 'name': 'wow'}, {'id': 3, 'name': 'now'}, ] def home(request): context = {'rooms' : rooms} return render(request, 'home.html', context) Then in my home.html page i have this code {% extends 'main.html' %} {% block content %} <h1>Home Template</h1> <div> <div> {% for room in rooms %} <div> <h1>{{room.name}}</h1> </div> {% endfor %} </div> </div> {% endblock content %} but the items in the dictionary are not displaying. the url and path are fine because <h1>Home Template</h1> displays but nothing else displays main.html <body> {% include 'navbar.html' %} {% block content %} {% endblock %} </body> urlpattern if that matters urlpatterns = [ path('', views.home, name="home") ] -
Django/Scrapy/Apache - Error downloading <GET https://example.com>
I've created a web scrapper which runs from Django view and it works as expected when I run it locally but it gives an error when I run it from my (Apache)server. [scrapy.core.scraper] ERROR: Error downloading <GET https://example.com> FYI. I use valid URL addresses for sure and it works locally without any issues. Also, I've set "TELNETCONSOLE_PORT" :None, . Not sure if this is related to the issues but without this parameter it gave me another error. Unable to listen "127.0.0.1: 6023" -
CI/CD pipeline for Django failure
My gitlab ci pipeline keeps failing. It seems am stuck here. Am actually still new to the CI thing so I don't know what am doing wrong. Any help will be appreciated Below is .gitlab-ci.yml file image: python:latest services: - postgres:latest variables: POSTGRES_DB: projectdb # This folder is cached between builds # http://docs.gitlab.com/ee/ci/yaml/README.html#cache cache: paths: - ~/.cache/pip/ before_script: - python -V build: stage: build script: - pip install -r requirements.txt - python manage.py migrate only: - EC-30 In my settings.py file, I have the following settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'thorprojectdb', } } But when I push to gitlab, the build process keeps failing. The - pip install -r requirements.txt runs perfectly but once it gets to - python manage.py migrate, it fails. Below is the error I do get django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Cleaning up project directory and file based variables ERROR: Job failed: exit code 1 -
How to loop inside Stripe
I have a problem I would like to loop inside Stripe to create dynamic multiple objects in checkout. I can not do that after stripe.checkout.Session.create() because I get an error. Also I can not create JSON object in for loop out of stripe.checkout.Session.create(). Any ideas? How can I use for loop and create multiple line_items? def create_checkout_session(request): if request.method == "GET": try: cart = Cart.objects.get(order_user=request.user) checkout_session = stripe.checkout.Session.create( payment_method_types=['card', 'p24'], line_items=[{ 'price_data': { 'currency': 'eur', 'product_data': { 'name': 'total' }, 'unit_amount': cart.total, }, 'quantity': 1, }], -
How can I extract URL of the video uploaded using Django Embed video
I am using Django Embed Video to upload videos to my website that works perfectly fine. The code below is how I extract the url of the video that I uploaded. HTML TEMPLATE: {% for course in courses %} <div class="name"> <h3>{{course.video}}</h3> </div> {% endfor %} That gives me the url but what i want is the video id for example the url it gives looks like "https://youtu.be/iHkKTGYc6aA" and I just need the "iHkKTGYc6aA". It can be done with the python using the .replace method but whenever I try to use the if tags of django html template i get this error: Could not parse the remainder: The HTML code that I use {% for course in courses %} <div class="name"> {% if text in course.video %} <h3>{{url=course.video.replace("https://youtu.be/", "")}} </h3> {% endif %} </div> {% endfor %} I know it's not the right way of doing it but I shared it just to show what i want to achieve. My views.py: def Courses(request): courses = Video.objects.all() total_uploaded_videos = courses.count() text = "https://youtu.be/" url = "" context = {'courses':courses, 'total_uploaded_videos':total_uploaded_videos, 'text':text, 'url':url} return render(request, 'accounts/Course.html', context) Models.py: class Video(models.Model): name = models.CharField(blank=False, max_length=100, default="", null=False, primary_key=True) video = EmbedVideoField() def __str__(self): … -
How to print host information from Django model while using ModelViewSet of REST Framework
I'm using Django REST Framework that will allow users to save information and generate QR code image which will be URL of the user profile such as: http://127.0.0.1:8000/user/detail/fahad-md-kamal-fd028af3/ Something Like How can I access host address from Django Model so that I can use it to generate QR code? DRF Model class UserInfo(models.Model): def save(self, *args, **kwargs): if not self.slug: self.slug =f'{slugify(self.name)}' qrcode_image = qrcode.make(f"{host}/{self.slug}/") super(UserInfo, self).save(*args, **kwargs) Serializer Class class UserBaseReadSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.UserBase fields = ( 'url', 'phone', 'name', 'address', 'qr_code', 'slug', ) View Class: class UserInfoViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserBaseSerializer queryset = models.UserInfo.objects.all() While I was doing it with standared Django and Functional View I did it like: Functional View: def add_user_info(request): if request.method == 'POST': form_data = UserInfomationForm(request.POST) if form_data.is_valid(): obj = form_data.save(commit=False) obj.save(host =request.META['HTTP_ORIGIN']) Over ridding Model Class's save method class UserInfo(models.Model): def save(self, host=None, *args, **kwargs): if not self.slug: self.slug =f'{slugify(self.name)}-{str(uuid.uuid4())[:8]}' qrcode_image = qrcode.make(f"{host}/{self.slug}/") super(UserInfo, self).save(*args, **kwargs) -
Django: passing context data between html file in different apps
How can I pass the context data (int his case profile_total variable) create in one of my views to the html template of another app? This is my code: app1.views.py def view_profile(request): profile_total = UserProfile.objects.all().count() return render(request, 'profile/user_profile.html', {'profile_total': profile_total}) app2.stats.html <div class="container"> <h1> Show </h1> Profile submitted: {{ profile_total }} </div> Right now it's only displayed a blank space instead that the count of the profile submitted. Thank you all for your helps! -
Implementing a custom authentication in DRF which can read request.data
I have a foreign key on my models like Patient, and Doctor, which point to a Clinic class. So, the Patient and Doctor are supposed to belong to this Clinic alone. Other Clinics should not be able to see any detail of these Models. From my Vue app, I will post using Axios to the django app which uses DRF, and thus get serialized data of Patients and Doctors. It all works fine if I try to use the following sample code in function view: @api_view(['GET', 'POST']) def register_patient_vue(request): if request.method == 'POST': print("POST details", request.data) data = request.data['registration_data'] serializer = customerSpecialSerializer(data=data) if serializer.is_valid(): a = serializer.save() print(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) else: print("Serializer is notNot valid.") print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Sample output: POST details {'registration_data': {'name': 'wczz', 'ageyrs': 21, 'agemonths': '', 'dob': '', 'gender': 'unspecified', 'mobile': '2', 'email': '', 'alternate': '', 'address': '', 'marital': 'unspecified', 'city': '', 'occupation': '', 'linkedclinic': 10}} data: {'name': 'wczz', 'ageyrs': 21, 'agemonths': '', 'dob': '', 'gender': 'unspecified', 'mobile': '2', 'email': '', 'alternate': '', 'address': '', 'marital': 'unspecified', 'city': '', 'occupation': '', 'linkedclinic': 10} However, I need to authenticate the request by special custom authentication. I have another class called UserGroupMap which has Foreign Keys for … -
Get a single string attribute from my user's extended model
i think my question it's simple, but i'm new and i cannot figure it out. I have a user default Django model and my extended user model, and in my views.py i just want to get my logged user's address like a single string, i have been trying with different ways using (UserProfile.objects.values/filter/get etc...) but i just get errors. Thank you for your time! Models.py class UserProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) profile_pic = models.ImageField(null=True, blank=True, upload_to="profile_imgs") address = models.CharField(null=True, blank=True, max_length=150) curp = models.CharField(null=True, blank=True, max_length=18) Views.py @login_required(login_url='log') def test(request): address = "answer" context = { 'address': address, } return render(request, "test.html", context) -
How do I get Django to save Twilio Voice DTMF input to db.sqlite3?
I'm building an IVR using Python (3.9.5) Django (3.2.8) and Twilio Python Helper Library (7.1.0). My views.py contains multiple views which use Twilio's Gather verb to collect digits. How do I save this info to db.sqlite3? Example: models.py class Survey(models.Model): question1 = models.CharField(max_length=2) question2 = models.CharField(max_length=2) question3 = models.CharField(max_length=2) caller_id = models.CharField(max_length=12) date_time = models.DateTimeField(auto_now_add=True) Example: views.py def question1(): response = VoiceResponse() gather = Gather(input='dtmf') gather.say('How many cars do you own?') response.redirect('../question2') print(response) def question2(): response = VoiceResponse() gather = Gather(input='dtmf') gather.say('How many homes do you own?') response.redirect('../question3') print(response) def question3(): response = VoiceResponse() gather = Gather(input='dtmf') gather.say('How many boats do you own?') response.redirect('../end') print(response) def end(): response = VoiceResponse() response.say('One moment please.') response.pause(length=1) response.say('Thank you. Your input has been saved.') response.hangup() print(response) How do I save the collected digits to the appropriate fields specified in models.py? I only want to save the data once all 3 questions have been answered. If a caller hangs up before answering all 3 questions then I don't want to save anything. How do I save the caller id and date time to the appropiate fileds specified in models.py? I want this info to be displayed in the admin panel. Please help and thanks … -
How to provide context to django class view get method
I have a class based view which I want supply some context to but I don't know how I can achieve this Below is the views.py class Dashboard(LoginRequiredMixin, View): def get(self, request): if request.user is not None and len(request.user.payment_set.all()): if request.user.is_active and request.user.payment_set.first().active: print(eligible_to_review(self.request)) return render(request, 'main.html') else: return redirect('home') else: return redirect('membership') How can I pass a context to this view in order to use it in the html file -
PYODBC Multiple cursors
I hope you're ok Im writing a django app on py3.9.1 and want to execute multiple cursors on mssql server. Here is my connection to mssql database conn = pypyodbc.connect("....") cursor = conn.cursor() cursor1 = conn.cursor() Here is my views.py @login_required(login_url="user:login") @allowed_users(allowed_permissions=["Management Perm","Boss Perm","Account Perm"]) def bills(request): keyword = request.GET.get("keyword") header = "Faturalar | Mavis Development" company = UserCompany.objects.filter(user = request.user).values_list("company__company",flat=True)[0] role = request.user.groups.all()[0].name if keyword: bills_for_acc = cursor.execute("Select * From bills where mancheck = 0 and acccheck = 0 and company = ? and title = ? order by created_date",(company,keyword,)) bills_for_man = cursor1.execute("Select * From bills where mancheck = 0 and acccheck = 1 and company = ? and title = ? order by last_checked_date",(company,keyword)) content = { "bills_for_man":bills_for_man, "bills_for_acc":bills_for_acc, "header":header, "role":role, } return render(request,"bills.html",content) bills_for_acc = cursor.execute("Select * From bills where (acccheck = 0 and mancheck = 0) and company = ? order by created_date",(company,)) bills_for_man = cursor1.execute("Select * From bills where (mancheck = 0 and acccheck = 1) and company = ? order by last_checked_date",(company,)) content = { "bills_for_man":bills_for_man, "bills_for_acc":bills_for_acc, "header":header, "role":role, } return render(request,"bills.html",content) When I trying to show bills.html i get '('HY000', '[HY000] [Microsoft][ODBC SQL Server Driver]'Connection is busy with results for another hstmt.') On … -
How to add additional field in Django Rest Framework for a model that is a foreign key on another model
I am looking to list out all of the teachers in a certain department in Django rest framework and am unsure of how to do so. I believe this would be done by adding a field to the Department serializer but I am not sure. Is there an easy way of how this can be done. models.py class Department(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=300) department = models.ForeignKey(Department, on_delete=models.CASCADE) tenure = models.BooleanField() serializers.py class DepartmentSerializer(serializers.HyperlinkedModelSerializer): #What I believe the serializer field would look like to list teachers connected #with a department teacher = serializers.DjangoModelField( Teacher.objects.filter(department=self.department)) class Meta: model = Department fields = ['url', 'name', 'teacher'] urls.py router = DefaultRouter() router.register(r'teachers', TeacherViewSet) router.register(r'departments', DepartmentViewSet) router.register(r'users', UserViewSet) urlpatterns = [ path('api/', include(router.urls)), ] views.py class TeacherViewSet(viewsets.ModelViewSet): queryset = Teacher.objects.all() serializer_class = TeacherSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] class DepartmentViewSet(viewsets.ModelViewSet): queryset = Department.objects.all() serializer_class = DepartmentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] -
OpenLDAP docker Osixia - can not authenticate
I've just tried to configure docker-compose.yml file according to YTB video and github, but with any result. version: "2" services: web: # the application's web service (container) will use an image based on our Dockerfile build: "." # map the internal port 80 to port 8000 on the host ports: - "8000:80" # map the host directory to app (which allows us to see and edit files inside the container) volumes: - ".:/app:rw" - "./data:/data:rw" # the default command to run whenever the container is launched # command: python manage.py runserver 0.0.0.0:80 # the URL 'postgres' or 'mysql' will point to the application's db service links: - "database_default" env_file: .env-local database_default: # Select one of the following db configurations for the database image: postgres:9.6-alpine environment: POSTGRES_DB: "db" POSTGRES_HOST_AUTH_METHOD: "trust" SERVICE_MANAGER: "fsm-postgres" volumes: - ".:/app:rw" openldap_service: image: osixia/openldap:1.1.8 ports: - "636:636" volumes: - ".:/data:rw" environment: - LDAP_ORGANISATION=ramhlocal - LDAP_DOMAIN=ramhlocal.com - LDAP_ADMIN_USERNAME=admin - LDAP_ADMIN_PASSWORD=admin_pass - LDAP_CONFIG_PASSWORD=config_pass - "LDAP_BASE_DN=dc=ramhlocal,dc=com" - LDAP_TLS_CRT_FILENAME=server.crt - LDAP_TLS_KEY_FILENAME=server.key - LDAP_TLS_CA_CRT_FILENAME=ramhlocal.com.ca.crt - LDAP_READONLY_USER=true - LDAP_READONLY_USER_USERNAME=user-ro - LDAP_READONLY_USER_PASSWORD=ro_pass phpldapadmin-service: image: osixia/phpldapadmin:0.9.0 environment: - PHPLDAPADMIN_LDAP_HOSTS=127.0.0.1 ports: - "6443:443" volumes: - ".:/data:rw" I can go to the phpldapadmin, but it shows this:enter image description here Would you know, where is the problem? … -
Django & microservices - How can I design microservices in django
I'm learning Microservices and there s requirement to develop like a Amazon filter and there are other filter as well.How could I able to do it with microservices. UI Design specifically has the filters on the right whenever the user select the filter the particular element containing row should be displayed on the right side of the table. For designing the microservices can I take the all data which is provided in microservices and filter in another microservices. I just stuck with the filter part how can I design with django it supposed to be done from the front side ? Or can it be designed through microservices. I design only the api with the microservices or do I make back end functionality for that.i have major doubt if I design only the api how could I call in django template? Is microservices only creating an api.for instance there is an django project where user can like and comment on the post. In like where users can like the post and comment project where user can comment on the post. And both are dockerised as well.Both connected through microservices in order to get a like and comment together in the … -
Deploying Django app : Forbidden You don't have permission to access this resource
I was deploying my django app on my VPS using the apache web server. It works totally fine on http://192.46.209.82:8000/ but when I try to access the same using my IP address, 192.46.209.82. I get Forbidden You don't have permission to access this resource. Apache/2.4.41 (Ubuntu) Server at 192.46.209.82 Port 80 Here is my conf file nano /etc/apache2/sites-available/000-default.conf <VirtualHost *:80> ServerAdmin webmaster@example.com DocumentRoot /root/django/myproject ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /root/django/myproject/static <Directory /root/django/myproject/static> Require all granted </Directory> <Directory /root/django/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/root/django/myproject python-home=/root/django/myprojectenv WSGIProcessGroup myproject WSGIScriptAlias / /root/django/myproject/myproject/wsgi.py </VirtualHost> I am using python's virtual environment, where myprojectenv is my virtual env path and the pwd is /root/django Note : I tried the answer from the question that I was getting as suggestion to this question but that did not work for me. -
How do I install Python web project on Centos
I have created a Python web application using VS2022 (Django Web Project type). It is working as I expect using local url access - executing from VS2022. However, how do I proceed to implementing this as an operating web site on a server. I have a Centos 8 server with complete root control. With simple html pages I can upload this then enter my URL in a browser and all ok. Can anyone give me the broad details of how to achieve the same thing with my Python code. I know I have to install pip, Python (3 in this case) and Django but beyond that I am not sure how to proceed. Apologies as this is such a broad question, I just need some pointers or tutorial type links. thanks in advance -
Django api requests not working on AWS elastic beanstalk
I've created a django application and deployed it using aws elastic beanstalk. The GET requests to fetch the static files are working fine. But any other requests made directed to the django app specifically, is timing out. Here is the commands in .ebextensions folder 01_packages.config packages: yum: postgresql-devel: [] django.config option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "app_server.settings" "PYTHONPATH": "/var/app/current:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: app_server.wsgi:application NumProcesses: 3 NumThreads: 20 aws:elasticbeanstalk:environment:proxy:staticfiles: /static/: "staticfiles/" These are installed apps and middleware settings in settings.py file INSTALLED_APPS = [ 'insta_backend.apps.InstaBackendConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'storages' ] 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', # 'corsheaders.middleware.CorsMiddleware', # "whitenoise.middleware.WhiteNoiseMiddleware", 'django.middleware.common.CommonMiddleware', ] The routes of the django app work fine locally. But when deployed using EB, the requests are timing out or cancelled. The preflight request made here times out. Following is the screenshot of the network requests from chrome dev tools -
In Django, how to bind the dropdown list with data from another table using foreign key?
model.py class LabTable(models.Model): LabNo = models.AutoField(primary_key=True) Pid = models.IntegerField() Weight = models.IntegerField() DoctorId = models.ForeignKey(DoctorTable,on_delete=models.CASCADE) Date = models.DateField() Category = models.CharField(max_length=50) PatientType = models.CharField(max_length=50) Amount = models.IntegerField() 1.Here, I have created the lab model and a foreign key with doctor table. I want to use doctor table to present data in dropdown. -
upload multiple images with django formset and ajax request
I'm trying to upload multiple images with django formset and through ajax request . i know i have to use formData.append("name",document.getElementById("img_1_id").files[0]); but i dont know how to do it for several image fields ? is there something to fix it please ? i dont want to use several input files statically , i want to implement it dynamically , so i have used model formset factory , class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) def __str__(self): return str(self.booking.id) and here is my forms.py class UploadDocumentsForm(forms.ModelForm): class Meta: model = Document fields = ['docs'] UploadDocumentFormSet = modelformset_factory(Document,form=UploadDocumentsForm,extra=1,can_delete=True) and here is my views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.is_ajax() and request.method == 'POST': images = UploadDocumentFormSet(request.POST,request.FILES) if images.is_valid(): for img in images: if img.is_valid() and img.cleaned_data !={}: img_post = img.save(commit=False) img_post.booking = obj img_post.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('choose right image ..')) images = UploadDocumentFormSet(queryset=Document.objects.none()) return render(request,'booking/add_img.html',{'obj':obj,'images':images}) and here is my templates $('#addButton').click(function() { var form_dex1 = $('#id_form-TOTAL_FORMS').val(); $('#images').append($('#formset').html().replace(/__prefix__/g,form_dex1)); $('#id_form-TOTAL_FORMS').val(parseInt(form_dex1) + 1); }); <button id="addButton" class="px-4 py-1 pb-2 text-white focus:outline-none header rounded-xl"> {% trans "add new image" %} </button> <div class="flex flex-wrap justify-between "> <div class="text-lg w-full border p-3 border-purple-900 rounded-lg"> <form action="" method="POST" enctype="multipart/form-data" dir="ltr">{% csrf_token %} {% for form … -
Invalid boundary in multipart: None Django Rest API
I am using function based api views on django to handle an image upload initiated through react (axios). The frontend work works but I am having a problem in django views. Invalid boundary in multipart: None This is my code @api_view(['get', 'post']) @parser_classes([MultiPartParser]) def HandleUpload(request): .... if request.method == 'POST': image = request.data.get('image') instance.image = image instance.save() I am even using the parser_classes to allow MultiPartParser in this case. Why is it not possible to get the file from request.data.get? I tried even with request.FILES but still I had the same problem. I have searched online for 2 day but none offer a suitable solution to this particular problem as most are using class based views or using form serializers to upload images. Is it possible to upload images in function based api views after all? Can anyone help me understand the problem? -
How do I display Images in React from a Django Rest API?
I want to send my images from the django media folder to my react front end. And the view I build works when I go to the Url 'api/id/1' the image gets displayed but when I want to open it in my react app under loacalhost:8000 the image is not being displayed the view class PNGRenderer(renderers.BaseRenderer): media_type = 'image/png' format = 'png' charset = None render_style = 'binary' def render(self, data, media_type=None, renderer_context=None): return data class ImageAPIView(generics.RetrieveAPIView): queryset = Images.objects.filter(id=1) renderer_classes = [PNGRenderer] def get(self, request, *args, **kwargs): renderer_classes = [PNGRenderer] queryset = Images.objects.get(id=self.kwargs['id']).image data = queryset return Response(data, content_type='image/png') the API call export function apiImage(image,callback) { const endpoint = `id/${image}` backendlookup('GET', endpoint ,callback) } function App() { const classes = useStyles() const handleLookup = (response, status) => { if (status === 200) { console.log(response) } } const [img, setImg]=useState(apiImage(2,handleLookup)) const ImgChange =(e) =>{ if(e === 'laugh'){ setImg(Trainer_Laugh) } if(e === 'smile'){ setImg(Trainer_Smile) } } return ( <Grid container display="flex" direction="column" justifyContent="center" alignItems="center" className={classes.grid}> <img src={img} alt='girl' className={classes.img}/> <Paper className={classes.paper} > <Textfield handleWaifuChange={ImgChange}/> </Paper> </Grid> ); } export default App;