Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I need to separate my main App from celery, in different servers. How could i achieve this goal?
Today i have a AWS EC2 instance where i run my main App (Django). I'm using docker to containerize my services, which are: Django, Nginx, Mysql, Redis, Celery. I now that all those services in one instance is the wrong path to follow and i want to make things right. I would like to start by separating the workers from my main App, because the App consumes a lot of processing in some tasks and i want to isolate those tasks from main App, in another server. Let's call it of Server B. How could i achieve this, using a Server A, running the main App, and Server B, handling i/o bound tasks with celery? Did i was clear? Sorry about my english. -
Why the content of my object disappeares when I submit the form instead of being saved in the database?
I'm trying to create a tweeter app using Django3.2 and Python3.9 and I stumble upon a difficult problem to solve. When I try to save a tweet, it's content disappear. If I manually save the content of a tweet using the Python shell directly, the content is saved properly. However, if I submit the tweet from the /home page or from the /create-tweet/, the id is created but with an empty content. It is not saved in the db.sqlite3 database neither. So it seems that the form is not being submitted properly but I can't figure out why exactly? my file structure is the following: tweeterapp ┣ db.sqlite3 ┣ manage.py ┣ templates ┣ components ┃ ┣ footer.html ┃ ┣ form.html ┃ ┗ navbar.html ┣ pages ┃ ┗ home.html ┣ tweets ┗ base.html ┣ tweeterapp ┣ settings.py ┣ urls.py ┣ wsgi.py ┗ __init__.py ┣ tweets ┣ migrations ┣ admin.py ┣ apps.py ┣ form.py ┣ models.py ┣ tests.py ┣ views.py ┗ __init__.py form.hmtl: <form method='POST'>{% csrf_token %} {{ form.as_p }} <button type='submit' class='btn btn-secondary'>Save</button> </form> home.html: {% extends 'base.html' %} {% block head_title %} Test {% endblock head_title %} {% block content %} <div class='row text-center'> <div class='col'> <h1> Welcome to the … -
How to alter Django widget validation behavior for conditionally required fields?
I have a mixed set of formsets. Let's say that I have formsets A and B, and that there are 3 full forms of type A and 2 full forms of type B all in the same html form. All formsets are submitted (because I want to save all entries), but only one set of formsets is ever validated. I have it all worked out, except for the display of {{ forms.A.errors.val }}. The val field is a TextInput field that is required based on a javascript-created select list at the top where they choose to search using formsets A or B. If they choose A, the forms of formset A are shown and B are hidden. Both are submitted because I want them to be able to switch to their previous entries in formset B when the results are presented. The problem is that when they switch to formset B after seeing the results of the search using A, the "This field is required." error is shown next to any empty val fields. I thought that I'd successfully avoided that field validation... I have tried multiple means of preventing that error from displaying. I tried overriding clean to only … -
populate django database, txt or CSV file
How to populate django database, with txt(delimited by "|") or CSV file? From admin panel on site? the customer asked to make it so that he could replenish the site database, txt document or CSV table -
I can't make a single project in django in my vs code after installing all the extensions
enter image description here I have installed python extension as well as installed django also in my VS code still I can't make any project in it.It's showing the following error -
i want to know how to use models id to fetch the right data in django
i create two model name subject and section so what i want for user is if a user click on a subject only the section related to that subject open up but it opens all the section of all the subject no matter which subject link you are clicking i hope you get it here is my models.py class Subject(models.Model): name = models.CharField(max_length=80, blank=False,) thumbnail = models.ImageField(upload_to='subject thumbnail', blank = False) about = models.TextField(default='SectionWise' ) total_Section = models.FloatField(default='100') joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Section(models.Model): subject = models.OneToOneField(Subject, on_delete=models.CASCADE) sub_section = models.CharField(max_length=500, blank=True) title = models.CharField(max_length=5000, blank=False) teacher = models.CharField(max_length=500, blank=False) file = models.FileField(upload_to='section_vedios', blank=False) about_section = models.TextField(blank=False, default=None) price = models.FloatField(blank=False) content_duration = models.DurationField(blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject.name my views.py for sections @login_required def sections(request): section_list = Section.objects.all() return render (request, 'sections.html', {'section_list': section_li my html code for viewing section acc to click of subjects <div> {% for section in section_list %} <li class="sub"> <a name='thumb' class="thumb" href="#"> <span><strong> {{ section.title }} </strong> </span> </a> <p>Name: {{ subject.section.teacher }} </p> {{ subject.section.price }} </li> </div> {% endfor %} my html for viewing subject in template {% for subject … -
How to change template in Django class based view
If i have a class based view like: class equipmentdashboardView(LoginRequiredMixin,ListView): context_object_name = 'equipmentdashboard' template_name = 'equipmentdashboard.html' login_url = 'login' def get_queryset(self): #some stuff How can I change the template name depending on a query? I want to do something like: class equipmentdashboardView(LoginRequiredMixin,ListView): context_object_name = 'equipmentdashboard' if self.request.user.PSScustomer.customerName == 'Customer X': template_name = 'equipmentdashboard_TL.html' else: template_name = 'equipmentdashboard.html' login_url = 'login' def get_queryset(self): #some stuff But you can't access the request before the get_queryset. Or maybe there is an even simpler way of achieving the same behavior? -
Where does my django signals look for a missing argument Created in the createprofile function?
I am using django signals to create a profile after a user is created but I get this wird error telling that the create profile function is missing the created argument I even tried without a decorator but It didn't work. I don't know what I am missing. here is the model and the signal itself. class Profile(models.Model): user = models.OneToOneField( User, verbose_name="user", related_name="profile", on_delete=models.CASCADE ) full_name = models.CharField(max_length=150, blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) bio = models.TextField() location = models.CharField(max_length=100, blank=True, null=True) picture = models.ImageField( default="media/profile_pics/default.jpg", upload_to="media/profile_pics" ) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.user.username}'s profile" @receiver(pre_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(pre_save, sender=User) def create_profile(sender, instance, **kwargs): instance.profile.save() And I am using django allauth for the authentication and authorization. Here is the the error from the terminal File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\allauth\account\adapter.py", line 246, in save_user user.save() File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\db\models\base.py", line 750, in save_base pre_save.send( File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send return [ File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) TypeError: create_profile() missing 1 required positional argument: 'created' [09/Jul/2021 18:54:00] "POST /accounts/signup/ HTTP/1.1" 500 136997 -
Static files not served when using docker + django + nginx
I am trying to dockerize a django project and use nginx to serve static files. Everything seems to be working except the static files are not served. When I go to the admin page, always get Not Found: /django_static/rest_framework/css/prettify.css for files in django_static folder. folder structure: backend server apps django_static media ... docker backend Dockerfile wsgi-entrypoint.sh nginx production default.conf development default.conf Dockerfile Here is my docker-compose: services: nginx: build: ./docker/nginx ports: - 1234:80 volumes: - ./docker/nginx/production:/etc/nginx/conf.d - django_static:/app/backend/server/django_static - media:/app/backend/server/media depends_on: - backend restart: "on-failure" backend: build: context: . dockerfile: ./docker/backend/Dockerfile entrypoint: /app/docker/backend/wsgi-entrypoint.sh ports: - "8001:8001" volumes: - django_static:/app/backend/server/django_static - media:/app/backend/server/media expose: - 8001 volumes: django_static: media: dockerfile for django: FROM python:3.7-slim WORKDIR /app ADD ./backend/requirements.txt /app/backend/ ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN pip install gunicorn RUN pip install -r backend/requirements.txt ADD ./backend /app/backend ADD ./docker /app/docker wsgi-entrypoint.py #!/bin/sh until cd /app/backend/server do echo "Waiting for server volume..." done until ./manage.py migrate do echo "Waiting for db to be ready..." sleep 2 done ./manage.py collectstatic --noinput gunicorn server.wsgi --bind 0.0.0.0:8001 --workers 1 --threads 1 #./manage.py runserver 0.0.0.0:8003 nginx docker file: FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf CMD ["nginx", "-g", "daemon off;"] nginx config file: server … -
Why I get an operational error even I migrate
I'm building a blog with django and I tried to add new field to models.And also I makemigrations and migrate to database.And also I tried many other things like these stackoverflow,stackoverflow question 2 But I finally got a operational error. from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = RichTextField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) image = models.ImageField(upload_to='images',null=True, blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title -
Error: <circle> attribute r: Expected length, "NaN" for d3js bubble chart
I am using a jsonresponse from a django backend to create a bubble chart. The data is reaching the script properly but the chart is not showing as there is an issue with one of the attributes. Here's the code: <script type="text/javascript"> dataarr = d3.json("{% url 'find_arr'%}", function(dataarr){ dataarr.forEach(function(d){ console.log(d) }) }) dataset = { "children": dataarr }; var diameter = 600; var color = d3.scaleOrdinal(d3.schemeCategory20); var bubble = d3.pack(dataset) .size([diameter, diameter]) .padding(1.5); var svg = d3.select("body") .append("svg") .attr("width", diameter) .attr("height", diameter) .attr("class", "bubble"); var nodes = d3.hierarchy(dataset) .sum(function(d) { return d.Count; }); var node = svg.selectAll(".node") .data(bubble(nodes).descendants()) .enter() .filter(function(d){ return !d.children }) .append("g") .attr("class", "node") .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); node.append("title") .text(function(d) { return d.Name + ": " + d.Count; }); node.append("circle") .attr("r", function(d) { return d.r; }) .style("fill", function(d,i) { return color(i); }); node.append("text") .attr("dy", ".2em") .style("text-anchor", "middle") .text(function(d) { // return d.Name.substring(0, d.r / 3); return d.Name; }) .attr("font-family", "sans-serif") .attr("font-size", function(d){ return d.r/5; }) .attr("fill", "white"); node.append("text") .attr("dy", "1.3em") .style("text-anchor", "middle") .text(function(d) { return d.Count; }) .attr("font-family", "Gill Sans", "Gill Sans MT") .attr("font-size", function(d){ return d.r/5; }) .attr("fill", "white"); d3.select(self.frameElement) .style("height", diameter + "px"); </script> The console … -
Http Error 500 Django on Ubuntu server 20.04
I build a django app that later deploys to ubuntu 20.04 server (office's private server) and i using Apache2 as web-server. I update all settings such as WSGI and etc and enable conf file i just updated. I try to run manage.py runserver 0.0.0.0:8000 and access it via browser ipaddress:8000 and it works just fine. But i can't access with just ipaddress only, it throw an Internal Server Error (500). before that, i follow this tutorial to set up apache2 server before deploying my django app. Any idea what i missed? -
How do I keep a list of 100 secret keys safe on heroku (django), to be given out only to people with a secret link/password?
I have 100 signed messages that I want to give out to people on twitter randomly. So I want to be able to give them a password or a link on twitter, and then when they enter that password or click that link they get one specific secret key from my website. Obviously if that link leaks then it's fair game for anyone, but each link would only give them access to one secret signed message. Where can I store this? I wanted to store it in a static file and then serve it to complex urls. Like if they go to mywebsite/123SatoshiGoodPassword or whatever, it gives them the 4th secret signed message, and if they go to mywebsite/928VitalikGoodPassword it gives them the 12th secret signed message. (I'm doing this so they can submit an ethereum transaction for a free mint of a token or whatever by the way. They can copy the signed message to send with their transaction or I can use the link to prompt them to submit it on their own. I already have that part worked out.) I don't really want to mess with database stuff as I'm new at all of this. I was … -
How to best submit multiple Django formset_factory forms at once?
This is probably too broad/complex of a question for stack, but I had to go through the process of asking this to clarify my thoughts. I'm very open to suggestions on how to break it up or narrow it down. ATM, I'm not sure how to do that without all this context... I'm fairly new to Django, and I just finished a proof of concept advanced search page that took 2 weeks for me to get working how I want - and it works (pretty well, in fact), but it's really kludgey, and now that I have the proof of concept working, I'm interested in learning how to do it properly, and am looking for suggestions on how to refactor this to make it more straightforward. To summarize the functionality, the interface allows the creation of a complex search query using a dynamic hierarchical form. It does this (currently) for 1 of 2 output formats (which is effectively results in the rendering of a join of 5 or 6 tables in the model, depending on the selected output format), but it submits all the hierarchies and performs the search on the selected one. Here's a gif demo of the interface, … -
media file not found in a simple django-admin application
I have seen many questions here regarding media files in Django, but honestly I can't find a valid solution for my problem. So I have decided to streamline the environment to a very simple application. You can find it here: github project I have created a project with django-admin and I called 'documents' and then I have created an app called 'docs'. Then I defined a simple class: def get_path(instance, filename): fn, ext = os.path.splitext(filename) ts = str(int(time.time())) return os.path.join('{}_{}{}'.format(fn, ts, ext)) class doc(models.Model): doc_name = models.CharField(max_length=30, verbose_name=u"doc name", help_text=u"name of the doc") doc_document = models.FileField(upload_to=get_path, verbose_name=u"document", help_text=u"document") class Meta: unique_together = ("doc_name", ) def __str__(self): return f"{self.doc_name}" This changes the filename and it adds a timestamp. I also changed the urls.py file adding the following: path(r'', admin.site.urls), Now the question is: without using MEDIA_URL and MEDIA_ROOT is it possible to make this working? I have tried to add a files and it works: and it properly save the file in the root of the project. But when I go to the link and click I am getting the following: Now is it possible to know where is it looking for the file? Do you think that adding MEDIA_URL and … -
django deployment crashed with error code H10 (heroku)
After a lot of tries I was finally able to deploy my django app on heroku, but it gave me application error. I tried logging error it was - 2021-07-09T15:43:59.937940+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/admin" host=examtaker-001.herokuapp.com request_id=b3758753-7826-49b6-b22d- c5b1aba1b903 fwd="223.233.68.190" dyno= connect= service= status=503 bytes= protocol=https 2021-07-09T15:44:00.824183+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=examtaker-001.herokuapp.com request_id=8085f766-548e-4dde- 852f-8ae40db54afa fwd="223.233.68.190" dyno= connect= service= status=503 bytes= protocol=https I dont really know where the problem is, Exam- Exam- settings.py urls.py wsgi.py main- migrations static- js css admin.py urls.py views.py apps.py templates- index.html manage.py Procfile requirements.txt This is my directory. Inside my Procfile - web: gunicorn Exam.wsgi --log-file- In settings.py - import django_heroku BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ['examtaker-001.herokuapp.com', '127.0.0.1'] MIDDLEWARE = [ #other defaults 'whitenoise.middleware.WhiteNoiseMiddleware', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' django_heroku.settings(locals()) Rest most of the things remain default. Not sure but I think problem is with BASE_DIR. Any help would be appreciated. -
Django ManyToManyField field: render formset in template
There are two models with a many to many relationship like this: class Client(models.Model): first_name = models.CharField( max_length=50, ) last_name = models.CharField( max_length=50, ) class Event(models.Model): event_name = models.CharField( max_length=50, ) start = models.DateTimeField() end = models.DateTimeField() clients = models.ManyToManyField( Client, db_table='ClientsAttendingEvent', blank=True, ) I want to create 2 templates with basic forms. A "create_event.html" page, and an "edit_event.html" page. Assuming really simple forms like: class EventForm(ModelForm): class Meta: model = Event fields = ['all'] class ClientForm(ModelForm): class Meta: model = Client fields = ['all'] I am struggling a lot with the view. def UpdateEvent(request, EventID): obj = get_object_or_404(Event, pk=EventID) form = SessionsForm(instance=obj) clients_formset = inlineformset_factory(parent_model=Event, model=Client, fields=('first_name', 'last_name',)) if request.method == 'POST': form = EventForm(request.POST, instance=obj) clients_forms = clients_formset(request.POST) if form.is_valid() and clients_forms.is_valid(): final_form = form.save(commit=False) final_form.save() form.save_m2m() return HttpResponseRedirect(reverse('homepage', kwargs={'EventID': EventID})) return render(request, './forms/edit_event.html') Problem: Here I tried various solutions using formset_factory and inlineformset_factory. But I usually get "X has no ForeignKey to Y" or "No fields with name ... ", and so on. Basically I don't get how to use formset factories with a m2m field instead of foreign keys or a dedicated m2m model. Using dot-Notation, "through" and other attempts didn't succeed either. Desired outcome: Having … -
Why serializer.is_valid() is always false in this scenario?
I'm try to Update this model in Django rest-api but I don't get any idea why serializer is always not valid when I try to Update; models.py class Profile(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE, to_field='email') gender = models.CharField(max_length=20, null=True, blank=True) blood_group = models.CharField(max_length=20, null=True, blank=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE, to_field='short_name', null=True, blank=True, default="CSE") program = models.CharField(max_length=20, null=True, blank=True) student_id = models.CharField(max_length=20, null=True, blank=True) phone = models.CharField(max_length=20, null=True, blank=True) photo = models.ImageField(upload_to='Student/Profile/Profile_Photos/', null=True, blank=True) address = models.CharField(max_length=100, null=True, blank=True) current_semester = models.CharField(max_length=20, null=True, blank=True) level = models.IntegerField(null=True, blank=True) term = models.IntegerField(null=True, blank=True) sec = models.CharField(max_length=20, null=True, blank=True) sub_sec = models.CharField(max_length=20, null=True, blank=True) complete_cr = models.FloatField(null=True, blank=True) sgpa = models.FloatField(null=True, blank=True) cgpa = models.FloatField(null=True, blank=True serializer.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' views.py class ProfileUpdateView(generics.UpdateAPIView): model = Profile serializer_class = ProfileSerializer permission_classes = [IsAuthenticated] parser_classes = (MultiPartParser, FormParser) def post(self, request): token = request.headers.get("Authorization").split(" ")[-1] print(token) try: token_obj = get_object_or_404(Token,key = token) user = token_obj.user data =Profile.objects.get(user=user) serializer = ProfileSerializer(instance = data, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response({"invalid"}) except: return Response({'failed': _('bad request'),},status = status.HTTP_406_NOT_ACCEPTABLE) Already 12hrs pass. But still, I didn't get any solution or explanation. Thanks in advance... -
formset in create view not adding new forms and not working with crispy
My code is : views.py: class OrderCreate(CreateView): model = Order template_name = 'order_create.html' form_class = orderForm def get_context_data(self, **kwargs): context = super(OrderCreate, self).get_context_data(**kwargs) context['formset'] = orderDetailForm() context['order_form'] = orderForm() return context def post(self, request, *args, **kwargs): formset = orderDetailForm(request.POST) order_form = orderForm(data=request.POST) if formset.is_valid() and order_form.is_valid(): return self.form_valid(formset, order_form) def form_valid(self, formset, order_form): order = order_form.cleaned_data['order'] instances = formset.save(commit=False) order.created_by = self.request.user order.save() for instance in instances: instance.save() content = {"name": order.created_by, "id": order.pk} send_gmail_message(['philippe@gustafoods.com', 'doro@gustafoods.com'], content) return reverse_lazy("procurement:order_detail",kwargs={'pk':self.object.pk}) def get_success_url(self): return reverse_lazy("procurement:order_detail", kwargs={'pk': self.object.pk}) models: class Order(models.Model): STATUS_TYPES = (('draft', _('draft')), ('pending', _('pending')), ('quote', _('quote requested')), ('ordered', _('ordered')), ('received', _('received')), ('BO', _('back order')), ('cancelled', _('cancelled'))) URGENT_LIST = (('Very Urgent', _('Very Urgent (less than a day)')), ('Urgent', _('Urgent (before 48 hours)')), ('Normal', _('normal (a week)')), ('Other', _('Other (need search)')), ) status = models.CharField('Status', max_length=20, choices=STATUS_TYPES, default='pending') urgent = models.CharField('Urgent', max_length=20, choices=URGENT_LIST, default='Normal') date_created = models.DateField(_('requested'), auto_now_add=True, help_text=_('Date when order was created')) date_ordered = models.DateField(_('ordered'), blank=True, null=True, help_text=_('Date when order was placed')) date_validation = models.DateField(_('validated'), blank=True, null=True, help_text=_('Date when order was validated')) date_received = models.DateField(_('received'), blank=True, null=True, help_text=_('Date when product was received')) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=False, db_index=True, verbose_name='requested by', related_name='requests', help_text=_('user who created this order')) comment = models.TextField(_('comments & … -
Indirect way of usine Model.objects.all() in a formset
I'm using something like this to populate inlineformsets for an update view: formset = inline_formsetfactory(Client, Groupe_esc, form=GroupEscForm, formset=BaseGroupEscInlineFormset, extra=len(Groupe.objects.all())) (Basically I need as many extra form as there are entries in that table, for some special processing I'm doing in class BaseGroupEscInlineFormset(BaseInlineFormset)). That all works fine, BUT if I pull my code & try to makemigrations in order to establish a brand new DB, that line apparently fails some django checks and throws up a "no such table (Groupe)" error and I cannot makemigrations. Commenting that line solves the issues (then I can uncomment it after making migration). But that's exactly best programming practices. So I would need a way to achieve the same result (determine the extra number of forms based on the content of Groupe table)... but without triggering that django check that fails. I'm unsure if the answer is django-ic or pythonic. E.g. perhaps I could so some python hack that allows me to specific the classname without actually importing Groupe, so I can do my_hacky_groupe_import.Objects.all(), and maybe that wouldn't trigger the error? -
chart.js Line chart doesn't display line past a certain point in the chart
For some reason, my line chart isn't correctly displaying the lines past a certain point in the dataset and I can't figure out the reason why this is the case. I have another chart which loads basically the same dataset and that one is displaying just fine (only difference is the line chart has a fill, bordercolor and tension attributes). <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script> const data_bar_chart = { labels: {{ labels | safe }}, datasets: {{ data_list | safe}} }; const config_bar_chart = { type: 'bar', data: data_bar_chart, options: { plugins: { title: { display: true, text: 'Bar Chart - Stacked' }, }, legend: { position: "top", align: "start" }, responsive: false, scales: { xAxes: [{ stacked: true, ticks: { padding: 20 } }], yAxes: [{ stacked: true, }], }, } }; const data_line_chart = { labels: {{ labels | safe }}, datasets: {{ data_list_line_chart | safe}} }; const config_line_chart = { type: 'line', data: data_line_chart, options: { plugins: { title: { display: true, text: 'Line Chart' }, }, legend: { position: "top", align: "start" }, responsive: false, scales: { xAxes: [{ ticks: { padding: 20 } }], }, } }; window.onload = function() { var ctx_bar_chart = document.getElementById('bar-chart-stacked').getContext('2d'); window.myPie = … -
Django how to pass context or model objects in base.html without pass views in url
I know I can pass context using somethings like this in base.html class MyViews(request): #my code..... context= {#my context} return render(request, 'base.html', context) then pass the views in url. But is there any to pass context in base.html without using url?? any idea?? I also tried this 'context_processors': [ ... # add a context processor 'my_app.context_processor.my_views', ], #getting this error No module named 'contact.context_processor' -
How to add a photo to an object ? Django REST
I have person model: class Assistant(models.Model): name = models.CharField(max_length=100) age = models.PositiveIntegerField() photo = models.ImageField(upload_to='photos/') using Django REST how a photo was loaded from https://thispersondoesnotexist.com when creating a new assistant I understand that you need to override the create method how to do it in the best way? ss -
Overwriting django Integer choices output in graphene
I'm working with graphene and graphene-django and I have a problem with a IntegerField with choices. graphene create an Enum and the output is "A_1" if the value is 1; "A_2" if the value is 2 and so on. Example: # model class Foo(models.Model): score = models.IntegerField(choices=((1, 1), (2, 2), (3, 3), (4, 4), (5, 5))) # query query { foo { score } } # response { "data": { "foo": { "source": "A_1" } } } How I can overwrite this output? (ps: I've copied the question from an old post but there is no any proper comment for today, because it is from 4,5 years ago. I've had exactly the same problem today) Thanx -
[Python:Django]AttributeError
I am following django tutorial but i am stuck in part 4. When i try to run server i get error "AttributeError: module 'polls.views' has no attribute 'ResultsView'" My code: polls/views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from .models import Question, Choice from django.template import loader from django.urls import reverse def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list } return render(request, 'polls/index.html', context) def detail(request, question_id): question =get_object_or_404(Question, pk=question_id) return render(request, "polls/detail.html", {'question':question}) def results(request, question_id): response = "You are looking at results of question %s" return HttpResponse(response % question_id) #render(request, 'polls/results', {"question_id": question_id}) #HttpResponse(response % question_id) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question' : question, "error_message" : "You didn't select a choice'", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=[question.id])) # Create your views here. polls/urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns=[ path("", views.index, name="index"), path("<int:question_id>/", views.detail, name="detail"), path("<int:pk>/results/", views.ResultsView.as_view(), name="results"), path("<int:question_id>/vote/", views.vote, name="vote"), ] polls/results.html <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text}} -- {{ choice.votes }} vote{{ choice.votes|pluralize}}</li> {% endfor %} <ul/> </ul> <a href …