Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF and Celery: FileNotFoundError: [Errno 2] No such file or directory
This works fine on my local deployment but on the cloud deployement it does not. with open(file_path, "wb+") as fp: for chunk in file: fp.write(chunk) result = upload.delay(name, file_path) In a different file: @shared_task def upload(name, file_path): path = Path(path_tmp) if os.path.isfile(path): do something The error is Not a path /mediafiles/rawfiles/file.png", FileNotFoundError: [Errno 2] No such file or directory When I navigate in the docker to -> /mediafiles/rawfiles, the file is there and has a size. I am using DRF -> Celery -> Django. Can someone help why the cloud deployment is not able to find the file? -
PUT method is also Posting the Data in DRF
I am building a simple Blog App and I am using Django-Rest-Framework for the APIs, Everything is working fine But when, Post is working fine. I was using API URL like http://127.0.0.1:8000/api/blogs/ to get the results and post the results, then I started to work on PUT method. so when I insert the URL with ID like http://127.0.0.1:8000/api/blog/19/ then it is showing Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS so I tried to make a PUT request through there But it was not editing the data, It was posting the data, I mean it was creating the new data. then I read some tutorials and created a new UpdateView (genericView) then defined every function to it. But then it is again posting the data NOT editing the data. models.py class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=1000, default='') description = models.CharField(max_length=1000, default='') class Image(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='images') image_text = models.CharField(max_length=1000, default='') views.py class BlogView(viewsets.ModelViewSet): serializer_class = BlogSerializer queryset = Blog.objects.all() class BlogUpdateView(generics.UpdateAPIView): queryset = Blog.objects.all() serializer_class = BlogSerializer def update(self, request, *args, **kwargs): instance = self.get_object() instance.title = request.data.get("title") instance.description = request.data.get("description") instance.save() serializer = BlogSerializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) serializers.py class BlogSerializer(serializers.ModelSerializer): images = ImageSerializer(many=True) class … -
Django-filter. Lookup expression doesn't work properly
When I use MultipleChoiceFilter with lookup_expr='iexact' it looks like the parameters are still case sensitive and Select a valid choice is returned. What am I doing wrong? It's my filter class: class PostFilter(filters.FilterSet): lang = filters.MultipleChoiceFilter( field_name='language', choices=[('ENG', 'ENG'), ('DEU', 'DEU')], lookup_expr='iexact') class Meta: fields = ('lang',) model = Post Request: posts/?lang=eng&lang=deu Response: Select a valid choice. eng is not one of the available choices. My DB: PostgreSQL 14 -
Django ORM Group By Field by another field
I have SessionLog model class SessionLog(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ip_address = models.CharField(max_length=20, null=True) I want to get list of ip addresses for duplicated users only. So, if different users logged in with same IP address, I want to get list of such IP addresses. Also, I want to get users list who logged in same ip. So expected result would be [ { "ip_address": "170.221.23.56", "user_id": [21, 23, 45] }, { "ip_address": "170.221.23.58", "user_id": [25, 23, 45] }, ] How can I implement with django ORM? -
Connect AWS elasticsearch to Django
I have a django application which I succesfully linked to elasticsearch that is running on AWS. So I created a GET API using elasticsearch_dsl and elasticsearch_dsl_drf and more while this API now works perfectly, it only works in my localhost. I've deployed my Django App on AWS Lambda using Zappa. Below is how I make the connection ELASTICSEARCH_DSL = { 'default': { 'hosts': 'https://myendpoint.eu-central-1.es.amazonaws.com/', 'use_ssl': True, 'http_auth': ('***************', '***************'), 'connection_class': RequestsHttpConnection } } The problem that I'm getting when deployed is I get a timeout message: {"message": "Endpoint request timed out"} Is there any configuration I am doing wrong? or do I have to give some kind of permissions to AWS elasticsearch or AWS Lambda ? -
Unsure if its Pycharm Django or Myself?
So I am new to Django, familiar with Python and learning the Pycharm IDE. trying to setup a blog page for my 3 boys and wife to document our craziness and ran into this problem as I was adding apps to the program. When I use the Django startapp command in an attempt to start a todolist app I get this back and no new app created... I'm am definitely stumped as to what the problem is. Any feedback is appreciated. (.three_gees_venv) PS C:\Users\geeks\Desktop\GeeksGeckos&GoodVibes\three-gees- backend> python manage.py startapp todolist Traceback (most recent call last): File "C:\Users\geeks\Desktop\GeeksGeckos&GoodVibes\three-gees-backend\manage.py", line 22, in <module> main() File "C:\Users\geeks\Desktop\GeeksGeckos&GoodVibes\three-gees-backend\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\geeks\Desktop\GeeksGeckos&GoodVibes\three-gees- \.three_gees_venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\geeks\Desktop\GeeksGeckos&GoodVibes\three-gees- backend\.three_gees_venv\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\geeks\Desktop\GeeksGeckos&GoodVibes\three-gees- backend.three_gees_venv\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\geeks\Desktop\GeeksGeckos&GoodVibes\three-gees- backend.three_gees_venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\geeks\Desktop\GeeksGeckos&GoodVibes\three-gees- backend.three_gees_venv\lib\site-packages\django\apps\config.py", line 228, in create import_module(entry) File "C:\Users\geeks\AppData\Local\Programs\Python\Python310\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1047, in _gcd_import File "", line 981, in _sanity_check ValueError: Empty module name -
Invoke Django Signal only if the record is newly created - Django
I am using Django post_save signal, which will trigger whenever the new record is created. This signal is called every time a save action takes place. Even though it has the created boolean field, this function is executed all the time. The problem here is, at each request I am updating the User table last_login and last_active fields. Hence on each request this signal is getting executed. even though we are having created Boolean field, the function call is happened. which may cause performance impact when we have million request at a time. I am looking for a solution, the signal should get executed only if the new record is created in the User table. Sample code: @receiver(post_save, sender=User, dispatch_uid="call_method") def call_method(sender, instance, created, **kwargs): print ('>>>>>>>>>> Signal Called ', instance) if created: print ('$$$$$$$$$$$ User created') Kindly help me to find the better solution. -
relation "main_featured" does not exist
I'm using PostgreSQL and Django. I get "relation "main_featured" does not exist" even though I've migrated. I tried deleting migrations as well, but no luck. I've seen an answer that suggests I reset my database. But unlike that case, this is a production website and I have a lot of data in my database. This is what the error looks like: relation "main_featured" does not exist LINE 1: ..."."book_id", "main_featured"."creation_date" FROM "main_feat... ^ -
Django POST JSON from frontend to JSONfield
to start with what I want/need: when I click a button on the frontend, it registers the JSON it output to my database. I have a function in my template that outputs JSON as a string on click on my template. <script> const form = document.getElementById("myValue").addEventListener("click", myFunction); function myFunction() { let myValues = { "posX": pos.x, "posY": pos.y, "posZ": pos.z, "anAZ": anAZ, "anPo": anPo, } var myJSON = JSON.stringify(myValues) console.log(myJSON) console.log(typeof(myJSON)); // Console outputs the values. $.ajax({ type: 'POST', data: $('#form').serialize(), dataType: 'json', success: function(data) { if (data.msg === 'Success') { alert('Values are Saved') } } }) } and on the template.html: <button id="myValue">Save Values<form id="form" method="post">{% csrf_token %} </button> on models.py: class myJSON(models.Model) myValue = models.JSONField(default=dict, null=True) form.py: class myValuesForm(ModelForm): class Meta: model = myJSON fields = [ "myValue" ] on views.py if request.is_ajax(): form = myValuesForm(request.POST) if form.is_valid(): form.save I'm not sure what's wrong and why it's not writing the data. I don't receive any error in terminal. a help in this will be great.. -
Calculate the area of text on a photo in pixels in python
Are there ready-made libraries in Python for working with photos? I need a script to calculate the area of text on an image! Help me please! -
django debug toolbar - sql logging with websocket
Today my senior introduce a debugging tool 'django-debug-toolbar'. So I read this document and set files to display it. Now it is displayed, but I think it doesn't work. Nothing is logged even a query is executed. I read the document again because of it, I read this sentences. Does the async projects represent projects that made with websocket? Then, is there any similar tool to django debug toolbar that shows what query is executed and how long does it taken? -
How to create and if user is exits just update other data in django rest framework
I want to create an API in the Django rest framework. Task is Highlight will create and when the same user has the same book id then it'll update . I added the code below. but I'm not finding any way to update the values without creating new data. models.py class HighLight(models.Model): id = models.AutoField(primary_key=True) book = models.ForeignKey( BookDetails, on_delete=models.CASCADE, related_name='book_highlight' ) customer = models.ForeignKey('user_profile.CustomerProfile', on_delete=models.CASCADE,null=True,blank=True) start = models.IntegerField(blank=True, null=True) end = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Serializer.py class HighLightSerializer(serializers.Serializer): class Meta: model = HighLight fields = ('id','book','customer','start','end',) Views.py class HighLightedBooks(generics.ListCreateAPIView): permission_classes = (IsAuthenticated,) serializer_class = HighLightSerializer authentication_classes = (TokenAuthentication,) def perform_create(self, serializer): book_id = self.request.data.get('book', False) try: customer = CustomerProfile.objects.get(user=self.request.user) except Exception as e: raise ValidationError('You must have to update your profile before submitting a review') serializer.save(customer_id=customer.id, book_id=book_id) -
Pytest django database access not allowed with django_db mark
I'm using pytest and I have problem with database access in fixture below. I have django_db mark everywhere. [test_helpers.py] import pytest from django.test import Client from weblab.middleware.localusermiddleware import _set_current_user @pytest.fixture(scope="class") @pytest.mark.django_db def class_test_set_up(request): request.cls.client = Client() username = "username" user = User.objects.get(username=username) _set_current_user(user) I'm getting RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. In line user = User.objects.get(username=username) [test_tmp_fixture.py] import pytest from tests.factories.sample.test_factories import TestFactory from tests.tests_helpers.test_helpers import class_test_set_up SIZE = 5 @pytest.mark.django_db @pytest.fixture(scope="class") def set_up_objs(request): request.cls.factory = TestFactory request.instance.objs = request.cls.factory.create_batch(SIZE) @pytest.mark.django_db @pytest.mark.usefixtures("class_test_set_up", "set_up_objs") class TestTest: @pytest.mark.django_db def test_test(self): print("Hello Pytest") My setup is pytest-7.0.1 with plugins: lazy-fixture-0.6.3, Faker-13.3.2, django-4.5.2 and django version 3.2.12 In traceback console shows problems with /pytest_lazyfixture.py:39: -
Submitting form in the same page in Django
How to send "get" request in the same page URL with other parameters present already. I have a URL http://127.0.0.1:8000/search/?search=adi , and inside this , I have another form which takes and sends "get" request . I want to submit that "Get" request in same page via the form. I tried <form action="{{ request.get_full_path }}" method="get"> but this does not give the "search=adi" parameter after form is submitted. I want to send like http://127.0.0.1:8000/search/?search=adi&min=100&max=120 -
Django REST: Create a model object with the user field as current user
I have a Document model which has user field as a ForeignKey. I'm trying to implement two very common features: user creates a new document withCredentials=True; the document will of course have the owner as the user that created it user can later fetches all documents that have the owner as themselves This is my current code. I am assuming I got the model fields correct as I can see the User field as a dropdown menu in the admin panel. However, I am not sure which part (backend vs frontend) I need to modify in order to allow frontend to make an AXIOS POST request. BACKEND (DJANGO REST FRAMEWORK) models.py class Document(models.Model): id = HashidAutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=100, default="Untitled") template = models.CharField(max_length=100, default="") editorState = models.JSONField(default=[]) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) serializers.py class DocumentSerializer(serializers.ModelSerializer): id = HashidSerializerCharField(source_field="documents.Document.id", read_only=True) question_blocks = QuestionBlockSerializer(many=True) outline_blocks = OutlineBlockSerializer(many=True) mysource = MySourceSerializer(many=True) user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) class Meta: model = Document fields = "__all__" def create(self, validated_data): question_blocks = validated_data.pop("question_blocks") outline_blocks = validated_data.pop("outline_blocks") document = Document.objects.create(**validated_data) for qBlock in question_blocks: QuestionBlock.objects.create(document=document, **qBlock) for oBlock in outline_blocks: OutlineBlock.objects.create(document=document, **oBlock) document.save() return document FRONTEND (REACT) export const … -
Django I/O web app to trigger databricks notebook, do the process and store the results on s3
I have a fully functional django web app running in windows local machine. However, I now need to deploy it in aws ec2 windows server. This is "upload - process - download" type of application. since the processing is quite heavy, I want to shift it to databricks notebook. So, DB Notebook should access the input file, process it and later save the output which can be downloaded by using web app. My question is, Can this be done ? I was thinking of a way, where I can trigger a notebook through rest API request with required parameters. ( I couldn't find any way ) If I trigger DB Notebook with AWS-lambda, then can I trigger AWS- lambda through rest API ? Both Input and Output can be saved to either DBFS / S3 ? If someone has worked on similar activity, can anyone suggest a way to do it. I am quite new to databricks, thus not aware of most of it's functionalities. Note - Both Input & Output are .csv format files. I understand this could be a similar to some other question here, I couldn't find such specific use case. -
I need to list my new product to ebay by using api
Now I am developing ebay automation software. I need to list new product to ebay. But I dont know which api do I have to use If someone has experiences with ebay product upload api then please share code simply. -
Django Rest Framework returns: "a valid integer is required"
I created a react form using django with the rest framework in the background. If i leave the integer field empty during form submission i get the following error from the rest api: "a valid integer is required" The problem is that this field is not required for the user to fill in and using a default of 0 doesn't work either since some people will type in a number and then change their mind and empty the field again. So what i'm trying to do is when the field is empty the form sends null instead of an empty string. I should propably mention that i'm using formik to build my forms. models.py PriceRangeMax = models.IntegerField(null=True, blank=True) FacilityUpdate.py <Field name="PriceRangeMin"> {({ field, form }) => ( <label className="mt-3 block"> <span className="text-gray-700">Price Range</span><br></br> <input {...field} type="number" className="mt-2" style={ form.touched.PriceRangeMin && form.errors.PriceRangeMin ? ( { border: '2px solid var(--primary-red)'} ) : null } /> </label> )} </Field> -
django.db.utils.IntegrityError: NOT NULL constraint failed: app_users.key_value_id
Here i have two models Keys and Users i am creating POST API so i got encounter with this Error UserModel.py class Users(AbstractBaseUser): vendor_name = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None) key_value = models.ForeignKey(KeyTable, on_delete=models.CASCADE, default=None, null=True) username = models.CharField(max_length=100, verbose_name="username", unique=True) password = models.CharField(max_length=100) hardware_id = models.CharField(max_length=150, null=True) created_by = models.DateField(verbose_name="created_by", auto_now_add=True) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['password', 'hardware_id'] is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_role_vendor = models.BooleanField(default=False) is_role_customer = models.BooleanField(default=True) def __str__(self): return self.username objects = UserManager() KeyModel.py where Keys are stored class KeyTable(models.Model): key_id = models.IntegerField(unique=True, auto_created=True) key_value = models.CharField(max_length=100) issue_date = models.DateField(max_length=100) expiry_date = models.DateField() status = models.CharField(max_length=50) license_tenure = models.IntegerField() def __str__(self): return self.key_value KeySerializer class KeySerializer(serializers.ModelSerializer): class Meta: model: Keys fields = ['key_id', 'key_value', 'issue_date', 'expiry_date', 'status', 'license_tenure'] Error Encounters: django.db.utils.IntegrityError: NOT NULL constraint failed: app_users.key_value_id Need Help me to resolve this error, i will be grateful, Thanks -
Invalid property specified for object of type plotly.graph_objs.pie.Marker: 'color'
I am trying to design pie chart in plotly and django,I am getting error when i use pie instead of bar. data_plots = go.Pie(x=repo_names, y= repo_stars,marker = {'color' : '#0000FF'}) layout = {'title': '','xaxis': {'title': 'Date and time'},'yaxis': {'title': 'Total Import'},'plot_bgcolor':'#E8E8E8'} fig = {'data': data_plots, 'layout': layout} plot_div = offline.plot(fig, output_type='div') return plot_div error is. Invalid property specified for object of type plotly.graph_objs.Pie: 'x' Did you mean "ids"? -
Import "rest_framework.authtoken.models" could not be resolvedPylance
this error shows when I hover over it along with a yellow line. I installed rest_framework from the terminal and added it to the installed apps on the settings page, but it still won't work. these are the libraries I am using on the same file from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager , Group as DjangoGroup from django.utils.translation import gettext_lazy as _ from rest_framework.authtoken.models import Token -
Can variables be shared between different apps in Django?
For whatever reason, two different apps have been requested for a particular task ( divided in two stages ). Both apps use the same variable, which was generated in the 1st app. Currently, two approaches are being used. Return the variable to client side and send it again to the 2nd app. Save the results in memory, and read it back in the 2nd app. Is there any way to share this across apps? Thanks. -
The previous button isn't working for pagination in my html file. Any solution would be great
html file {% if page_obj.has_previous %} <button method="post" type="submit" class="action-btn checkRequired Submit" name="action" value="Submit"> previous</button> <input type="hidden" name="page_no" value="{{ page_obj.previous_page_number }}"> {% endif %} Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} {% if page_obj.has_next %} <button method="post" type="submit" class="action-btn checkRequired Submit" name="action" value="Submit"> next</button> <input type="hidden" name="page_no" value="{{ page_obj.next_page_number }}"> {% endif %} views.py def practise(request): print(request) questions_list = Question.objects.get_queryset().order_by('id') paginator = Paginator(questions_list, 1) page_number = request.POST.get('page_no') page_obj = paginator.get_page(page_number) print(request.GET) if request.method=="POST": answer = request.POST.get('answer') difficulty = request.POST.get('myRange') surety=request.POST.get('surety') return render(request, "try.html", {'page_obj': page_obj}) Here, I have declared the next and previous button values(links), but after clicking on the Previous button, it is rendering to the next page instead of the previous. Please, any help would be appreciated. -
Object of type User is not JSON serializable error when logging using custom serializer
I am trying to use signals to check whether or not a user is logged in. Since I am using DRF when a user logs in they get a JWT token, I need to re-write validate to trigger user-logged-in when a user receives a valid token when logging in. However I am getting the error message: Object of type User is not JSON serializable Here is a breakdown of what I have tried: this is my login API endpoint: path('api/token/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'), My CustomObtainPairView: class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer My CustomTokenPair Serializer: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer; from rest_framework_simplejwt.views import TokenObtainPairView; ... class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): credentials = { self.username_field: attrs.get(self.username_field), 'password': attrs.get('password') } if all(credentials.values()): user = authenticate(request=self.context['request'], **credentials) if user: if not user.is_active: msg = 'User account is disabled.' raise serializers.ValidationError(msg) user_logged_in.send(sender=user.__class__, request=self.context['request'], user=user) return { # 'token': jwt_encode_handler(payload), 'user': user } else: msg = 'Unable to log in with provided credentials.' raise serializers.ValidationError(msg) else: msg = 'Must include "{username_field}" and "password".' msg = msg.format(username_field=self.username_field) raise serializers.ValidationError(msg) @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['first_name'] = user.first_name token['last_name'] = user.last_name token['country'] = user.profile.country token['city'] = user.profile.city token['bio'] = user.profile.bio token['photo'] = json.dumps(str(user.profile.profile_pic)) return token and … -
Python application Framework for QTEST dashboard
I am a QA tester, trying to create a web application for first time I want to create a python based application . Below are my requirements Web based application hosted in some cloud It retrieves data from Qtest Test management tools like , number of test disabled , executed on daily basis Store in some data base use can see the data is some kind of table and grap What framework approach should i use ?