Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Testing DRF GenericViewSet with parameters in url_path
I'm trying to test DRF endpoint with unittest. View under the test: class HwView(mixins.ListModelMixin, viewsets.GenericViewSet): @action(detail=False, methods=['get'], url_path='switch_state/(?P<switch_id>\d+)') def switch_state(self, request, switch_id): print(f'sw: {switch_id}') results = {"state": 'ok'} return Response(results) Entry in the url.py from rest_framework import routers router = routers.DefaultRouter() router.register(r'hw', hw_views.HwView, basename='HwModel') And the test code from rest_framework.test import APIRequestFactory, APITestCase class TestCommandProcessor(APITestCase): def setUp(self): pass def test_switch_state(self): factory = APIRequestFactory() request = factory.get( '/api/hw/switch_state/3', ) view = HwView.as_view({'get': 'switch_state'}, basename='HwModel') response = view(request) self.assertIn('state', response.data) self.assertEqual('ok', response.data['state']) As I run the test I'm getting the error: TypeError: switch_state() missing 1 required positional argument: 'switch_id' Any other methods in this view (GET without parameters, POST with parameters) work fine with the same testing approach. Can you help me find out why my view can't parse parameters in the URL? Or any advice on how can I rewrite my test to successfully test my code. -
django print value of checked box from HTML form
I have a HTML form that is displaying a table with data. I added checkboxes to the form and now want to take baby steps to print the value of the checked box, when the button named "test_btn" on my HTML form is clicked. However, based on the lack of console logs, I know that I am not entering the get_checked_items function. Any ideas would be greatly appreciated. Here is my HTML Form named show.html <body> <div class="container"> <form method="POST" action=#> {% csrf_token %} <table class="table table-striped"> <thead> <tr> <th>Shipment ID</th> <th>Load Number</th> <th>Booked By</th> <th>Pickup City</th> <th>Pickup State</th> <th>Pickup Date</th> <th>Pickup Time</th> <th>Destination City</th> <th>Destination State</th> <th>Trailer Number</th> <th>Seal Number</th> <th>Primary Driver</th> </tr> </thead> <tbody> {% for ship in shipment %} <tr> <td><input type="checkbox" name="checks" id="{{ship.id}}" value="{{ship.id}}" />{{ship.id}}</td> <td>{{ship.load_number}}</td> <td>{{ship.booked_by}}</td> <td>{{ship.pickup_city}}</td> <td>{{ship.pickup_state}}</td> <td>{{ship.pickup_date}}</td> <td>{{ship.pickup_time}}</td> <td>{{ship.destination_city}}</td> <td>{{ship.destination_state}}</td> <td>{{ship.trailer_number}}</td> <td>{{ship.seal_number}}</td> <td>{{ship.primary_driver}}</td> </tr> {% endfor %} </tbody> </table> <div class="form-group"> <button><a href="/showform">Enter New Shipment</a></button> <div class="form-group"> <button><a href="/updatedata">Update Data</a></button> </div> <input type ="submit" class="btn" value="TESTING" name="test_btn"> </form> Here is my views.py file. I have a couple of print statements in there just to give me some more visibility as to which functions I'm actually entering. from django.shortcuts import render,redirect from django.http import … -
How to validate a formset in django
I am using formset to input my data into the database but for some reason it just doesn't validate, whenever I test in the terminal and call the .is_valid() It just returns false no matter what I try. Here's the code in my views.py and forms.py . Any help will be much appreciated! # Advanced Subjects (Advanced Biology) def form_5_entry_biology_view(self, request): current_teacher = User.objects.get(email=request.user.email) logged_school = current_teacher.school_number students_involved = User.objects.get(school_number=logged_school).teacher.all() data = {'student_name': students_involved} formset_data = AdvancedStudents.objects.filter(class_studying='Form V', combination='PCB') student_formset = formset_factory(AdvancedBiologyForm, extra=0) initial = [] for element in formset_data: initial.append({'student_name': element}) formset = student_formset(request.POST or None, initial=initial) print(formset.is_valid()) context = {'students': students_involved, 'formset': formset, 'class_of_students': 'Form V', 'subject_name': 'Advanced Biology'} return render(request, 'analyzer/marks_entry/marks_entry_page.html', context) And here is my forms.py class AdvancedBiologyForm(forms.ModelForm): student_name = forms.CharField() class Meta: model = ResultsALevel fields = ('student_name', 'advanced_biology_1', 'advanced_biology_2', 'advanced_biology_3',) -
how know id form.model while editing Djando
i have to check if a name is already in use but to do it i have to exclude item i'm going to edit class EditItemForm(forms.ModelForm): name = forms.CharField( max_length=80, min_length=3, required=True ) def clean_name(self): # Get the name name = self.cleaned_data.get('name') if Item.objects.filter(name=name).exclude(id=id).exists(): raise forms.ValidationError('This name is already in use.') class Meta: model = Item fields = ('type', 'name', ) class Item(models.Model): type = models.IntegerField(choices=TYPE, blank=False, default=NO_CAT) name = models.CharField(max_length=250 ) def __str__(self): #metodo righiesto return self.name how i can retrive current item id/pk to exlude it? -
How can I autocomplete Forms in Django with Foreign Keys?
My intention is that the form takes the available book with its respective foreing key but I cannot with the 'book_id' field of loans. I have managed to take the user crazy but not the book # Model class Prestamos (models.Model): libro_id = models.ForeignKey(Libros, on_delete=models.CASCADE) usuario_id = models.ForeignKey(Usuarios, on_delete=models.CASCADE) cantidad_dias = models.SmallIntegerField('Cantidad de dias a prestar', default= 5) fecha_prestamo = models.DateField('Fecha de prestamo', auto_now=False, auto_now_add=True) fecha_vencimiento = models.DateField('Fecha de vencimiento de la reserva', auto_now=False, auto_now_add=False, null = True, blank = True) estado = models.BooleanField(default=True, verbose_name= 'Prestado') # Form class PrestamoForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in iter (self.fields): self.fields['cantidad_dias'].widget.attrs['readonly'] = False class Meta: model = Prestamos fields = [ 'cantidad_dias'] exclude = ['libro_id', 'usuario_id','fecha_prestamo','fecha_vencimiento', 'estado'] def clean_libro(self): libro = self.cleaned_data['libro_id'] if libro.cantidad < 1: raise ValidationError('No se puede prestar este libro, no hay unidades disponibles') return libro # View class RegistrarPrestamo(CreateView): model = Prestamos template_name = 'libro/prestar_libro.html' success_url = reverse_lazy('libros:disp_libro') form_class = PrestamoForm def form_valid(self, form): form.instance.usuario_id = self.request.user libro= Libros.objects.get(pk=int(id)) form.instance.libro_id = libro return super (RegistrarPrestamo, self).form_valid(form) #Url path('libro/prestar-libro/', login_required(RegistrarPrestamo.as_view()), name = 'prestar_libro') int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' -
Running a Django REST-API on AWS - apache server does nothing
I have built a functional API with the django rest_framework, but as the runserver command is not suitable for production I am trying to get the AWS Apache to run the server as documented all over the place (e.g. : https://aws.amazon.com/getting-started/hands-on/deploy-python-application/ , https://dzone.com/articles/deploy-django-application , etc etc). Essentially, it's an image translation application that takes an image via a POST request and returns a modified image in the Response. Fairly simple, just one major endpoint. When I start or restart apache after running through all those configuration steps, i get a response saying "Restarted Apache" as expected. However, nothing is accessible! I can't run a POST command as I could with built-in server ./manage.py runserver 0.0.0.0:8000 So what's going on here? When I run with the built-in django server there are several parts of the start-up process that I can see and I get responses as expected, but with Apache? Nothing. -
CORS fetch issue HeaderDisallowedByPreflightResponse
I have an app running locally (Django app serving a React frontend, localhost:5000) and I have an external Django service on localhost:8888. Both work fine separately. The app needs to perform a GET to the service, but fails with: CORS error: HeaderDisallowedByPreflightResponse. The OPTIONS goes through OK, but this one fails. If I try performing the same request through Postman, it works fine. I've tried many header versions in my fetch, and this is what I ended up with, still not working: fetch(`${baseUrl}/programs`, { method: 'GET', mode: 'cors', headers: { 'X-API-Key': 'testing', 'Access-Control-Request-Method': 'GET', 'Access-Control-Allow-Origin': 'localhost:5000', // tried "*", as well 'Access-Control-Expose-Headers': 'X-API-Key, Content-Type, Access-Control-Request-Method, Access-Control-Allow-Origin', 'Access-Control-Allow-Methods': 'OPTIONS, GET, POST', 'Access-Control-Allow-Headers': 'X-API-Key, Content-Type, Access-Control-Request-Method, Access-Control-Allow-Origin', 'Content-Type': 'text/plain', 'Access-Control-Allow-Credentials': true, }, }).then((re) => { console.log(re); }) .catch(err => console.log(err)); Initially I started with just method, mode and headers X-API-Key, Access-Control-Allow-Origin and worked my way up from there. The external Django service has installed django-cors-headers and allowed all origins in the settings file so I'm not sure if this is the service's issue or frontend's. Any ideas what to try? -
Python Django Post Queue
Hi I have a Django Project. In my project, I want to queue all incoming post requests and show the sequence number. First in, first out. How can I go about this? Because I have created a project where many people can submit requests at the same time. When I receive a request like this at the same time, the server may crash or delays may occur.For this, I thought about queuing and giving sequence numbers to users, but I couldn't find much source about it. For example, 10 requests came all of a sudden, the server calls the functions on the backend and the sequence number 10 appears. Then the user who made the first request gets a response and the sequence number drops to 9. -
Django 2.0.7 Exception Type: OperationalError
enter code here Environment: enter code here Request Method: POST enter code here Request URL: http://127.0.0.1:8000/admin/products/product/add/ enter code here Django Version: 2.0.7 enter code here Python Version: 3.8.6 enter code here Installed Applications: enter code here ['django.contrib.admin', enter code here 'django.contrib.auth', enter code here 'django.contrib.contenttypes', enter code here 'django.contrib.sessions', enter code here 'django.contrib.messages', enter code here 'django.contrib.staticfiles', enter code here 'products',] enter code here Installed Middleware: enter code here ['django.middleware.security.SecurityMiddleware', enter code here 'django.contrib.sessions.middleware.SessionMiddleware', enter code here 'django.middleware.common.CommonMiddleware', enter code here 'django.middleware.csrf.CsrfViewMiddleware', enter code here 'django.contrib.auth.middleware.AuthenticationMiddleware', enter code here 'django.contrib.messages.middleware.MessageMiddleware', enter code here 'django.middleware.clickjacking.XFrameOptionsMiddleware'] enter code here Exception Type: OperationalError at /admin/products/product/add/ enter code here Exception Value: no such table: main.auth_user__old I'm getting this error on django adminstration site when i click on the save button. These are the errors, Exception Type: OperationalError at /admin/products/product/add/ and Exception Value: no such table: main.auth_user__old -
What is a good way for private hosting of a (django) website?
Let's say I have created a website using the django framework. I would like to to host it and access the website by my own AND by certain people that I choose. I don't want to host it on a public domain on the internet. What I can do: Host the website on a local computer (let's say a Raspberry Pi with RaspbianOS) with a certain IP address and port Access the website from anywhere using VPN Now I do not like the VPN solution as I also have other devices in my network. I want certain people to be able to access the website but I don't want them in my network. What is a good way to achieve what I want or is there maybe even a way? -
Update column in Django with child columns
I have 2 models Parent, Child class Parent(models.Model): id = Base64UUIDField(primary_key=True, editable=False) cost = models.DateTimeField(default=None, blank=True, null=True) class Child(models.Model): id = Base64UUIDField(primary_key=True, editable=False) cost = models.DateTimeField(default=None, blank=True, null=True) parent = models.ForeignKey(Parent, related_name= "children", related_query_name= "child") I need to populate cost column of Parent objects to maximum cost of all children of that parent I have tried to annotate to a new column new_cost, and its works. parents.annotate(new_cost=Max('child__cost')) But I need to populate values to existing column cost. Tried something like this, but not working. parents.update(cost=Max('child__cost')) -
nginx configuration error: try to open a file which does not exist in sites-enabled
I tried to check the nginx configuration with sudo nginx -t output: nginx: [emerg] open() "/etc/nginx/sites-enabled/django1" failed (2: No such file or directory) in /etc/nginx/nginx.conf:60 nginx: configuration file /etc/nginx/nginx.conf test failed I once created django1 but I removed/deleted this project. Now Iam trying to start a new project but cannot solve this issue. I googled a lot and tried to change the nginx.conf file but without success. Does anyone know whats going wrong here? Best alex -
BLEACH_DEFAULT_WIDGET django
I have django-bleach in my project. In models use: class Post(models.Model): title = models.CharField(max_length=255) content_2 = HTMLField() In settings.py: BLEACH_DEFAULT_WIDGET = 'wysiwyg.widgets.WysiwygWidget' How to write the correct path to process the bleach for HTMLField in BLEACH_DEFAULT_WIDGET ? -
Reduce mysql query ( Fulltext-search ) execution runtime, server-side?
VPS: ubuntu Django (latest) Python3.6 Mysql Current Code: posts = mytable.objects.raw('SELECT id, MATCH (tags) AGAINST (\''+some.tags+'\') as score FROM table ORDER BY score desc;') Excution Time (5 runs): 6.103515625e-05 6.4849853515625e-05 6.318092346191406e-05 8.034706115722656e-05 8.273124694824219e-05 The table have col name tags, how do I performing a search effectively. Considering the data in table is large (20k+ rows). is there a better way. or something with Django ORM. -
Django - What is the reason for "can't set attribute" error in this form?
In my Django project, I'm receiving the "can't set attribute" error on runtime, when loading a CreateView which looks like this: class DonationCreateView(InventoryEditingPermissionMixin, CreateView): model = Donation template_name = 'inventories/donation/donation_form.html' form_class = DonationForm success_url = reverse_lazy('donations_list') success_message = 'Donación creada correctamente' def form_valid(self, form): obj = form.save() ammount = obj.ammount autotank = obj.auto_tank tank = SaleWarehouseTank.objects.filter( warehouse__id=autotank.pk).last() tank.current_level -= ammount tank.save(update_fields=['current_level']) self.object = obj return HttpResponseRedirect(self.get_success_url()) def get_context_data(self, **kwargs): context = super(DonationCreateView, self).get_context_data(**kwargs) context['autotanks'] = SaleWarehouse.objects.filter(type=0) context['user_type'] = self.request.user.user_type context['clients'] = Client.objects.all() context['initial_client_name'] = '' context['is_update'] = False return context def get_form_kwargs(self): form_kwargs = super(DonationCreateView, self).get_form_kwargs() form_kwargs['user'] = self.request.user return form_kwargs And "DonationForm" looks like this: class DonationForm(forms.ModelForm): client_name = forms.CharField(required=False, label='Cliente') region = forms.ModelChoiceField(queryset=Region.objects.all(), required=False, label='Región') def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) self.user_type = user.user_type super(DonationForm, self).__init__(*args, **kwargs) self.fields['auto_tank'].required = False self.fields['client'].required = False self.fields['client'].widget = forms.HiddenInput() if user.user_type == 'region_admin': self.fields['auto_tank'].queryset = SaleWarehouse.objects.filter(type=0, region__id=user.region_id) elif user.user_type == 'admin': self.fields['auto_tank'].queryset = SaleWarehouse.objects.filter(type=0) def clean(self): cleaned_data = self.cleaned_data client_name = cleaned_data['client_name'] if client_name.strip() == '': cleaned_data['client'] = None else: if Client.objects.filter(social_reason__icontains=client_name).count() > 0: cleaned_data['client'] = Client.objects.filter(social_reason__icontains=client_name).last() else: raise forms.ValidationError('Por favor, elige un cliente de la lista, o deja el espacio en blanco') region = cleaned_data['region'] auto_tank = cleaned_data['auto_tank'] … -
How to apply multiple if condition filter in djago template
I am rendering two filter from my views to html template. 1) notifications_approved 2)notifications_pending. I am using this two filter separately in my html. Is there any way to use this two filter together in if statement? here is my code: #html template {% if notification in notifications_approved %} {% endif %} {% if notification in notifications_pending %} {%endif%} I tried this but it's not rendering anything's in my template: {%if notification in notifications_approved or notifications_pending %} {%endif%} I also tried this {%if notification|notifications_approved or notification|notifications_pending %} {%endif%} #getting TemplateSyntaxError views.py def ShowAuthorNOtifications(request): notifications_approved = Notifications.objects.filter(notification_type="Comment Approved").order_by('-date') notifications_pending = Notifications.objects.filter(notification_type="New Comment").order_by('-date') -
MongoDB migration from local host to a Linux server
So, I have a Django app, that is connected to a MongoDB database on my local machine. I brought my Django app on a Redhat Linux server. So, now I need MongoDB to be installed on the server: 1- Do I need to have access to the root on Linux server to install MongoDB? 2- I could not find any straight forward instruction to what to do for migration of MongoDB. Do know any references? I appreciate if you could help me with this. Thanks -
How to automate createsuperuser with django on Heroku?
I am trying to have Django superusers automatically created on my review apps on Heroku. As per this answer that points to an older version of these Django docs I should be able to run createsuperuser non-interactively and rely on environment variables for DJANGO_SUPERUSER_EMAIL, DJANGO_SUPERUSER_USERNAME, DJANGO_SUPERUSER_PASSWORD. However, I still get asked for a username, when I run this: $ heroku run python manage.py createsuperuser --noinput -a myapp-pr-3 Running python manage.py createsuperuser --noinput on ⬢ myapp-pr-3... up, run.9300 (Free) CommandError: You must use --username with --noinput. I have the environment variables and they are correctly set. Is there something I am overlooking? -
Styling items on a webpage to scroll right to left in one row
I have created a webpage that lists products from the database using for loop. The products are displayed in many rows where the user needs to scroll down to view them. Like this: current display But I want the items to display on one row, where the user will scroll the items on that single row, right to left. So that it displays like this: desired display Which code do I add so as to achieve the above? Below is my current code: html <div class="container my-5"> <h2 class="my-5">Products</h2> <div class="row"> {% for product in object_list %} <div class="col-md-6 col-sm-12 col-lg-3"> <figure class="card card-product"> <div class="img-wrap"> <a href="{% url 'shopapp:productdetail' pk=product.pk %}"><img src="/media/{{ product.mainimage }}" style="width:100%; height:300px;"></a> </div> <figcaption class="info-wrap"> <h6 class="title">{{ product.name }}</h6> <div class="action-wrap"> <div class="price-wrap h5"> <span class="price-new">${{ product.price|floatformat:2 }}</span> <span class="price-old"><strike>${{ product.oldprice|floatformat:2 }}</strike></span> </div> </div> </figcaption> </figure> </div> {% endfor %} </div> </div> css .card{ height: 385px; margin-bottom: 20px; } .card-product:after{ content: "" display: table; clear: both; visibility: hidden; } .card-product .price-new, .card-product .price{ margin-right: 5px; color: #0000FF; } .card-product .price-old{ color: #ff0000; } .card-product .image-wrap{ border-radius: 3px 3px 0 0; overflow: hidden; position: relative; height: 220px; text-align: center; } .card-product .img-wrap img{ max-width: 100%; max-height: … -
After creating a configuration file named db-migrate.config in .ebextnsions, code is not deploying its showing instances error (i)what to do?
container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: portfolio.settings -
Detail page error after using slugify in django
I am getting this error when i click on any item detail page. Generic detail view must be called with either an object pk or a slug in the URLconf. URL: path('item/<slug:item_slug>/', ItemDetailView.as_view(), name='item_detail'), VIEW: class ItemDetailView(DetailView): model = Item slug_field = 'item_slug' MODEL: class Item(models.Model): title = models.CharField(max_length=100) description= RichTextField(blank=True, null=True) main_image= models.ImageField(null=True, blank=True,upload_to='images/') date = models.DateTimeField(auto_now_add=True) item_category = models.ForeignKey(Categories, default='Coding', on_delete=SET_DEFAULT) slug = models.SlugField(unique=True, blank=True, null=True) # new def save(self, *args, **kwargs): if not self.slug and self.title: self.slug = slugify(self.title) super(Item, self).save(*args, **kwargs) def __str__(self): return self.title -
docker Can't connect to MySQL server on 'localhost'
Error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 99] Cannot assign requested address)") My docker-compose.yaml version: "3" services: web: container_name: antiquely build: ./ # command: python manage.py runserver 0.0.0.0:8000 command: "bash -c 'python manage.py runserver 0.0.0.0:8000'" working_dir: /usr/src/antiquely ports: - "8000:8000" volumes: - ./:/usr/src/antiquely links: - db #mysql db: image: mysql container_name: mysql_container restart: always environment: MYSQL_DATABASE: baby MYSQL_USER: soubhagya MYSQL_PASSWORD: Thinkonce MYSQL_ROOT_PASSWORD: Thinkonce volumes: - /var/lib/mysql ports: - "3306:3306" Here is my docker-compose when i am running the application i am getting above error. Please take a look where i am doing mistake -
django/wagtail - object attribute showing None when admin panel states otherwise?
I'm having a problem understanding why my {{ post.categories }} in templates is showing itself with blog.PostPageBlogCategory.None when the admin panel shows a chosen category for the post object. Here is my model.py set up: from django.db import models # Create your models here. from django.db import models from modelcluster.fields import ParentalKey from modelcluster.tags import ClusterTaggableManager from taggit.models import Tag as TaggitTag from taggit.models import TaggedItemBase from wagtail.admin.edit_handlers import ( FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel, PageChooserPanel, StreamFieldPanel, ) from wagtail.core.models import Page from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.snippets.edit_handlers import SnippetChooserPanel from wagtail.snippets.models import register_snippet class BlogPage(Page): description = models.CharField(max_length=255, blank=True,) content_panels = Page.content_panels + \ [FieldPanel("description", classname="full")] class PostPage(Page): header_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) tags = ClusterTaggableManager(through="blog.PostPageTag", blank=True) content_panels = Page.content_panels + [ ImageChooserPanel("header_image"), InlinePanel("categories", label="category"), FieldPanel("tags"), ] class PostPageBlogCategory(models.Model): page = ParentalKey( "blog.PostPage", on_delete=models.CASCADE, related_name="categories" ) blog_category = models.ForeignKey( "blog.BlogCategory", on_delete=models.CASCADE, related_name="post_pages" ) panels = [ SnippetChooserPanel("blog_category"), ] class Meta: unique_together = ("page", "blog_category") @register_snippet class BlogCategory(models.Model): CATEGORY_CHOICES = ( ('fighter', 'Fighter'), ('model', 'Model'), ('event', 'Event'), ('organization', 'Organization'), ('other', 'Other') ) name = models.CharField(max_length=255) slug = models.SlugField(unique=True, max_length=80) category_type = models.CharField( max_length=100, choices=CATEGORY_CHOICES, blank=True) description = models.CharField(max_length=500, blank=True) panels = [ FieldPanel("name"), FieldPanel("slug"), FieldPanel("category_type"), FieldPanel("description"), ] … -
psycopg2.errors.InvalidTextRepresentation for Django migration to PositiveSmallIntegerField
Running a Django 1.11 app (Python 3.6.5) with a Postgres database. We originally had a CharField on a model that needed choice types, so, without thinking fully about the implications, I modified: foo = models.CharField(max_length=50, blank=True) to TYPE_1 = 1 TYPE_2 = 2 TYPE_3 = 3 MY_TYPES = ( (TYPE_1, _('Foo')), (TYPE_2, _('Bar')), (TYPE_3, _('Etc')), ) foo = models.PositiveSmallIntegerField(choices=MY_TYPES, default=TYPE_1, blank=True) ran and generated the migration file and redeployed the app to our test server on Heroku: remote: Running migrations: remote: Applying management.0084_auto_20210708_1730...Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute remote: return self.cursor.execute(sql, params) remote: psycopg2.errors.InvalidTextRepresentation: invalid input syntax for integer: "" remote: remote: remote: The above exception was the direct cause of the following exception: remote: remote: Traceback (most recent call last): remote: File "manage.py", line 19, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle remote: fake_initial=fake_initial, remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate remote: state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) … -
use csv file and plot data django
I have a simple app that import csv file and make plot but without having any error message it doesn't show plot It's part of my module: ... def plot_data(self): df = pd.read_csv("file.csv") return plotly.express.line(df) ... and it's part of my app file: import panel def app(doc): gspec = pn.GridSpec() gspec[0, 1] = pn.Pane(instance_class.plot_data()) gspec.server_doc(doc)