Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django download files from a list (s3 as back-end)
I need to list an html table the content of a S3 bucket and enable the option to download the file. To do so I have done he following: The code shows the list of the bucket files correctly, but I'm not sure how I can write the code to download the files. inventory.html: {% block title %} title{% endblock %} {% block content %} <table class="table table-striped"> <thead> <tr> <th scope="col">Date&nbsp;<a href="?order_by=ord_date&direction=desc">{% load static %}<img src="{% static "arrow.png" %}" width="12" height="12" alt="order desc"></a><a href="?order_by=ord_date&direction=asc">{% load static %}<img src="{% static "sort-down.png" %}" width="12" height="12" alt="order asc"></a></th> <th scope="col">Name&nbsp;<a href="?order_by=ord_source&direction=desc">{% load static %}<img src="{% static "arrow.png" %}" width="12" height="12" alt="order desc"></a><a href="?order_by=ord_source&direction=asc">{% load static %}<img src="{% static "sort-down.png" %}" width="12" height="12" alt="order asc"></a></th> <th scope="col">Size</th> <th scope="col">Action</th> </tr> </thead> <tbody> {% for item in items %} <tr> <td>{{ item.LastModified }}</td> <td>{{ item.Key }}</td> <td>{{ item.Size }}</td> <td><button type="Button" class="btn btn-secondary btn-sm"><a href="?key_download={{ item.Key }}">Download</button></a></td> </tr> {% endfor %} </tbody> </table> {% endblock %} views.py: client = boto3.client('s3') def inventory(request): if request.GET.get('key_download'): url = client.generate_presigned_url('get_object', Params = { 'Bucket':'url_of_the_bucket', 'Key':request.GET.get('key_download')}, ExpiresIn = 86400) return **"I don't know how I can return it"** else: fdc_inventories = client.list_objects_v2(Bucket='url_of_the_bucket') fdc_inventories['Contents'].sort(key=itemgetter('LastModified'), reverse=True) return render(request, 'inventory.html', {'items': … -
How can I do a left join in Django?
What I want to do is: select * from employer e left join person p on p.employer.id = e.id and p.valid = True That means that I will see |employer|null| for any employer that does not have a person working for them and I will see the same thing if there is a person working for them but they are invalid. In django I wish I could do: employers.objects.all().values('id', 'person') and have the value of person show up as None rather than show me the invalid person. -
How can I append the page number in the request endpoint
I am having a URL as below: HTTP Request Method : GET Endpoint: http://localhost:8000/api/<client_id>/getshowscount I am using a paginator class in my Django code. class ShowListPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 1000 class ClientShowSongListViewSet(viewsets.ModelViewSet): permission_classes = (DashboardAccess,) serializer_class = ShowCountSerializer pagination_class = ShowListPagination def get_queryset(self): return ShowSong.objects.filter(user = self.request.user) Everything works fine. But, the requirement says that I need to have URL endpoint as below: Endpoint examples: http://localhost:8000/api/<client_id>/getshowscount/?page=1 http://localhost:8000/api/<client_id>/getshowscount/?page=2 By the above endpoint examples, I mean to say that I need to append the page also in the URL depending upon the pages. I checked the paginator class. But I didn't find anything useful. Can anyone suggest some workarounds for the same? -
basic django site gives error as "Not found: /nettrack/
I am totally new to django and stuck with basic learning of django. I have below structure of django project: G:\virtualenvs\Netsite\netmon-- enter image description here I have below urls.py under netmon enter image description here I have below urls.py under nettrack enter image description here This is basic_generic.html And I have below index.html enter image description here Now, whats wrong? I get error as below in the cmd window of "python manage.py runserver" enter image description here Please help. Also, I dont know whether I need any IIS running on my windows desktop machine so as to test site as http:/127.0.0.1:8000/nettrack/ in edge browser. -
How to get large-size scraped data quickly?
I select news from one website and display it on my page. But when I go to the news tab or refresh the page, the page loads data for a while (10 seconds). How can I upload data instantly? I tried to load data, but the problem is that if the text to the article is too large, the page load will still not be instantaneous. Maybe i can upload text in chunks some way? My code: def get_summary(url): new_d = BeautifulSoup(requests.get(url).text, 'html.parser') return '\n'.join(i.text for i in new_d.find('div', {'class':'flexible_content_wrap'}).find_all('p')) def scrape(request): website_url = requests.get("https://loudwire.com/news/").text soup = BeautifulSoup(website_url, "html.parser") more = [] teaser = soup.find_all('div', {'class':'teaser_feed_common'}) for i in teaser: mine = get_summary(i.a['href']) print(mine) more.append(mine) context = {'more_info': more} return render(request, 'music/news.html', context) In advance, thanks for any help. -
cannot resolve keyword 'user' into field - django error
this is the error message I am getting --->Cannot resolve keyword 'user' into field. Choices are: date_joined, email, emailconfirmed, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, order, password, profile, user_permissions, useraddress, userdefaultaddress, username, userstripe<---- it is highlighting these two pieces of code as key areas as where the problem seems to arise. new_order = Order.objects.get(cart=cart) ///// new_order.user = User.objects.get(user=request.user) all help would be greatly appreciated in solving this! views.py - orders import time import stripe from django.contrib.auth.decorators import login_required from django.conf import settings from django.contrib.auth.models import User from django.shortcuts import render, HttpResponseRedirect from django.urls import reverse # Create your views here. from users.forms import UserAddressForm from carts.models import Cart from .models import Order from users.models import Profile, UserAddress, UserAddressManager from .utils import id_generator stripe.api_key = settings.STRIPE_SECRET_KEY def orders(request): context = {} template = "orders/user.html" return render(request, template, context) @login_required def checkout(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse("cart")) try: **new_order = Order.objects.get(cart=cart)** except Order.DoesNotExist: new_order = Order() new_order.cart=cart **new_order.user = User.objects.get(user=request.user)** new_order.order_id = id_generator() new_order.final_total = cart.total new_order.save() except: return HttpResponseRedirect(reverse("cart")) try: address_added = request.GET.get("address_added") except: address_added = None if address_added is None: address_form = UserAddressForm() else: address_form = None current_addresses = … -
syntax error in using SECRET_KEY in __init__py in django
I have read that it is not secure to store the SECRET_KEY in settings.py as its default. So, I decided to store it in my __init__.py. I wrote in __init__.py which is beside settings.py: export SECRET_KEY= 'hf7^vrmc!^agnpba#^+$9ac-@eullgd-=ckq&u1zu$b7nqc)%_' This is the only line in my __init__.py. Then in settings.py I changed the line SECRET_KEY = 'hf7^vrmc!^agnpba#^+$9ac-@eullgd-=ckq&u1zu$b7nqc)%_' into SECRET_KEY = get_env_variable('SECRET_KEY') but when I try to runserver, I receive Syntax error as below: … __init__.py", line 1 export SECRET_KEY= 'hf7^vrmc!^agnpba#^+$9ac-@eullgd-=ckq&u1zu$b7nqc)%_' ^ SyntaxError: invalid syntax What's wrong here? Thank you in advanced. -
django dynamically loading a static file
I am trying to send a static link to a download button. The static link results in a views.py function and will be returned as a dict. in views.py: def some_fct(request): handling the request return render(request,'site.html',{'processed_request': 'name_of_static_file'}) I tried to locate the data in a seperate div and change the href with: <div id="data">{{processed_request}}<\div> <a href="" id="download"><button class="download_btn"><i class="fa fa-download"></i> Download</button></a> <script> let file = document.getElementbyId('data').innerHTML; let file_static = "{% static '${file}' %}" document.getElementById('download').setAttribute("href",file_static); </script> which leads to the console.log https://..../static/%24%7Bfile%7D instead of https://..../static/name_of_static_file How can I access the static_file? -
ImportError: cannot import name 'BaseContact'
I have a problem while running my Django code. File "E:\sophienwald\amocrm\models.py", line 3, in <module> from amocrm import BaseContact, amo_settings, fields, BaseLead ImportError: cannot import name 'BaseContact' But I noticed a strange feature... If I swap "BaseContact" and "BaseLead" it says that compiler can't import BaseLead. "fields" and "amo_setting" work fine. Bit of code from amocrm\models.py: import logging from amocrm import BaseContact, amo_settings, fields, BaseLead from django.conf import settings from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.functional import cached_property from wagtail.admin.edit_handlers import MultiFieldPanel, FieldPanel from wagtail.contrib.settings.models import BaseSetting from wagtail.contrib.settings.registry import register_setting logger = logging.getLogger(__name__) @register_setting class AmocrmSettings(BaseSetting): PIPELINE_FIELDS = [ ('stay_tuned_pipeline_name', 'stay_tuned_status_name'), ('new_posts_pipeline_name', 'new_posts_status_name'), ('back_call_pipeline_name', 'back_call_status_name'), ] login = models.CharField('Логин', max_length=120, null=True, blank=True) token = models.CharField('Токен', max_length=120, null=True, blank=True) subdomain = models.CharField('Поддомен', max_length=120, null=True, blank=True) run_async = models.BooleanField('Обновлять асинхронно', default=False) # forms.StayTunedContact stay_tuned_pipeline_name = models.CharField('Название воронки', max_length=120, null=True, blank=True) stay_tuned_status_name = models.CharField('Статус при создании', max_length=120, null=True, blank=True) # forms.NewPostsContact new_posts_pipeline_name = models.CharField('Название воронки', max_length=120, null=True, blank=True) new_posts_status_name = models.CharField('Статус при создании', max_length=120, null=True, blank=True) # forms.BackCallContact back_call_pipeline_name = models.CharField('Название воронки', max_length=120, null=True, blank=True) back_call_status_name = models.CharField('Статус при создании', max_length=120, null=True, blank=True) panels = [ MultiFieldPanel([ FieldPanel('login'), FieldPanel('token'), FieldPanel('subdomain'), FieldPanel('run_async'), ], 'Авторизация'), ] -
Show the download button only if file is available on server in Django template (html)
Following code shows the download option on the page whether file is present or not on server. <a href="{%static 'media/reports/finance'%}/sap-daily.csv" download >Download</a> I want to show not available option if the file is not present on server. -
How can I access serializer's field data before its type validation?
How to access the field value before serialization in my serializer (serializers.Serializer) or rest view (UpdateAPIView)? I have something like this: class MySerializer(serializers.Serializer): my_field = serializers.IntegerField() If I try to fill my field with 'test' string, it will immediately raise the ValidationError telling me about wrong data type (expecting an integer number of course). Before that error raise, I want to capture the value and do something with it but I have no idea how and where can I access it. It has an empty string value everywhere. I tried to get it in is_valid() before call super() or with raise_exception=False, but I still can not see it: '_kwargs': {'context': {'format': None, 'request': <rest_framework.request.Request object>, 'view': <rest.views.MyUpdateAPIView object>}, 'data': <QueryDict: {'my_field': ['']}>, 'initial_data': <QueryDict: {'my_field': ['']}>, When I try to find it in my view I can also see nothing: serializer.initial_data <QueryDict: {'my_field': ['']}> request.data <QueryDict: {'my_field': ['']}> When I try to check validate() or validate_my_field() methods, I can not even get there because of the ValidationError I mentioned above. How the serializer validation actually works? What is the order in it and how can I access data before it is "cleaned"? -
Authentication in Django Channels v2 tests with WebSocketCommunicator
In the process of writing tests for my chat consumer I encountered with a problem of being unable to authenticate in tests, using WebSocketCommunicator. I have custom JwtTokenAuthMiddleware that implements authentication in sockets by using token in request query, because as I know, decent authentication with the use of authorization headers is not possible yet. Can you guys advise me on that or provide me with the example code, which I couldn't find across the net ? Btw, my chat is working without problems. Also tests should be perfectly fine, I took the guide from official documentation Django Channels 2.x Testing. --JwtTokenAuthMiddlewate-- class JwtTokenAuthMiddleware: def __init__(self, inner): self.inner = inner def __call__(self, scope): close_old_connections() try: raw_token = scope['query_string'].decode().split('=')[1] auth = JWTAuthentication() validated_token = auth.get_validated_token(raw_token) user = auth.get_user(validated_token) scope['user'] = user except (IndexError, InvalidToken, AuthenticationFailed): scope['user'] = AnonymousUser() return self.inner(scope) JwtTokenAuthMiddlewareStack = lambda inner: JwtTokenAuthMiddleware(AuthMiddlewareStack(inner)) --Example Test-- @pytest.mark.django_db(transaction=True) @pytest.mark.asyncio async def test_trainer_auth_success(): room = await database_sync_to_async(RoomFactory.create)() trainer = room.trainer trainer_token = await sync_to_async(get_token_for_user)(trainer.user) room_url = f'ws/room/{room.id}/' trainer_communicator = WebsocketCommunicator(application, f'{room_url}?t={trainer_token}') connected, _ = await trainer_communicator.connect() assert connected trainer_connect_resp = await trainer_communicator.receive_json_from() assert_connection(trainer_connect_resp, [], room.max_round_time) await trainer_communicator.disconnect() --Traceback of Error-- ___________________________________________________________ test_trainer_auth_success ___________________________________________________________ self = <channels.testing.websocket.WebsocketCommunicator object at 0x7f6b9906f290>, timeout = 1 … -
Django - Login form customization doesn't render
I want to be able to customize my login form but when my login page render, the login form doesn't appear. I tried to do it the way I customized my registration form but I always have the same problem. I'm pretty sure my settings.py and urls.py are correct: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'inscription.apps.InscriptionConfig', 'profil.apps.ProfilConfig', 'questions.apps.QuestionsConfig', ] from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from inscription import views as i from home import views as h from profil import views as p from questions import views as q urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('accueil/', h.index, name='accueil'), path('inscription/', i.inscription, name='inscription'), path('connexion/', i.connexion, name='connexion'), path('deconnexion/', i.deconnexion, name='deconnexion'), path('profil/', p.profil, name='profil'), path('questions/', q.questions, name='questions') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I created my login form based on the existing AuthenticationForm (forms.py): from django import forms from django.contrib.auth.models import User from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm, AuthenticationForm class FormulaireConnexion(AuthenticationForm): username = forms.CharField( label = 'Nom de compte' ) password = forms.CharField( label = "Mot de passe", strip = False, widget = forms.PasswordInput(), ) class Meta: model = User fields = ['username','password'] Then I used my … -
Calculate percentage In Django Database Query
I am trying to calculate the total cost of all the services with taxes in the bill using a single query. I don't understand where I am going wrong. MODELS: class Bill(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) number = models.CharField(max_length=100, blank=True) class BillService(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) bill = models.ForeignKey(Bill, related_name='billservices', on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) class Service(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) business = models.ForeignKey(Business, related_name='services', on_delete=models.CASCADE, blank=True) short_code = models.IntegerField(default=0) class ServiceTax(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) service = models.ForeignKey(Service, on_delete=models.CASCADE, related_name="servicetaxes") tax = models.ForeignKey(Tax, on_delete=models.CASCADE) class Tax(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) business = models.ForeignKey(Business, related_name='taxes', on_delete=models.CASCADE) name = models.CharField(max_length=50) tax = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(100)], default=0) MY QUERY TO GET A SINGLE VALUE, THAT IS TOTAL COST OF THE BILL value = bill.billservices.all() .annotate(sum_of_taxed_percentages=Subquery( Service.objects.filter(billservice=OuterRef('id')) .annotate(total_tax_value=Subquery( ServiceTax.objects.filter(service=OuterRef('id')) .values('tax') .annotate(total_tax=Sum('tax__tax', output_field=FloatField())) .values('total_tax') )).annotate(taxed_value=F('price') + ((F('price') * F('total_tax_value')) / 100)) .values('taxed_value') .annotate(total_services_taxed_value=Sum('taxed_value', output_field=FloatField())) .values('total_services_taxed_value') )) print(value[0].sum_of_taxed_percentages) -
How to CreateView/UpdateView using foreign key in Nested model
Was able to perform CRUD on Branch. However I am stuck in create/update/delete for Feature.. Also when i move to Testcase CRUD, what steps do i need to do.? Please help.. Please Let me know if u need more info regarding this. ....... PS: I am new to django (2 weeks in.. enjoying it :-)). Model: class Branch(models.Model): """Model representing a Branches""" name = models.CharField(max_length=200, db_index=True, unique=True) summary = models.CharField(max_length=200, db_index=True) def __str__(self): """String for representing the Model object.""" return self.name def get_absolute_url(self): """Returns the url to access a particular branch instance.""" return reverse('branch-detail', args=[str(self.id)]) class Feature(models.Model): """Model representing a Feature""" branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True, related_name='features') name = models.CharField(max_length=200, db_index=True, unique=True) def __str__(self): """String for representing the Model object.""" return self.name def get_absolute_url(self): """Returns the url to access a particular feature instance.""" return reverse('feature-detail', args=[self.branch, str(self.id)]) class Testcase(models.Model): """Model representing a Testcase""" feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True, related_name='testcases') name = models.CharField(max_length=200) def __str__(self): """String for representing the Model object.""" return self.name def get_absolute_url(self): """Returns the url to access a detail record for this testcase.""" return reverse('testcase-detail', args=[self.feature.branch, self.feature, str(self.id)]) View: class BranchCreate(CreateView): model = Branch fields = '__all__' success_url = reverse_lazy('index') class BranchUpdate(UpdateView): model = Branch fields = ['name', … -
Django web app Docker - unable to coonect
I am new on Django and Docker and I have a problem to enter site localhost:8000. I built django app and it is working on my local server but I'd like to dockerize my app. So I created two files: Dockerfile : ROM python:3.6.7-alpine ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD ./ /code/ CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] and docker-compose.yml version: '3' services: web: build: . command: python mysite/manage.py runserver 8000 ports: - "8000:8000" My next steps: docker built --tag django_docker:latest . docker run django_docker It's open server, but when I want to open lokalhost:8000 from my browser I can't because of "Unable to connect" Where is my fault? I More about django app : it's project from book Python Crash Course : Learning_log. I'd like to build an image and push it to hub docker, but I am stuck. Thanks for help! -
Django Create Temporary File for Download
I have a model named 'Report Data'. I have a form which will get 'report_name' and will perform a operation. This operation basically loops through objects, every object returned has a file field having '.docx' file, this function will merge all these files into one docx file. After this 'convert' method will convert 'docx' to 'pdf'. I am able to perform this workflow but I need to create a temporary file instead of real files in media directory. My class based view is below class FilesListView(LoginRequiredMixin,ListView): model = ReportData template_name = 'report/myfiles.html' context_object_name = 'reportdata' def get_queryset(self): return ReportData.objects.filter(preparedby=self.request.user).order_by('-date_created') def post(self,request,*args,**kwargs): filtervalue = request.POST.get("report_name","") reportsforPDF = ReportData.objects.filter(reportname=filtervalue) reporturl = settings.MEDIA_ROOT[0:-6] master = Document(reporturl + reportsforPDF.first().document.url) composer = Composer(master) i=0 for object in reportsforPDF: if i>0: doc = Document(reporturl + object.document.url) composer.append(doc) i+=1 storage = settings.MEDIA_ROOT + '/merged/{}.docx'.format(filtervalue) composer.save(storage) pythoncom.CoInitialize() convert(settings.MEDIA_ROOT + '/merged/{}.docx'.format(filtervalue)) context = { 'pdf_url': '/media/merged/{}.pdf'.format(filtervalue) } return render(request, 'report/myfiles.html', context=context) Also how can I use get_query_set inside the post function because my current code returns no objects? -
Django Web Server is not opening open source project
I'm trying to run the Django medicine web-app. it's an open-source project. here's the link https://github.com/jai-singhal/croma when I run this command python manage.py runserver I got this error enter image description here -
Redirect from one admin view to another model view in Django
I'm trying to find a way of opening different admin view on column selection. My very simplified models are following: class modelA(models.Model): created = models.DateTimeField(auto_now_add=True) description = models.CharField(max_lenght=200) class modelB(models.Model): modelsA = models.ForeignKey(on_delete=models.CASCADE, related_name='modelBs') value = models.IntegerField() And in admin I have following view: class modelA_Admin(admin.ModelAdmin): list_view = ('__str__', 'total_modelBs') def total_modelBs(self, obj): try: total = obj.modelBs.all().count() except modelB.DoesNotExist: total = 0 return total What I'd like to get is be able to open modelB Admin view with values filtered for those that have given modelA id once I click on value total_modelBs. Any idea, how this can be achieved? -
Css and Javascript failing to load in html
Trying to add a slider to an html page in my django project, but css and javascript is not loading. Because of this instead of the slider being an actual slider ie. images sliding across, I get a vertical line of pictures. These are the errors i am getting in my browser console Failed to load resource: the server responded with a status of 404 (Not Found) slider.js:1 Uncaught ReferenceError: $ is not defined at slider.js:1 main.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) countdown.js:26 Uncaught TypeError: Cannot set property 'innerHTML' of null at updateClock (countdown.js:26) at initializeClock (countdown.js:36) at countdown.js:41 main.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) slider.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) This is the structure of my static folder static -->second ---->css >app slider.css ---->js >app slider.css my html {% load static %} <link rel="stylesheet" href="{% static 'second/css/app/slider.css' %}"> <script src="{% static 'second/js/app/slider.js' %}"></script> <div class="container"> <h3>Our Partners</h3> <section class="customer-logos slider"> <div class="slide"><img src="https://image.freepik.com/free-vector/luxury-letter-e-logo-design_1017-8903.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/3d-box-logo_1103-876.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/blue-tech-logo_1103-822.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/colors-curl-logo-template_23-2147536125.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/abstract-cross-logo_23-2147536124.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/football-logo-background_1195-244.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/background-of-spots-halftone_1035-3847.jpg"></div> <div … -
How to assign custom color in google column chart based on value (Django)
I have values : m=72 n=34 z=59 I got the fowlloing google column chart : <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load("current", {packages:['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ["Apple", {{m}}, "green"], ["Orange", {{n}}, "red"], ["Grape", {{z}}, "orange"],); var view = new google.visualization.DataView(data); view.setColumns([0, 1, { calc: "stringify", sourceColumn: 1, type: "string", role: "annotation" }, 2]); var options = {title: "Fruits",width: 1000, height: 400, bar: {groupWidth: "95%"},}; var chart = new google.visualization.ColumnChart(document.getElementById ("columnchart_values"));chart.draw(view, options);} </script> <div id="columnchart_values" style="width: 900px; height: 300px;"></div> i want to color values m,n or z in the following way: if value (m,n or z) more than 70 color green if value (m,n or z) more than 50 but less than 70 color orange if value (m,n or z) less than 50 color red Any help is appreciated. -
Djnago, is it possible to create multiple status choice with a model?
This is my actually models.py, that give me the possibility to create the status for a multiple choice: class Status(models.Model): slug = models.SlugField(unique=True) category = models.TextField() class Example(models.Model): category= models.ForeignKey(Status) I want to have the possibility to add a sub category. In other words, if I create a new category "Product" in my status model, I want to have the possibility to create the sub category choice, dipendet from the category, and selectable in my Example model in a new field called sub_category. -
TemplateDoesNotExist at /login/ registration/login.html
While I am creating login and logout using built-in login() and logout() views the following error occured. The templates login.html, logout.html are present in 'djangobin/templates/djangobin/login.html', 'djangobin/templates/djangobin/logout.html' TemplateDoesNotExist at /login/ registration/login.html Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Reference website: Overiq.com Reference website Link: https://overiq.com/django-1-11/django-logging-users-in-and-out/#using-built-in-login-and-logout-views Python version: 3.8.2 Django version: 3.0.5 OS: Windows 8.1 (32-bit) In settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'djangobin', ] MIDDLEWARE = [ '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', 'django.middleware.common.BrokenLinkEmailsMiddleware' ] ROOT_URLCONF = 'django_project.urls' In urls.py: from django.contrib.auth.views import LoginView, LogoutView url(r'^login/$', LoginView.as_view(), {'templates_name': 'djangobin/login.html'}, name='login'), url(r'^logout/$', LogoutView.as_view(), {'templates_name': 'djangobin/logout.html'}, name='logout'), In login.html: {% extends "djangobin/base.html" %} {% block title %} Login - {{ block.super }} {% endblock %} {% block main %} <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6"> <h4>Login</h4> <hr> {% if messages %} {% for message in messages %} <p class="alert alert-info">{{ message }}</p> {% endfor %} {% endif %} <form method="post"> {% csrf_token %} <table class="table"> {{ form.as_table }} <tr> <td>&nbsp;</td> <td><button type="submit" class="btn btn-primary">Submit</button></td> </tr> </table> </form> </div> <div class="col-lg-6 col-md-6 col-sm-6"> <h4>Related Links</h4> <p> <a href="/password-reset/">Forgot Password?</a> <br> <a href="/register/">Create new account.</a> <br> <a href="#">Feedback</a> </p> </div> </div> {% endblock %} -
Is there a left join in django.extra() which can help me to join tables without any relationship in django
class Ordman(models.Model): pcod = models.CharField(db_column="PCOD", max_length=6) class Meta: managed = False db_table = "ORDMAN" class Shademst(models.Model): code = models.CharField(db_column="CODE", primary_key=True, max_length=6) class Meta: managed = False db_table = "SHADEMST" These both are connected without any relationship and I need to fire a left join query with the help of extra() in ORM in django but the join I can apply is inner join so can anyone help me to figure out how to apply left join in it. The database is a legacy database so can't do changes on it -
Django: Import models.py in other views.py
Basically a user can login, once the user is logged in she/he can takes a quiz, after have taken the quiz, on user_profile.html page she/he can sees the score. If the score is > x then can see the progress bar and some jobs applications. I created all to the point of "if score > x shows the progress bar" I can't print the {{ job.posizione }} I created on the "jobs" app. The idea was to import the jobs/models.py on the core/views.py but then I get stuck on a nested for loop on the user_profile.html template core/views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.list import ListView # Create your views here. from quiz.models import Questions def homepage(request): return render(request, 'core/homepage.html') def userProfileView(request, username): user= get_object_or_404(User, username=username) categories = Questions.CAT_CHOICES scores = [] for category in categories: score = Questions.objects.filter(catagory=category[0], student= request.user).count() scores.append(score) context = { 'user' : user, 'categories_scores' : zip( categories,scores) } return render(request, 'core/user_profile.html' , context) class UserList(LoginRequiredMixin, ListView): model = User template_name = 'core/users.html' core/user_profile.html {% extends 'base.html'%} {% block content %} <br> <div class="card-header"> <h3> {% if request.user == user %} Il tuo {% endif %} Profilo …