Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Patch to add a new instance of a nested field when using a RetrieveAPIView in Django Rest Framework
I have a set up a route for a RetrieveAPIView and am testing it in Postman using PATCH. I am writing a value into a nested field, which is working but deletes all other instances of that nested model. Here is what I enter in 'JSON body' in Postman { "cards": [ 9 ] } When I PATCH the value '9', it deletes all other 'card' instances. I was expecting it to simply add that 'card' instance without taking the others away. This is an example of the response: { "id": 19, "name": "collector two", "email": "two@example.com", "cards": [ 9 ] } Here is my view code class CollectorRetrieveView(generics.UpdateAPIView): queryset = Collector.objects.all() serializer_class = SmallCollectorSerializer permission_classes = [HasAPIKey | IsAuthenticated] lookup_field = 'email' Serializer class SmallCollectorSerializer(serializers.ModelSerializer): class Meta: model = Collector fields = ["id", "name", "email", "cards"] Route path("collector_retrieve/<email>", CollectorRetrieveView.as_view(), name="collector_retrieve"), I tried to PATCH 'card' 9 without deleting the other card instances -
Thumbnail display problem in django templates - sorl-thumbnail
I hope you're all well. I'm making a small Django site, for the frontend I wanted to integrate thumbnail to properly visualize the graphics of the site but this is not displayed So I went through 3 steps with the sorl-thumbnail github: pip install sorl-thumbnail in the django settings, specify 'sorl.thumbnail' in the apps section Put the following lines in a template where I want to display a thumbnail {% load thumbnail %} {% thumbnail item.image "100x100" crop="center" as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endthumbnail %} But nothing is displayed. Do you have any idea why? -
Docker-Compose: Can't find entrypoint.sh when mounted
I'm trying to build a compose file with Django services with an entrypoint for each service to perform migrations, but docker can't locate the entrypoint.sh when I mount my directory, but it works when I don't. the container shows this error exec /code/dev/point.sh: no such file or directory dockerfile FROM python:3.11-slim-bullseye WORKDIR /code COPY req.txt . RUN pip3 install -r req.txt --no-cache-dir COPY ./dev/entrypoint.sh ./dev/ RUN sed -i 's/\r$//g' ./dev/entrypoint.sh RUN chmod +x ./dev/entrypoint.sh # Convert line endings to Unix-style (LF) RUN apt-get update && apt-get install -y dos2unix && dos2unix ./dev/entrypoint.sh && chmod +x ./dev/entrypoint.sh COPY . . ENTRYPOINT ["/code/dev/entrypoint.sh"] CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] compose.yaml services: auth: build: context: ./Auth dockerfile: dev/dockerfile container_name: Auth env_file: - "./Auth/Auth/.env" ports: - 8001:8000 expose: - 8001 networks: - backend volumes: - ./Auth:/code artifact: build: context: ./Artifact dockerfile: dev/dockerfile container_name: Artifact env_file: - "./Artifact/Artifact/.env" ports: - 8002:8000 expose: - 8002 networks: - backend volumes: - ./Artifact:/code networks: backend: entrypoint.sh #!/bin/sh # entrypoint.sh python manage.py makemigrations # Run migrations python manage.py migrate # Then run the main container command (passed to us as arguments) exec "$@" directory structure inside docker: -
Why does this error Django throw the error cannot resolve keyword slug
I have been trying to build a students learning platform but am having some real issues using slug in Django to create readable urls but i have encountered this error Cannot resolve keyword 'slug' into field. Choices are: Notes, Standard, Standard_id, created_at, created_by, created_by_id, id, lesson_id, name, position, ppt, slugs, subject, subject_id, video Request Method: GET Request URL: http://127.0.0.1:8000/curriculumprimary-four/001/None/ Django Version: 3.2.12 Exception Type: FieldError Exception Value: Cannot resolve keyword 'slug' into field. Choices are: Notes, Standard, Standard_id, created_at, created_by, created_by_id, id, lesson_id, name, position, ppt, slugs, subject, subject_id, video Exception Location: /usr/lib/python3/dist-packages/django/db/models/sql/query.py, line 1569, in names_to_path Python Executable: /usr/bin/python3 Python Version: 3.10.6 Python Path: ['/home/aiden/Projects/LMS/LMS', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/aiden/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Tue, 25 Jul 2023 09:27:05 +0000 This my models.py file code from typing import Iterable, Optional from django.db import models import os from django.template.defaultfilters import slugify from django.contrib.auth.models import User from django.urls import reverse class Standard(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(null=True, blank = True) description = models.TextField(max_length=500, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) return super().save(*args, **kwargs) def save_subject_img(instance, filename): upload_to = 'Images/' ext = filename.split('.')[-1] #get filename if instance.subject_id: filename = 'Subject_Pictures/{}.{}'.format(instance.subject_id, ext) return os.path.join(upload_to,filename) class Subject (models.Model): … -
TyoeError: context must be a dict rather than set
When I input the 127.0.0.1:8000/decore_detail/123B/, I want to get the decore_detail.html. But, I run the following config code, it reports me the error. How to solve it? "TyoeError: context must be a dict rather than set" Traceback (most recent call last): File "C:\Users\daiyij\Anaconda3\envs\django\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\daiyij\Anaconda3\envs\django\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\decoredesigner\mySite\DecoreGenerator\views.py", line 14, in decore_detail return render(request,'decore_detail.html',{'decore_detail',decore_detail}) File "C:\Users\daiyij\Anaconda3\envs\django\lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\daiyij\Anaconda3\envs\django\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\daiyij\Anaconda3\envs\django\lib\site-packages\django\template\backends\django.py", line 57, in render context = make_context( File "C:\Users\daiyij\Anaconda3\envs\django\lib\site-packages\django\template\context.py", line 278, in make_context raise TypeError( Exception Type: TypeError at /decore_detail/7520N/ Exception Value: context must be a dict rather than set. The urls.py: from myapp.views import decore_detail urlpatterns = [ path('admin/', admin.site.urls), path('decore_detail/<str:decore_detail>/',views.decore_detail,name='decore_detail'), ] The views.py: def decore_detail(request,decore_detail): context = {"decore_detail": decore_detail} return render(request,'decore_detail.html',{'decore_detail',decore_detail}) The decore_detail.py: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Item Detail</title> </head> <body> <h1>Item Detail - {{decore_detail}}</h1> </body> </html> -
No module named 'celery.tasks' when trying to import inspect/revoke function in celery
I was trying to import revoke() method from celery module as follows - from celery.tasks.control import revoke but it says, "No module named 'celery.tasks'". Why is it so? All celery tasks are working perfectly fine but whenever I try to revoke/inspect a particular celery task using it's ID, this returns error. Is there any other way to revoke/inspect a celery task using it's ID? -
How to run a react+django app as an Ubuntu service?
I know I can run a React + Django app from the command line, e.g.: > npm start > python manage.py runserver But I want it to keep running even after I exit the terminal, or reboot the computer, just like the other services on my Ubuntu machine. Is there a simple way to run the app by e.g. > service react start > service django start and stop it using > service react stop > service django stop so that the service automatically starts at startup? -
Django Model field isn't visible in Django Admin
Django admin isn't showing category field I have Model class UserCart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) menu_item_quantity = models.SmallIntegerField(max_length=2), unit_price = models.DecimalField(max_digits=6, decimal_places=2) price = models.DecimalField(max_digits=6, decimal_places=2) class Meta: unique_together = ('user', 'menu_item') And I have also registered in admin.py from django.contrib import admin from .models import Category, MenuItem, Order, OrderItem, UserCart (...) admin.site.register(UserCart) but Django admin shows only user, menu item, unit price, and price field How can i fix it -
Need matching Django ORM query with SQL
I am having table structure like below and my input is like 2018 id registration_year 1 2014-2016 2 2017-2019 My sql query is like below, SELECT id FROM table_name WHERE SUBSTRING(registeration_year,1,4) <= 2018 AND SUBSTRING(registeration_year,6,4) >= 2018 then id will be 2. I want to convert it into Django ORM query. Thanks in advance. Kindly help with Django. -
'auth/captcha-check-failed', message: 'Hostname match not found',
My Firebase configurations are correct still I'm getting a hostname match not found error. Even if the hostname is mentioned in the authorized domain of Firebase. What I'm trying to do is when the user fills in the phone number field and clicks on send code, he will see recaptcha and then after verifying, he will get OTP code on the phone number he gave as input. `{% extends 'customer/base.html' %} {% load bootstrap5 %} {% block head %} <script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-auth.js"></script> <script src="https://www.google.com/recaptcha/api.js" async defer></script> {% endblock head %} {% block main %} <b class="text-secondary">Basic Information</b><br> <div class="card mb-5 mt-2 bg-white"> <div class="card-body"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form userForm %} {% bootstrap_form customer_Form %} <input type="hidden" name="action" value="update_profile"> <button type="submit" class="btn btn-warning">Save</button> </form> </div> </div> <b class="text-secondary">Change Password</b><br> <div class="card mb-5 mt-2 bg-white"> <div class="card-body"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form password_form %} <input type="hidden" name="action" value="update_password"> <button type="submit" class="btn btn-warning">Save</button> </form> </div> </div> <b class="text-secondary">Phone Number</b><br> <div class="card mb-5 mt-2 bg-white"> <div class="card-body"> <div id="recaptcha-container"></div> <div id="get-code" class="input-group mb-3"> <input type="text" class="form-control" placeholder="Phone Number" > <button class="btn btn-warning" type="button">Send Code</span> </div> <div id="verify-code" class="input-group mb-3 d-none"> <input type="text" class="form-control" placeholder="Verification Code" > … -
How to run django project contains an docker file
I'm trying to run my Django project first time I'm using docker readme file Docker should be running In the project root run `docker-compose up` Go to localhost to view the project docker-compose.yml version: '3.7' services: web: build: context: . dockerfile: Dockerfile entrypoint: "/app/run_server.sh" ports: - "80:8000" env_file: - .env volumes: - .:/app/ restart: "on-failure" depends_on: - db - redis db: image: postgres:11-alpine volumes: - ~/pgsql/quiz_bot:/var/lib/postgresql/data/ environment: - POSTGRES_PASSWORD=password - POSTGRES_DB=postgres - PGPORT=5432 - POSTGRES_USER=postgres restart: "on-failure" # Redis redis: image: redis hostname: redis I tried to do makemigrations but it shows an error like RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "db" to address: Unknown host How to solve this issue? -
I want to create a API endpoint to fetch User and User Profile by attribute "user_id" in djangoRestAPI, user_id will be sent by the client
models.py class User_profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=False) phone = models.CharField(max_length=20, blank=False) profileImg = models.ImageField(upload_to='User/Profile_Picture', default='User/Profile_Picture/logo.png') city = models.CharField(max_length=50, blank=False, default=None) state = models.CharField(max_length=50, blank=False, default=None) birthdate = models.DateField(blank=False) bio = models.TextField(max_length=1000, blank=True, null=True) privacy = models.CharField(max_length=20, choices=PRIVACY_CHOICES, default='public', blank=False) requests = models.ManyToManyField(User, related_name='follow_request_user', default=None, blank=True) verified = models.BooleanField(default=False, blank=False) following_user = models.ManyToManyField(User, related_name='following_user', default=None, blank=True) followers = models.ManyToManyField(User, related_name='user_followers', default=None, blank=True) objects = models.Manager() def __str__(self): return self.name serializer.py from rest_framework import serializers from .models import * class ProfileSerializer(serializers.ModelSerializer): class Meta: model = User_profile fields = "__all__" **api_views.py ** from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework.views import APIView from .serializer import * from .models import * class ProfileAPI(APIView): def get(self, request, *args, **kwargs): user = get_object_or_404(User, id=kwargs['user_id']) profile_serializer = ProfileSerializer(user,many=True) return Response(profile_serializer.data) **api_urls.py ** from django.urls import path from . import api_views urlpatterns = [ path('profile/<user_id>', api_views.ProfileAPI.as_view(), name="profile") ] I want my response in JSON format so that i can use it in android app. I went through many blogs and Stackoverflow answers but any of that didn't give desired output In Short i just expect that client sends a userid and get User and UserProfile in json format getting "TypeError: 'User' object … -
How to parse a array variable into a Django template
So I have a views.py which contains the following code that is applicable to the problem. def check(request): data = [] if request.method == 'POST': prompt = request.POST['pathway'] youtube = request.POST.get('youtube') udemy = request.POST.get('udemy') # Uses the user's prompt to generate the roadmap data = scrapeSite(prompt) looprange = range(len(data)) if youtube == "youtubego": ytid, yttitle,ytthumbnail = searchyt(prompt, data) context = { 'ytid': ytid, 'yttitle': yttitle, 'loopnum': looprange, 'ytthumbnail': ytthumbnail, } return render(request, 'generate.html', context) basically it gets the thumbnails, titles and ids of a variable number of YouTube videos. They are all stored in different arrays. Each of these are assigned to a value in the context dictionary which is then sent to the template generate.html shown below {% extends 'main.html'%} {% block title %}CourseCounduit || A University In Your Pocket{% endblock title%} {% block content %} <h1>Your roadmap for</h1> <div id="Course-container"> {%for i in loopnum %} <div> <img src="{{ytthumbnail.i}}" alt="" sizes="100px" srcset="100px"> <h5>{{yttitle.i}}</h5> </div> {%endfor%} </div> {% endblock %} so the main result i was expecting is for the div "course container " to be duplicated to the amount of loopnum specified in views.py and for each iteration the img tag would display the ith url of the array … -
How to dynamically update sitemap.xml in react?
I want to update the sitemap.xml file dynamically like showing all the url possible from the database using API call. I am using django rest framework for this and from the backend I generated all the url possible but I dont know how can I update sitemap.xml. class SiteMap(APIView): def get(self,request): posts = list(Posts.object.values('id','publish_date').all()) return JsonResponse(posts,safe=False) Using the id, publish_date I want to generate xml file and show it. How can i achieve this? -
Django. How to create a new instance of a model from views.py with an image field in the model
I am trying to create a new instance of a model that has an image field in it. I take a PDF from a form and convert it to a png file format and am now trying to save the png image to a model data base but get the error 'PngImageFile' object has no attribute '_committed'. I know you cant save an image directly to a data base but i'm wondering how can you save the image to the media folder and save the image url path to the image in the data base? Help greatly appreciated. This is my form to take in the PDF (forms.py) class DrawingPDFForm(forms.Form): drawing_name = forms.CharField(max_length=50) file = forms.FileField() This is my view to convert PDF to PNG and then create new instance of model to save to database(views.py) def upload_drawings(request): if request.method == "POST": form = DrawingPDFForm(request.POST, request.FILES) drawing_name = request.POST['drawing_name'] file = request.FILES['file'] pdf_byt = file.read() pdf_content = BytesIO(pdf_byt) pdf_content.seek(0) pdf_converted = convert_from_bytes(pdf_content.read(), poppler_path=r"C:\Python\Python\Programs\plant_locator\poppler\poppler-23.07.0\Library\bin") buffer = BytesIO() pdf_converted[0].save(buffer, 'png') png_byt = buffer.getvalue() my_string = base64.b64encode(png_byt) pdf_png_byt_decode = base64.b64decode(my_string) png = Image.open(BytesIO(pdf_png_byt_decode)) drawing = Drawing.objects.create(drawing_name=drawing_name, drawing=png)#error occurs here as #expected drawing.save() return HttpResponseRedirect('/upload_drawings') else: form = DrawingPDFForm() return render(request, 'upload_drawings.html', {'form':form}) This … -
Celery and Redis error when running celery
I'm making a django app with celery and redis that udpates stock prices asynchronously. I'm working on the background tasks right now and celery won't run properly. I turn on the Redis server then django server and when I turn on the celery one with celery -A celery worker -l info I get this error... [2023-07-24 20:25:37,798: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 61] Connection refused. Trying again in 2.00 seconds... (1/100) There's also this above it and I want to point out that it's not connecting to my broker url I provided it.. [2023-07-24 20:25:37,688: WARNING/MainProcess] No hostname was supplied. Reverting to default 'localhost' celery@Gabes-MBP.hsd1.ca.comcast.net v5.3.1 (emerald-rush) macOS-13.2.1-arm64-arm-64bit 2023-07-24 20:25:37 [config] .> app: default:0x101ecc220 (.default.Loader) .> transport: amqp://guest:**@localhost:5672// .> results: disabled:// .> concurrency: 8 (prefork) .> task events: OFF (enable -E to monitor tasks in this worker) [queues] .> celery exchange=celery(direct) key=celery [tasks] This is my settings.py, #celery settings CELERY_BROKER_URL = "redis://localhost:6379" CELERY_ACCEPT_CONTENT = 'application.json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'America/New_York' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' This is my celery.py, from __future__ import absolute_import, unicode_literals import os from celery import Celery # from django.conf import settings # from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.\_base') app … -
Setting up a postgresql testing database for pytest suite for django project
I am relatively new to Python/Django and Pytest. I have a couple of methods that I would like to test that require changes to be made to my database. I have been utilizing fixtures to set up and tear down my database per session. However, my pytests want to keep using my original database, which defeats the purpose of having a test database (I am getting access denied anyway saying "I cannot access this database in Testing"). I believe this is due to my database router I have setup. I plan to have a database per app in the project, so my logic is "app_name == database_name". Below is what I have for my setup and teardown: import pytest import psycopg2 import os @pytest.fixture(scope='session') def postgresql_db(): # Set up the test database connection db_name = 'test_db' connection = psycopg2.connect( dbname=os.environ.get('POSTGRES_DB', 'postgres'), user=os.environ.get('POSTGRES_USER', 'postgres'), password=os.environ.get('POSTGRES_PASSWORD', ''), host=os.environ.get('POSTGRES_HOST', 'localhost'), port=os.environ.get('POSTGRES_PORT', '5432'), ) # Create the test database with connection.cursor() as cursor: cursor.execute(f"CREATE DATABASE {db_name};") yield connection # Close the connection and clean up the test database connection.close() with psycopg2.connect( dbname=os.environ.get('POSTGRES_DB', 'postgres'), user=os.environ.get('POSTGRES_USER', 'postgres'), password=os.environ.get('POSTGRES_PASSWORD', ''), host=os.environ.get('POSTGRES_HOST', 'localhost'), port=os.environ.get('POSTGRES_PORT', '5432'), ) as cleanup_connection: with cleanup_connection.cursor() as cursor: cursor.execute(f"DROP DATABASE IF EXISTS {db_name};") Am … -
bind(): Operation not supported [core/socket.c line 230]
I'm having a problem running django with uwsgi/nginx on docker. please what could be the issue?uwsgi error I'm not quite sure what the issue is and I've tried googling the error, but nothing comes up. bellow is my uwsgi and nginx set up. [uwsgi] socket=/code/educa/uwsgi_app.sock chdir= /code/educa/ module=educa.wsgi:application master=true chmod-socket=666 uid=www-data gid=www-data vacuum=true # upstream for uWSGI upstream uwsgi_app { server unix:/code/educa/uwsgi_app.sock; } server { listen 80; server_name www.educaproject.com educaproject.com; error_log stderr warn; access_log /dev/stdout main; location / { include /etc/nginx/uwsgi_params; uwsgi_pass uwsgi_app; } } -
Specifying filename when using boto3.upload_file()
I am using boto3.client('s3').upload_file(source_file_path, bucket, key) to upload a file I have generated. How do I specify a user friendly file name for this file when it is downloaded? -
Django: How do I serialize a nested relationship when the nested target has inherited subtypes?
How can I create a serializer for a nested relationship, with a transaction, where the nested relationship has several child types? I’ve read through the documentation and that doesn’t seem to be well-covered. We have an application for insuring homeowners, with the following structure: class Homeowner(models.Model): name = models.CharField(max_length = 100, null = True, blank = True) property = models.ForeignKey(Property, null = True) class Property(models.Model): address = models.CharField(max_length = 500, null = True, blank = True) # lots more removed. Not an abstract model. class House(Property): number_of_floors = models.IntegerField(default = 1) class Condo(Property): has_doorman = models.BooleanField(default = False) (This is strictly for show; the different home types have a lot of discount or liability fields.) For years, the way we’ve done this is that we’ve entered the property by hand, and then entered the homeowner as two separate stages, linking them with a search-for-properties dialog on the homeowner page. It’s always been a zero-or-one-to-one relationship: A property may have zero or one homeowners, and a homeowner may have zero-or-one properties. The orders have come down to create a unified experience that the homeowner can fill out themself: enter the whole thing, homeowner and property, and validate them together, rolling everything … -
Django allauth not able to login custom user, giving error asking to enter correct credentials--user exists in database
I having issues logging in a user with a custom user model with allauth. The user is in the database but is not able to login. I am able to login as admin but not as other testusers I get an error asking to enter the correct username and password--the username and password are correct and the user is active. models.py from django.db import models # Create your models here. from django.contrib.auth.models import AbstractUser, AbstractBaseUser class UserModel(AbstractUser): ACCOUNT_TYPE = ( ('account_type_a','Account Type A'), ('account_type_b','Account Type B'), ('account_type_c','Account Type C'), ) username = models.CharField(max_length=50) email = models.EmailField(max_length=50) account_type = models.CharField(choices=ACCOUNT_TYPE, max_length=50, null=True, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField( default=False) I using the allauth login form like so: html <a class="nav-link" href="{% url 'account_login' %}">Login</a> settings.py AUTH_USER_MODEL = 'accounts.UserModel' AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] LOGIN_REDIRECT_URL = 'memberships:profile' LOGOUT_REDIRECT_URL = 'account_login' ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_USERNAME_REQUIRED = False # This removes the username field ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USER_MODEL_USERNAME_FIELD = None -
Django + Django Tenants + DRF API = http: error: gaierror: [Errno 11001] getaddrinfo failed
Can someone please help to resolve the error i am getting? I am using django-tenants package with DRF REST API The issue is that accessing API VIEW via browser works fine, for example: http://demo.localhost:9000/api/zakaz But sending requests to this address via "requests" gives the error: HTTPConnectionPool(host='demo.localhost', port=9000): Max retries exceeded with url: /api/zakaz/3/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000017E1D9FEB00>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')) Similarly and PING or HTTPIE request from console even to basic address "demo.localhost:9000" gives the same: http http://demo.localhost:9000/ http: error: gaierror: [Errno 11001] getaddrinfo failed Couldn’t resolve the given hostname. Please check the URL and try again. Meaning that this address is only resolved in browser, but not from Django or Python console.. What am i doing wrong? How do i send api request in django-tenants separately for each tenant? I have added rest framework to TENANT APPS: TENANT_APPS = ( # your tenant-specific apps 'rest_framework', 'api.apps.ApiConfig', 'orders.apps.OrdersConfig', 'patients.apps.PatientsConfig', ) -
Submit Button corrupting
I have a simple profil page and I want to change the profile picture. forms: class UserProfilePictureUpdateForm(forms.ModelForm): class Meta: model = UserProfile fields = ['profile_photo',] template: <form method="post" enctype="multipart/form-data" action='{% url "update_profil_photo" %}'> {% csrf_token %} <button class="btn btn-info" type="submit" value="{{ profile_form.profile_photo }}"> <i class="fa fa-fw fa-camera"></i> <span>Change Photo</span> </button> </form> views: @login_required def update_profil_photo(request): user_profile = get_object_or_404(UserProfile, user=request.user) user = request.user if request.method == 'POST': profile_form = UserProfilePictureUpdateForm(request.POST, request.FILES, instance=user_profile) if profile_form.is_valid(): profile_form.save() messages.success(request, 'Update is successful') else: profile_form = UserProfilePictureUpdateForm(instance=user_profile) return render(request, 'profile.html', {'profile_form': profile_form}) When I click the button the design corrupts. I see very big submit button, link of picture and file upload buttons. what's wrong with my approach -
I want to create a API endpoint to fetch User and User Profile by attribute "username" in djangoRestAPI, username will be sent by the client,
**model.py ** class User_profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=False) phone = models.CharField(max_length=20, blank=False) profileImg = models.ImageField(upload_to='User/Profile_Picture', default='User/Profile_Picture/logo.png') city = models.CharField(max_length=50, blank=False, default=None) state = models.CharField(max_length=50, blank=False, default=None) birthdate = models.DateField(blank=False) bio = models.TextField(max_length=1000, blank=True, null=True) privacy = models.CharField(max_length=20, choices=PRIVACY_CHOICES, default='public', blank=False) requests = models.ManyToManyField(User, related_name='follow_request_user', default=None, blank=True) verified = models.BooleanField(default=False, blank=False) following_user = models.ManyToManyField(User, related_name='following_user', default=None, blank=True) followers = models.ManyToManyField(User, related_name='user_followers', default=None, blank=True) objects = models.Manager() def __str__(self): return self.name I want my response in JSON format so that i can use it in android app. I went through many blogs and Stackoverflow answers but any of that didn't give desired output In Short i just expect that client sends a username and get User and UserProfile in json format -
code works in code pen but not in vs code
I have a next button that's supposed to go to the next fieldset in a form. It works in the code-pen(https://codepen.io/atakan/pen/nPOZZR) in which I found it the. There were people asking about this same problem but the solution is supposed to be just adding the jquery cdn call but that did not work. anyone know whats up with this? (there is no error messages and I'm using Django version 4.2.3) this html: <!-- multistep form --> {%load static%} <head> <!-- ... your other links and scripts ... --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="{% static 'assets/js/profile_completion.js' %}"></script> <link rel="stylesheet" href="{% static 'assets/css/profile_completion.css' %}"> </head> <body> <form id="msform"> <!-- progressbar --> <ul id="progressbar"> <li class="active">Account Setup</li> <li>Social Profiles</li> <li>Personal Details</li> </ul> <!-- fieldsets --> <fieldset> <h2 class="fs-title">Create your account</h2> <h3 class="fs-subtitle">This is step 1</h3> <input type="text" name="email" placeholder="Email" /> <input type="password" name="pass" placeholder="Password" /> <input type="password" name="cpass" placeholder="Confirm Password" /> <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> <fieldset> <h2 class="fs-title">Social Profiles</h2> <h3 class="fs-subtitle">Your presence on the social network</h3> <input type="text" name="twitter" placeholder="Twitter" /> <input type="text" name="facebook" placeholder="Facebook" /> <input type="text" name="gplus" placeholder="Google Plus" /> <input type="button" name="previous" class="previous action-button" value="Previous" /> <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> <fieldset> …