Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deployment fails without prompting any errors on console on digitalocean app-engine django app
We have 2 apps that are running with similar settings, now we are trying to deploy another app but this time it's failing without telling any error in app engine. Python django app starts and then suddenly app engine stops deployment. How to find reason behind that? -
Django logging does not work inside views and viewsets
Can someone please help me understand why django does not print logging messages that I put inside views methods? When I call logger.debug() from outside views it works correctly my views.py import logging logger = logging.getLogger(__name__) logger.debug('THIS LOGGING MESSSAGE SHOWS UP IN LOGS') class RequestGetResultViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin): permission_classes = (IsAuthenticated,) serializer_class = serializers.RequestGetResultSerializer queryset = Request.objects.all() def get_queryset(self):] logger.debug('THIS LOGGING MESSSAGE DOES NOT SHOW UP') return self.queryset.filter(user=self.request.user.id) @action(methods=['get'], detail=True, renderer_classes=(PassthroughRenderer,)) def download(self, *args, **kwargs): logger.debug('THIS LOGGING MESSSAGE DOES NOT SHOW UP') # working code here return response my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'DEBUG' , }, 'loggers': { 'django': { 'handlers': ['console'], }, } -
Hello everyone, help me write a test to Check if a post has been removed from the old group
You need to check that the post has disappeared from the old group page. You get our old band by its slack. old_group_response = self.authorized_client.get( reverse('group_list', args=(self.group.slug,)) ) And you compare, что old_group_response.context['page_obj'].paginator.count equals zero. This means that there are no posts in our old group. You can check another new one, that there is 1 post there. Please help me write correctly) from django import forms from django.test import Client, TestCase from django.urls import reverse from ..models import Group, Post, User NEW_POST = reverse('posts:post_create') class PostFormTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.author_auth = User.objects.create_user(username='test auth') cls.not_author = User.objects.create_user(username='Not Author') cls.group = Group.objects.create( title='Test group_title', slug='test_slug', description='Test description') def setUp(self): self.authorized_client = Client() self.authorized_client.force_login(PostFormTests.author_auth) self.authorized_client_not_author = Client() self.authorized_client_not_author.force_login( PostFormTests.not_author) def test_post_old_group_response(self): """ Check if a post has been removed from the old group.""" post = Post.objects.create( group=PostFormTests.group, author=PostFormTests.author_auth, text='test post') group_2 = Group.objects.create( title='Test group_title2', slug='test_slug2', description='Test description2') posts_count = Post.objects.count() form_data = { 'text': 'text_post', 'group': group_2.id} old_group_response = self.authorized_client.get( reverse('posts:group_list', args=(self.group.slug)), data=form_data, follow=True) self.assertEqual( old_group_response, reverse( 'posts:post_detail', kwargs={'post_id': post.pk})) self.assertEqual(Post.objects.count(), posts_count) self.assertEqual(old_group_response.context[ 'page_obj'].paginator.count == 0) I know what rubbish is written here (I'm just learning), this is what I was able to sketch)) -
Django: create_user_profile() missing 1 required positional argument: 'self'
I want to change the user's password. For this I use the following code user = User.objects.get(id=kwargs.get('user_id')) user.set_password(kwargs.get('password')) user.save() I get an error in response create_user_profile() missing 1 required positional argument: 'self' But I don't create a user. I checked, it finds the right user -
Styling prefilled Django radio input as buttons
I have a Django form field that is prefilled({form.clothingType}) and using widget gave it the attribute of class="closet-form-section form-clothing-type". The form is rendered out in html as <div id="id_clothingType" class="closet-form-section form-clothing-type"> <div> <label for="id_clothingType_0"><input type="radio" name="clothingType" value="11" class="closet-form-section form-clothing-type" required="" id="id_clothingType_0"> Accessory</label> </div> <div> <label for="id_clothingType_1"><input type="radio" name="clothingType" value="12" class="closet-form-section form-clothing-type" required="" id="id_clothingType_1"> Top</label> </div> <div> <label for="id_clothingType_2"><input type="radio" name="clothingType" value="13" class="closet-form-section form-clothing-type" required="" id="id_clothingType_2"> Outerwear</label> </div> <div> <label for="id_clothingType_3"><input type="radio" name="clothingType" value="14" class="closet-form-section form-clothing-type" required="" id="id_clothingType_3"> Bottom</label> </div> <div> <label for="id_clothingType_4"><input type="radio" name="clothingType" value="15" class="closet-form-section form-clothing-type" required="" id="id_clothingType_4" checked> Shoe</label> </div> </div> My question is how do I style the radio inputs as buttons such that it changes its background color when it is checked without changing the html (form template)? Is there an alternative solution via widget, views.py of even models.py? Thank you! The problem is that the input is within the labels, so I am unable use the conventional way of the input:checked + label to style the radio inputs. In this case the 5th radio button(Shoe) should have a different background color as the others. -
Docker/Django/Gunicorn/Nginx Websockets not connecting
Dockerized Django chat app using gunicorn, nginx for reverse proxy (static files). I managed to get stuck trying to get the websockets to work, but I can't connect to daphne: daphne -p 8001 project.asgi:application. The app only says, "Connection refusesed for upstream localhost:8001". I'm using django-channels and redis and on local everything is working fine. Am I missing something? Here are some files: nginx.conf upstream project { server web:8000; } upstream websocket { server localhost:8001; } server { listen 80; location /ws/ { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { proxy_pass http://project; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/staticfiles/; } } asgi.py import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack import scrumboard.routing application = ProtocolTypeRouter({ "http": django_asgi_app, 'websocket': AuthMiddlewareStack( URLRouter( scrumboard.routing.websocket_urlpatterns ) ) }) settings.py """ Django settings for project project. Generated by 'django-admin startproject' using Django 4.1.2. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib … -
Script JS only working on HTML page , is there a way to make it work and include the path to HTML?
I have an issue where I have a html 'p' tags where it should applies a javascript function. It is an animated typing script , however it doesn't seems to be working. The script only works if I put it below the html 'P' tags. <link href="{% static 'js/animation.js' %}" rel="stylesheet"/> <!--test active type writing animation--> <div class="container-animation"> <p id="p_type">I'm <span class="typed-text"></span><span class="cursor">&nbsp;</span></p> </div> <!-- To check , how to implement the script in js file and why it isn't working and only working--> <script> const typedTextSpan = document.querySelector(".typed-text"); const cursorSpan = document.querySelector(".cursor"); const textArray = ["a Data Analyst", "a Developer", "Henry Dumont"]; const typingDelay = 100; const erasingDelay = 100; const newTextDelay = 2000; // Delay between current and next text let textArrayIndex = 0; let charIndex = 0; function type() { if (charIndex < textArray[textArrayIndex].length) { if(!cursorSpan.classList.contains("typing")) cursorSpan.classList.add("typing"); typedTextSpan.textContent += textArray[textArrayIndex].charAt(charIndex); charIndex++; setTimeout(type, typingDelay); } else { cursorSpan.classList.remove("typing"); setTimeout(erase, newTextDelay); } } function erase() { if (charIndex > 0) { if(!cursorSpan.classList.contains("typing")) cursorSpan.classList.add("typing"); typedTextSpan.textContent = textArray[textArrayIndex].substring(0, charIndex-1); charIndex--; setTimeout(erase, erasingDelay); } else { cursorSpan.classList.remove("typing"); textArrayIndex++; if(textArrayIndex>=textArray.length) textArrayIndex=0; setTimeout(type, typingDelay + 1100); } } document.addEventListener("DOMContentLoaded", function() { // On DOM Load initiate the effect if(textArray.length) setTimeout(type, newTextDelay + 250); }); … -
Django rest framework - restricting user from granting himself permission
I have a django-program that has a few number of different permission levels. For example, I have a super-user, a doctor, an assistant and a patient. I have a class AssistantViewSet(ModelViewSet) which allows to change an assistant user. I just found out that an assistant might go directly to the link that corresponds to that ModelViewSet with method PUT (which is a resonable behavior as an assistant can change their own information), and change their permissions by sending a permission_list key with many permissions they shouldn't have. how can I make sure that an assistant will be able to change their information without having the ability to change their permissions? my code: class AssistantViewSet(ModelViewSet): serializer_class = AssistantSerializer queryset = Assistant.objects.all() permission_classes = [AssistantViewPerm, ] def get_queryset(self): assistants = Assistant.objects.filter(...) return assistants and the permission class: class AssistantViewPerm(BasePermission): def has_permission(self, request, view): action = view_action_map(request) try: if action == 'update': ... except: ... return checkBasicPerms(...) and checkViewPerm(...) -
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User'
I am working on a Django chat application using Django channels but I have run into a problem. I am getting the error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User' in my console and I cannot figure out how to solve this issue. In my project, I am checking whether users have an history in their chat, and if there is no history I create one. Inside the users app where I am registering users, I have used the AbstractUser model and therefore I have AUTH_USER_MODEL='users.User' inside the setting.py. Here is my Models.py for the chat application: from django.contrib.auth import get_user_model from django.conf import settings User = get_user_model() class TrackingModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Thread(TrackingModel): THREAD_TYPE = ( ('personal', 'Personal'), ('group', 'Group') ) name = models.CharField(max_length=50, null=True, blank=True) thread_type = models.CharField(max_length=15, choices=THREAD_TYPE, default='personal') users = models.ManyToManyField('users.User') objects = ThreadManager() def __str__(self) -> str: if self.thread_type == 'personal' and self.users.count() == 2: return f'{self.users.first()} and {self.users.last()}' return f'{self.name}' class Message(TrackingModel): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey('users.User', on_delete=models.CASCADE) text = models.TextField(blank=False, null=False) def __str__(self) -> str: return f'From <Thread - {self.thread}>' And here is the Managers.py file: User = get_user_model() … -
Not use Django static files
I am quite new to Django, and I hope my question is not too silly. I am currently running my project locally, and each time I do an API call with the browser, I see the server log something similar: my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/css/default.css HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/bootstrap.min.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/jquery-3.5.1.min.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/csrf.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/ajax-form.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/default.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/prettify-min.js HTTP/1.1" 404 179 There are a tons of static files that are served via the API. If I do the same with Postman or similar, here is the log: my_table | [08/Jan/2023 20:25:12] "GET /api/v1/category/ HTTP/1.1" 200 2 It looks like it only sends the response I wanted, via JSON or whatever. I was wandering if there is a way to prevent Django from serving static files at all, since I will only use the Rest Framework, or maybe gRPC in the future, but never static files. I tried to delete the static file constant from settings, and then nothing … -
Use node module in django
I'm trying to use nodejs modules (lodash) inside of my Django app but nothing happen. The architecture is as follow: - myproject - dist - myapp - templates - index.html - apps.py - views.py - ... - myproject - settings.py - urls.py - ... - nodes_module - static - js - script.js - manage.py - package.json I edited my settings.py so nodes_module/ is considered as static: STATIC_URL = "/static/" STATIC_ROOT = 'dist/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ('node_modules', os.path.join(BASE_DIR, 'node_modules/')), ) And here is the content of my index.html: hello <div id="result"></div> <script>console.log("yolo")</script> <!-- This should write "2 4 6 8 10" on console and page but doesn't --> {% load static %} <script src="{% static 'node_modules/lodash/lodash.js' %}"> import _ from 'lodash'; console.log("yolo2") const array = [1, 2, 3, 4, 5]; const doubled = _.map(array, function(n) {return n * 2;}); const resultElement = document.getElementById('result'); resultElement.innerHTML = doubled; console.log(doubled); </script> I got a lot of errors while trying but now, with this architecture and code, I don't have errors anymore but nothing appear on my page except the "hello". For some reasons, the first console.log("yolo") does appear on the console but not the second one console.log("yolo2"). It's like it never went … -
How can I add related models on the form at the same time?
I need your help with something. I'm new to the software field. I would like to consult you on an issue that I am stuck with. I don't know much about Django docs. My English is not very good. My problem is that I have two models, Boat model and Features model, I assigned a foreignkey to the features model and associated it with the boat model. I created two forms for these models. Features Model Boat Model BoatForm FeaturesForm I need to save the form at the same time in the views, but I can't assign the foreign key. In summary, while adding a new boat, I need to save its features at the same time. Sorry if the English pronunciations are wrong. -
How to check if a model is an intermediate model
Taking the example in the docs, I'm trying to check if a model is an intermediate model. from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) So a function like this, that takes a model as input and returns true if the model is an intermediate model and false otherwise. def is_intermediate(model): pass # is_intermediate(Person) -> False # is_intermediate(Group) -> False # is_intermediate(Membership) -> True I believe Django REST Framework has a way of doing this with the has_through_model attribute. Looking at that, I wrote this: def is_intermediate(model): for field in model._meta.get_fields(): if field.is_relation: for related_field in field.related_model._meta.get_fields(): through = getattr(related_field.remote_field, "through", None) if through and not through._meta.auto_created and through == model._meta.model: return True return False And it works. But to me, this sounds entirely inefficient. Is there a more performant way of finding if a model is intermediate? -
Django custom user profile image not saving properly
I've got a custom user model that when the image is updated it adds characters to the file path making django unable to find the new updated profile image. MODELS.PY from django.db import models from django.contrib.auth.models import AbstractUser from PIL import Image from django.conf import settings import os class CustomUser(AbstractUser): username = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) email = models.EmailField(unique=True) # Add any additional fields you want to store about users, such as their profile picture, etc. image = models.ImageField(default='default.png', upload_to='profile_pics', null=True, blank=True) def save(self, *args, **kwargs): # Check if the image field has changed if self.pk: orig = CustomUser.objects.get(pk=self.pk) if orig.image != self.image: # Delete the previous image file if orig.image: orig.image.delete(save=False) # Create a thumbnail image if self.image: try: image = Image.open(self.image) except FileNotFoundError: print("Image file not found:", self.image.path) return image.thumbnail((200, 200), Image.ANTIALIAS) # Save the image to the correct path image_path = os.path.join( settings.MEDIA_ROOT, self.image.field.upload_to, self.image.name) image.save(image_path) super().save(*args, **kwargs) Views.py class UserPostListView(ListView): model = Post template_name = 'gorl/user_posts.html' context_object_name = 'posts' # paginate_by = 5 def get_queryset(self): user = get_object_or_404( CustomUser, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = get_object_or_404( CustomUser, username=self.kwargs.get('username')) context['user'] = user context['show_profile_settings'] = self.request.user.username == user.username context['comments'] = Comment.objects.all() total_likes … -
Ktor client - CSRF post request
I am doing a project where I am using django for server and ktor client for jetpack compose application to make request.However the CSRF protection reject my login request(An unsafe post request). As django has a built-in CSRF protection middleware, when I am testing the login post request with localhost, the server return Forbidden (CSRF cookie not set.): /user/login/ to the client and the login function cannot work. I tried to search for some documents and solutions to disable CSRF check (@csrf_exempt) but they are not working for me.I have added the CSRF_TRUSTED_ORIGINS in setting.py as the following(To be honest I don't know if these works or not): CSRF_TRUSTED_ORIGINS = [ 'http://localhost', 'http://*.127.0.0.1:*', 'http://10.0.2.2', 'http://127.0.0.1', 'https://127.0.0.1', 'https://127.0.0.1:*', 'https://127.0.0.1:', ] I have also tried to disable the middleware but not work. Is there any way that I can use ktor client to satisfy the CSRF thing from django?? Or what else should I do if that is not possible. Thank you for any answer. -
There is no cookie at all in my Next.Js frontend
I am super newbie on programming. I made Django Backend. and Next.js Frontend There is cookie which has _ga, csrftoken when I tested on local server 127.0.0.1 BUT, there is no cookie at all on my production. (production:which has different domain backend and frontend). I guessed that everything happened because I used different domain when production (just guess... I don't know it clear) here is some django settings.py i have ALLOWED_HOSTS = [ "127.0.0.1", "localhost", "BACKENDURL", "FRONTENDURL", "*.FRONTENDURL", ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:3000", "http://localhost:3000", "https://*.frontendURL", "https://FRONTENDURL", ] CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True I've searched all over the internet world. Please help me out from this hell... :-( -
Error "ImproperlyConfigured at /dj-rest-auth/login/" in use "dj_rest_auth"
I Want Use packeage 'dj_rest_auth' in django-rest-framework for login but get error: ImproperlyConfigured at /dj-rest-auth/login/ No default throttle rate set for 'dj_rest_auth' scope In setting.py File: INSTALLED_APPS = [ ... # 3rd Party 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'dj_rest_auth', # local ... ] REST_USE_JWT = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':[ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ], 'DEFAULT_PERMISSION_CLASSES':[ 'rest_framework.permissions.AllowAny' ], 'DEFAULT_RENDERER_CLASSES':[ 'rest_framework.renderers.JSONRenderer' ], 'DEFAULT_THROTTLE_CLASSES':[ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle', 'rest_framework.throttling.ScopedRateThrottle', ], 'DEFAULT_THROTTLE_RATES':{ 'anon':'50/hour', 'user':'200/hour', 'register':'5/hour', 'ref_token':'5/minute', 'create_article':'5/minute', } } And url.py: urlpatterns = [ ... path('dj-rest-auth/',include('dj_rest_auth.urls')), ] -
Django Taggit Filtering Invalid for Icontains
I have a model that contains a tags field using the Django Taggit library. I am currently trying to use a search bar to see if any items contains the same tag such as "Savoury" "Sweet" etc. However i am getting the error "Related Field got invalid lookup: icontains" and im not sure why. I have doubled checked the value in the post request from the search bar and it matches so the problem lies in the filtering using icontains. Here is my code: models.py `class Food(models.Model): name = models.CharField(max_length=100) tags = TaggableManager()` views.py class SearchFood(TemplateView): ... def post(self, request): result = request.POST['search_result'] if Food.objects.filter(tags__icontains=result): object = Food.objects.filter(tags__icontains=result) ... Im not sure why this doesnt work as i have tried searching for the food name using icontains and it works perfectly. However doing it with Django Taggit i get errors. Any help would be appreciated. -
NoReverseMatch at / Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name
I'm working on my Django blog. I was working on a registration form, everything it was working until I tested it and redirection was not working properly. Trying to fix errors, I got this message django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. blog/urls.py from . import views from django.urls import path app_name = 'my_blog' urlpatterns = [ path('', views.home, name='home'), path('post/<slug:slug>/', views.post_detail, name='post_detail'), path('category/<slug:slug>/', views.category_detail, name='category_detail'), path('register/', views.register_request, name='register'), path('login/', views.login_request, name='login'), ] views.py def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, "Registration successful." ) return redirect("my_blog:homepage") messages.error(request, "Unsuccessful registration. Invalid information.") form = NewUserForm() return render (request=request, template_name="register.html", context={"register_form":form}) def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}.") return redirect("my_blog:homepage") else: messages.error(request,"Invalid username or password.") else: messages.error(request,"Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form":form}) In home.html I used "{{ post.get_absolute_url }}", and now this is error when I try to reload page, I have no idea why this is happening. … -
Django postgres "No migrations to apply" troubleshoot
I had to modify the table of my app so I dropped it from postgres database (using objectname.objects.all().delete() in django python shell and with postgres at PGAdmin). I deleted the appname migrations folder. When I run python manage.py makemigrations appname, the folder migrations gets created with a 0001_initial.py creating the tables. When I run python manage.py migrate appname, nothing happens and I cannot see the tables in postgres PGAdmin. (website) C:\Users\Folder>python manage.py makemigrations appname Migrations for 'appname': food\migrations\0001_initial.py - Create model Table1 - Create model Table2 - Create index Table2_search__7dd784_gin on field(s) search_vector of model Table2 (website) C:\Users\Folder>python manage.py migrate Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, appname, sessions Running migrations: No migrations to apply. When I deleted the folder migrations I can see the migrations are gone with python manage.py showmigrations. I also tried python manage.py migrate --run-syncdb but still no result. (website) C:\Users\Folder>python manage.py migrate --run-syncdb Operations to perform: Synchronize unmigrated apps: messages, postgres, staticfiles Apply all migrations: accounts, admin, auth, contenttypes, appname, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: No migrations to apply. Any other idea on what may be happening and how to get the tables in postgres … -
How to change representation while keeping field editable in DRF?
I have two classes: class ClassA(models.Model): name = models.Charfield(...) tags = models.ManyToManyField("TagClass", blank=True) class TagClass(models.Model): tag_name = models.Charfield(...) def __str__(self): return f"{self.tag_name}" And then I serialize like so: # serializers.py class ClassASerializer(serializers.ModelSerializer): class Meta: model = ClassA fields = "__all__" class TagClassSerializer(serializers.ModelSerializer): class Meta: model = TagClass fields = "__all__" So when I create a tag say "red", it has ID=1, and I link it to a ClassA object, in the ClassA's object representation it shows this : { "id": 1, "name": "Some name", "tags": [ 1 ], } Instead I'd like it to display like so : { "id": 1, "name": "Some name", "tags": [ "red", ], } I've seen the StringRelatedField but it makes editing the tags field disabled (read-only). Is there a way to proceed to have the String repr but staying editable? -
Django server unable to get data from react Axios
I'm not getting an error but when I saw the logs of my server it prints an empty object {} whenever I send a request to the sever from my react app using axios. I double checked everything every other request in another components of my app works fine, but only in this particular request the data is not being sent! I have no CORS issue! My react axios request // PrivateAxios instance to send api request const axiosPrivate = useAxiosPrivate(); const handleSearch = async () => { const data = JSON.stringify({ from_company: keyWord }); try { const response = await axiosPrivate.get(SEARCH_URL, data); console.log(response); setRecords(response?.data); } catch (err) { if (!err?.response) { console.log("NO SERVER RESPONSE"); } else { console.log("SOMETHING WRONG"); } } }; Server log {} <-- Prints the request.data as an empty object "GET /api/find_many/ HTTP/1.1" 200 6276 The django server responses with correct details when I send a request with Postman or Thunder Client. The server also prints the object that were sent with the Postman request. I don't know why the server is unable to get the object or data when I request from my react app. Request sent from Postman returns {'from_company': 'Jethmal Paliwal'} <-- Prints … -
djLint code H030 and H031 linter issue vscode
djLint (vscode) gives error in every html file which has html tag and I can't figure out the real problem or the solution. The error messages: Consider adding a meta description. (H030) Consider adding meta keywords. (H031) There is 3 example, but I do not understand that, why example_3 doesn't have any error. example_1 (linter on, with error): example_1 example_2 (linter off for H030 and 031): example_2 example_3 (linter on, but no error if a commented block inserted before the html): example_3 My settings.json: settings I've checked the djLint docs and googled it, but no luck. Already reinstalled extensions and packages. Any idea or solution? I'm new to HTML (and programming) so maybe I'm doing something wrong. -
Having trouble running django on Pycharm
I'm sure you guys have heard enough of these questions but I am a new programmer looking to start using Django. I have done pip install django and by the time it's almost done download I received a warning. WARNING: The script django-admin.exe is installed in 'C:\Users\bryan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. I have ignored this earlier and ran the command django-admin startproject and of course I receive another error. The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Not quite what to do. I need your help. Or at least direct me to a post similar to this matter. Thank you! I have tried redirecting the PATH with pip install--install-option="--prefix=C:\Users\bryan\PycharmProjects\mySite" django I saw this on another post and thought it would help but nothing really worked. -
Beginner question. Started learning Django without knowing HTML, CSS and Javascript. is it possible? If not why?
Beginner question. Started learning Django without knowing HTML, CSS and Javascript. is it possible? If not why? Beginner question. Started learning Django without knowing HTML, CSS and Javascript. is it possible? If not why?