Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set permissions for HR and TL for request approval in django rest framework
I'm working on HRMS application in django rest framework I want to set permissions for Hr and Team leader to approve leave request of employees. How can i achieve. If it's admin approval i can easily do that. But since it's hr and tl i should manually create that. How can i achieve it? Also how to request a leave and how tl approved and it can be forwarded to hr for approval? -
I am getting the following error in my Django file. Can someone help me out?
I am getting the following erroR. Can someone look into it and help me out: File "C:\Users\myUsrename\AppData\Roaming\Python\Python310\site-packages\django\contrib\gis\gdal\libgdal.py", line 69, in <module> lgdal = CDLL(lib_path) File "C:\Program Files\Python310\lib\ctypes\__init__.py", line 374, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 127] The specified procedure could not be found -
Get request followed by a Post request in Django, How to?
through my GET request here I can get some mp3 files and download them, Now I would like to pass those files to an other API as a payload. Can you do this in one call ? here is the example : class UserSearchView(APIView): def get(self, request, link): url = config('BASE_URL') querystring = {"track_url": f'{link}'} headers = { "X-RapidAPI-Key": config('API_KEY'), "X-RapidAPI-Host": config('API_HOST') } response = requests.request("GET", url, headers=headers, params=querystring) name = response.json()['url'] filename = name.split('/')[-1] doc = requests.get(name) with open(filename, 'wb') as f: f.write(doc.content) wave = f.name base_path = '/Users/cyhl/Desktop/TrackID/backend/' absolute_path = base_path + wave sound = AudioSegment.from_mp3(absolute_path) # split sound in 20-second slices and export for i, chunk in enumerate(sound[::20000]): with open("sound-%s.mp3" % i, "wb") as f: chunk.export(f, format="mp3") return JsonResponse(status.HTTP_200_OK) **Not sure how to proceed from here, I would like to loop from this files I've just downloaded and pass them as a payload ** **def post(self, request) : url = config('BASE_URL') payload = "" headers = { "content-type": "multipart/form-data; boundary=---011000010111000001101001", "X-RapidAPI-Key": config('API_KEY'), "X-RapidAPI-Host": config('API_HOST') } response = requests.request("POST", url, data=payload, headers=headers)** What is the best way to go here -
DRF always return not authenticated in Django rest framework fed on NextJS and Axios
After testing on postman i get the right response but when i pushed the code for the frontend guys, I get a report that it's always returning false... views.py # Check authentication status def check(request): data = {} if request.user.is_authenticated: data['response'] = 'user is authenticated' data['name'] = request.user.name data['email'] = request.user.email data['phone_number'] = request.user.phone_number data['id_user'] = request.user.id_user data['passed_kyc'] = request.user.passed_kyc else: data['response'] = 'user is not authenticated' return JsonResponse(data) -
Using the URLconf defined in myworld.urls
My directory index.html: <h1>Members</h1> <table border="1"> {% for x in mymembers %} <tr> <td><a href="update/{{x.id}}" style="decoration: none">{{x.id}}</a></td> <td>{{ x.f_name }}</td> <td>{{ x.l_name }}</td> <td><a href="delete/{{x.id}}">Delete</a></td> </tr> {% endfor %} </table> <p> <a href="add/" style="decoration: none">Add members</a> </p> update.html: <h1>Update member</h1> <form action="updaterecord/{{mymember.id}}" method="post"> {% csrf_token %} First Name:<br /> <input name="first" value="{{mymember.f_name}}" /> <br /><br /> Last Name:<br /> <input name="last" value="{{members.l_name}}" /> <br /><br /> <input type="submit" value="Submit" /> </form> members/url.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('add/', views.add, name='add'), path('add/addrecord/', views.addrecord, name='addrecord'), path('delete/<int:id>', views.delete, name='delete'), path('update/<int:id', views.update, name='update'), path('update/updaterecord/<int:id>', views.updaterecord, name='updaterecord'), ] myworld/urls.py: from django.contrib import admin from django.urls import include,path urlpatterns = [ path('members/', include('members.urls')), path('admin/', admin.site.urls), ] the url:http://127.0.0.1:8000/members/update error it might be a silly mistake or something but i cant just figure it out...help is appreciated!thanks -
how add custom fild to all objects of django model
i have db where is companies and custom users, i want add custom field for different companies. Example: user have only NAME, if company is "EXAMPLE": user have fields only NAME and AGE, elif "VIN": user have only NAME and SIZE and AGE and WORK, else: only name. How add this custom fields and update it. Thanks, sory for my English)) Company 1: name "+add field" company2: -name -age "+add field" company 3: -name -age -size "+add field" I try many to many, many to one, simple fields, dont work how i want. I wand many custom field how i can edit for every user -
Making a user to edit his/her data only in django admin
I am creating a website in which users can add details about him/her or remove them but I don't want to make a separate page in the front end for that... is there any way that I can only let the logged-in user edit his/her details only.. here is my models.py code from django.db import models from django.contrib.auth.models import User DEPARTMENTS = ( ('CSE', 'Computer Science and Engineering'), ('ECE', 'Electronics and Communication Engineering'), ('EEE', 'Electrical and Electronics Engineering'), ('ME', 'Mechanical Engineering'), ('CE', 'Civil Engineering'), ('R&A', 'Robotics and Automation'), ) class Staff(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=100) address = models.CharField(max_length=100) designation = models.CharField(max_length=100) department = models.CharField(max_length=3, choices=DEPARTMENTS, default='CSE') bio = models.CharField(max_length=1000) join_date = models.DateField() scholar_id_link = models.CharField(max_length=100) irns_link = models.CharField(max_length=100) image = models.ImageField(upload_to='display_pictures', blank=True) def __str__(self): return self.user.get_username()+ " " + self.department + " " + self.designation class WorkExperience(models.Model): staff = models.ForeignKey(Staff, on_delete=models.CASCADE, default=1) place = models.CharField(max_length=100) designation = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() def __str__(self): return self.staff.user.get_username() + " " + self.place + " " + self.designation -
Database Query returning empty in test cases - Django
I have updated the Django version for my project from Django-2.2.16 --> Django3.2.14. But with this update, some of my test cases are failing and I cannot understand the reason for the failure. My test-case file: import json from os import access from unittest import mock from unittest.mock import patch import asyncio from app.models import UserProfile from django.test import TestCase, TransactionTestCase from requests.models import Response from services.check_status import check_status loop = asyncio.get_event_loop() @mock.patch("services.check_status.save_status") @mock.patch("services..check_status.send_wss_message") class TestUserStatus(TransactionTestCase): def setUp(self): super().setUp() self.account_id = 4 self.sim_profile = UserProfile.objects.create() def test_check_status_completed( self, mock_send_wss_message, mock_save_status, ): mock_save_status.return_value = {} send_wss_message_future = asyncio.Future() send_wss_message_future.set_result(True) mock_send_wss_message.return_value = send_wss_message_future loop.run_until_complete( check_status( self.sim_profile.id, ) ) self.assertTrue(mock_save_status.called) self.assertTrue(mock_send_wss_message.called) My pseudo check_status file is :- import logging from app.models import UserProfile, UserStatus from services.constants import WebsocketGroups from services.user.constants import USER from app.api.serializers import UserStatusSerializer from services.utils import send_wss_message, sim_states, log_activity logger = logging.getLogger(__name__) def save_status(**kwargs): status = UserStatus.objects.filter( status_id=kwargs.get("status_id") ).first() data = kwargs user_status_serializer = UserStatusSerializer(status, data, partial=True) if user_status_serializer.is_valid(): user_status_serializer.save() async def check_status( profile_id ): user_profile = UserProfile.objects.get(id=profile_id) login_token = get_login_token(user_profile) user_creds = env["user_api"] headers = USER["headers"] subscription_details = SimClient.get( USER["url"], headers ) transaction_status = subscription_details.json()["Status"] subscription_data = subscription_details.json()["Data"][0] transaction_status_details = subscription_data["TransactionStatusDetails"] error_message = "" status = "" if transaction_status … -
can't stop celery woker
I have a problem with celery worker. I need to start default celery worker but an error accurate. It says that already using this process mailbox! and when I try below command for kill process it says no processes found. ps auxww | grep 'celery worker' | awk '{print $2}' | xargs kill -9 I tried to kill process but could not kill it. In addition I use celery in django application. -
Django Graphene mutation deletes objects instead of update
There is a such mutation and a pretty simple update function, I expect it will only update one parameter of the object, then saves it. Actually, at the first request, it returns the expected response, but objects delete from DB. class PortfolioMutation(graphene.Mutation): class Arguments: portfolio_id = graphene.ID() visible = graphene.Boolean() portfolio = graphene.Field(PortfolioType) @classmethod def mutate(cls, root, info, portfolio_id, visible): portfolio = Portfolio.objects.get(pk=portfolio_id) portfolio.visible = visible portfolio.save() return PortfolioMutation(portfolio=portfolio) class UpdatePortfolio(graphene.ObjectType): """ Portfolios mutation """ update_portfolio = PortfolioMutation.Field() schema = graphene.Schema(query=QueryPortfolios, mutation=UpdatePortfolio) Exact request mutation UpdatePortfolio{ updatePortfolio(portfolioId: 1509, visible: false) { portfolio { name visible } } } Respnse { "data": { "updatePortfolio": { "portfolio": { "name": "High Yield Corporate Bonds", "visible": false } } } } Where I messed up? -
migration problem while hosting a django project on PythonAnywhere
I recently finished my django project and i switched my database from the local SQLite database witch django provides you to an online postgreSQL database provided by elephantSQL. Clearly, by entering my database credential in the setings.py file of my django project i am able to mugrate to my new database, localy(meaning that when i run my server on port 8000 it loads my data from the postgreSQL, but when i push my website to PythonAnywhere and try to run my migrations from the bash console of PythonAnywhere it throws out the following error:` django.db.utils.OperationalError: connection to server at "'USER'.db.elephantsql.com" ("DATABASE_IP"), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? ` I even changed my database Host from elephanSQL to nhost, but still it promps the same result. -
I want to create custom signup form and add extra fields in Django default user model
enter image description hereI want to add full name instead of first and last name and I also want to add some others fields like address phone number city from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): full_name=forms.CharField(max_length=50,required=True) phone_number=forms.CharField(widget=forms.TextInput(attrs={'type':'number'})) address=forms.CharField(max_length=200,required=True) city=forms.CharField(max_length=200,required=True) class Meta: model = User fields = ('username', 'email', 'password1', 'password2','full_name','phone_number','address','city') def register(self): self.save() I created form by using this method first created froms.py for extra fieds then inherit it its working but still some fields are diappear -
using subquery in annotate django
i have two models want to query from Job and user class Job(models.Model): #other fields removed personnel_assigned = assigned_personnel = models.ForeignKey( User,on_delete=models.RESTRICT,related_name="assigned_jobs", blank=True,null=True, ) is_performed = models.BooleanField(default=False) what i want to get all users with annotated field of count equal to number of jobs assigned and not performed ive tried this so far engineers = ( User.objects.filter(groups__name="maintenance") .annotate(count=Count(F("assigned_jobs"))) .order_by("count") ) though I understand that this will return the count of all jobs assigned to that specific user I also, tried jobs = Job.objects.filter(is_performed=False,personnel_assigned__isnull=False).values_list('pk',flast=True) then User.objects.filter(groups__name="maintenance") .annotate(count=Count(Q(assigned_jobs__in=jobs))) .order_by("count") but still nothing works -
Increment each of the value of the table
We have two model class: Student and Instructor. Student and Instructor have one to many relationship. Models: class Student(models.Model): instructor = models.ForeignKey(Board, on_delete=models.CASCADE, related_name="students") name = models.CharField(max_length=255) roll = models.IntegerField() mark = models.DecimalField(decimal_places=8, max_digits=16, default= 0.0) class Instructor(models.Model): name = models.CharField(max_length=255) Serializers: class StudentSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'name', 'roll', 'mark') model = Student class InstructorSerializer(serializers.ModelSerializer): students = StudentSerializer(many=True, read_only=True) class Meta: fields = ('id', 'name', 'students') model = Instructor We have a hypothitical scenario where instructor wants to increase each students marks with a crazy formula: student's ranking * 2 . That means, we have to update each of the student table's row for that corresponding teacher id. For example: there are 3 students - Student 1: ( name: "A", roll: 3, mark: 10) ; Student 2: ( name: "B", roll: 4, mark: 15) ; Student 3: ( name: "B", roll: 4, mark: 13) ; after operation: Ranking of the students by marks : Student 2 ( Rank 1), Student 3 ( rank 2 ), Student 1 ( rank 3). Student-2(Rank-1)'s mark will be increase as follows ( 1 * 2 ), Student-3(Rank-2)'s mark will be increase as follows ( 2 * 2 ), Student-3(Rank-3)'s mark will be … -
importing decoreators.py in top-level directory django project
Is there any way to create decorators.py file in top-level folder of the project in Django so many applications can use it? If the file is in top-level dir and I try to import it to myapp/views.py by: from ..decorators import student_required, teacher_required I get an error: from ..decorators import student_required, teacher_required ImportError: attempted relative import beyond top-level package However when importing this way: from .decorators import student_required, teacher_required The output is: from .decorators import student_required, teacher_required ModuleNotFoundError: No module named 'myapp.decorators' I need to use this decorators in myapp1, myapp2, myapp3 and I don't want to populate the same file over and over again. Is there any quick workaround for this? How can I point to the decorators.py properly? -
How to upload file directly to s3 django
I create a form field and uploading file using that. I want those file to be uploaded directly to s3 without saving locally. Here is the code class UploadFileForm(forms.Form): file = forms.FileField() if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): print('file upload',request.FILES['file']) s3 = boto3.client('s3') now how can i upload request.FILES['file'] via s3 -
Copying only non-relation attributes django/python
I am copying a model object to another, but I want that it doesn’t copy the relations For example, assume you have a model like class Dish(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) def __str__(self): return self.name Then I do my_dish = Dish.objects.get(pk=dish.id) serializer = Dish_Serializer(my_dish) my_new_object = serializer.data I want my_new_object to include only those attributes that are not relations, in this case, name and description How do I do that without accessing name and description directly Thanks in advance Rafael -
Change Django Default Language
I've been developing a web application in English, and now I want to change the default language to German. I tried changing the language code and adding the locale directory with all the translations, but Django still shows everything in English. I also want all my table names to be in German along with the content in the templates. I also tried Locale Middleware and also this repo for a custom middleware but it still doesn't work. Not to mention, Django changes the default language of the admin panel, but my field and table names remain English. MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'language.DefaultLanguageMiddleware', # 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'de' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True LOCALE_PATH = ( os.path.join(BASE_DIR, 'locale') ) Here is my locale directory: This is how I use translation in my templates: {% load i18n static %} {% translate "Single User" %} This is how I have defined my models: from django.utils.translation import gettext_lazy as _ class Facility(models.Model): name = models.CharField(_('Name'), max_length=100, null=True, blank=True) class Meta: verbose_name_plural = _('Facilities') -
getting data from the backend django models
I am working on a project pastly the i used sql querys, but change in the django models the models i used are for the members table class Members(models.Model): name = models.CharField(max_length = 50) address = models.CharField(max_length = 50) phoneNo = models.CharField(unique=True, max_length = 50) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) def __str__(self): return self.name for the bills table salesPerson = models.ForeignKey(User, on_delete = models.SET_NULL, null=True) purchasedPerson = models.ForeignKey(Members, on_delete = models.SET_NULL, null=True) cash = models.BooleanField(default=True) totalAmount = models.IntegerField() advance = models.IntegerField(null=True, blank=True) remarks = models.CharField(max_length = 200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] i am having a query that is credits = Bills.objects.all().filter(cash = False).values ('purchasedPerson').annotate( cnt = Count('purchasedPerson'), debit = Sum( 'totalAmount' ), credit = Sum( 'advance' ), balance = Sum( 'totalAmount' ) - Sum( 'advance' ) ).order_by ('purchasedPerson') getting the output as [{'purchasedPerson': 1, 'cnt': 2, 'debit': 23392, 'credit': 100, 'balance': 23292}, {'purchasedPerson': 2, 'cnt': 1, 'debit': 1280, 'credit': 0, 'balance': 1280}] but i need in the out put name, address and phone number also how can i get those -
Notifications for an app React Django using GraphQL
I am working on an app React Django using GraphQL. I heard about websocket with subscriptions but I cannot use that with graphene. What I want it something really simple I mean send a signal from the server to the clients if there is a new comment. Do you have any ideas how can I do to implement that ? Thank you very much ! -
Docke Preparing editable metadata (pyproject.toml) did not run successfully
Working on a fairly simple django task. It works as expected. I am trying to build and run a docker. It is the Dockerfile: FROM python:3.10 ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ PIP_NO_CACHE_DIR=off \ POETRY_NO_INTERACTION=1 \ POETRY_NO_ANSI=1 \ APP_PATH="/usr/src" WORKDIR $APP_PATH RUN pip install poetry COPY poetry.lock pyproject.toml ./ # --no-dev is depricated (--only main) RUN poetry install --no-root --only main # Copy in source code. COPY . . # Install ourselves; all dependencies should be there already. RUN pip install --no-input --no-color --no-deps -e . EXPOSE 8000 It fails in RUN pip install -e . line! It is also pyproject.toml : [tool.poetry] name = "dj-task" version = "0.1.0" description = "" readme = "README.md" packages = [{include = "dj_task"}] [tool.poetry.dependencies] python = "^3.10" Django = "^4.1.3" requests = "^2.28.1" Pillow = "^9.3.0" mimetype = "^0.1.5" pandas = "^1.5.2" celery = "^5.2.7" django-redis = "^5.2.0" [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" The final error is Preparing editable metadata (pyproject.toml): started Preparing editable metadata (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error × Preparing editable metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [20 lines of output] Traceback (most recent call last): ...... File "/tmp/pip-build-env-wgrjgnli/overlay/lib/python3.10/site-packages/poetry/core/masonry/utils/package_include.py", line 66, in check_elements … -
How can I return a context from views.py in different html files in Django?
So, I have a method called 'room' in my views.py file. I can only access this room on my room.html page as I'm returning it there but I would like to use this data on my index page as well. How can I do that? Advance Thanks. Views.py def room(request): rooms = Rooms.objects.all() photos = RoomImage.objects.all() context = {'rooms':rooms, 'photos':photos} return render(request, 'hotelbook/room.html', context) -
wrong path instead of the actual file is being saved to backend in Django
Been really struggling with this I have a Vue front end with a HTML form <form id="postForm" method="POST" action=""> <div class="mediaButtons horizontal mb10"> <div class="mediaButton"> <input type="file" name="" id="postImages" accept="image/jpg, image/png, image/jpeg, image/tiff, image/webp, image/bmp, image/svg" @change="handleImages" multiple maxFileSize="50000" /> <div class="buttonImage"> <img class="buttonImg" src="../assets/img/pic.png" /> </div> </div> </div> <fieldset class="postButtons mt20" v-if="catChosen"> <button class="topBtn" type="button" name="addPost" @click="submitPost"> Post </button> <button class="canBtn" type="button" name="addPost" @click="store.hideAddaPost" > Cancel </button> </fieldset> </form> The function to handle the images and display them is this: import { ref } from "vue"; const fields = ref({ previews: [], images: [], }); function handleImages(event) { var input = event.target; var count = input.files.length; function isFileImage(file) { return file && file["type"].split("/")[0] === "image"; } if (count > 8) { return store.messages.push("Max 8 images per post please"); } for (const file of input.files) { if (isFileImage(file)) { } else { return store.messages.push("Only image files are allowed"); } } var index = 0; while (count--) { var reader = new FileReader(); reader.onload = (e) => { fields.value.previews.push(e.target.result); }; fields.value.images.push(input.files[index]); reader.readAsDataURL(input.files[index]); index++; } } I send the data to the backend using this function: function submitPost() { let uploaded_images = [] fields.value.images.forEach((val) => uploaded_images.push(val)) const fieldsData = { "category": selectedCat.value, … -
Dynamically positioning an element depending on the models properties in Django
As a personal project I am working on a custom calendar. I have an Event model that includes TimeFields describing when the event starts and ends which I've redacted to only include relevant fields in this post. class Event(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() start_time = models.TimeField(null=True, blank=True) end_time = models.TimeField(null=True, blank=True) summary = models.CharField(max_length=200, help_text="Enter summary") description = models.CharField( max_length=1000, help_text="Enter description and relevant data") The calendarView returns an array of querysets for each day that I iterate through to create a grid of events. @login_required def index(request): startingDate = datetime.date(2022, 11, 21) datesDisplayed = [startingDate + datetime.timedelta(days=i) for i in range(7)] eventsByDate = [] for i in range(7): eventsByDate += [Event.objects.filter(owner=request.user).filter( start_date=datesDisplayed[i]).exclude(start_time=None)] context = {"eventsByDate": eventsByDate,} return render(request, 'index.html', context=context) The template: {% for events in eventsByDate %} <div class="eventsByDate"> {% for event in events %} <div class="event"> <b>{{ event }}</b>, {{event.timeDisplayed.0}} </div> {% endfor %} </div> {% endfor %} As the title describes I would like to position the events dynamically depending on the starting time of each event. So far the best way I could think of how to do that is to create a value in the view and pass … -
Django translation. RuntimeWarning: DateTimeField received a naive datetime
English is the default language of the project. When I switch language, values of all date fields are disrepair. When I try to fill up the form and send it, appear this error: RuntimeWarning: DateTimeField received a naive datetime (2022-11-27 12:00:00.045143) while time zone support is active. I think the problem with time zone. if make this USE_TZ = False the translation is not working at all...