Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot redirect logged in users to home page in django
When I log in I cannot get the site to redirect me to the home page. Instead, it simply logs me out again. urls.py urlpatterns = [ path("", views.home, name='home'), path("accounts/login/", views.login, name="login"), path("accounts/register/", views.register, name="register"), path("accounts/", include("django.contrib.auth.urls"), name="accounts"), path("search/", views.search), ] views.py def home(request): return render(request, template_name="home.html", context={"session":request.session.items}) def login(request): if (request.method == "POST"): form= UserLoginForm(request.POST) user = authenticate(username=request.POST["username"], password=request.POST["password"]) if (user.is_authenticated): user.save() return HttpResponseRedirect(reverse("home", kwargs={"user":user})) else: return render(request, "registration/register.html", {}) else: return render(request, "registration/login.html", {}) Then I handled logging in and registering by inheriting the default classes used for that. So this is what it looks like: forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) username = forms.CharField(max_length=32, help_text='username') class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user class UserLoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) username = UsernameField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': '', 'id': 'hello'})) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': '', 'id': 'hi', } )) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user Lastly the error is: django.urls.exceptions.NoReverseMatch: Reverse for 'home' with … -
Danjgo Model update_or_create with field pre-processing
I am new to Danjgo and it maybe a simple thing, but random searching does not seem to have helped. I am using Django Ninja API example, but I think this is not about Ninja. In a simple model e.g. models.py class Person (models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) schemas.py class PersonIn(ModelSchema): class Config: model = Person model_fields = ["first_name", "last_name"] I want to have simple create/read api e.g. api.py def create_person(request, payload: PersonIn): data = payload.dict() try: person, created = Person.objects.update_or_create(**data) except Exception: return { "mesg": "Some error happened"} What I wanted was to ensure that First Name and Last names are capitalized, before storing in DB. I found that one method is to override Model method .save class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def save(self, *args, **kwargs): self.first_name = self.first_name.capitalize() self.last_name = self.last_name.capitalize() super().save(self, *args, **args) But, in this case update_or_create always creates a new object as it first checks for lower case fields and never finds it. I also found that one can overwrite .clean method class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def clean(self): self.first_name = self.first_name.capitalize() self.last_name = self.last_name.capitalize() In this caseI understand I need to call .clean method manually. But … -
Handling a JSON API with Django and putting the data in a model
I have a basic JSON API with some data, I need to dynamically get this data in python and put it in a model, more basically, Let's say the API is for cars, each car has a name and model, how to get the data from the JSON API for cars and put in a model called "Car" in models.py? I searched but I couldn't find a way to do that. -
how to post images from client side to Next.js API endpoint and then to Django REST Framework API
I attempted to create a feature that allows users to upload product images to an ecommerce website. My plan initially was to receive the form submission from the client side in Next.js, and then pass it to the built-in Next.js API endpoint. I wanted to add an authorization token to the header and post it to the Django REST framework API, where I save the image and connect it to the user model using a foreign key. Although posting the image directly from the client side to the Django server worked well, I needed to add an authorization token to the header to retrieve the user in the backend. As I used the HTTP-only method, so I had to post it to the Next.js API endpoint. The problem is I keep running in to is when I post it to the api end point I couldn’t get the image directly to repost it to a djano api end point. Any help would be appreciated. Nextjs client side code. import React,{useState} from 'react' import { useSelector} from 'react-redux'; import { Oval } from 'react-loader-spinner'; function ProductUpload() { const loading = useSelector(state => state.auth.loading) const [formData, setFormData] = useState({ name: '', alt: … -
Django not getting static files in Docker
im not getting any static files in my django app when running docker with nginx. Can someone please look at my config and point out where the issue is? Let's start with Dockerfile for the app from python:3.11-slim-buster ENV PYTHONUNBUFFERED=1 ENV PYTHONWRITEBYTECODE 1 WORKDIR /usr/src/app COPY requirements.txt requirements.txt RUN pip install --no-cache-dir -r requirements.txt COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] COPY . . In entrypoint.sh we can find python manage.py collectstatic --no-input gunicorn core.wsgi:application --bind 0.0.0.0:8000 --reload docker-compose for the app version: "3.11" services: app_django: build: . volumes: - .:/usr/src/app/ - staticfiles:/usr/src/app/staticfiles ports: - 8000:8000 env_file: - .env image: app_django:django container_name: meant_container nginx: build: context: ./nginx/ ports: - 80:80 volumes: - ./nginx/conf.d/:/etc/nginx/conf.d/ - staticfiles:/home/app/staticfiles container_name: nginx_container volumes: staticfiles: here is docerfile for nginx FROM nginx:1.24-alpine RUN mkdir -p /home/app/staticfiles and Nginx cofig upstream dserver { server app_django:8000; } server { listen 80; location / { proxy_pass http://dserver; } location /static/ { alias home/app/staticfiles/; } } here is folder location django settings STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / "staticfiles" -
How to add extra columns for a model if in particular category in Django + Postgres
I need to add extra columns if product is in a particular category. I thought of using JSON or allowing null columns, but is there any better way of handling this situation. I'm using Postgresql database. Here are my model structure. class Product(Base): def __str__(self): return self.name name = models.CharField(max_length=255, unique=True, validators=[validate_alphanumeric]) is_safari = models.BooleanField(default=True) Product table has mapped to agents like this class Agent(Base): def __str__(self): return self.agent_user.username agent_user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.RESTRICT, ) country = CountryField() city = models.CharField(max_length=255) AgentProduct model class AgentProduct(Base): agent = models.ForeignKey( Agent, on_delete=models.RESTRICT, ) product = models.ForeignKey( Product, on_delete=models.RESTRICT, ) a_rate = models.IntegerField() c_rate = models.IntegerField() I would like to add some extra information if is_safari is true to the AgentProduct model like per_v_charge = models.IntegerField() extra_p_charge = models.IntegerField() # something like this -
'TemporaryUploadedFile' object has no attribute 'get'
I'm getting this error every time I'm trying to upload video file, and I think the problem is come from the moviepy library that I'm using to cut every video that are higher than 10 minute. the error: AttributeError at /CreateVideo 'TemporaryUploadedFile' object has no attribute 'get' views: from moviepy.video.io.VideoFileClip import VideoFileClip from django.core.exceptions import ValidationError def create_video(request): if request.method == 'POST': title = request.POST['title'] video = request.FILES['video'] banner = request.FILES['banner'] video_file = video video_clip = VideoFileClip(video_file.temporary_file_path()) duration = video_clip.duration video_clip.close() if duration > 600: # 10 minute in seconds raise ValidationError('the video cannot be longer than 10 minute') return video_file new_video = Video.objects.create( user=request.user, title=title, video=video, banner=banner ) new_video.save() return redirect('Video') return render(request, 'video/create_video.html') models: class Video(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=70) video = models.FileField(upload_to='videos') created_on = models.DateTimeField(auto_now_add=True) banner = models.ImageField(upload_to='banner') slug = models.SlugField(max_length=100, unique=True) -
How to organize Django REST Framework urls
so I am working on some dummy e-commerce application in Django (DRF) and I am a bit confused how to write good REST API's. Models class Category(models.Model): name = models.Char... class Product(models.Model): category = models.ForeignKey(...) name = models.Char... Views class ProductListView(APIView): def get(self, request, category_slug=None): products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) serializer = ProductSerializer(products, many=True) return Response(serializer.data, status=status.HTTP_200_OK) First Question So my question is if I should put logic for filtering with capture value (categori_slug) in this view or would it be more clear if I create two endpoints? Second Question In DRF is bottom code good practice to send multiple data trough result/endpoint? return Response({data: serializer.data, other_data: serializer_other.data}, status=st...) So as I am learning all the time only one serializer.data is passed trough one Response API but what if I want that client can also access some other data. Is better to split it in multiple views and than let client make multiple requests? PS: This is my first Stackoverflow question so I would appreciate some feedback on this as well. -
How to use 'auth_user' table of remote database in django?
I want to access 'auth_user' table from another Django project and use it in my current Django project. I am using database routers:- DATABASE_ROUTERS = ['to.your.router.CurrentRouter'] DATABASES = { 'default': eval(os.environ.get('DATABASE_REMOTE', str(DEFAULT_DATABASE))), 'database_current': eval(os.environ.get('DATABASE_CURRENT', str(DEFAULT_DATABASE))) } class CurrentRouter: route_app_labels = { 'admin', 'contenttypes', 'sessions', 'tracking', 'data_collect' } def __str__(self): super().__str__() def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'database_current' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'database_current' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'database_current' return None How can i use 'auth_user' table from DATABASE_REMOTE for logging into django admin panel and delete object from DATABASE_CURRENT. And how to set permission deleting objects in current database using User of remote database? For logging into admin panel using remote database user I have used custom authentication. https://docs.djangoproject.com/en/4.2/topics/auth/customizing/ class CustomAuthenticationBackend(BaseBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = User.objects.get(email=username) except ObjectDoesNotExist: return None if user.check_password(password): return user else: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except ObjectDoesNotExist: return None But when deleting an object from DATABASE_CURRENT using the DATABASE_REMOTE 'User' … -
Django - Filter queryset by latest ForeignKey
I have following models: class Version(models.Model): version_date = models.DateField() # Other fields class Document(models.Model): version = models.ForeignKey(Version, related_name="documents") title = models.CharField(max_length=128) And I have following objects based on the models: # Version objects version_1 = Version.objects.create(version_date="2020-02-2") version_2 = Version.objects.create(version_date="2021-02-2") version_3 = Version.objects.create(version_date="2022-02-2") # Documents doc_1 = Document.objects.create(version=version_1, title="the title of doc") doc_2 = Document.objects.create(version=version_2, title="the title of doc") doc_3 = Document.objects.create(version=version_3, title="the title of doc") My problem is to filter documents only the documents that are in the latest version. If I use Document.objects.filter(title="the title of doc"), I want to only get doc_3 that is under the latest version. Is there any ways to do that by django ORM? Thanks. -
Llama_index index.query returns proper response when .py file is run via CLI but return "None" when used with (Django)api call
I am trying to het a response from openai. This works fine when I run the file form the CLI.(see code below) Because it prints the response to the command line. from django.views.decorators.csrf import csrf_exempt from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader import os os.environ["OPENAI_API_KEY"] = "<MY_OPENAI_API_KEY>" @csrf_exempt def ask_ai( prompt ): print( prompt ) documents = SimpleDirectoryReader("data").load_data() index = GPTSimpleVectorIndex.from_documents( documents ) response = index.query( prompt ) print( response ) ask_ai("<my prompt>") However, when I use Django to call the mostly the same but slightly modified file(see below) the response is always printed as "None" and returned as null. from django.views.decorators.csrf import csrf_exempt from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader import os os.environ["OPENAI_API_KEY"] = "<MY_OPENAI_API_KEY>" @csrf_exempt def ask_ai( prompt ): print( prompt ) documents = SimpleDirectoryReader("data").load_data() index = GPTSimpleVectorIndex.from_documents( documents ) response = index.query( prompt ) print( response ) return response.response What can I do to make it print/return the response for the API call in the same way that it does for the CLI? I have tried: async/await. This returns an error. TypeError: Object of type coroutine is not JSON serializable adding a second function with async await applied that returns the query response to ask_ai which then returns it to the … -
Django and Telegram Bot - Save functions fires but doesn't saves changes
I've got one function which can be called from WEB and inside telegram bot (with await) #views.py from .models import SomeModel def save_function(id): record = SomeModel.objects.get(pk=id) bot = telebot.TeleBot("123:abcdef") message = bot.send_message(1234,'message') print(message.message_id) ## runs ok record.message_id = message.message_id record.save() ## no changes in async call from bot from asgiref.sync import sync_to_async @sync_to_async def save_function_async(id,context): from .views import save_function save_function(id=id) ### message_handler_function async def entered_text(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: await save_function_async(123,context) If i run save_function from any Web-Views - it runs hot it should be But, run save_function from telegram bot - there is any error, the message from bot sends sucessfully, but model's data doesn't changes. How it can be fixed? -
Why can't I output the full values using get_foo_display?
There is a Django form. When I send a GET-request, I output a new empty form, when I click "Submit", I display on the page what the user entered in the questionnaire. The problem is that I want some data to be output not as an internal representation, but as an full one (idk how it called correctly). I'm a beginner in Django and may not understand many nuances. I tried to add data to the dictionary individually, but it didn't lead to anything. pool.html: <p><b>Ваше имя:</b> {{ form_data.name }}</p> <p><b>Ваш пол:</b> {{ form_data.get_sex_display }}</p> forms.py: class FeedbackForm(forms.Form): SEX_OPTIONS = ( ('m', 'Мужской'), ('f', 'Женский'), ('none', 'Паркетный') ... sex = forms.ChoiceField( widget=forms.RadioSelect, choices=SEX_OPTIONS, label='Ваш пол:' ) views.py: def pool(request): assert isinstance(request, HttpRequest) context['title'] = 'Обратная связь' if request.method == 'GET': form = FeedbackForm() else: form = FeedbackForm(request.POST) if form.is_valid(): form_data = request.POST.dict() context['form_data'] = form_data context['form'] = form return render(request, 'app/pool.html', context=context) -
Django changes the MEDIA URL if I pass request from views to serializer
I am working on a Social Media project. I successfully implemented image upload and now working on Like model which allows users to like a post. At present state, if a user clicks on Like button, it turns red. All I want is if the page reloads or the same user logins again, the specific post's like button must remain red. In order to achieve so, I am trying to add extra field in serializer(below): liked_by_current_user with which I can filter out as to when the like color must be red. (The REST APIs are working correctly) models.py: class Comment(models.Model): text = models.TextField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=100, blank=True) profile_image = models.ImageField(upload_to='user_image', null=True, blank=True) class Like(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) selected views.py def feed(request): context = { 'MEDIA_URL': settings.MEDIA_URL, # pass MEDIA_URL to the template } return render(request, 'post_list_temp.html', context) class PostListView(APIView): def get(self, request, *args, **kwargs): posts = Post.objects.filter(deleted=False).order_by('-created_on') context = { 'post_list' : posts, } paginator = defPagination() result = paginator.paginate_queryset(posts, request, view=self) serializer = feedSerializer(result, context={"request":request}, many=True) return paginator.get_paginated_response(serializer.data) def post(self, request, *args, **kwargs): if request.user.is_authenticated: print(request) serializer … -
TimescaleDB: Image does not recognize created hypertables
I am running a django app with timescaledb as local DB image. It was working until recently (maybe 2 days ago). Now I get the following error: ERROR: function create_hypertable(unknown, unknown, chunk_time_interval => interval) does not exist at character 8 HINT: No function matches the given name and argument types. You might need to add explicit type casts. Answers to other questions (e.g: TimescaleDB: Is it possible to call 'create_hypertable' from Python?) regarding this topic suggest to install the timescaledb extension. But I am running the timescaledb-ha image which comes with the extension included (https://hub.docker.com/r/timescaledev/timescaledb-ha). I also tried to create the hypertables with if_not_exists => TRUE as suggested here: https://github.com/timescale/timescaledb/issues/189. I assume there is a bug in the image since it was updated 2 days ago and before it was working. Parts of my dockerfile: postgres: container_name: postgres_postgis image: timescale/timescaledb-ha:pg14 volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres Can somebody help? Would be highly appreciated. Thanks in advance -
Converting multiple left join SQL into a django ORM query
I am having trouble creating a corresponding django ORM query for the following SQL Join: select su.user_id from slack_slackuser as su left join auth_user as au on su.user_id = au.id left join core_profile as cp on au.id = cp.user_id where cp.org_id = 8; Here slack_slackuser maps to SlackUser django model, auth_user maps to the django's AUTH_USER_MODEL and core_profile maps to Profile model. This is what I was trying to do, but this fails.: SlackUser.objects.filter(user_id__core_profile__org_id=org.id).values_list('user_id', flat=True) -
Taking three records from the products in the table according to their categories
I have two tables named categories and products. How can I get three records from each category on the homepage? Thanks in advance class Category(models.Model): name = ... class Produc(models.Model): name = ... category = models.ForeignKey(Category, ... class Home_Cls(TemplateView): ... def homepro(self): cats = Category.objects.all() for cat in cats : que= Products.objects.filter( category_id=cat[..] ).order_by('?')[:3] return que I tried a little. :( Waiting for your help. -
Nginx doesn't see or use subdomain config
Problem: nginx doesn't apply configuration for subdomain if there are domain and subdomain config at the same time. Disclaimer: I'm new to nginx and server deployment. Question: What I do wrong with nginx configuration? Additional info: Nginx 1.18.0 Ubuntu 20.04 Details: I have main domain (it's my portfolio) (let's say example.com) and subdomain (todo-tracker.example.com). Both are django projects started with gunicorn (main on 127.0.0.1:8000, todo-tracker on 127.0.0.1:8001). I have two sites-available config files: default - for main domain server { server_name example.com; location / { proxy_pass http://127.0.0.1:8000/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /static { autoindex on; alias /home/portfolio/portfolio/staticfiles; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80 ipv6only=on; server_name example.com; return 404; # managed by Certbot } todo-tracker - for subdomain server { server_name todo-tracker.example.com; location / { proxy_pass http://127.0.0.1:8001/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header … -
Database error "Access denied for user 'admin'@'localhost' (using password: YES)")
While working on my first Django project, I am trying to connect my application to MySQL database and it keeps giving me this error. I have installed mysqlclient. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'minesupdb', 'USER': 'admin', 'PASSWORD': 'my_password', 'HOST': 'localhost', -
DJango allauth Microsoft Graph
I have a DJango program called 'p_verison1'. Then I have a second application to manage users called "users". There I have implemented login and it works fine. I have added that you can login with Microsoft using "allauth". The problem is that after pressing the "sign in with microsoft" button, instead of taking you directly to the page to choose the microsoft account, it first takes you to a second page where you have to click on the continue button. I want to remove that second page, I want it to always take as the user clicks the button and continue and directly take you to the Microsoft page. I've been trying different ways but I can't remove the second page. My "login.html": <div class="form-group"> <div class="socialaccount_providers" style="margin=0px"> {% include "socialaccount/snippets/provider_list.html" with providers="microsoft" process="login" %} </div> </div> My "provider_list.html" {% load socialaccount %} {% load static %} {% get_providers as socialaccount_providers %} {% for provider in socialaccount_providers %} {% if provider.id == "openid" %} {% for brand in provider.get_brands %} <div> <a title="{{brand.name}}" class="socialaccount_provider {{provider.id}} {{brand.id}}" href="{% provider_login_url provider.id openid=brand.openid_url process=process %}" >{{brand.name}}</a> </div> {% endfor %} {% endif %} <div class="my-2"> <a title="{{provider.name}}" class="socialaccount_provider {{provider.id}}" href="{% provider_login_url provider.id process=process … -
At Console : Uncaught TypeError: $.get is not a function
i am writing a django application, and using autocomplete this is my home.html file where i am trying to load the jquery files {% block home_css %} <link rel="stylesheet" type="text/css" href="{% static 'home.css' %}"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="stylesheet"> <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script> <script type="text/javascript" src="{% static 'autocomplete.js' %}"></script> {% endblock %} and this is my autocomplete.js file var $ = jQuery.noConflict(); $(document).ready(function() { $('#ticker').on('input', function() { var input = $(this).val(); if (input.length >= 3) { $.get('https://www.alphavantage.co/query', { function: 'SYMBOL_SEARCH', keywords: input, apikey: 'my_api_key' //i have uploaded my key in my local code }, function(response) { $('#autocomplete').empty(); for (var i = 0; i < 5 && i < response.bestMatches.length; i++) { $('#autocomplete').append('<div class="autocomplete-suggestion">' + response.bestMatches[i]['1. symbol'] + '</div>'); } $('.autocomplete-suggestion').on('click', function() { var symbol = $(this).text(); $('#ticker').val(symbol); $('#autocomplete').empty(); }); }); } else { $('#autocomplete').empty(); } }); }); and i don't know if this is necessary to upload, but i am extending base.html in my home.html <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://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'base.css' %}"> <title>GrittyGains</title> {% block home_css %} {% endblock %} </head> i have tried rearranging files as some solution showed … -
Django docker - template does not exists but admin page loads
im dockerizing my app. App builds and runs, but when i try to access some base URL like /login I get TemplateDoesNotExist at /login/ However when I'm accessing my REST, ADMIN, SWAGGER I can see everything properly so I think the problem is on my side. Here is the dockerfile from python:3.11-slim-buster ENV PYTHONUNBUFFERED=1 WORKDIR /basicapp COPY requirements.txt requirements.txt RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD python manage.py runserver 0.0.0.0:8000 here is docker-compose version: "3.11" services: app: build: . volumes: - .:/basicapp ports: - 8000:8000 image: app:django container_name: basic_container command: python manage.py runserver 0.0.0.0:8000 Here is my template settings 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', ], }, }, ] and the app structure is simple core <-settings etc app templates static -
AssertionError: The field 'uploaded_file' was declared on serializer LessonPlanNotesSerializer, but has not been included in the 'fields' option
My Models class LessonPlan(models.Model): planner=models.ForeignKey('LessonPlanner', on_delete=models.CASCADE) title=models.CharField(max_length=100, null=True, blank=True) details=models.TextField(null=True, blank=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) class LessonStudyMaterial(models.Model): Lesson=models.ForeignKey('LessonPlan', on_delete=models.CASCADE) file=models.FileField(upload_to=get_upload_path, null=True, blank=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) My Serializer class LessonPlanSerializer(serializers.ModelSerializer): uploaded_file=serializers.ListField(child=serializers.FileField(max_length=2000) class Meta: model = LessonPlan fields=['id', 'planner', 'title', 'details', 'uploaded_file',] My post request contains title, details, and multiple files that will post in the child model LessonStudyMaterial so I have added the uploaded_file field to validate data while posting but it showing an error -
we are using postman and swagger for JWT authorization to authorize token ... is it possible in drf UI for authorization of JWT token?
We are using postman and swagger for authenticating and authorizing the JWT authentication we are logging in and we are getting both access token and refresh token and we are placing this access token in swagger/postman as bearer token and authorizing.. Is it possible in DRF UI for authorizing token and accessing the API's Expecting JWT Authorizing and accessing all the API's in DRF UI instead of swagger and Postman -
AttributeError: module 'logging' has no attribute 'getLogger' when creating a new environment
I was trying to create a new virtual environment using python. but when I executed the command python3 -m venv env It shows the following error. Traceback (most recent call last): File "/usr/lib/python3.8/runpy.py", line 185, in _run_module_as_main mod_name, mod_spec, code = _get_module_details(mod_name, _Error) File "/usr/lib/python3.8/runpy.py", line 144, in _get_module_details return _get_module_details(pkg_main_name, error) File "/usr/lib/python3.8/runpy.py", line 111, in _get_module_details __import__(pkg_name) File "/usr/lib/python3.8/venv/__init__.py", line 15, in <module> logger = logging.getLogger(__name__) AttributeError: module 'logging' has no attribute 'getLogger' Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 72, in apport_excepthook from apport.fileutils import likely_packaged, get_recent_crashes File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module> from apport.report import Report File "/usr/lib/python3/dist-packages/apport/report.py", line 32, in <module> import apport.fileutils File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 12, in <module> import os, glob, subprocess, os.path, time, pwd, sys, requests_unixsocket File "/usr/lib/python3/dist-packages/requests_unixsocket/__init__.py", line 1, in <module> import requests File "/usr/lib/python3/dist-packages/requests/__init__.py", line 43, in <module> import urllib3 File "/usr/lib/python3/dist-packages/urllib3/__init__.py", line 7, in <module> from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 29, in <module> from .connection import ( File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 41, in <module> from .util.ssl_ import ( File "/usr/lib/python3/dist-packages/urllib3/util/__init__.py", line 20, in <module> from .retry import Retry File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 20, in <module> log = logging.getLogger(__name__) AttributeError: module 'logging' has no attribute …