Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django : 'app name' is not a registered namespace
i have a "NoReverseMatch" error, how can i slove this i don't understand- Project_name/urls.py path('orders/',include('orders.urls')), ordres/urls.py from .views import chack_out path('chack_out/', chack_out, name='chack_out') ordres/views.py def chack_out(request): ..... product(anther app name)/product/templates/cart.html <form action="{% url 'orders:chack_out' %}" method="POST"> {% csrf_token %} error page -
The model is used as an intermediate model, but it does not have a foreign key error with through models
I am new to Django and currently trying to improve on a design I have been using. This is my models.py file. from djongo import models import uuid PROPERTY_CLASSES = ( ("p1", "Video Property"), ("p2", "Page Property"), ("trait", "Context Trait"), ("custom", "Custom Property") ) class Device(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) class Platform(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) class EventPlatformDevice(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = "Event Specifics" event_field = models.ForeignKey('Event', on_delete=models.CASCADE) applicable_apps = models.ForeignKey('Platform', on_delete=models.CASCADE) applicable_devices = models.ManyToManyField('Device') property_group = models.ManyToManyField('PropertyGroup', blank=True) custom_properties = models.ManyToManyField('Property', blank=True) class Event(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, unique=True) applicable_platforms = models.ManyToManyField(Platform, through=EventPlatformDevice) class PropertyGroup(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) applicable_properties = models.ManyToManyField('Property') class Property(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) #applicable_platform = models.ManyToManyField(Platform, through=PlatformDevice) property_class = models.CharField(max_length=20, choices=PROPERTY_CLASSES) format_example = models.TextField(blank=True) notes = models.TextField(blank=True) The issue I am running into is with the EventPlatformDevice model. Right now in the Admin Panel I am able to select multiple items for the applicable_devices, property_group, and custom_properties field. The applicable_apps field is a single select. I am trying to turn that into a multi select as well but when changing the … -
The current path, /django_plotly_dash/app/test/, didn’t match any of these
We have a platform deployed on Django and we wanted to implement a dashboard created using plotly and dash in the existing Django application that we have. I followed some tutorials and integrated the dashboard application just the way everyone did but whenever I tried to go to the application url I get this message: The current path, /django_plotly_dash/app/test/, didn’t match any of these. I have created an app cars_dashboard. settings.py: MIDDLEWARE = [ 'django_plotly_dash.middleware.BaseMiddleware' ] INSTALLED_APPS = [ 'django_plotly_dash.apps.DjangoPlotlyDashConfig', 'channels', 'channels_redis', 'cars_dashboard' ] CRISPY_THEME_PACK = 'bootstrap4' ASGI_APPLICATION = 'cars_dashboard.routing.application' PLOTLY_DASH = { 'stateless_loader': 'cars_dashboard.dash_app.cars_dashboard', 'cache_arguments': False, 'serve locally': False } CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [ ('127.0.0.1', 6379), ], }, }, } STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django_plotly_dash.finders.DashAssetFinder', 'django_plotly_dash.finders.DashComponentFinder', 'django_plotly_dash.finders.DashAppDirectoryFinder', ] PLOTLY_COMPONENTS = [ 'dash_core_components', 'dash_html_components', 'dash_bootstrap_components', 'dash_renderer', 'dpd_components', 'dpd_static_support', ] main website's urls.py: urlpatterns = [ path('django_plotly_dash/', include('django_plotly_dash.urls')), path('cars_dashboard/', include('cars_dashboard.urls')), ] cars_dashboard views.py import django_plotly_dash from django.shortcuts import render, HttpResponse def home(request): return render(request, 'cars_dashboard.html') cars_dashboard urls.py from django.urls import path from . import views from .dash_app import cars_dashboard urlpatterns = [ path('', views.home, name='home'), ] The third line in the above code import the cars_dashboard.py script which contains the code for dashboard … -
Django Unit Test Login and Registration
I'm new with Django. I would like to write a unit test to test login (and possibly registration) but after several attempts I'm not sure where to start. Would you have any suggestions on how I could write these tests? Another question is: would be in this case BDD the best choice (with Behave) or should I remain for unit-test here? Thanks Code for the view.py: from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse from django.contrib.auth import login,logout,authenticate from labs.models import Category from .forms import createuserform def index(request): categories = Category.objects.all() context = { 'categories':categories, } return render(request, 'landing/index.html', context) def registerPage(request): if request.user.is_authenticated: return redirect('/labs') else: form=createuserform() if request.method=='POST': form=createuserform(request.POST) if form.is_valid() : user=form.save() return redirect('/login') context={ 'form':form, } return render(request,'landing/register.html',context) def loginPage(request): if request.user.is_authenticated: return redirect('/labs') else: if request.method=="POST": username=request.POST.get('username') password=request.POST.get('password') user=authenticate(request,username=username,password=password) if user is not None: login(request,user) return redirect('/') context={} return render(request,'landing/login.html',context) def logoutPage(request): logout(request) return redirect('/') -
Regex in django query is throwing InterfaceError: (-1, 'error totally whack')
Query1: Model.objects.filter(slug__istartswith="dfe") This is working fine in the shell. while Query2: Model.objects.filter(slug__regex="^dfe") This is throwing Error, InterfaceError: (-1, 'error totally whack') What could be the issue? -
Django , unable to get URL parameter from GET request
I have a class that accept user input and returns the filtered database class SearchView(ListView): model = Post ... ... def get_queryset(self): qs = self.model.objects.all() state = self.request.GET.get('state') print (state ) return qs When passing url, it supposed to print the state data from URL, but its not. -
django-celery-beat spams due tasks
I'm using django-celery-beat for some hourly/daily tasks. However, strange behaviour made me clueless what to do. I'm creating a task using this piece of code: periodic_task = apps.get_model('django_celery_beat', 'PeriodicTask') interval_schedule = apps.get_model('django_celery_beat', 'IntervalSchedule') schedule, _ = interval_schedule.objects.get_or_create(every=2, period='hours') periodic_task.objects.update_or_create( task=TASK, defaults={'name': 'Check missing documents', 'interval': schedule}, ) where TASK is a string pointing to this task: @app.task(ignore_result=True) def task(): <things to do> pass In the code you see that I use an interval of 2 hours, and once I started the beat with celery -A [project-name] beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler, no error pops up (I don't know if it actually works, 2 hours is a lot of time). However, when I change the interval to 1 hour, it spams these: [2021-12-21 15:32:45,333: INFO/MainProcess] Task app.tasks.task[6c0343b0-faf1-4eae-a8e0-721c862120a9] succeeded in 0.0s: None [2021-12-21 15:32:45,336: INFO/MainProcess] Scheduler: Sending due task <task description> (app.tasks.task) and then it continues to eternity, only stoppable with Ctrl+C. I do have the RabbitMQ Management plugin installed, and from the UI everyting looks fine - no queue, nothing unacked, etc. Any clue what this could cause? Even after purging the queue, it still happens (with celery -A [project-name] purge). -
django signal wont work after adding a save function
I have a simple model like this: class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) info1 = models.CharField(max_length=64, choices=SURVEY_CHOICES, blank=True) info2 = models.CharField(max_length=64, choices=SURVEY_CHOICES, blank=True) info3 = models.CharField(max_length=64, choices=SURVEY_CHOICES, blank=True) is_interviewed = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.info1: self.is_interviewed = 'True' super(ScientificInfo, self).save(*args, **kwargs) Every time a user is added to the app, a ScientificInfo object will be created for it using this signal: @receiver(post_save, sender=User, dispatch_uid='save_new_user_survey') def survey_create(sender, instance, created, **kwargs): user = instance if created: survey = ScientificInfo(user=user) survey.save() everything worked fine until I added that save method inside my model. the method works but the signal is disabled. Can you guys help me? thanks -
Annotation inside an annotation in Django Subquery?
I've got a few models and am trying to speed up the page where I list out users. The issue is that I was leveraging model methods to display some of the data - but when I listed the Users out it was hitting the DB multiple times per User which ended up with hundreds of extra queries (thousands when there were thousands of User objects in the list) so it was a serious performance hit. I've since began using annotate and prefetch_related which has cut the queries down significantly. I've just got one bit I can't figure out how to annotate. I have a model method (on Summation model) I use to get a summary of Evaluation data for a user like this: def evaluations_summary(self): evaluations_summary = ( self.evaluation_set.all() .values("evaluation_type__name") .annotate(Count("evaluation_type")) ) return evaluations_summary I'm trying to figure out how to annotate that particular query on a User object. So the relationship looks like this User has multiple Summations, but only one is ever 'active', which is the one we display in the User list. Each Summation has multiple Evaluations - the summary of which we're trying to show as well. Here is a summary of the relevant parts … -
How to bootstrap style ModelFormset
I've have a view that uses the formset factory but I'm trying to style the rendered html form. But the usual styling for forms doesn't work and im not sure what i need to do to apply the CSS stytles. My View def get_questionnaire(request, project_id, questionnaire_id): # Get the Response object for the parameters response = Response.objects.get( project_name_id=project_id, questionnaire_id=questionnaire_id ) AnswerFormSet = modelformset_factory(Answer, fields=('answer',), extra=0) answer_queryset = Answer.objects.filter(response=response ).order_by('question__sequence' ).select_related('question') if request.method == 'POST': # to be completed pass else: # Get the list of questions for which no Answer exists new_answers = Question.objects.filter( questionnaire__response=response ).exclude( answer__response=response ) # This is safe to execute every time. If all answers exist, nothing happens for new_answer in new_answers: Answer(question=new_answer, response=response).save() answer_formset = AnswerFormSet(queryset=answer_queryset) return render(request, 'pages/formset.html', {'formset': answer_formset}) for the moment im just trying to style a single field by applying the widgets in forms.py. But this isn't working. class answer_formset(ModelForm): class Meta: model = Answer fields = ('answer',) widgets = { 'answer': forms.Select(attrs={'class': 'form-select'}), } HTML {{ formset.management_form }} {% for form in formset %} {{ form.id }} {{ form.instance.question.question }} {{ form.answer }} <br> {% endfor %} Thanks -
How to show 10 product in django template by using _set(reverse lookup class)?
{% for item in i.product_set.all %} <div class="col-md-6 col-sm-6 col-xs-12 isotope-item {{ i|lower }} mb-5"> <div class="menu-list"> <span class="menu-list-product"> <img width="80" height="80" src="{{ item.image.url }}" alt=""> </span> <h5>{{ item.name }} <span>৳ {% if item.discount %} {{ item.price|sub:item.discount }} {% else %} {{ item.price }} {%endif%}</span></h5> <p>{{ item.description|truncatewords:6 }}</p> </div> </div> {% endfor %} Above code show all product but I want to show last 10. -
Django: It takes a long time to filter the m2m model from the m2m-connected model by specifying the field values of the m2m model
The m2m through table has about 1.4 million rows. The slowdown is probably due to the large number of rows, but I'm sure I'm writing the queryset correctly. What do you think is the cause? It will take about 400-1000ms. If you do filter by pk instead of name, it will not be that slow. # models.py class Tag(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(unique=True, max_length=30) created_at = models.DateTimeField(default=timezone.now) class Video(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=300) thumbnail_url = models.URLField(max_length=1000) preview_url = models.URLField(max_length=1000, blank=True, null=True) embed_url = models.URLField(max_length=1000) sources = models.ManyToManyField(Source) duration = models.CharField(max_length=6) tags = models.ManyToManyField(Tag, blank=True, db_index=True) views = models.PositiveIntegerField(default=0, db_index=True) is_public = models.BooleanField(default=True) published_at = models.DateTimeField(default=timezone.now, db_index=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Video.objects.filter(tags__name='word').only('id').order_by('-published_at'); Query issued SELECT "videos_video"."id" FROM "videos_video" INNER JOIN "videos_video_tags" ON ("videos_video"."id" = "videos_video_tags"."video_id") INNER JOIN "videos_tag" ON ("videos_video_tags"."tag_id" = "videos_tag"."id") WHERE "videos_tag"."name" = 'word' ORDER BY "videos_video"."published_at" DESC; EXPLAIN(ANALYZE, VERBOSE, BUFFERS) QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Sort (cost=4225.63..4226.23 rows=241 width=24) (actual time=456.321..473.827 rows=135178 loops=1) Output: videos_video.id, videos_video.published_at Sort Key: videos_video.published_at DESC Sort Method: external merge Disk: 4504kB Buffers: shared hit=540568 read=11368, temp read=563 written=566 -> Nested Loop (cost=20.45..4216.10 rows=241 width=24) (actual time=5.538..398.841 rows=135178 loops=1) Output: videos_video.id, videos_video.published_at Inner Unique: true Buffers: … -
Python Django ERROR: 'int' object has no attribute 'lr' [closed]
I am trying to build my Keras model using TensorFlow and Keras. code is following: This Django project is to find the predictive analysis of data. This project is running live. but I am going to run it locally for militance. An issue is found that, " 'int' object has no attribute 'lr', here 'lr' is the learning rate. Admin.py def build(self, request, queryset): count = 0 for p in queryset: if build_id(p.project_management.id): count += 1 else: messages.warning(request, f"Could not build model for {p}") messages.success( request, f"Successfully built models for {count} projects") build.short_description = "Build models for selected Projects" Build.py # build models for project with id project_id def build_id(project_id): # get directory path to store models in path = fetch_model_path(project_id, True) # train model model, scaler_in, scaler_out = train_project_models(project_id) # ensure model was trained if model is None: return False # store models store_model(f'{path}/model.pkl', model) store_model(f'{path}/scaler_in.pkl', scaler_in) store_model(f'{path}/scaler_out.pkl', scaler_out) # clear current loaded model from memory keras_clear() return True Utils.py # train models for project with id project_id def train_project_models(project_id): # get relevant data project, df = fetch_project_data(project_id) if project is None: return None, None, None # extract list parameters dense_shape = [int(x) for x in project.dense_shape.split(',')] lstm_shape = … -
Filtering in a many-to-many relationship in Django
I have three models, here I show two: class Product(models.Model): description = models.CharField(max_length=50) price = models.IntegerField() stock = models.IntegerField() def __str__(self): return self.description # Many-to-many relations class ProductsCategories(models.Model): idProduct = models.ForeignKey(Product, on_delete=CASCADE) idCategory = models.ForeignKey(Category, on_delete=CASCADE) How can I get in the views.py file products filtered by the category number 3 for instance? I have this: products_list = Product.objects.all() Thanks in advance. -
django-bootstrap-modal-forms saving instance twice (couldn't resolve with other issues open)
I am implementing a django-bootstrap-modal-forms 2.2.0 on my django app but I am having a problem. Every time I submit the modal form, the instance is created twice. I read that it is expected to have two post requests...the issue is that I am doing a few things on the form before saving it (adding a many to many value) and as I am trying to override the save function now it ends up saving the model twice. class DirectorModelForm(BSModalModelForm): class Meta: model = Contact exclude = ['owner', 'matching_user', 'id', 'referral', 'name_surname','title','city'] class NewDirectorView(BSModalCreateView): template_name = 'action/forms/DirectorModelForm.html' form_class = DirectorModelForm success_message = 'Success: Director was created.' success_url = reverse_lazy('action:new_jobproject') def get_object(self): pk = self.kwargs.get('pk') director = get_object_or_404(Contact, pk=pk) return director def form_valid(self, form): obj = form.save(commit=False) obj.owner = self.request.user obj.save() obj.title.add(Title.objects.get(title_name='Director', title_department='Production')) return super().form_valid(form) -
Expo Push Notification not Working on Heroku App (Back End)
Expo Push Notifications are working locally. I use Django on backend. But, once the app is deployed on Heroku server, Expo Push Notifications are not working, and I get an error. The code is breaking on backend, when communicating with Expo Backend Service (when calling https://exp.host/--/api/v2/push/send). -
Django Search returning the detailed view page
in models.py class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField(blank=True, null=True) in views.py def index(request): entry = Person.objects.all() context = {'entry':entry} return render(request, 'searching/index.html', context) def detail(request, pk): entry = Person.objects.get(id=pk) context = {'entry':entry} return render(request, 'searching/detail.html', context) in urls.py path('name/', views.index, name='index'), path('name/<str:pk>/', views.detail, name='detail'), I am stuck, i want to make a search bar where if you search the exact id, example my model has id of 1 if i search 1 in the box it should return mysite.com/name/1 instead of getting a page with results of queries that contain the 1 i want the exact one i searched for. I have looked so hard but i can't find a solution, it seems like a simple question and i feel so dumb. Is there an easy solution that i am missing? -
How to give tabs in django admin inline?
I am using django-baton and like to give tabs inside inline, but unable to give it Here is my code for admin.py and model.py file admin.py class ContentInLine(admin.StackedInline): model = Content extra = 1 class schoolProfileAdmin(admin.ModelAdmin): # exclude = ('content',) inlines = [ContentInLine] save_on_top = True list_display = ('school_name',) fieldsets = ( ('Main', { 'fields': ('school_name', ), 'classes': ('baton-tabs-init', 'baton-tab-group-fs-multi--inline-items', 'baton-tab-group-inline-things--fs-another', ), 'description': 'This is a description text' }), ('Multiple inlines + fields', { 'fields': ('email', ), 'classes': ('tab-fs-multi', ), }), ) models.py class SchoolProfile(models.Model): id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE,unique=True) school_name = models.CharField(max_length=255) school_logo=models.FileField(upload_to='media/', blank=True) incharge_name = models.CharField(max_length=255, blank=True) email = models.EmailField(max_length=255, blank=True) phone_num = models.CharField(max_length=255, blank=True) num_of_alu = models.CharField(max_length=255, blank=True) num_of_student = models.CharField(max_length=255, blank=True) num_of_cal_student = models.CharField(max_length=255, blank=True) #content = models.ManyToManyField(Content, blank=True, related_name='groups') def __str__(self): a = Content.objects.all() for e in a: print(e.shows_name,'************************') return self.school_name class Content(models.Model): id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE) content_type = models.CharField(max_length=255) # show=models.CharField(max_length=255) show=models.ForeignKey(Show,on_delete=models.CASCADE) sponsor_link=models.CharField(max_length=255) status=models.BooleanField(default=False) added_on=models.DateTimeField(null=True) content_file=models.FileField(upload_to='media/') title = models.CharField(max_length=255) shows_name = models.CharField(max_length=255) subtitle = models.CharField(max_length=255) description = models.CharField(max_length=500) publish_now = models.BooleanField(default=False) schedule_release = models.DateField(null=True) expiration = models.DateField(null=True) tag = models.ManyToManyField(Tag) topic = models.ManyToManyField(Topic) category = models.ManyToManyField(Category) school_profile = models.ForeignKey(SchoolProfile, on_delete=models.CASCADE,unique=True, blank=True) def __str__(self): return self.title Following is link for screenshot of admin page where i am unable to get … -
'int' object has no attribute 'lr' in python Django?
I am trying to build my Keras model using TensorFlow and Keras. code is following: This Django project is to find the predictive analysis of data. This project is running live. but I am going to run it locally for militance. An issue is found that, " 'int' object has no attribute 'lr', here 'lr' is the learning rate. Admin.py def build(self, request, queryset): count = 0 for p in queryset: if build_id(p.project_management.id): count += 1 else: messages.warning(request, f"Could not build model for {p}") messages.success( request, f"Successfully built models for {count} projects") build.short_description = "Build models for selected Projects" Build.py # build models for project with id project_id def build_id(project_id): # get directory path to store models in path = fetch_model_path(project_id, True) # train model model, scaler_in, scaler_out = train_project_models(project_id) # ensure model was trained if model is None: return False # store models store_model(f'{path}/model.pkl', model) store_model(f'{path}/scaler_in.pkl', scaler_in) store_model(f'{path}/scaler_out.pkl', scaler_out) # clear current loaded model from memory keras_clear() return True Utils.py # train models for project with id project_id def train_project_models(project_id): # get relevant data project, df = fetch_project_data(project_id) if project is None: return None, None, None # extract list parameters dense_shape = [int(x) for x in project.dense_shape.split(',')] lstm_shape = … -
Kindly help here, am stuck and keep getting this error. ModuleNotFoundError: No module named 'webHomePage'
Below are my Url Patterns from django.conf.urls import include from django.contrib import admin from django.urls.conf import path from.import index urlpatterns = [ path('admin/', admin.site.urls), path('',index.webhomepage,name='HomePage'), path('PublicSchools',index.webpublicschoolspage,name='PublicSchools'), path('PrivateSchools',index.webprivateschoolspage,name='PrivateSchools'), ] And this is my Function definitions from django.http import HttpResponse from django.shortcuts import render def webhomepage(request): return render(request,"HomePage.html") def webpublicschoolspage(request): return render(request,"PublicSchools.html") def webprivateschoolspage(request): return render(request,"PrivateSchools.html") This is the image to the structure of the code. [enter image description here][1] [1]: https://i.stack.imgur.com/UZM12.jpg -
Django: why does annotate add items to my queryset?
I'm struggling to do something simple. I have Item objects, and users can mark them favorites. Since these items do not belong to user, I decided to use a ManyToMany between User and Item to record the favorite relationship. If the user is in favoriters item field, it means the user favorited it. Then, when I retrieve objects for a specific user, I want to annotate each item to specify if it's favorited by the user. I made the add_is_favorite_for() method for this. Here is the (simplified) code: class ItemQuerySet(query.QuerySet): def add_is_favorite_for(self, user): """add a boolean to know if the item is favorited by the given user""" condition = Q(favoriters=user) return self.annotate(is_favorite=ExpressionWrapper(condition, output_field=BooleanField())) class Item(models.Model): objects = Manager.from_queryset(ItemQuerySet)() favoriters = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) This does not work as expected, it seems Django adds an item for every user that favorited the item. It leads to crazy things like: Item.objects.count() # 10 Item.objects.add_is_favorite_for(some_user).count() # 16 -> how the hell an annotation can return more results than initial queryset? I'm missing something here... -
What are DCC packages in programming?
enter image description here This is the requirement of a job profile of a company i want to apply in future. They're asking for having knowledge about DCC packages, but i have no idea about them. I've searched on internet but couldn't find anything. Can anyone pleaseee tell me what it is. I'd be grateful. -
Google Cloud Storage Bucket is not associated with CNAME on DNS record for using my domain as origin
I intend to use Google Cloud Storage through my own domain name supereye.co.uk . However, When I try to associate CNAME on my DNS record for supereye.co.uk with the Google Cloud Bucket production-supereye-co-uk, I get the following message when I try to access to production-supereye-co-uk.supereye.co.uk/static/default-coverpng : <Error> <Code>NoSuchBucket</Code> <Message>The specified bucket does not exist.</Message> </Error> What shall I do ? -
Stored procedure in PyODBC writes: not all arguments converted during string formatting
I have this code: with connections["mssql_database"].cursor() as cursor: sql = "EXEC SaveActivity @id_workplace=?, @personal_number=?, @id_activity=?" params = (id_workplace, personal_number, id_activity) cursor.execute(sql, params) TypeError: not all arguments converted during string formatting -
Chartjs not showing charts in my django project
I am trying to visualize data in my django project using Chartjs. right now I'm only concerned with the visualize part and not the backend stuff but for some strange reason the charts refuses to display even though I copied and pasted them directly from Chartjs website. <div id="chart_div" class="option-chart"> <canvas id="myChart" width="648" height="495"></canvas> </div> <script> const ctx = document.getElementById('myChart'); const myChart = { type : 'bar', data : { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options : { scales: { y: { beginAtZero: true } } } }; </script> As you can see from the code above. its boilerplate but I just cant get it to visualize.