Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Own Middleware for Restricting Users Django
i am going to write a model which contains following fields example. user_id, role_id, company_id, functionality_id, has_access. I want to write middleware where user will be raised NOT ACCESS where field has_access is false. Please help how should i do it and i can't use in-built permission due to my dependencies. I have created middleware.py and followed official document. This is just my start for writing middleware class ACLMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response i have found some reference to this code but i don't know if it is right way to do because i'm using django 2.1 version from django.core.urlresolvers import reverse from django.http import Http404 class RestrictStaffToAdminMiddleware(object): """ A middleware that restricts staff members access to administration panels. """ def process_request(self, request): if request.path.startswith(reverse('admin:index')): if request.user.is_authenticated(): if not request.user.is_staff: raise Http404 else: raise Http404 -
How to asynchronously generate Google Text-To-Speech audio files in Django view to use in webpage?
One of my webpages takes about 3 seconds to load locally, and 15 seconds to load when it's live on Heroku. I believe the problem is how many synchronous Google TTS (Text-To-Speech) API calls and synchronous database / Amazon S3 writes I make. I think asynchronous coding would help, but I'm not entirely sure how to implement it. Here's an oversimplified example of what's happening in the view: def slow_loading_view(request): for i in range(100): audio_str = str(i) google_audio = synthesize_text(audio_str) # returns audio file # WAIT for google's response to come back save_string_and_audio_to_database(audio_str, google_audio) # WAIT to complete writing the audio string to my database and # storing the audio file in my Amazon S3 bucket for future use # Now I would like to query the database to obtain these audio strings and files I just saved # And then pass them in my context to use in the webpage return render(request, 'my_page.html', context) As you can see, there's a lot of waiting (idle time) going on in the view, so ideally i'd be able to 1) asynchronously send all the google API requests to generate the audio files, and then after I have all those audio files returned … -
Django QuerySet filtering not working with views, showing blank view even though there are entries
I am attempting to view a particular set of objects with a certain attribute by using QuerySet filtering, however when I use the filter, the view returns blank. Not sure if I'm using this particular filter wrong, or if I'm calling on the attribute wrong, however I accessed other attributes (as seen below, the attribute "status") and found that it worked fine. views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .models import * from .forms import * @login_required def vendorView(request): return render(request, 'inv/vendorInventory.html') @login_required def consumerView(request): return render(request, 'inv/consumerInventory.html') def unauthenticatedView(request): return render(request, 'inv/unauthenticatedInventory.html') ################ need to edit other views to render consumer/vendor/unauth def display_drinks(request): items = Drinks.objects.all() context = { 'items': items, 'header': 'Drinks', } if not request.user.is_authenticated: items = Drinks.objects.filter(status='AVAILABLE') context = { 'items': items, 'header': 'Drinks', } return render(request, 'inv/unauthenticatedInventory.html', context) elif request.user.profile.vendor: items = Drinks.objects.filter(donatorID=request.user.username) context = { 'items': items, 'header': 'Drinks', } return render(request, 'inv/vendorInventory.html', context) elif not request.user.profile.vendor: items = Drinks.objects.filter(status='AVAILABLE') context = { 'items': items, 'header': 'Drinks', } return render(request, 'inv/consumerInventory.html', context) inventory/models.py: from django.db import models from django.contrib.auth.models import User from users.models import * # Create your models here. class Donation(models.Model): description = models.CharField(max_length=200, … -
Modal positioning on mobile - bootstrap
Hopefully you can advise, I have a script that loops through DB records and creates a row & modal for each. It's great, but when I get to the middle of the page on mobile & click on the button, opening the modal, it shows right at the top of the page, so I have to scroll up and use it. Is there any way to make a modal appear at the right point on the screen? {% for todo in todo_list %} {% if todo.complete is False %} <div class="col-sm-3"> <div class="card"> <h5 class="card-header">{{ todo.id }} :{{ todo.text }}</h5> <div class="card-body"> <p class="card-text"> <table class="table table-hover"> <tr> <td>Created By</td> <td>{{ todo.creator }}</td> </tr> <tr> <td>Assigned To</td> <td>{{ todo.assignee }}</td> </tr> <tr> {% if todo.priority == "High" %} <td>Priority</td> <td class="table-danger">{{ todo.priority }}</td> {% elif todo.priority == "Medium" %} <td>Priority</td> <td class="table-warning">{{ todo.priority }}</td> {% else %} <td>Priority</td> <td class="table-info">{{ todo.priority }}</td> {% endif %} </tr> </table> <table class="table table-hover"> <tbody> <tr class="table"> <th scope="col"><form action="/complete/" name="form2", id="form2" method="post"> {% csrf_token %} <button name="donebutton" type="submit" value={{ todo.id }} data-toggle="tooltip" data-placement="top" title="Complete Task" class="btn btn-success"><i class="fas fa-check"></i></button></th> </form> <td> <!-- Button trigger modal --> <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#EditModal{{ todo.id … -
Form field calculations online with Ajax
I have a current django application with a form, and as user selects options, it updates the total price at the bottom of the form. The form is extense, and field combinations large. I have all this calculations implemented in my view, so when the user posts the form, I have the total and correct amount calculated. I also have the calculations in a javascript file, so the user can see the total amount on the fly. Now I want to get rid of the javascript file, and have calculations only on my view (hate double implementation). I thought on having an ajax call on some field changes so the view can be called, the values updated and return a full form back (or something like that). My question is: is out there some django package that does that? (So I don't have to do it from scratch) -- couldnt find from my research. -
Django Views: Is this the correct way to use the dispatch method of a Django class based view?
I have a class based view, and from the get and post request I have been calling a method, to obtain information from information in the HttpResponseRedirect kwargs. code: class View1(View): def get(self, request, *args, **kwargs): ... stuff ... return render(request, self.template_name, self.context) def post(self, request, *args, **kwargs): ... stuff ... return HttpResponseRedirect( reverse('results:report_experiment', kwargs={ 'sample_id': current_sample_id } )) class View2(CustomView): def dispatch(self, request, *args, **kwargs): self.obtainInformation(kwargs) return super(View2, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): ... stuff ... return render(request, self.template_name, self.context) def post(self, request, *args, **kwargs): ... stuff ... return HttpResponseRedirect( reverse('results:report_experiment', kwargs={ 'sample_id': current_sample_id } )) My question is, when I call self.obtainInformation(kwargs) in the dispatch method, I can access any class variables I define in BOTH the get and post methods. Previously I was calling self.obtainInformation(kwargs) in both the get and post methods of view2 (so calling the method twice). Is this a sensible way to use the dispatch method? -
How to keep a text inside a div when resizing the browser window
So I have a simple div in which I have a p with some text. I want the text to stay inside the div, and that is going good so far, but when I resize the window of my browser horizontal, the text inside the div is flowing out of the div on the bottom. This is the css part. #textbox { position: absolute; left: 180px; top: 420px; height: 250px; width: 20%; background-color: white; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); } #text { text-align: center; font-family: 'Roboto', sans-serif; font-style: italic; font-size: 20px; word-wrap: break-word; } Here is the html part. <div id="textbox"> <p id="text">Here is some example text that is about the same amount as I really have here, but I don't want to reveal what.</p> </div> According to the answers on similar questions, I have to add word-wrap: break-word; which I already have. If this helps, the text is not flowing out at left or right, it flows out at the bottom. So my question, what do I do, to keep the text inside the div when I'm moving the browser window? -
How to fix cv2.imread() returning None in django view?
I am creating a simple Django view that reads a image present in the same directory as view.py. However whenever I try to read the image it returns None object although the code works fine when written in another script file read.py from django.shortcuts import render import numpy as np import cv2 def stream(request): value = cv2.imread('test.png',cv2.IMREAD_UNCHANGED) return render(request, 'live/live.html',{'value' : value}) -
django static files are showing error while loading from aws-s3 bucket
PLease check the screenshots. i am creating my aws-s3 bucket in above way.it is compying everything when i am using python manage.py collectstatic But static files are showing error when i am checking from my view source . please check last screenshot for errors -
Ajax in function based view
I've come a cross a lot of tutorials regarding how to setup a class based view for ajax. Example: class JoinFormView(FormView): form_class = JoinForm template_name = 'forms/ajax.html' success_url = '/form-success/' def form_valid(self, form): response = super(JoinFormView, self).form_valid(form) if self.request.is_ajax(): print(form.cleaned_data) data = { 'message': "Successfully submitted form data." } return JsonResponse(data) else: return response I'm wondering how would insert the required code for ajax into this function based view. Does the code required depend on whether or not I want to pull from or write to the db asynchronously? def my_func_view(request): template = 'accounts/profile.html' form = Form123(request.POST or None) if request.method == 'POST': if form.is_valid(): instance = form.save(commit=True) return redirect('/accounts/profile/') else: messages.error(request, 'There was an error.') context = {'form': form,} return render(request, template, context) else: context = {'form': form,} return render(request, template, context) Thanks for your help! -
Django - Conditionnal filtering
I am trying to display the list of the latest articles for each users. My condition: if a user has bookmarked one of his articles, I want to display the latest bookmarked article for this user ; otherwise I want to display the latest article. models.py class Article(models.Model): author = models.ForeignKey(User) bookmarked = models.BooleanField() views.py class ArticlesListView(ListView): context_object_name = 'articles' model = models.Article def get_queryset(self): articles = self.model.objects.order_by('-date')\ .filter(pk__in=Article.objects.values('author__id') .annotate( latest=Case( # Displaying the latest article default=Max('id') ) ) .values('latest')) In this code I am trying to implement a condition using the Case expression to check my condition, but I am stuck how to formulate it... -
how to integrate mysql as primary database and mongodb as secondary database
I am working on a Django project where I need to use both mysql/postgresql as well as mongoDB, one as primary and one as secondary database. How do I configure my db settings to use two databases? I am able to use 1 database as postgresql or mongoDB, but not able to use both. I have provided the code below of what I have tried. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': os.environ.get("DB_HOST", DB_HOST), 'PORT': os.environ.get('DB_PORT', DB_PORT), 'NAME': os.environ.get("DB_NAME", DB_NAME), 'USER': os.environ.get("DB_USER", DB_USER), 'PASSWORD': os.environ.get("DB_PASSWORD", DB_PASSWORD), }, } -
Django Rest Framework - Create and Update Parent-Child relation
I'm trying to use the Django Rest Framework serializers to make API's for my front-end to create / update and delete articles in a store. These articles can have multiple prices (depending on time). So there is a one-to-many relation from article (one) to price (many). I have defined this in models.py: class Article(models.Model): article_id = models.AutoField(primary_key=True, verbose_name="Article ID") article_name = models.CharField(max_length=250, verbose_name="Name") article_order = models.IntegerField(verbose_name="Order") class Price(models.Model): price_id = models.AutoField(primary_key=True, verbose_name="Price ID") article_id = models.ForeignKey(Article, on_delete=models.CASCADE, verbose_name="Article ID", related_name="Prices") price_price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="Price") My serializers.py file looks like this: from rest_framework import serializers from .models import * class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = ('price_price',) class ArticleSerializer(serializers.ModelSerializer): Prices = PriceSerializer(many=True) def create(self, validated_data): prices_data = validated_data.pop('Prices') article = Article.objects.create(**validated_data) for price_data in prices_data: Price.objects.create(article_id=article, **price_data) return article def update(self, instance, validated_data): prices_data = validated_data.pop('Prices') Article.objects.filter(article_id=instance.article_id).update(**validated_data) for price_data in prices_data: Price.objects.get_or_create(article_id=instance, **price_data) return instance class Meta: model = Article fields = '__all__' This works perfectly and I can create a new article-price measurement with this data: (article_order will be used later for ordering the list) {"Prices":[{"price_price":"1"}],"article_name":"Article A","article_order":"1"} Until this point, everything is working as expected. But when I try to update the prices, the Price.objects.get_or_create() statement does … -
Display value of choicefield of the tuple in template django
i have tuple PRICES_DATES_SD_PRICES_CHOICES = (('SD-A', 'Option SD-A'), ('SD-B', 'Option SD-B'), ('SD-C', 'Option SD-C')) and my model like this: class PackagePricesAndDates(models.Model):` prices_SD = models.CharField(max_length=255, choices=PRICES_DATES_SD_PRICES_CHOICES)` in the template when i loop in object_list : {% for pricedate in object_list %} <tr> <td colspan=3 style="border-top:rgba(255, 255, 255, 0.7) solid 1px;padding-top:17px;"> <table class="sub"> <tr> <td style="width:50%">Prices SD</td> <td>""""{{ pricedate.prices_SD }}</td> </tr> <tr> <td>Prices HD</td> <td>""""{{ pricedate.prices_HD }}</td> </tr> </table> </td> </tr> the value of pricedate.prices_SD display the key not the value of tuple (the first value not the second) how can i get the second value ? -
Get Django variable in HTML template with Javascript part
Happy new year to everybody ! I would like to get your help because I'm thinking how I can rewrite a little part from my code. I have a django variable sets in my context and I pick up this variable in my HTML template (especially in my JavaScript part in my HTML template). It works, but it's not a good idea because I would like to set all JS in one JS file and don't have piece of JavaScript in each HTML template. In Django I have : submethods = SubMethod.objects.all() submethods_item = [] for item in submethods: submethods_item.append({'id': item.id, 'text': item.name}) context['submethods_item'] = submethods_item In my HTML template, I have this piece of JavaScript : function get_sub_method_options(keep_cur) { var sel_option = $('select#id_method-group').find("option:selected"); var sel_val = sel_option.val(); if (!sel_val) { $("select#id_method-sub_method").empty(); let all_sub_methods = {{ submethods_item|safe }}; for (var i = 0; i < all_sub_methods.length; i++) { $("select#id_method-sub_method").append('<option value="' + all_sub_methods[i].id + '">' + all_sub_methods[i].text + '</option>'); //here add list of all submethods } return; }; ... } As you can see, I get the Django variable here : let all_sub_methods = {{ submethods_item|safe }}; How I can make the same things, but with a method which let to … -
how to change the row color in dataTable based on the value in jquery
I am using the DataTable in javascript and jquery in order to setup a interactive table. I want to change the row color based on cell value. I tried to use the fnRowCallback function and i tried to use rowCallback function. in both functions are not working and the page is not displaying the table. if i remove these functions the table is displayed and all data are available. $(function(){ var destsData=[ ] var sections={} var theTable = $('#SearchT2chiraTable').DataTable({ language: { search: 'ﺑﺤﺚ : ', lengthMenu:'ﻣﺸﺎﻫﺪﺓ _MENU_ ﺑﻴﺎﻧﺎﺕ', paginate: { first: "اﻻﻭﻝ", previous: "اﻟﺴﺎﺑﻖ", next: "اﻟﺘﺎﻟﻲ", last: "اﻻﺧﻴﺮ" } }, select: 'single' }) var destsTable = $('#DestsTable').DataTable({ "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ if ( aData[2] == "DEFAULT VALUE" ) { $('td', nRow).css('background-color', 'red' ); } else { $('td', nRow).css('background-color', 'white'); } language: { search: 'ﺑﺤﺚ : ', lengthMenu:'ﻣﺸﺎﻫﺪﺓ _MENU_ ﺑﻴﺎﻧﺎﺕ', paginate: { first: "اﻻﻭﻝ", previous: "اﻟﺴﺎﺑﻖ", next: "اﻟﺘﺎﻟﻲ", last: "اﻻﺧﻴﺮ" } }, select: 'single', data: destsData, columns: [ { "data": "destination_id","title":'اﻟﺮﻣﺰ' }, { "data": "te2chira_id_id","title":'ﺭﻣﺰ اﻟﺘﺄﺷﻴﺮﺓ' }, { "data": "opinion", "title": 'اﻻﻗﺘﺮاﺡ' }, { "data": "destination_date","title":'اﻟﺘﺎﺭﻳﺦ' }, { "data": "section","title":'اﻟﻘﻄﻌﺔ' , "render":function(val,type,row,meta){ console.log('the Value is ',val) if (type == 'set'){ console.log('doing here ') row.section = val row.section_display=sections[row.section] row.section_filter=sections[row.section] return }else … -
could not connect to server: Connection refused for postresql from django using docker
I'm using Django 2.x and configuring it using Docker. I'm using postresql database engine. Dockerfile contents are FROM python:3-alpine RUN apk --update add libxml2-dev libxslt-dev libffi-dev gcc musl-dev libgcc curl RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev postgresql-dev RUN apk add --no-cache bash ENV PYTHONUNBUFFERED 1 ENV LC_ALL C.UTF-8 ENV LANG C.UTF-8 RUN set -ex && mkdir /app COPY Pipfile /app COPY Pipfile.lock /app WORKDIR /app RUN pip install pipenv RUN pipenv install --system --deploy ADD . /app/ RUN chmod +x start.sh # Expose port EXPOSE 9010 docker-compose.yml file contains version: '3' services: nginx: image: nginx:alpine container_name: "originor-nginx" ports: - "10080:80" - "10443:43" volumes: - .:/app - ./config/nginx:/etc/nginx/conf.d depends_on: - web networks: - originor_web_network web: build: . container_name: "originor-web" command: ./start.sh volumes: - .:/app ports: - "9010:9010" depends_on: - db networks: - originor_web_network - originor_db_network db: image: postgres:11 container_name: "originor-postgres-schema" volumes: - originor_database:/var/lib/postgresql/data networks: - originor_db_network environment: - POSTGRES_USER=originor_schema_u - POSTGRES_PASSWORD=ADF45sa98SD9q9we8r34& - POSTGRES_DB=originor_schema networks: originor_web_network: driver: bridge originor_db_network: driver: bridge volumes: originor_database: and Django settings.py file has DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'originor_schema', 'USER': 'originor_schema_u', 'PASSWORD': 'ADF45sa98SD9q9we8r34&', 'HOST': 'db', 'PORT': '5432', } } But when I run docker-compose up It gives error as … -
ImproperlyConfigured - Django
Error: ImproperlyConfigured at /acl/ PermissionGroupView is missing a QuerySet. Define PermissionGroupView.model, PermissionGroupView.queryset, or override PermissionGroupView.get_queryset(). Views.py class PermissionGroupView(LoginRequiredMixin, generic.CreateView): template_name = 'acl/acl-dashboard.html' success_url = '/acl/' def get_context_data(self, **kwargs): context = super(PermissionGroupView, self).get_context_data(**kwargs) if self.request.method == 'POST': context['groups'] = GroupForm(self.request.POST) if context['groups'].is_valid(): context['groups'].save() return HttpResponseRedirect(self.get_success_url()) else: context['groups'] = GroupForm() return context Forms.py class GroupForm(forms.ModelForm): class Meta: model = Group fields = '__all__' acl-dashboard.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="col-md-12 grid-margin stretch-card"> <div class="card"> <div class="card-body"> <h4 class="card-title">Enter New Group</h4> <div class="row"> <div class="col-md-8"> <form class="forms-sample" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ groups | crispy}} <button class="btn btn-success mr-2" type="submit">Save</button> </form> </div> </div> </div> </div> </div> {% endblock content %} -
Where to store the .mpd file on django to play on a dash player?
I am trying to build a video player on django. I am using MPEG-DASH for adaptive streaming of the video file. I have chosen a sample video in the beginning. Then, using ffmpeg commands, I have encoded the video into 240p, 360p, 480p and 720p videos. Also have encoded audio separately. Then, using mp4box, I have generated the .mpd file. I have read that mpd files cannot be run from the local file system and need to be hosted on a server. I have a dash player setup as follows: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>player</title> <script src="https://cdn.dashjs.org/latest/dash.all.min.js"></script> <style> video { width: 640px; height: 360px; } </style> </head> <body> <div> <video data-dashjs-player autoplay src="https://dash.akamaized.net/envivio/EnvivioDash3/manifest.mpd" controls></video> </div> </body> </html> The url in the src field is a random manifest file that i used to test the player out. It works fine. Then, on my django project, I have created a media folder which stores the media files uploaded via a form(root included in settings.py). My question is where do i store the video, audio and .mpd file so that i can play them using the html code which resides in the templates folder. I have tried using the … -
Interacting with text in Django for loop
I am working on a Django project where I want to output a text file and apply certain operations like highlighting to the text. My idea was to implement it in such a way that each word can be clicked, for a popup window (or tooltip window) to appear, displaying all the options. {% for Line in File.body %} <div> {% for Token in Line %} {% if not Token.content == None %} <span class="inline token" id="token"> <strong style="color: {{ Token.highlight }};"> {{ Token.content }} </strong> </span> <div id="{{ Token.unique_id }}"> POPUP </br> <button onclick="changeColor()">Highlight</button> </div> <script> tippy('.token', { content: document.getElementById("{{ Token.unique_id }}"), delay: 100, arrow: true, arrowType: 'round', size: 'large', duration: 500, animation: 'scale', allowHTML: true, hideOnClick: true, trigger: "click" }) function changeColor() { var token = document.getElementById("token"); token.style.color="blue;"; } </script> {% endif %} {% if Token.endline %} </br> {% endif %} {% endfor %} </div> {% endfor %} I tried using the tippjs tooltip library (https://atomiks.github.io/tippyjs/), but clicking the highlight button doesn't do anything. If i don't put the javascript part in the loop, nothing happens at all. I am new to django and even newer to javascript, so I'm not sure if this is even the right … -
i need help overriding user registration field in django rest auth package
my custom user model requires the full_name email and password in order to authenticate and the django rest auth displays only fields for user name email and two passwords fields.i was able to override it by declaring my own serializer and it worked. but i get this error saying save() takes 1 positional argument but 2 were given { "username": "", "email": "", "password1": "", "password2": "" } save() takes 1 positional argument but 2 were given Exception Location: C:\Users\zeus\Desktop\alihub-back\env\lib\site-packages\rest_auth\registration\views.py in perform_create, line 73 -
inlineformset_factory Saves only First Row data?
I am working on inlineformset factory all work fine but formset data stores only first value. i am using formset.js file to aad rows. parent model data saved but formset data stored only first row information here is my code forms.py here is my formset code SizeChartFormSet = inlineformset_factory( TailoringProductsMaster, SizeChart, extra=1, fields='__all__', form =SizeChartForm, can_delete=True, widgets={'SizeType': forms.TextInput(attrs={'class':"form-control col-md-7 col-xs-12",}), 'RequiredFabric': forms.TextInput(attrs={'class': "form-control col-md-7 col-xs-12",}), }, ) Views.py here is my view code class TailoringProductsMasterCreateView(CreateView): model = TailoringProductsMaster form_class = TailoringProductsMasterForm success_url = reverse_lazy('home') def get_context_data(self, **kwargs): context = super(TailoringProductsMasterCreateView, self).get_context_data(**kwargs) if self.request.POST: context['operations_form'] = SizeChartFormSet(self.request.POST, self.request.FILES) else: context['operations_form'] = SizeChartFormSet() return context def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) operations_form = SizeChartFormSet(self.request.POST, self.request.FILES) if (form.is_valid() and operations_form.is_valid()): return self.form_valid(form, operations_form) else: return self.form_invalid(form, operations_form) def form_valid(self, form, operations_form): self.object = form.save() operations_form.instance=self.object operations_form.save() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, operations_form): return self.render_to_response( self.get_context_data(form=form, operations_form=operations_form )) html page <tbody> {% if operations_form.errors %} {{ operations_form.errors }} {% endif %} {{ operations_form.non_field_erros }} {% for object in operations_form %} {{ object.id }} <tr id="formset"> <td class="m-ticker">{{ object.SizeType }}</td> <td>{{ object.RequiredFabric }}</td> <td></td> </tr> {% endfor %} </tbody> </table> {{ operations_form.management_form }} -
django using xhr change image from db(sqlite)
I want to load two images from sqlite(db) using xhr, and when click one image than the data will be send to server (asynchronous) and two images will be change to next images from db. now i have no errors but i can't see image on browser. i think json - django - db connection is not correct. i wrote code now only for one image. please teach me survey.html <script type="text/javascript"> var xhr = new XMLHttpRequest(); xhr.onload = function () { {% for wheel in wheels|slice:"1:2" %} xhr.open('GET', '{{ wheel.wheel_sample.url }}', true); var img = new Image(); var response = xhr.responseText; var binary = "" for(i=0;i<response.length;i++){ binary += String.fromCharCode(response.charCodeAt(i) & 0xff); } img.src = 'data:image/jpeg;base64,' + btoa(binary); var canvas = document.getElementById('showImage'); var context = canvas.getContext('2d'); context.drawImage(img,0,0); {% endfor %} } xhr.overrideMimeType('text/plane; charset=x-user-defined'); xhr.send(); </script> <div class="wheels-img-container"> <canvas class="wheel-first" id="showImage" onclick="img1_click();" width="135" height="135"/> <canvas class="wheel-second" id="showImage2" onclick="img2_click();" width="135" height="135"/> </div> views.py def survey(request): json_serializer = serializers.get_serializer("json")() wheels = json_serializer.serialize(Wheel.objects.all(), ensure_ascii=False) return render(request, 'polls/survey.html', {'wheels' : wheels}) models.py image_storage = FileSystemStorage( # Physical file location ROOT location='/media/'.format(settings.MEDIA_ROOT), # Url for file base_url='/media/'.format(settings.MEDIA_URL), ) def image_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/media/<filename> return 'media/{0}'.format(filename) def logo_directory_path(instance, filename): # file will … -
Deploy django2 project with apache and wsgi 500 Error
Good people, I was trying to Deploy my Django 2 project and I was following a tutorial for deploying Django project into my ubuntu server but after my full setup, I get an Internal 500 Error Internal Server Error 500 The server encountered an internal error or misconfiguration and was unable to complete your request. I'm Using Ubuntu 18 and using apache2 Server Here is my apache 000-default.conf <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. ServerName www.search2source.com ServerAdmin webmaster@search2source.com #DocumentRoot /var/www/s2s # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined … -
How to Display Permission Form in Django
I want to create a permission form which will look similar to image.