Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Movie cast with characters in Django
So, I'm doing the classical movie app in Django (I'm loving the framework!) and I feel like I hit a stump. So, I have my Movie model: class Movie(models.Model): TitlePRT = models.CharField(max_length=100) TitleORG = models.CharField(max_length=100) TitleAlt = models.CharField(max_length=100) Poster = models.ImageField(upload_to=posterPath, max_length=100) Synopsis = models.TextField() Year = models.IntegerField() DubStudio = models.ForeignKey("Studio", on_delete=models.CASCADE) Trivia = models.TextField() CreatedBy = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="+") CreatedAt = models.DateTimeField(auto_now=False, auto_now_add=True) Modifiedby = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="+") ModifiedAt = models.DateTimeField(auto_now=True, auto_now_add=False) My Actor model: class Actor(models.Model): Bio = models.TextField() Name = models.CharField(max_length=50) FullName = models.CharField(max_length=50) DateOfBirth = models.DateField() Country = models.TextField(max_length=100) Nationality = models.TextField(max_length=50) Debut = models.ForeignKey("Movie", on_delete=models.CASCADE) CreatedBy = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="+") CreatedAt = models.DateTimeField(auto_now=False, auto_now_add=True) ModifiedBy = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="+") ModifiedAt = models.DateTimeField(auto_now=True, auto_now_add=False) ClaimedBy = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="+") And, finally, my Cast model: class Cast(models.Model): Movie = models.ForeignKey("Movie", on_delete=models.CASCADE) Actor = models.ForeignKey("Actor", on_delete=models.CASCADE) Character = models.TextField(max_length=50) Observations = models.TextField(max_length=50) Right now, I can add content through Django admin, but it's awkward, because I can't add a cast in the Movie form. I have to go to the Cast form, and a character one by one I've searched about customizing admin forms and whatnot, but I get a little confused. Is there to create a form … -
Django - Exclude URL from Django REST API Documentation? Using drf-yasg
How do I remove the path below from my API documentation with my current code? path('users/reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view()), I don't want this path to be generated. I’m using drf_yasg to generate re-doc and swagger documentation. Below is some of what's under the hood of settings.py. Any help is gladly appreciated! Thanks! settings.py from rest_framework.documentation import include_docs_urls from rest_framework.schemas import get_schema_view from rest_framework import permissions from allauth.account.views import ConfirmEmailView, EmailVerificationSentView from dj_rest_auth.views import PasswordResetConfirmView from drf_yasg import openapi from drf_yasg.views import get_schema_view API_TITLE = ‘Test API API_DESCRIPTION = ‘Test ‘Description schema_view = get_schema_view( openapi.Info( title=“title-test”, default_version='v1', description=“blah blah.”, ), public=True, permission_classes=(permissions.IsAuthenticated,), ) urlpatterns = [ # AllAuth Authentication path('accounts/', include('allauth.urls')), # Django REST API Paths path('api/', include('api.urls')), path('api-auth/', include('rest_framework.urls')), # ConfirmEmailView Needs to be defined before the registration path path('api/dj-rest-auth/registration/account-confirm-email/<str:key>/', ConfirmEmailView.as_view()), path('api/dj-rest-auth/', include('dj_rest_auth.urls')), path('api/dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('api/dj-rest-auth/registration/account-confirm-email/', EmailVerificationSentView.as_view(), name='account_email_verification_sent'), # path('api/dj-rest-auth/reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view()), # API Documentation Paths path('docs/', include_docs_urls(title="GameStation API", description=API_DESCRIPTION)), # path('schema/', schema_view), path('swagger<format>/', schema_view.without_ui(cache_timeout=0), name='schema-json'), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ## This path is what I’m trying to remove path('users/reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view()), ] -
IntegrityError when Adding Social Application in Django: Null Value in Column "provider_id"
IntegrityError when Adding Social Application in Django: 'Null Value in Column "provider_id" violates non-null constraint' I am encountering an IntegrityError in my Django application when attempting to add a social application using Django Allauth. The error specifically points to a null value in the provider_id column, and I'm seeking assistance to resolve this. The error occurs when I try to add a new social application through the Django admin panel. Here's the detailed error message: ($ symbols are to block for privacy IntegrityError at /admin/socialaccount/socialapp/add/ null value in column "provider_id" violates not-null constraint DETAIL: Failing row contains (8, google, google, 888982092733-51qdar9ln6i5onjoli2blj9bb6$$$$$$$.apps.googleusercon..., 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, , null, null). provider to Google, which is the only drop down option all migrations have taken place in the code Google OAuth via django details Authorised redirect URIs are linking to port urls. Publishing status is in production. Resources being consulted. Akamai DevRel. “Set up Google Sign-in for Faster Django Login Experience Feat. Tech with Tim.” YouTube, YouTube Video, 12 Dec. 2022, https://youtu.be/yO6PP0vEOMc?feature=shared&t=1386. Accessed 11 Nov. 2023. all steps have been followed to implement a google oauth with this tutorial, the issue arises around 23:06 when adding a social account. “Django.” Django Project, 2023, https://docs.djangoproject.com/en/4.2/topics/auth/. Accessed 11 … -
get last 3 object of model from database in Django
I'm working on blog project & I have 'Last posts' section for posts in car category i want to get last 3 object of my model from db and send with context to template. 'car_post' : post.objects.filter(category__name = 'car')[:3] I tried this code but i think it shows first 3 post in db what can i do? -
How do i install django spirit forum package to my django application with its own custom usermodel?
I have a django application that has its own user model, authentication pages etc. When i install the spirit forum package with pip and create the app as a new project in a separate empty project to inspect the package and what the forum will look like (by running it), i see that it requires a username to login, create account and it has it own profile pages. My custom user model doesnt use username, only email adress and it has its own profile pages. How do i smoothly install the package and do i need to modify my current custom user model? I did as explained above, install the package in an empty project to inspect it but here i worry that it will not automatically adjust to my custom user model. -
How to implement "create link" function in django?
I am coding real time chat application that has rooms with hash as a pk. On the index page, there is input field that takes a link and let user join to specific chat Room. On the chat room page, there is create link button and it is only visible if you are owner of this chat room Link should always be unique and expire after some amount of Time. Maybe you know this function from Discord Any ideas on how to implement this? My thought is to create Link and Room models. Room has a foreign key to Link model and Link model has URLField ( URL field can be none ). And just to hash a hash of the Room? I just don't want users to join chat room via URL on the top of the browser -
TypeError at / object HttpResponse can't be used in 'await' expression
Code doesn't run after running it in the venv. I use django for backend, vue for frontend and tailwind for css. Error goes like this: Traceback (most recent call last): File "C:\Users\docto\OneDrive\Desktop\bms\backend\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\docto\OneDrive\Desktop\bms\backend\venv\Lib\site-packages\whitenoise\middleware.py", line 124, in __call__ return self.get_response(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\docto\OneDrive\Desktop\bms\backend\venv\Lib\site-packages\asgiref\sync.py", line 240, in __call__ return call_result.result() ^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\concurrent\futures\_base.py", line 449, in result return self.__get_result() ^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\concurrent\futures\_base.py", line 401, in __get_result raise self._exception ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\docto\OneDrive\Desktop\bms\backend\venv\Lib\site-packages\asgiref\sync.py", line 306, in main_wrap result = await self.awaitable(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Exception Type: TypeError at / Exception Value: object HttpResponse can't be used in 'await' expression [TypeError Message] (https://i.stack.imgur.com/NsCIP.png) Code which the error was raised: class LandingPageView(TemplateView): template_name = 'public_pages/landing.html' def __init__(self, **kwargs): super().__init__(**kwargs) seasons = Season.seasons.all()[:2] self.is_landing = 'active' self.previous_season = seasons[1] if seasons.count == 2 else seasons.first() self.season = seasons.first() self.main_image = MainImage.images.all().first() self.news = News.images.all().first() self.unupdated_accounts = get_activation_requests().first() def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: return {'self': self} Tried searching for the await expressions, checked the middlewares, even the whitenoise. Didn't find anything -
Fail to map ports from docker container
I managed to start a Docker container with a trivial django application. But I do not know why can't I access it from my browser? I used this command: docker run -p 8000:8000 --name c1 django:1 screenshot of my terminal But I still can't access django app from the web-browser. enter image description here Here is my Dockerfile: FROM python:3-slim ENV PYTHONUNBUFFERED=1 #RUN addgroup app && adduser -S -G app app #USER app WORKDIR /app/ COPY requirements.txt . RUN pip install -r requirements.txt COPY . . ENV API_URL=http://api.myapp.com EXPOSE 8000 CMD ["python", "manage.py", "runserver"] Could you please tell me what I am doing wrong so I can't access django app from the terminal please? I tried searching and troubleshooting but no effect. -
Cannot access django-admin panel on port
Expecting to be able to access django admin panel and add social accouunt opening admin panel by adding standard admin/ extension to local preview port URL. This is expected to lead to classic django admin panel. going to the admin url instead leads to an error message the website is otherwise displaying fine. A simple google oath signin is currently being implemented. Error message: DoesNotExist at /admin/login/ Site matching query does not exist. Request Method: GET Request URL: http://8000-lmcrean-project4-avaw7dd1zq8.ws-eu106.gitpod.io/admin/login/?next=/admin/ Django Version: 3.2.23 Exception Type: DoesNotExist Exception Value: Site matching query does not exist. Exception Location: /workspace/.pip-modules/lib/python3.9/site-packages/django/db/models/query.py, line 435, in get Python Executable: /home/gitpod/.pyenv/versions/3.9.17/bin/python3 Python Version: 3.9.17 Python Path: ['/workspace/Project-4', '/home/gitpod/.pyenv/versions/3.9.17/lib/python39.zip', '/home/gitpod/.pyenv/versions/3.9.17/lib/python3.9', '/home/gitpod/.pyenv/versions/3.9.17/lib/python3.9/lib-dynload', '/workspace/.pip-modules/lib/python3.9/site-packages', '/home/gitpod/.pyenv/versions/3.9.17/lib/python3.9/site-packages'] Server time: Sat, 11 Nov 2023 15:17:58 +0000 traceback details in full Currently trying to fix with this tutorial “Set up Google Sign-in for Faster Django Login Experience Feat. Tech with Tim.” Akamai DevRel, YouTube Video, 12 Dec. 2022, https://youtu.be/yO6PP0vEOMc?feature=shared&t=1328. Accessed 11 Nov. 2023. have followed correctly with all working up to 22 minutes in migration was recently made after setting up urls, views and templates for google oauth as per the tutorial, there were no obvious issues with this before that django-admin panel seemed to … -
Save the images of ckeditor fields to local media and not s3
I'm working on a django project and I have used s3 cloud storage to save my media files. The challenge that I have faced is that I want the images of ckeditor fields to be saved on local and not s3. How should I do that? I haven't found any solution for my problem in any community -
revoking celery task, redis broker
I'm trying to revoke, terminate, abort or getting currently active tasks from celery in a django project; all methods are sent to worker after the currently running task has been finished, look at logs here: [2023-11-11 17:50:01,299: INFO/MainProcess] Task NPS.tasks.keys[8e4136d8-f9f8-45bf-9f29-5e0dbf11235d] succeeded in 98.43799999996554s: {'count': 10683923 } [2023-11-11 17:50:01,339: DEBUG/MainProcess] pidbox received method active(safe=None) [reply_to:{'exchange': 'reply.celery.pidbox', 'routing_key': '4bb6ba45-6e90-346d-89f9-01731fee3fa4'} ticket:c822c5ec-37b0-44a8-a721-675a328532ca] [2023-11-11 17:50:01,340: DEBUG/MainProcess] pidbox received method reserved() [reply_to:{'exchange': 'reply.celery.pidbox', 'routing_key': '1a5ee3c4-a5df-3642-a853-6a6fcba4a215'} ticket:ca112a23-39b4-4978-bdee-36b7cb13cc4d] [2023-11-11 17:50:01,343: DEBUG/MainProcess] pidbox received method revoke(task_id='c6bf8ad6-787a-4a76-ab4a-edb804fc8cdd', terminate=True, signal='SIGTERM') [reply_to:None ticket:None] [2023-11-11 17:50:01,345: INFO/MainProcess] Task NPS.tasks.keys[c6bf8ad6-787a-4a76-ab4a-edb804fc8cdd] received [2023-11-11 17:50:01,345: INFO/MainProcess] Discarding revoked task: NPS.tasks.redis_keys[c6bf8ad6-787a-4a76-ab4a-edb804fc8cdd] [2023-11-11 17:50:03,330: DEBUG/MainProcess] Timer wake-up! Next ETA 1.0 secs. active, reserved and revoke method has been called during the process of task, but none of them executes on time. what should I do? and whats the solution? -
login to a seperate user group in django
I have created a distinct user registration in django. class Trainer(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) bio = models.TextField(blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = TrainerManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] groups = models.ManyToManyField(Group, related_name='trainer_groups', blank=True) user_permissions = models.ManyToManyField(Permission, related_name='trainer_user_permissions', blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" i have created a user signup from and its working. I am facing challenges while trying into logging in to the user. Its always showing "Please enter a correct username and password. Note that both fields may be case-sensitive." any idea on how to specify the trainer user model while logging in? The new User model is under TRAINERS app have tried logging in using the below code def trainer_login(request): if request.method == 'POST': form = AuthenticationForm(request, data=request.POST) if form.is_valid(): email = form.cleaned_data.get('username') # Use email as the username field password = form.cleaned_data.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) messages.success(request, 'Login successful.') # Redirect to the desired page after login return redirect('dashboard') # Change 'dashboard' to your desired URL name else: messages.error(request, 'Invalid email or password.') else: form = AuthenticationForm() return render(request, 'trainer_login.html', {'form': … -
Lost local file main.css after commit & push
I've finished my project and was trying to commit and push changes. I trought it was successfully, but when I went to the site I saw that there are no styles. Everything was committed successfully except main.css. It was replaced from last commit to my local pc and full-done css file was delated respectively PS. Commit and push were done by PyCharm PS2. Pycharm Local History - Show History not available for main.css I tried git reflog, but nothing heppened. Here's my tries: PS D:\PyProjects\ElectricCarsStore> git reflog 9b2ccd3 (HEAD, origin/master) HEAD@{0}: checkout: moving from c6f4aa2b2196603cd1af12e0e06ae9e6767b8b1a to 9b2ccd3 c6f4aa2 HEAD@{1}: checkout: moving from afcf0469d2369145e0296eac5b7e693a0508ba29 to c6f4aa2 afcf046 (master) HEAD@{2}: checkout: moving from master to afcf046 afcf046 (master) HEAD@{3}: reset: moving to afcf046 9b2ccd3 (HEAD, origin/master) HEAD@{4}: merge origin/master: Merge made by the 'ort' strategy. c6f4aa2 HEAD@{5}: commit: Ready project v.1.0 afcf046 (master) HEAD@{6}: commit (initial): Initial commit I will be grateful for your advice. -
django doesn't apply all css properties
I want to port my .html file to django project. I edited the file and inserted static tags, transferring .html and .css files into the django project, django did not apply all the styles specified in the .css file that's how page looks in vs code:vs code and how it's looks in django: django so, you can see several blocks that are not in vs code, but they are displayed in django, this is because the style file specifies "display: none" for these classes, but django ignores these how can i fix this problem? -
axios give me error (POST /api/v1/users/token/refresh/ HTTP/1.1" 401 65) , How solve it?
in windows 10 , i'm using react-router-dom 5.2.0 and react-redux 7.2.5 and react 17.0.2. and axios 0.21.4 and WebStorm 2023.1.3 IDE. Consider 1 - axiosInstanse.js: import jwt_decode from 'jwt-decode'; import dayjs from 'dayjs'; import axios from 'axios'; import {updateAccessToken} from '../actions/userActions'; const baseURL = 'http://127.0.0.1:8000'; const axiosInstance = (userInfo , dispatch) => { const instance = axios.create({ 'mode': 'cors', baseURL, headers: { 'Content-Type': 'application/json', Authorization:`Bearer ${userInfo?.access}`, } }); instance.interceptors.request.use(async req=> { try { const user = jwt_decode(userInfo.access); const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 5000; if (!(isExpired)) { return req } const response = await axios.post( '/api/v1/users/token/refresh/' , {refresh:userInfo.refresh}, ); dispatch(updateAccessToken(response.data)) req.headers.Authorization = `Bearer ${response.data.access}`; return req; } catch (error) { console.log(error) } }); return instance } export default axiosInstance; Consider 2 - userActions.js: export const userFurtherInformationAction = (image, gender) => async (dispatch, getState) => { try { dispatch({ //USER FURTHER INFORMATION REQUEST type: USER_FURTHER_INFORMATION_REQUEST, }); const {userLogin: {userInfo}} = getState(); const formData = new FormData(); const image_url = URL.createObjectURL(image) formData.append('userPicture', image); formData.append('sex', gender); // var object = {}; // formData.forEach(function(value, key){ // object[key] = value; // }); // var json = JSON.stringify(formData); // const config = { // 'mode': 'cors', headers: { // // 'Content-type': 'multipart/form-data', 'Authorization': `Bearer ${userInfo.token}` // } … -
token authentication in django rest framewok is not working with digitalocean, but it is working perfectly in my local
i have deployed a django rest framework in digitalocean,eveything is working perfectly when make a post and get request with postman software,but when make a post request to this TestView which is bellow, it is showing this error : "Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x7f10fecb2ed0>." in this line : score = Score.objects.get(user=request.user.id). this is the TestView : class TestView(APIView): authentication_classes = [TokenAuthentication] def get(self, request): questions = Question.objects.all() questions_serializer = QuestionsSerializer(questions,many=True,context={'request': request}) return Response(questions_serializer.data) def post(self, request): question_id = request.data.get('id') user_answer = request.data.get('answers') correct_answer = Answer.objects.filter(question=question_id, is_correct=True).values_list('answer', flat=True).first() if correct_answer is not None: if user_answer == correct_answer: try: score = Score.objects.get(user=request.user.id) print(self.user) score.score += 1 score.save() except Score.DoesNotExist: score = Score.objects.create(user=request.user, score=1) score_serializer = ScoreSerializer(score) return Response({'message': 'your answer was correct', 'score': score_serializer.data}, status=status.HTTP_200_OK) else: return Response({'message': 'your answer was incorrect'}, status=status.HTTP_400_BAD_REQUEST) else: return Response({'message': 'correct answer not found for this question'}, status=status.HTTP_404_NOT_FOUND) if hard coded the user id in this line of code like this: instead of this : score = Score.objects.get(user=request.user.id) changed to this : score = Score.objects.get(user=1) then it works. i also printed the print(request.user),print(request.user.id) and print(request.auth) they are null, but in my local print(request.user) is printing the user. i also contact … -
Postgres Database connection pooling in django
I want to implement database connection pooling in django.I have tried setting "CONN_MAX_AGE" to None and even to a number like 1800 but this does not seem to help also I have tried setting DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": env("POSTGRES_DB"), "USER": env("POSTGRES_USER"), "PASSWORD": env("POSTGRES_PASSWORD"), "HOST": env("POSTGRES_HOST"), "PORT": env("POSTGRES_PORT"), 'OPTIONS': { 'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED, 'conn_max_age': 600, }, } } but still I can't see database connections getting pooled. I have another question how will I check if database connection is getting pooled or not? tried above with no result -
Search for rows in the Sqlite database that contain certain words
I was making a killboard for EVE online and wanted to do a database search for certain words contained in the string. Here are all the column names of my database: id final_blow_name final_blow_ship_type victim_name victim_corporation victim_birthday victim_gender victim_security_status victim_ship_type sistem_security_status attackers_len I did it using LIKE and WHERE. But it gives the error "no such column: the name I was looking for". Here is my code: path = 'C:/Users/mrjol/PycharmProjects/myboard/board_veiw/database.db' connection = sqlite3.connect(path) cursor = connection.cursor() search_request = str(request.session.pop('search_request', 'None')) character_name_1 = search_request.partition(' ')[0] character_name_2 = search_request.partition(' ')[2] if character_name_2 != '': search_request = character_name_1 + '_' + character_name_2 search_answer = cursor.execute('SELECT final_blow_name FROM Killmails WHERE final_blow_name = Cosmo_Blink') connection.close() -
How can you use JavaScript to send a video blob to a Django view using a Django form?
In a nutshell How can I use JavaScript to get a blob of video data to a Django view through a Django form? Background I'm building a feature to record a webcam video. I've successfully figured this part out. I can use JavaScript to stream the user's camera and mic, record the stream, turning it into a blob, and then I'm able to turn the blob into a file. However, I don't want a file because I need users' videos to simply be sent to my backend, and I don't want users to interact with a video file (and I just learned that you can't programmatically assign <input type='file'> elements a file because of security reasons). This is why I'm looking to just send the binary data. What I've Tried (and what the result was) Like I said, I tried using a FileField in my Django form (but cuz inherent web security restrictions, no worky). Having users download and upload the file themselves does not work with project requirements. I've tried using a JSONField for my Django form and submitting the binary in JSON format. Perhaps this could still work, but I can't get the binary data into JSON format. … -
SearchVector is splitting hyphens in my UUID field
I have a django application and I am trying to use a field named external_id, that is a UUID string to build my SearchVector (from django.contrib.postgres.search) . The problem is that the search_vector being created in the Postgres DB is splitting the strings between the hyphens, for example: external_id = 5f4ffd5b-0738-4aa4-8961-3114b54d1e20 search_vector = '-0738':2 '-3114':6 '-4':3 '-8961':5 '5f4ffd5b':1 'aa4':4 'b54d1e20':7 So, when I am trying to search for the complete UUID, I do not get a match, but searching for the parts created in the search_vector matches, like: 5f4ffd5b or -8961. I have tried changing my Postgres search configuration using: CREATE TEXT SEARCH CONFIGURATION public.my_search_config (copy=simple); ALTER TEXT SEARCH CONFIGURATION public.my_search_config DROP MAPPING FOR hword, hword_part, word, word_part; CREATE MAPPING FOR asciiword, asciihword, hword_ascii WITH simple; but got: SQL Error [42601]: ERROR: syntax error at or near "MAPPING" Position: 8 I have also tried to modify the text search parser: ALTER TEXT SEARCH PARSER default_parser SET TOKEN_TYPE = 'word', START = 'a' , GETTOKEN = 'dsimple'; but got: SQL Error [42601]: ERROR: syntax error at or near "TOKEN_TYPE" Position: 45 -
error getting credentials - err: exec: "docker-credential-desktop": executable file not found in %PATH%, out: `
I am working on a django project in window 10 Home, with docker desktop. When trying to create a multiple container with the command docker compose up -d (or docker-compose up -d) it gives me the following error: $ docker compose up -d [+] Running 0/1 mysql Pulling error getting credentials - err: exec: "docker-credential-desktop": executable file not found in %PATH%, out: I have tried the following: -Change the path found in the PATH of the environment variables, the original is C:\Program Files\Docker\Docker\resources\bin, but if I change it to C:\Program Files\Docker\Docker\resources\ bin\docker.exe or C:\Program Files\Docker\Docker\resources\bin\docker-compose.exe, it gives me another error: $ docker compose up -d bash:docker:command not found -I have also changed the value "credsStore" to "credStore" in the config-options.json file, as some users suggest in other similar cases, but it has no effect I hope you can help me -
prefetch_related not working when using SerializedMethodField
I have four levels of nested models, the Company > Division > Team > TeamMember. The following code serializes everything correctly. My issue is when trying to use prefetch_related in views.py. Based on the SQL queries reported in the debugger, it looks like the Division and Team tables are being prefetched correctly, but there are hundreds of extra SQL queries for the TeamMember table. I suspect the issue might be that within CompanySerializer, I am using a SerializerMethodField to get Teams. Could it be that using Team.objects.filter(division__company=obj) is not compatible with prefetching? models.py class TeamMember(models.Model): name = models.CharField("Name", max_length=300, unique=True) team = models.ForeignKey("Team", on_delete=models.RESTRICT) class Team(models.Model): name = models.CharField("Name", max_length=300) division = models.ForeignKey("Division", on_delete=models.RESTRICT) class Division(models.Model): name = models.CharField("Name", max_length=300, unique=True) company = models.ForeignKey("Company", on_delete=models.RESTRICT) class Company(models.Model): name = models.CharField("Name", max_length=300) serializers.py class TeamMemberSerializer(ModelSerializer): class Meta: model = TeamMember fields = '__all__' class TeamSerializer(ModelSerializer): teammembers = TeamMemberSerializer(read_only=True, many=True, source="teammember_set") class Meta: model = Team fields = '__all__' class DivisionSerializer(ModelSerializer): teams = TeamSerializer(read_only=True, many=True, source="team_set") class Meta: model = Division fields = '__all__' class CompanySerializer(ModelSerializer): # I suspect the issue might here. I wish to return the company's divisions AND # teams in this fashion. When the SerializedMethodField is removed, the … -
Django always acesses default DB
I'm creating an API with a dynamic database (based on the client accessing it), but for testing purposes, I manually defined two in settings.py: DATABASES = { 'default': {}, 'test1': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'model_base1', 'USER': 'root', 'PASSWORD': '123', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': {'charset': 'utf8mb4'}, }, 'test2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'model_base2', 'USER': 'root', 'PASSWORD': '123', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': {'charset': 'utf8mb4'}, }, } I have this view file: from rest_framework import generics from cadastro.models.enderecos import Enderecos from cadastro.serializers.enderecos import EnderecosSerializer class EnderecoListarCriarAPIView(generics.ListCreateAPIView): queryset = Enderecos.objects.using('test1').all() serializer_class = EnderecosSerializer and I have this serializer: from rest_framework import serializers from cadastro.models.enderecos import Enderecos class EnderecosWriteOnlyMixin: def get_fields(self): fields = super().get_fields() fields['id_referencia'].read_only = True fields['tipo_tabela_referencia'].read_only = True return fields class EnderecosSerializer(EnderecosWriteOnlyMixin, serializers.ModelSerializer): id_referencia = serializers.IntegerField() tipo_tabela_referencia = serializers.IntegerField() class Meta: model = Enderecos fields = [ "id_endereco", "id_referencia", "tipo_tabela_referencia", "cep", "logradouro", "numero", "complemento", "bairro", "cidade", "uf", ] def to_internal_value(self, data): # Aplicar uppercase para todos os campos for field_name, field_value in data.items(): if isinstance(field_value, str): data[field_name] = field_value.upper() return super().to_internal_value(data) Model.py of this view / serializer: from django.db import models from cadastro.validators.enderecos import * class Enderecos(models.Model): id_endereco = models.AutoField(primary_key=True) cep = models.CharField( max_length=10, blank=False, null=False, validators=[validate_cep] ) numero = models.CharField( … -
Encountering "Not Found" Error Only in Production Environment
Not Found The requested resource was not found on this server. I think the issue is in my setting.py file: from pathlib import Path import os import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', default='your secret key') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = 'RENDER' not in os.environ ALLOWED_HOSTS = [] RENDER_EXTERNAL_HOSTNAME = os.environ.get('RENDER_EXTERNAL_HOSTNAME') if RENDER_EXTERNAL_HOSTNAME: ALLOWED_HOSTS.append(RENDER_EXTERNAL_HOSTNAME) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'coreapi', 'tareas', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'calendar_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'calendar_app.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': dj_database_url.config( default='postgresql://postgres:postgres@localhost/postgres', conn_max_age=600) } # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = … -
Problem uploading multiple images to s3 with a single API call
I have a post API which receives an array of response objects from frontend. Each object consists of certain string fields and a 'pic' field which contains a pic. What happens at backend is an object is made from the string fields and the pic is stored in s3 bucket. I tested this whole flow on my local multiple times and it worked perfectly fine. However when I pulled the code on the AWS server, the submit API fails if the pic exists in request from frontend. Moreover if there is a pic in just one object from the request data it gets uploaded but multiple images fail to get uploaded. And this happens only on server, locally it worked fine. My API looks like: class QuestionResponseCreateView(generics.CreateAPIView): serializer_class = QuestionResponseSerializer authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): print(request.user) responses = request.data print(request.data) saved_responses = [] for response_data in responses: try: # print(response_data) question_id = response_data['question_id'] outlet = response_data['outlet'] response = response_data['response'] image_data = base64.b64decode(response_data.get('pic')) image_file = BytesIO(image_data) remarks = response_data['remarks'] userName = response_data['userName'] question = Question.objects.get(id=question_id) photo_type = question.get_photo_type_label() current_datetime = timezone.now() year = current_datetime.year month = current_datetime.month day = current_datetime.day directory_path = f"{outlet}/{photo_type}" photo_name = …