Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use rest api in kivy to upload a file to a django website
am currently working on a system that involves building a website an a mobile application. I am using kivy to build my application however am facing an issue with using the django rest api to upload files to the site through kivy. How can I go about it. This is my function in main.py for uploading the file def upload(self, filepass, filename): print(str(filename)) def upload(self, filepass, filename): print(str(filename)) try: requests.post('http://127.0.0.1:8000/upload/', filepass) except: toast('Could not upload file')def upload(self, filepass, filename): print(str(filename)) try: requests.post('http://127.0.0.1:8000/upload/', filepass) except: toast('Could not upload file') try: requests.post('http://127.0.0.1:8000/upload/', filepass) except: toast('Could not upload file') This is my api view in my views.py class FileUploadView(APIView): parser_class = (FileUploadParser,) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data['files']) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is my models.py for the database of the uploaded file class File(models.Model): file = models.ImageField(upload_to='landbroker/', default='default.png') def __str__(self): return self.file.name This is my serializers.py for the file upload from rest_framework import serializers from .models import File class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = "__all__" And finally my urls.py path('upload/', views.FileUploadView.as_view()) With all that, whenever I try to submit the image django outputs unsupported file format. Please help. -
How to insert an image to an excel file with xlsxwriter?
I have to write images with some other datas to an excel file in my Django project and I have tried the code below. for counter_i, cost in enumerate(costs): counter_i += 1 for counter_j, feature in enumerate(features): value = getattr(cost, feature) if feature == 'image': image = str(value) worksheet.insert_image(counter_i, counter_j, image, {'x_offset': 15, 'y_offset': 10}) else: worksheet.write(counter_i, counter_j, value) In this code, the "value" contains image's path. But I got errors such as warn("Image file '%s' not found." % force_unicode(filename)) Also I have tried to give the whole path such as C:/Users/username/.. but this time, I got an Permission Denied error. How can I fix this? -
Field 'id' expected a number but got <QueryDict:
When I Submit Form I Got This Errors TypeError at /employee/ Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['vfO31XU2Y8x9MBzfUZ7rnq4widBlrt2uu6aF63ZorSW9DO6Rv8gjNE72SIN0YY1p'], 'name': ['Training'], 'designation': ['1'], 'department': ['1'], 'phone': ['12345'], 'date_of_birth': ['2020-12-31'], 'card_number': ['124'], 'pin': ['1234']}>. Request Method: POST Request URL: http://127.0.0.1:8000/employee/ Django Version: 3.0.3 Exception Type: TypeError Exception Value: Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['vfO31XU2Y8x9MBzfUZ7rnq4widBlrt2uu6aF63ZorSW9DO6Rv8gjNE72SIN0YY1p'], 'name': ['Training'], 'designation': ['1'], 'department': ['1'], 'phone': ['12345'], 'date_of_birth': ['2020-12-31'], 'card_number': ['124'], 'pin': ['1234']}>. Why i got this errors ? What's wrong in my code :( The code snippets of views.py def employee_list(request): if request.POST and request.FILES: form = EmployeeForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.user = RiverTimeUser.objects.create_user( username=request.POST.get('name'), pin=int(request.POST.get('pin')), password=request.POST.get('pin') ) data.save() messages.add_message(request, messages.SUCCESS, 'New Employee Added Successfuly') context = { 'object_list': Employee.objects.filter(department__institute=request.user.institute), 'form': EmployeeForm(request.user.institute) } return render(request, 'employee.html', context=context) -
Django/Nginx/Gunicorn/Supervisor: internationalisation is not applied
I try to deploy my Django project in a remote linux server (Ubuntu) I have followed an Openclassroom tutorial and it work except internationalisation I have had this problem when I deployed with alwaysdata because missing lines in my settings.py Here I checked all internationalisation settings are present (MIDDLEWARE, LANGUAGES, LOCAL_PATH) and it seems to be I try to set absolute path to my locale files (containing internationalisation files .po) but did not change anything but as gunicorn is running maybe change in settings;py have not been applyed ? architecture of my project: envs intensetbm_app | intensetbm-etool | | intenseTBM_eTool | | | wsgi.py | | | settings.py | | | ... | | manage.py | | locale | | | fr | | | | LC_MESSAGES | | | | | django.po | | ... intensetbm_static settings.py: import os import psycopg2.extensions from django.utils.translation import ugettext_lazy as _ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '***************************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['192.168.80.6',] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'widget_tweaks', 'bootstrap4', 'registration.apps.RegistrationConfig', 'monitor.apps.MonitorConfig', 'randomization.apps.RandomizationConfig', … -
Django jQuery-File-Upload upload Adding the user_id to the Model
I am using jQuery-File-Upload in Django based on this tutorial: https://simpleisbetterthancomplex.com/tutorial/2016/11/22/django-multiple-file-upload-using-ajax.html I want to add the User_id to the Model. This View is using JSON data passed from the html jquery. Do I modify the json or can I add it in the Model? Thank you. MODEL: class Files(models.Model): file = models.FileField(upload_to="uploads/%Y/%m/%d/") created = models.DateTimeField ( auto_now_add = True ) VIEW: class BasicUploadView(View): def get(self, request): file_list = Files.objects.all() content = { 'files': file_list } return render(self.request, 'upload/index.html', content ) def post(self, request): user_id = request.user.id form = UploadForm(self.request.POST, self.request.FILES) if form.is_valid(): file = form.save() data = {'is_valid': True, 'name': file.file.name, 'url': file.file.url} else: data = {'is_valid': False} return JsonResponse(data) -
Django mock not getting called at all
I have test defined looking like below @patch('user.serializers.validate_sns_token', return_value=True) def test_can_create_user(self, validate): """ Test that user can be created without logging in :return: """ user_payload = self.generate_user_payload() resp = self.client.post( CREATE_USER_URL, user_payload, ) self.assertTrue(validate.called) self.assertEqual( resp.status_code, status.HTTP_200_OK, ) Inside the user.serializers.py file I have below function that I would like to mock def validate_sns_token(**kwargs): try: ... return True except ValueError as e: ... return False It's an external call to google api so I would like to always return True from it. Inside the serializer I am calling the create function like below def create(self, validated_data): ... is_token_valid = validate_sns_token( sns_id=sns_id, sns_type=sns_type, token=token, ) if is_token_valid is False: raise serializers.ValidationError('토큰이 유효하지 않습니다. 다시 로그인해주세요.', code='AUTH') ... return user Unfortunately, the validate.called is always False and the original validate_sns_token is still getting called. How do I write a test so that the original validate_sns_token is not called at all but its return value is set to True? -
ConnectionResetError while playing a video file over Django, with FileField and HTML5 video tag
I'm having a Django project, where a FileField is applied for storing a video file (mp4). The Video File is actually stored on AmazonS3. The video file is then showed on the corresponding HTML, though Django DetailView, with an HTML5 video tag. <video width='50%' controls> <source src="{{ object.video_sample.url }}" type="video/mp4"> Your browser does not support the video tag. </video> The video is played well both locally (local ip) on and on deployed server. However, I'm keep getting this annoying error message on terminal/logs: > Exception happened during processing of request from (...) Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in init self.handle() File ".../env/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File ".../env/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer I think that it related with the fact user leaves the HTML page while the video is still open. Do you know how to get it resolved? BR, Shahar -
How to send notifications on email associated with user
i want to send sports related informatin on the email of users living in particular city, that users are already registered.How can i do that. I want to do that with the help of vieset and router,without serializer. class Notification(models.Model): Title=models.CharField(max_length=100,blank=False,null=False) Message=models.TextField() Location=models.CharField(max_length=20,blank=False) Sport=models.ForeignKey(Sport,on_delete=models.CASCADE) def __str__(self): return str(self.Title) -
Using and editing Python Site-packages
I'm using a package that I would like to be able to edit directly instead of appending views and functions to the package from my project. How would I do this? Can I copy the package into my project/root - or is this bad? I tried moving the package and then the Scripts could not execute the commands for that package anymore. Whats the best practice for this kind of stuff? I am aware that moving the package will mean I can't update it, but that's not an issue, editing the package would just be easier than appending things to it. Open to all suggestions :) -
How do I send image to backend from React without using FormData?
I want to send image with additional data from React.js to Django backend. When I used FormData() to create my form data, it could not send the array (because it converted it to string). Here is my code: let formData = new FormData(); formData.append('text', postForm.text); formData.append('image', postForm.image, postForm.image.name); formData.append('privacy', postForm.privacy); formData.append('custom_list', postForm.customList); props.createPost(formData); when I used this, I got this error: {"custom_list":["Incorrect type. Expected pk value, received str."]} So, I tried to create my own object to send to backend, but it can't handle image data. The code is: const formData = { text: postForm.text, image: postForm.image, privacy: postForm.privacy, custom_list: postForm.customList } This gave the following error: {"image":["The submitted data was not a file. Check the encoding type on the form."]} Is their any way I can send both list and image simultaneously? -
Django nice publication date rendering (i.e., "an hour ago" vs. "February 10, 2020")
I am building a dictionary app using Django. The app has a feed where definitions are displayed, where each definition has a publication date. My problem: publication dates rendered on templates look like "published on February 10, 2020", or similar. For my purpose, this is okay for old definitions, but not for more recent ones. My goal: recent publication dates should be rendered as "published an hour ago", "published yesterday", or similar. I have not been able to find any Django built-in tag or filter that does this automatically. Is there an easy way to achieve this in Django? If not, can anybody suggest a solution? -
Django ForeignKey with brackets: model cannot be resolved
I need to use brackets to define my foreign key in Django. Unfortunately I get an error I can't fix.. raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'Deck' cannot be resolved This is my model: class DeckDevice(models.Model): deck = models.ForeignKey( "Deck", on_delete=models.CASCADE, related_name="deckdevice" ) #somemorecode my migration: #somemoremigrations migrations.CreateModel( name="DeckDevice", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("start", models.DateTimeField()), ("end", models.DateTimeField(blank=True, null=True)), ( "deck", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="film.Deck" ), ), ], ), -
Python - extract all variables from a dict into locals
Is there a simple and elegant way to extract all variables from a dict to the current module locals? I am using Django and we would like to load all values of the local_settings.py file which is something like: DEBUG=True KEY="VALUE" NUMKEY=1 ... from a json, which will be compatible: { "DEBUG": true, "Key": "VALUE", "NUMKEY": 1 } so I'm looking for a simple way to extract all in few lines into the local variables of the settings.py file. Thank you! -
Django with Azure blob shared access signature
I am using azure blob storage for my media files in my django application. I need to implement shared access signature. Please help me to proceed. I am unable to find any docs or material to refer. Any help is appreciated. I tried with django-storages[azure] and upload alone works if i set the connection string. -
Django,HTML , connecting template to js,css
I have a Django project that contains a landing page. I worked on it outside the project and the HTML page was able to route to the js and CSS files and it worked great. Once I copied the folder into the project's templates folder (as shown in the structure below), And added routes and views in the project as required The server ran okay and open the page, But it's showing only the HTML and cannot refer to raises errors when trying to refer to the js scripts. for example: Not Found: /templates/js/main.js [19/Mar/2020 08:22:12] "GET /templates/js/main.js HTTP/1.1" 404 2490 # home.hmtl <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="yovelcohen" content="Sumon Rahman"/> <meta name="keywords" content="HTML,CSS,XML,JavaScript"/> <meta http-equiv="x-ua-compatible" content="ie=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!-- Title --> <title>Triangulation Calculator</title> <!-- Plugin-CSS --> <link rel="stylesheet" href=".css/bootstrap.min.css"/> <link rel="stylesheet" href=".css/owl.carousel.min.css"/> <link rel="stylesheet" href=".css/linearicons.css"/> <link rel="stylesheet" href=".css/magnific-popup.css"/> <link rel="stylesheet" href=".css/animate.css"/> <!-- Main-Stylesheets --> <link rel="stylesheet" href=".css/normalize.css"/> <link rel="stylesheet" href=".style.css"/> <link rel="stylesheet" href=".css/responsive.css"/> <script src="js/vendor/modernizr-2.8.3.min.js"></script> </head> <body> <!-- MainMenu-Area-End --> <!-- Home-Area --> <header class="home-area overlay" id="home_page"> </header> <!-- Home-Area-End --> <!-- About-Area --> # some HTML stuff ... <!-- Footer-Area-End --> <!--Vendor-JS--> <script src="templates/js/vendor/jquery-1.12.4.min.js"></script> <script src="templates/js/vendor/jquery-ui.js"></script> <script src="templates/js/vendor/bootstrap.min.js"></script> <!--Plugin-JS--> <script src="templates/js/owl.carousel.min.js"></script> <script src="templates/js/contact-form.js"></script> … -
Permission error in oauath2 using access token django
I am trying to generate an access token like this in django-rest-framework: def generate_access_token(request, user): expire_seconds = oauth2_settings.user_settings['ACCESS_TOKEN_EXPIRE_SECONDS'] scopes = oauth2_settings.user_settings['SCOPES'] application = Application.objects.get(name="test") expires = datetime.datetime.now() + timedelta(seconds=expire_seconds) access_token = AccessToken.objects.create(user=user, application=application, token=random_token_generator(request), expires=expires) token = { 'access_token': access_token.token, 'token_type': 'Bearer', 'expires_in': expire_seconds, 'scope': scopes } return token This is generating an access token, but when I am trying to use that access token to access other protected apis, it is giving me the following error:- { "detail": "You do not have permission to perform this action." } On the other hand, if I generate access token using the TokenView, that token is working fine. I am trying to manually create an access token using a user object returned on user registration and login. How can I get rid of this error, or what is the alternative to achieve this ? -
logout automatically in all tabs when logged out in one open tab with django
Is it possible to auto logout a user from all opened tabs(Popup window), if that user logoout from one of the open tab in the browser in django. If it is possible then How can I implement? Thanks in advance... -
How to properly setup facebook comment moderation tool?
I have added fb comments plugin on my django site, and would like to also use fb's moderation tool to moderate the comments on the pages involved. Previous dev made a mistake of not properly passing appId to the script, and I have rectified that. The problem is, some of the pages (without any comments present) do register new comments on the moderation tool, while others do not even though the its the same template, with the same script. Im including the related html and js code that I am using on the template <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v6.0&appId={{ SOCIAL_AUTH_FACEBOOK_KEY }}&xbfml=true&autoLogAppEvents=1" {% endif %} fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <meta property="fb:app_id" content="{{ SOCIAL_AUTH_FACEBOOK_KEY }}"/> <meta property="og:url" content="{{ article_url }}" /> <meta property="og:type" content="article" /> <meta property="og:title" content="{{ article.title }}" /> <meta property="og:description" content="{{ article.content|striptags|truncatechars:200 }}" /> <meta property="og:image" content="{{ article_full_image_url }}" /> <div id="fb-root"></div> <div class="fb-comments" data-href="https://{{ SITE.domain }}{{ LURL }}{{ request.path_info }}" data-num-posts="2" data-width="100%"></div> So the facebook sharing debugger tool picks up every meta tag properly, just comments are not being picked up on certain pages, while some do show up on the … -
Add interceptor for request in django rest framework like spring boot
I am new to python, I want to add HTTP request interceptor for each request like spring boot in python Django rest framework. where and how I can add in DRF. Anyone can help me ?. -
Django aws static file error on https while making request on swagger root
vendors.bundle.js:61 Mixed Content: The page at 'https://api.ereturns.co/' was loaded over HTTPS, but requested an insecure resource 'http://api.ereturns.co/register/'. This request has been blocked; the content must be served over HTTPS. Hi, i have deployed my django project on aws ec2(ssl added) . but, when i am going to swagger root and making request it is throwing error failed to fetch and showing above error in console of chrome browser. It is beacuse of one js file What does that mean how can i fix it ? -
Django: failed to config/start Supervisor -> FATAL/BACKOFF Exited too quickly
I try to deploy my django project on a test server (Ubuntu) using Nginx/Gunicorn/Supervisor but i made error in the intensetbm-gunicorn.conf files and firt had this error: FATAL can't find command '/home/test/env/bin/gunicorn' So I modify with the correct path and run cmd and get the trace bellow with a final error: sudo supervisorctl reread intensetbm-gunicorn: changed sudo supervisorctl update intensetbm-gunicorn: stopped intensetbm-gunicorn: updated process group sudo supervisorctl status > BACKOFF Exited too quickly (process log may have details) my project architecture: envs intensetbm_app | intensetbm-etool | | intenseTBM_eTool | | | wsgi.py | | | settings.py | | | ... | | manage.py | | ... intensetbm_static /etc/supervisor/conf.d/intensetbm-gunicorn.conf [program:intensetbm-gunicorn] command = /home/test/envs/envTbm/bin/gunicorn intenseTBM_eTool.wsgi.application user = test directory = /home/test/intensetbm_app/intensetbm-etool autostart = true autorestart = true -
How to update existing data and create new one django base command?
i am trying to store data in from json file and i added its not a problem to add data but when i trigger data again again they copy data and create same new one that i don't want , i want that it will update existing data and if there will new data in json file it will add in model . here is my django base command code. from django.core.management.base import BaseCommand import requests from demo.models import CoronaAge, CoronaSex, CoronaComorbidity class Command(BaseCommand): def handle(self, *args, **kwargs): url = 'https://api.the2019ncov.com/api/fatality-rate' r = requests.get(url) titles = r.json() print(titles) # For between age for title in titles['byAge'] or []: CoronaAge.objects.update_or_create( age=title['age'], rate=title['rate'] ) context = {'titles': CoronaAge.objects.all()} # for sex wise male and female for title in titles['bySex'] or []: CoronaSex.objects.update_or_create( sex=title['sex'], rate=title['rate'] ) context = {'titles': CoronaSex.objects.all()} for title in titles['byComorbidity'] or []: CoronaComorbidity.objects.update_or_create( condition=title['preExistingCondition'], rate=title['rate'] ) context = {'titles': CoronaComorbidity.objects.all()} -
Continously running Celery Task in Django
I've a Django app which should constantly listen for messages from Kafka and then send them via WebSocket to client. Problem is how to setup constant listener. For future scalability we decided to bring Celery in project to manage these issues with scaling. My task actually look like: class ConsumerTask(Task): name = 'consume_messages' def run(self, *args, **kwargs): consumer = get_kafka_consumer(settings.KAFKA_URL, settings.FAULT_MESSAGES_KAFKA_TOPIC, 'consumer_messages_group') logger.info("Kafka's consumer has been started") while True: messages = consumer.poll() for _, messages in messages.items(): messages, messages_count = self.get_message(messages) if messages_count > 0: messages = save_to_db() send_via_websocket_messages(messages) It properly saves and sends messages via WS, but problems comes from infinite loop in task. For some reason (probably task timeout constraint) task pop out if queue and never runs again. I am not sure that daemonizing celery workers will solve this problem. Could you please provide some strategies now organize "Constantly running part" of this process? -
Difference between add() and create() functions and the functionsality of save() method
I have been trying to understand the difference between .add() and .create() functions through django documentation. As far as I have understood is that: add() function with Foreign Key just updates the model and with m2m relation it does the bulk creation which eventually doesn't call for any save method. create function will create the instance of the object and save it. My doubt is: What does actually save does? If only create an instance without saving it, what does it mean? What is the main difference between add() and create() functions? -
Passing model instance's id in Django modelformset_factory
I am using modelformset_factory to be able to edit one parameter for all instances of a model. It works but I would like to display in the template the id of each individual model instance. How can I do that ? The view (the post request is handled by an other view): def habits(request): HabitFormSet = modelformset_factory( Habit, extra=0, form=HabitModelForm) context = { 'formset': HabitFormSet( queryset=Habit.objects.filter(user=request.user)) } return render(request, 'habits.html', context) the form: class HabitModelForm(MyFormMixin, forms.ModelForm): class Meta: model = Habit fields = [ 'name', ] the template: <form action="{% url 'bulk_edit' %}" method="post"> {% csrf_token %} <div class="table-responsive"> {{ formset.management_form }} <table> <tbody> {% for form in formset %} <tr> <td>test {{form.instance_id}}</td> / This would be ideal but not working {% for field in form %} <td>{{ field }}</td> {% endfor %} </tr> {% endfor %} <tr> <td> <button type="submit" class="btn btn-success text-right" value="Update">Update</button> </td> </tr> </tbody> </table> </div> </form> Thank you !