Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert string list to list in python [duplicate]
I have a List emp_id = "['1406','41232']" I want to convert the same into List ['1406','41232'] I tried emp_id = emp_id.strip('][').split(", ") But it resulted output was ["'1406'","'41232'"]" -
Is it possible to send an MQTT message with mqttasgi inside a Celery Worker that use Redis Backend
I am using mqttasgi library in Django to receive a large number of messages, and process them with a REDIS queue and I would like to publish this information back to another TOPIC. Is this possible? If yes, how can I do it ? For the moment I am only overriding the publish function into my consumer as below. from mqttasgi.consumers import MqttConsumer from mqtt_handler.tasks import processmqttmessage import json class MyMqttConsumer(MqttConsumer): async def connect(self): await self.subscribe('application/5/device/+/event/up', 2) async def receive(self, mqtt_message): print('Received a message at topic:', mqtt_message['topic']) print('With payload', mqtt_message['payload']) print('And QOS:', mqtt_message['qos']) print(type(mqtt_message['payload'])) dictresult = json.loads(mqtt_message['payload']) print(type(dictresult)) print(dictresult) jsonresult = json.dumps(dictresult) print(type(jsonresult)) print(jsonresult) processmqttmessage.delay(jsonresult) print("test") pass async def publish(self, topic, payload, qos=1, retain=False): await self.send({ 'type': 'mqtt.pub', 'mqtt': { 'topic': topic, 'payload': payload, 'qos': qos, 'retain': retain, } }) async def disconnect(self): await self.unsubscribe('application/5/device/+/event/up') I want to be able able to now publish but from the inside of my task processmqttmessage. Thank you. Pd: @Santiago Ivulich maybe you can help me with that. -
'NoneType' object has no attribute 'app' in saleor
I am using saleor backend for my current project. There I have to execute saleor graphql queries and mutations inside the code. So instead of hitting graphql api using url I am using schema.execute() with query and variables. With this approch the custom queries and mutations that I created are working perfectly fine. But when I am executing saleor's mutation or queries like- import graphene schema = graphene.Schema(ProductQueries) query = """ { products(first: 2, channel: "default-channel") { edges { node { id name defaultVariant{ id } } } } } """ data = schema.execute(query, context_value={"app":"app"}) print(data.data) output - {'products': None} And when I am checking for errors using print(data.errors), It is giving me this error- **[GraphQLLocatedError("'NoneType' object has no attribute 'app'")]** i checked out in types and schemas of these mutations and queries and nowhere this 'app' attribute is mentioned. Just to test I tried to pass this 'app' attribute in context_value with empty string as well but still It didn't work and this time the error was- **[GraphQLLocatedError("'dict' object has no attribute 'app'")]** -
error when Redirecting user to someone profile in other model
I want to redirected user to the profile page in the question model, I want when user click on url in the username of the question model, I want that url to redirected user to the author of that question to his/her public_profile page like facebook you can visit someone profile by clicking on his name when he/she post something, I have try using this method but it throws me an error: Reverse for 'Public_Profile' with arguments '('',)' not found. 1 pattern(s) tried: ['userProfile/(?P[-a-zA-Z0-9_]+)/\Z'] this is what i have try: my urls: urlpatterns = [ path('', views.rules, name='Rules'), path('create', views.login, name='login'), path('index/', views.index, name='index'), path('view/<slug:slug>/', views.viewQuestion, name='view-Question'), path('question/<int:pk>/answer/', views.My_Answer.as_view(), name='answer'), path('question/', views.My_Question.as_view(), name='question'), path('register/', views.register, name='register'), path('feedback/', views.PostFeedBack.as_view(), name='FeedBack'), path('notification/', views.NotificationListView.as_view(), name='notification'), path('profile/<int:pk>/', views.profile, name='Profile'), path('edit/<slug:slug>/', views.EditProfile.as_view(), name='edit'), path('userProfile/<slug:slug>/', views.public_profile, name='Public_Profile'), ] my index/home template: <div class="container"> <div class="row justify-content-center"> {% for question in list_of_question reversed %} <div class="col-md-4"> <div class="card my-3"> <div class="card-header"> <p class="card-title"><a href="{% url 'Public_Profile' profile.slug %}"> {{question.user.username.upper}} </a></p> </div> <div class="card-body"> <a href="{% url 'view-Question' question.slug %}" style="text-decoration: none;"> <p class="card-title">{{question.title}}</p> </a> <h5>{{question.category}}</h5> </div> </div> </div> {%endfor%} </div> </div> my views: def profile(request, pk): profiles = Profile.objects.filter(user=request.user) questions = Question.objects.filter(user=request.user) context = { 'profiles':profiles, 'questions':questions … -
Django on Google App Engine add version URL's to ALLOWED_HOSTS
I am hosting on GAE and want to be able to access different versions without promoting them. Currently, I get a 400 error: Invalid HTTP_HOST header: '1234568-dot-myapp.ey.r.appspot.com'. You may need to add '1234568-dot-myapp.ey.r.appspot.com' to ALLOWED_HOSTS. How can I add the URL to ALLOWED_HOSTS, so that I can access any version of my app? Currently, my ALLOWED_HOSTS looks like this: APPENGINE_URL = env("APPENGINE_URL", default=None) if APPENGINE_URL: if not urlparse(APPENGINE_URL).scheme: APPENGINE_URL = f"https://{APPENGINE_URL}" ALLOWED_HOSTS = [urlparse(APPENGINE_URL).netloc, 'my-personal-domain.com'] CSRF_TRUSTED_ORIGINS = [APPENGINE_URL, 'https://my-personal-domain.com'] SECURE_SSL_REDIRECT = True else: ALLOWED_HOSTS = ["*"] From my understanding, wildcards only work for sub-domains. How can I add something like this to the allowed hosts? [version-number]-dot-myapp.ey.r.appspot.com Thanks! -
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"?