Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to schedule a task with Celery that runs after three months and only once
I have created an advertising app in my websilte with django and the Ad model looks like this AdModel(models.Model): starting_date = models.DateField() expiring_date = models.DateField() active = models.BooleanField(default=False) My goal is to create a task using Celery to activate (set ad.active = True) and deactivate ads based on their starting and expiring date and since the celery beat is for periodic recurring task so it's not going to solve it. Probably passing the starting_date as eta to the task like this will be the solution: #signals.py @receiver(post_save, sender=AdModel) def start_task(sender, instance, created, **kwargs): if created: ad_activator_task.apply_async( (instance.id), eta=instance.starting_date) If the instance.starting_date is three months far from now, is it going to be executed ? i have read that Celery not usefull for long term future tasks (far future) and i'm kinda confused. note: im using Redis as broker -
How can I fix the ValueError at /add invalid literal for int() with base 10
Hi I can't figure out how to stop getting this error when is click on submit. Views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'home.html', {'name':'Noah'}) def add(request): val1 = int(request.POST ['num1']) val2 = int(request.POST ['num2']) res = val1+val2 return render(request, 'result.html', {'result':res}) home.html {% extends 'base.html' %} {% block content %} <h1>hello {{name}}!!!!</h1> <form action="add" method="POST"> {% csrf_token %} Enter 1st number: <input type="text" name="num1"> Enter 2nd number: <input type="text" name="num2"> <input type="submit"> </form> {% endblock %} my result.html {% extends 'base.html' %} {% block content %} Result : {{result}} {% endblock %} Please help I've been following a tutorial and can't figure out why I can't solve this error. -
How can i delete user images/avatar in user profile
if there's anyone who knows how can I delete images user, I made a code to do that but I cannot continue I get some stuck. so if anyone could tell me which way can I make it this method? also, I need to know about the outputs of (userprofile) in (delete_avatar) if this code is true how can I know it? I tried using print and repr but I didn't find this useful. so, anybody can get me help? views.py # Update Avatar @login_required def add_avatar(request, user_id): my_logo = request.user.userprofile form = AddAvatar(instance=my_logo) get_userid = UserProfile.objects.filter(user_id=user_id) context = {'form': form, 'get_userid': get_userid} if request.method == 'POST': form = AddAvatar(request.POST, request.FILES, instance=my_logo) if form.is_valid(): form.save() return redirect('account:view_profile') return render(request, 'account/change-image.html', context) # Remove Avatar @login_required def delete_avatar(request, user_id): my_request = request.POST.get('rm-img') userprofile = UserProfile(my_request) pdb.set_trace() if request.method == "POST": del_img = UserProfile.objects.get(user_id=user_id).logo.delete() # delete object return redirect('account:view_profile') return render(request, 'account/change-image.html') change-image.html {% extends 'base.html' %} {% block title %} Add New Image {% endblock %} {% block body %} <!-- Add new image for user-profile --> <div class="change-image"> <div class="add-image"> <div class="container"> <h1>This Image Is Current, <br>Choose Your Image From Your Personal Computer Or Delete</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token … -
Django - Application Database Tables not creating
I seem to be bumping into an issue where the database tables for my applications are not creating successfully in SQL Server Management Studio. I can confirm that I have deleted the database table, created a new database table, deleted the content of the migrations folder of the app I was migrating, I have then executed 'python manage.py makemigrations and 'python manage.py migrate . Still no joy. All my models use database routing for read and write operations, I have checked to make sure that the routing is set up correctly and can confirm the routing is set up correctly. The username and passwords for SQL seem to be OK since no errors are thrown. Any ideas? Would be greatful for any input ASAP. Best, Neil -
Django and models with different table names
Currently I'm in the design phase of creating a new application for championship tables. The goal is to provide an application where that game results of various leagues can be entered in a backend and the final tables are viewed in the frontend. As database I'd like to use PostgreSQL since it offers schemas to seperate differ between the leagues. The current schema will (most probably) look like: = schema ==== tablename ============== - public ___ teams - league1 ___ league1_<season>_results |_ league1_<season>_tables - league2 ___ league2_<season>_results |_ league2_<season>_tables - league3 ___ league3_<season>_results |_ league3_<season>_tables <season> ... 2019, 2020, ... As well as leagueX_results as leagueX_tables will have the same model, meaning _results in league 1 has the same layout as _results in league2, _tables in league1 is the same model in league2. The _tables are (re)created using Pandas as man in the middle to compute the tables (this part is already working and in the drawer). The only thing I'm still looking for is the possibility to change the tablename (dynamically) to be used within the same model. Unfortunately I'm not (yet) familiar with the Django framework, I was using Flask and SQLAlchemy before. For this combination I may … -
DRF customizing the validation sequence
Suppose the models from phonenumber_field.modelfields import PhoneNumberField class SomeModel1(models.Model): phone_number = PhoneNumberField(unique=True) class SomeModel2(models.Model): who = models.ForeignKey(to=SomeModel1, on_delete=CASCADE, related_name='who') PhoneNumberField is from Django Phone Number field. Trying to define a serializer SomeModel2Serializer for SomeModel2 class CustomSlugRelatedField(serializers.SlugRelatedField): def to_representation(self, obj): phone_number = super().to_representation(obj) # Default SlugRelatedField returns the phone number object, # which doesn't work well while sending the JSON response back, # so using the native data type return phone_number.as_e164 from phonenumber_field.validators import validate_international_phonenumber def validate_phone_number(phone_number): try: validate_international_phonenumber(phone_number) except ValidationError as error: raise serializers.ValidationError(error) return phone_number class SomeModel2Serializer(serializers.ModelSerializer): who = CustomSlugRelatedField(slug_field='phone_number', queryset=SomeModel1.objects.all(), validators=[validate_phone_number]) Now suppose we are trying to create an entry in the SomeModel2 using SomeModel2Serializer, Case1: Post data is valid {"who" : "+12345551234"} Validations are triggered in order of, Check if "+12345551234" exists in SomeModel1 Check if "+12345551234" is a validate_phone_number Case2: Post data is invalid {"who" : "Invalid Number !!"} Because of the order of validation, the error received is Object with phone_number=Invalid Number !! does not exist.. But the error that makes sense is The phone number entered is not valid., which would be raised from validate_phone_number. So the question is, Is there a way to make sure the validate_phone_number is run first, before the check … -
ERROR: WebSocket connection to 'wss://test-l-ink.herokuapp.com/lk/' failed: Error during WebSocket handshake: Unexpected response code: 200
I use python+Django and run gunicorn server on Heroku. But also I launch daphne to use WebSockets in my web app. But websockets does not work. Here is my Procfile: web: gunicorn Chat.wsgi web2: daphne Chat.asgi:channel_layer --port 8000 --bind 0.0.0.0 This is JS code, that tries to establish websocket connection: <script> $(document).ready(function(){ var msgArea = $('#msgArea') var elementMessage = $('#message') var webSocket = new WebSocket('wss://' + window.location.host + '/lk/'); webSocket.onmessage = function(message) { var data = JSON.parse(message.data) msgArea.append('<p><strong>'+ data.sender + '</strong>: ' + data.message + '</p>') } $('#btnSubmit').click(function(e) { webSocket.send(elementMessage.val()) }) }) </script> Everything works on my local machine, but does not work on Heroku. I've got an error: "WebSocket connection to 'wss://test-l-ink.herokuapp.com/lk/' failed: Error during WebSocket handshake: Unexpected response code: 200" This is log file: ... [web2.1]: Starting process with command `daphne Chat.asgi:channel_layer --port 8000 --bind 0.0.0.0` [web2.1]: State changed from starting to up [web.1]: Starting process with command `gunicorn Chat.wsgi` [web2.1]: 2020-02-08 19:14:00,707 INFO Starting server at tcp:port=8000:interface=0.0.0.0, channel layer Chat.asgi:channel_layer. [web2.1]: 2020-02-08 19:14:00,708 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) [web2.1]: 2020-02-08 19:14:00,708 INFO Using busy-loop synchronous mode on channel layer [web2.1]: 2020-02-08 19:14:00,708 INFO Listening on endpoint tcp:port=8000:interface=0.0.0.0 [web.1]: [2020-02-08 19:14:01 … -
Apply class to Django PasswordInput field? (Can apply class toTextInput field with no problem)
I am building a user sign up form and trying to add the bootstrap .form-control class to each input. The class is being added to the TextInput fields correctly, but not to the PasswordInput fields: from django import forms from django.forms import TextInput, PasswordInput from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',) widgets = {'username': TextInput(attrs={'class':'form-control'}), 'first_name': TextInput(attrs={'class':'form-control'}), 'last_name': TextInput(attrs={'class':'form-control'}), 'email': TextInput(attrs={'class':'form-control'}), 'password1': PasswordInput(attrs={'class':'form-control'}), 'password2': PasswordInput(attrs={'class':'form-control'}) } When I inspect the password fields, they do not have the .form-control class. Is applying this class to password inputs something that can be done? -
Docker run image_celery not able to detect redis
I have a django application i want to run redis and celery using docker run command after I build images using docker-compose file I run two commands on different windows powershell docker run -it -p 6379:6379 redis docker run -it image_celery my celery powershell is not able to detect redis [2020-02-08 13:08:44,686: ERROR/MainProcess] consumer: Cannot connect to redis://redis:6379/1: Error -2 connecting to redis:6379. Name or service not known.. Trying again in 2.00 seconds... version: '3' services: the-redis: image: redis:3.2.7-alpine ports: - "6379:6379" volumes: - ../data/redis:/data celery_5: build: context: ./mltrons_backend dockerfile: Dockerfile_celery volumes: - ./mltrons_backend:/code - /tmp:/code/static depends_on: - the-redis deploy: replicas: 4 resources: limits: memory: 25g restart_policy: condition: on-failure volumes: db_data: external: true Dockerfile_celery FROM python:3.6 ENV PYTHONUNBUFFERED 1 # Install Java RUN apt-get -y update && \ apt install -y openjdk-11-jdk && \ apt-get install -y ant && \ apt-get clean && \ rm -rf /var/lib/apt/lists/ && \ rm -rf /var/cache/oracle-jdk11-installer; ENV JAVA_HOME /usr/lib/jvm/java-11-openjdk-amd64/ RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code #ENV PYSPARK_SUBMIT_ARGS = "--packages=org.apache.hadoop:hadoop-aws:2.7.3 pyspark-shell" #RUN wget http://archive.apache.org/dist/hadoop/common/hadoop-2.8.0/hadoop-2.8.0.tar.gz #RUN tar -zxvf hadoop-2.8.0.tar.gz -C /usr/local/ #ENV HADOOP_HOME = /usr/local/hadoop-2.8.0 ENV REDIS_HOST=redis://the-redis ENV REDIS_PORT=6379 RUN pip install --upgrade 'sentry-sdk==0.7.10' ENTRYPOINT celery … -
How can I use `filter` when the `list` function is override?
I am using django rest framework When I overrided the list function somehow, filter_class doesn't work. I think I need to apply some filter related class in list function though, I googled around but not found the solution. class StationViewSet(viewsets.ModelViewSet): queryset = Station.objects.all() serializer_class = StationSerializer filter_class = StationFilter pagination_class = StandardResultsSetPagination def list(self,request,*args,**kwargs): station = Station.objects.all() page = self.paginate_queryset(station) if page is not None: custom_data = { 'list_of_items': StationSerializer(page, many=True).data } custom_data.update({ 'meta':{"time": "2020-02-02"} }) return self.get_paginated_response(custom_data) -
How to access Environment Variables in Django with Django Environ?
I'm a Node developer but I need to create a Django app (i'm totally beginner in Django). I need to read some data from an API but ofc, I shouldn't hardcode the API url. So having API_BASE_URL=api.domain.com in my .env file, in Node I would access the variables in my functions this way: import ('dotenv/config'); import axios from 'axios'; baseUrl = process.env.API_BASE_URL; function getApiData() { return axios.get(baseUrl); } So how would be the Python/Django version of it? Saying I have the function bellow: import ??? def get_api_data(): url = ???? -
Ajax pagination does not work correctly in Django 2
Separately, both ajax work as expected, but when used together, there is a problem: Problem - 1: After loading new articles, they are duplicated Problem - 2: The add to favorites button stops working on newly uploaded articles. AjaxPagination.js: function ajaxPagination() { $('#pagination a.page-link').each((index, el) =>{ $(el).click((e) => { e.preventDefault() let page_url = $(el).attr('href') console.log(page_url) $.ajax({ url: page_url, type: 'GET', success: (data) => { $('.do_it').append( $(data).filter('.do_it').html()) $('.pagination').empty() $('.pagination').append( $(data).find('.pagination').html()) } }) }) }) } $(document).ready(function() { ajaxPagination() }) $(document).ajaxStop(function() { ajaxPagination() }) AjaxAddToFavorites.js: const add_to_favorites_url = '/favorites/add/'; const remove_from_favorites_url = '/favorites/remove/'; const favorites_api_url = '/favorites/api/'; const added_to_favorites_class = 'added'; function add_to_favorites(){ $('.do_it').on('click', '.add-to-favorites', (e) => { e.preventDefault() const type = $(el).data('type'); const id = $(el).data('id'); if( $(e.target).hasClass(added_to_favorites_class) ) { $.ajax({ url: remove_from_favorites_url, type: 'POST', dataType: 'json', data: { type: type, id: id, }, success: (data) => { $(el).removeClass(added_to_favorites_class) } }) } else { $.ajax({ url: add_to_favorites_url, type: 'POST', dataType: 'json', data:{ type: type, id: id, }, success: (data) => { $(el).addClass(added_to_favorites_class) // get_session_favorites_statistics() } }) }; }) }; function get_session_favorites() { // get_session_favorites_statistics() $.getJSON(favorites_api_url, (json) => { if (json !== null) { for (let i = 0; i < json.length; i++) { $('.add-to-favorites').each((index, el) => { const type = $(el).data('type') … -
ValueError: Field 'id' expected a number but got 'deleted "" ' - Django Generic DeleteView
I've been trying to delete this model object but i keep getting this error: Field 'id' expected a number but got 'deleted template' I tried deleting the object from the admin side (thinking it is a problem with my view) but the error remain the same. models class TransactionalTemplate(models.Model): name = models.CharField(_('name'), max_length=30) role = models.ForeignKey(Group, on_delete=models.CASCADE, verbose_name=_('role')) content = models.TextField(_('body')) category= models.CharField(_('category'), max_length=10, choices=CATEGORIES) def __str__(self): return self.name def get_absolute_url(self): return reverse('mail_and_sms:template_list') def get_role(self): return self.role views class TemplateDeleteView(DeleteView): model = TransactionalTemplate template_name = 'template_confirm_delete.html' success_message = _('was sucessfully deleted') def delete(self, request, *args, **kwargs): messages.success(request, f'{self.get_object()} {self.success_message}') self.get_object().delete() return redirect('mail_and_sms:template_list') Any help is appreciated. Thanks. -
How do I execute a Python script in Django using javascript
I have a python + electronJS + Djangao app. I am trying to launch a python script with a button click (from the HTML front end). The app launches fine. But when I click the button to launch the python script from the HTML window, nothing happens (I get a blank HTML page). Here is my java script file: let {PythonShell} = require('python-shell') var path = require("path") function get_weather() { let pyshell = new PythonShell('Emotion-recognition-master/real_time_video.py', options); //let python = spawn('python', [path.join(__dirname, '/home/ironmantis7x/Documents/BSSTLLC/electronJS/electronpydemo1/python-app-with-electron-gui/engine/Emotion-recognition-master', 'real_time_video.py'), obsFilePath, navFilePath]); pyshell.on('message', function(message) { swal(message); }) //document.getElementById("city").value = ""; } Here is my HTML code for the gui launcher: <body> <div class="container"> <div class="jumbotron"> <h1><b><center>MAVERICK Sentry System</center></b></h1> <h3><i><center>by Maverick AI - a Saudi Company</center></i></h3> <br> <br> <center> <div class="row"> <div class="col-xs-4"> <img style="width:40%;padding:5px" src="images/weather-icon.png"/> <br> <button class="btn btn-info"><a style="color:white" href="weather.html">Weather</a></button> <div class="col-xs-4"> <img style="width:40%;padding:5px" src="images/emotion_recognition.png"/> <br> <button class="btn btn-info"><a style="color:white;" href="real_time_video.py">Emotion Recognition</a></button> </div> <div class="col-xs-4"> <img style="width:40%;padding:5px" src="images/text_recognition.png"/> <br> <button class="btn btn-info"><a style="color:white;" href="http://127.0.0.1:5000/detect">Text Recognition</a></button> </div> </center> </div> </div> <body> How can I run my python script from html button click properly? -
Django Forms DateInput widget not populating
I have a django edit form that has many fields from a model including some date fields, for a suitable format, I used a DateInput widget. Unfortunately, when we edit the object, all other fields are already populated with existing data, but the dates. The dates are in their initial state (dd/mm/yyyy) and since they are required, the user has to reenter the dates everytime they want to edit the object, even if they do not want to change the dates. does anyone have an idea on how to prepopulate the date data in these date fields? forms.py: class DateInput(forms.DateInput): input_type = 'date' input_formats = ('%d-%m-%Y') [...] date_sinistre = forms.DateField(widget=DateInput, label='Date sinistre') date_effet = forms.DateField(widget=DateInput, label='Date effet') date_echeance = forms.DateField(widget=DateInput, label='Date échéance') edit_object.html: <div class='row border border-primary rounded m-1 border-3'> <div class='col-md-4 p-0 pl-2 pr-2 justify-content-center align-self-center'> <strong>DATE DE SINISTRE:</strong> </div> <div class='col-md-8 p-0 pl-2 pr-0 justify-content-center align-self-center'> {{ dossierForm.date_sinistre|as_crispy_field }} </div> </div> <div class='row border border-primary rounded m-1 border-3'> <div class='col-md-4 p-0 pl-2 pr-2 justify-content-center align-self-center'> <strong>DATE EFFET:</strong> </div> <div class='col-md-8 p-0 pl-2 pr-0 justify-content-center align-self-center'> {{ dossierForm.date_effet|as_crispy_field }} </div> </div> <div class='row border border-primary rounded m-1 border-3'> <div class='col-md-4 p-0 pl-2 pr-2 justify-content-center align-self-center'> <strong>DATE ÉCHÉANCE:</strong> </div> <div … -
How can I run my Django app with gunicorn and daphna on heroku?
I try to make a chat. There are some functions that work with "original" Django (def index(request) and so on) but also there are functions, where I need to use websockets. I installed channels to make a websocket interface. So, I have two systems: gunicorn interconnects with HTTP(S) and daphna interconnets with WS(S) interface. On my local machine I set up all files (asgi.py, consumers.py, routing.py and settings.py) and I type: python manage.py runserver - everything works. But when I deploy it to heroku, I get a lot of errors. I tried everything, but didn't find the solution. Ask for your help. Here are my files: chat/Procfile web: daphne Chat.asgi:channel_layer --port $PORT web2: gunicorn Chat.wsgi chat/chat/asgi.py import os import channels.asgi os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Chat.settings') channel_layer = channels.asgi.get_channel_layer() chat/chat/routing.py from channels.routing import route channel_routing = { 'websocket.connect': 'user_chating.consumers.ws_connect', 'websocket.receive': 'user_chating.consumers.ws_message', 'websocket.disconnect': 'user_chating.consumers.ws_disconnect', #'send_email': 'user_chating.consumers.send_email_consumer' } chat/chat/settings.py ... # Application definition INSTALLED_APPS = [ 'user_chating', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', ] CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgiref.inmemory.ChannelLayer', 'ROUTING': 'Chat.routing.channel_routing', }, } ASGI_APPLICATION = "Chat.routing.application" MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Chat.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR, 'templates'], 'APP_DIRS': True, 'OPTIONS': … -
Django : How can I access to label in views?
I'd like to change the label in views.py but, it doesn't work. class UpdateProfileView(UpdateView): model = models.User context_object_name = "user_obj" template_name = "users/user_update_info.html" fields = ( "username", "language", "currency", "birthdate", ) def get_object(self, queryset=None): return self.request.user the other app, i change the label in forms.py by __init_, like: class UpdateTempfriendForm(forms.ModelForm): class Meta: model = models.Tempfriend fields = ( "name", ) widgets = { "name": forms.TextInput(attrs={"placeholder": "이름", "style": "width:100%"}), } def __init__(self, *args, **kwargs): super(UpdateTempfriendForm, self).__init__(*args, **kwargs) self.fields['name'].label = "이름" def save(self, *args, **kwargs): tempfriend = super().save(commit=False) return tempfriend but in views, it can't. How can I achieve it in views? -
Django tests: matching query does not exist
I have been working on a blog app that has three regular models: Post, Category, and Comment. And now I am trying to write some tests for these models. When I run tests individually they pass without errors. But when I run tests for the test_models.py as a whole I get four errors telling me that Comment/Category matching query does not exist. I understand that this error means that django can't find the id I want in the database that's created when running the tests. My question is why am I getting these errors only when I run tests on the test_model file but not when I run the test on the test classes individually? python manage.py test blog.tests.test_models.TestPostModel -v 2 # this command doesn't cause errors python manage.py test blog.tests.test_models -v 2 # but this one causes 4 errors in TestPostModel test_models.py from blog.models import Post, Category, Comment, Recipient from django.test import TestCase class TestPostModel(TestCase): @classmethod def setUpTestData(cls): Post.objects.create(title="creation of the first post", body="i am the body of the first post.") for i in range(1, 11): Category.objects.create(name=f"post_category{i}") for i in range(1,11): Comment.objects.create(name=f"user{i}", email=f"user{i}@email.com", comment=f"i am comment number {i}.") def test_post_str_method(self): post = Post.objects.get(id=1) self.assertTrue(isinstance(post, Post)) self.assertEqual(post.__str__(), post.slug) def test_post_get_absolute_url(self): … -
A valid POST param value is empty in cleaned_data
When posting data through my form, some of the fields become empty, either None or '' in cleaned_data. They are passed correctly and still there in request.POST. For example: forms.py class NotificationForm(forms.ModelForm): WEEKDAY_OPTIONS = no_chosen_day + [ (i, v) for i, v in enumerate(calendar.day_name) ] schedule_weekday = forms.ChoiceField( choices=WEEKDAY_OPTIONS, label="Day of the week", disabled=True, required=False, ) def clean_schedule_weekday(self): __import__('pprint').pprint(self.cleaned_data) models.py class Notification(models.Model): notification_id = models.AutoField(primary_key=True) schedule_weekday = models.SmallIntegerField(blank=False, null=False) No other clean methods in forms.py. The field value is already empty in the clean_schedule_weekday method: {'schedule_weekday': '',} While printing out request.POST in views.py still gives: {'csrfmiddlewaretoken': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'schedule_weekday': '0'} Why? -
Cannot read property 'valueOf' of null google gannt chart
hello i have been trying to use google gannt charts and it is im rendering this message instead of the chart : Cannot read property 'valueOf' of null× Here is some of my code: This is the script that is building the chart {% for project in projects %} google.charts.load('current', {'packages':['gantt']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { arr = [] data_arr = [] var pk = "{{project.sales_project_id}}" var endpoint2 = '/api/gantt/data/' $.ajax({ type: "GET", url: endpoint2, success: function(data){ for (i = 0; i < data.timeline.length; i++) { if (data.timeline[i][2] == pk) { data.timeline[i][0].toString() data.timeline[i][1].toString() data.timeline[i][2].toString() arr.push(data.timeline[i]) } } }, }); console.log(arr) var data = new google.visualization.DataTable(); data.addColumn('string', 'Task ID'); data.addColumn('string', 'Task Name'); data.addColumn('string', 'POC'); data.addColumn('date', 'Start Date'); data.addColumn('date', 'End Date'); data.addColumn('number', 'Duration'); data.addColumn('number', 'Percent Complete'); data.addColumn('string', 'Dependencies'); data.addRows(data_arr); var options = { height: 400, gantt: { trackHeight: 30 } }; var chart = new google.visualization.Gantt(document.getElementById('chart_div')); chart.draw(data, options); } </script> {%endfor%} </head> {% endblock content %} This is the data of my api end point: { "timeline": [ [ 1, 1, 2, "2020-02-08", "2020-02-01", null, 20, null ], [ 2, 2, 2, "2020-02-08", "2020-05-08", null, 80, null ], [ 3, 3, 2, "2020-02-08", "2020-09-08", null, 80, null ] ] } according to google … -
How to load SQL fixtures in Django
I have some fixtures of models in my code base for easy initial setup of the project. However, it includes SQL fixtures as well which means .sql files. I have looked deeply in Django loaddata but it does not support 'SQL' fixtures because, sql is not a known serialization format So, I tried to load data directly from MySQL using mysql --host={host} --port={port} --user={user} --password={password} {database} < {filename} command. But I have lots of sql files and I do not want to load each file individually, so I decided to add a script to load all sqls files from specified directory and run above command using os.system. And now bandit is giving security warning for it Issue: [B605:start_process_with_a_shell] Starting a process with a shell, possible injection detected, security issue. Severity: High Confidence: High So I am looking for a secure way to load data from SQL files. -
URL mapping mistake in Django
I am creating "Loan Application and Verification System" in which, This page http://127.0.0.1:8000/applicant_policy/2/ is rendering information about the applicant who has taken a few policies, The template is rendering the code given below ... ... {% for policy in orders %} <tr> <td>{{policy.id}}</td> <td>{{policy.policy_name}}</td> <td>{{policy.bank}}</td> <td>{{policy.Tenure}}</td> <td>{{policy.Processing_Fees}}</td> <td>{{policy.loan_amount}}</td> <td>{{policy.applicant.CIBIL_score}}</td> {# url 'applying_for_policy' policy.id #} <td><a class="btn btn-sm btn-info" href="{ url 'applying_for_policy' policy.id}">Check</a></td> </tr> {% endfor %} ... ... I have created an anchor tag in the last column which would take the user to http://127.0.0.1:8000/applying_for_policy/1/ instead it takes it to http://127.0.0.1:8000/applicant_policy/2/%7B%20url%20'applying_for_policy'%20policy.id%20%7D and gives "Page Not Found" error the urls.py file urlpatterns = [ path('', views.home, name='home'), path('adminpage/',views.admin_page, name='adminpage'), path('applicant_policy/<str:pk_test>/', views.applicant_policy, name="applicant_policy"), path('applying_for_policy/<str:pk>/',views.applying_for_policy, name="applying_for_policy"), ] The view function which is been handling the "applying_for_policy" view def applying_for_policy(request, pk): customer = Policy.objects.get(id=pk) ... ... ... Thus creating an URL mapping issue -
How to capture and store an image in django
I wanted to access the camera. capture an image and store in the database. models.py : class student(models.Model): Img = models.ImageField(upload_to='images/') HTML page : <!DOCTYPE html> <html> <head> <title> webcam </title> </head> <body> <div class = "video-wrap"> <video id = "video" playsinline autoplay></video> </div> <div class = "controller"> <button id = "snap">Capture</button> </div> <canvas id = "canvas" width = "640" height = "480"> </canvas> <script> 'use strict'; const video = document.getElementById('video'); const canvas = document.getElementById('canvas'); const snap = document.getElementById('snap'); const errorMsgElement = document.getElementById('span#ErrorMsg'); const constraints = { audio:true, video:{ width:1280,height:720 }}; async function init() { try { const stream = await navigator.mediaDevices.getUserMedia(constraints); handleSuccess(stream); } catch(e) { errorMsgElement.innerHTML =`navigator.getUserMedia.error:${e.toString()}`; } } function handleSuccess(stream) { window.stream = stream; video.srcObject = stream; } init(); var context = canvas.getContext('2d'); snap.addEventListener("click",function(){ context.drawImage(video, 0, 0, 640, 480);}); </script> </body> </html> This HTML page can access the camera and can capture. But I don't know how to access and get that to models. can anyone pls help -
Django ModelForm in template
i have got a question.Im new in Django and lear it since 3 weeks. I need to develop a Cookie Popup with optin for a project at University. My Question is. I develop it in Django python. In the backend i have services that collect all Cookie Information and pass it in a Cookie Model. So now i have the Cookie model and need to pass it as context in the view. For the moment i see all the Cookies that the services collects in Browser. But i need to validate if the typ is Esential or Marketing and seperate this in the collapse in template. How i can do this ? My idea is to validate it in the template with this line {% if cookie.typ == 'Essenziell' %} and if the typ is Essenziell i show this in the collapse. View.py def optin(request): if request.method == 'POST': form = CookieForm(request.POST) if form.is_valid(): return HttpResponseRedirect else: form = CookieForm cookie_list = Cookie.objects.all() context_dict = {'form': form, 'cookie_list': cookie_list} template = 'cookies/cookie.html' return render(request, template, context_dict ) This is a part of the Template <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#Marketing" aria-expanded="false" aria-controls="Marketing"> Marketing </button> <div class="collapse" id="Essenziell"> <div class="card card-body"> … -
Django Import Export - __str__ returned non-string (type NoneType)
Im working on a django project and I have implemented django import-export. The import works with this django model: class A(models.Model): model_name = models.CharField(null=True, blank=True, max_length=20) model_file = models.FileField(null=True, blank=True, upload_to=upload_image_path) model_date = models.DateTimeField(null=True, blank=True, auto_now_add=True) admin.py: @admin.register(A) class AModelAdmin(ImportExportModelAdmin): list_display = ["model_name", "model_date"] list_filter = ["model_name", "model_date"] search_fields = ["model_name", "model_date"] list_display_links = ["model_name"] class Meta: model = A class AResource(resources.ModelResource): class Meta: model = A exclude = ('model_date', ) But it fails with this model: class Project(models.Model): slug = models.SlugField(null=True, blank=True, unique=True,default="0") project_title = models.CharField(null=True, blank=True, max_length=120) project_post = models.TextField(null=True, blank=True) project_cat = models.CharField(null=True, blank=True,max_length=20) project_thumb = models.ImageField(upload_to=upload_image_path, null=True, blank=True) project_movie = models.FileField(upload_to=upload_image_path, null=True, blank=True,default='False') project_views = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,related_name='project_views',default=[0]) project_likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,related_name='project_likes',default=[0]) project_date = models.DateTimeField(null=True, blank=True, auto_now_add=True) and admin: @admin.register(Project) class ProjectModelAdmin(ImportExportModelAdmin): list_display = ["project_title", "project_date"] list_filter = ["project_title", "project_date"] search_fields = ["project_title", "project_date"] list_display_links = ["project_title"] class Meta: model = Project class ProjectResource(resources.ModelResource): class Meta: model = Project exclude = ('project_date',) I tried to import all fields and to exclude the M2M fields and also to import only the slug field, but I get always the same error: Line number: 1 - __str__ returned non-string (type NoneType) None, None, a, a, a, None, None, None, None …