Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django application with nginx and gunicorn only showing welcome page rest all pages showing 404 error
I tried to deploy a sample django application in amazon ec2 server with the help of nginx and gunicorn. I added proxy pass in nginx. After I run the server and accessing my IP I was able to view the welcome to django page. But when i navigate to some other urls, say admin its shows 404 not found error. How to fi this error -
Django view being called with no kwargs
I have a django.views.generic.DetailView-based class called LocationView that is set up like this: class LocationView(DetailView): model = Location pk_url_kwarg = 'location_id', template_name = 'accounts/locations/view_location.html' And the corresponding url definition: url( r'^accounts/(?P<account_id>\d+)/locations/(?P<location_id>\d+)/$' LocationView.as_view(), name='view_location', ) When I try to access LocationView in my browser, I get the following exception: AttributeError: Generic detail view LocationView must be called with either an object pk or a slug. After much digging, I found out that somewhere along the line, self.pk_url_kwarg gets changed from 'location_id' to ('location_id', ), which causes the view to fail to retrieve the object's pk when it runs self.kwargs.get(self.pk_url_kwarg) because none of the keys in self.kwargs matches the modified pk_url_kwarg value. Why is this happening and how can I fix it? django.VERSION == (1, 11, 'final', 0) -
How to customize horizontal bar in chart.js?
I wanna customize my horizontal bar chart. My chart looks like this. but I want to the chart like this. I use django to get the value and level from the backend. Here bar color different by the person. My settings are: Models.py class Publication(models.Model): person = models.ForeignKey( Person, on_delete=models.CASCADE ) publisher = models.CharField(max_length=300, blank=True) publication_Date = models.CharField(max_length=4, blank=True) def __str__(self): return self.publisher I get value and level from this method: def publication_by_publisher(self): user_id = self.request.user.id query = Person.objects.get(id=10) publisher = query.publication_set.values('publisher').values('publication_Date').annotate(Count('publication_Date')) level, value = [str(x.get('publication_Date')) for x in publisher], [y.get('publication_Date__count') for y in publisher] context = { 'ob': query, 'publisher': publisher, 'level': level, 'value': value } return context chart settings: var ctx = document.getElementById("publisher"); var data = { labels: {{ publisher.level|safe }}, datasets: [{ label: 'Publications by publisher', backgroundColor: [ 'rgb(77, 148, 255)', 'rgb(179, 0, 0)', 'rgb(57, 230, 0)', 'rgb(184, 0, 230)', ], data: {{ publisher.value|safe }}, scaleSteps : 10, }] }; $('#publisher').css('background-color', '#2f3133'); var publisher = new Chart(ctx, { type: 'horizontalBar', data: data, options: { scales: { yAxes: [{ barThickness : 35 }], xAxes: [{ ticks: { beginAtZero: true, suggestedMin: 0, suggestedMax: 10, scaleSteps: 5, }, } ] } } }); How do i get like this? -
How Secure Is Too Secure in OAuth 2.0?
Background: I am currently on a team responsible for building an API for University College, London. I am responsible for building an implementation of OAuth which sits on top of Shibboleth that we can provide to our users. In order to keep it as secure as possible (we are going to be providing student data, so we can't take any risks here), I have implemented a nonce parameter along with a client_secret_proof parameter (the appsecret_proof that is described at sakurity.com/oauth). The difference is that in my implementation a request is made to a nonce endpoint and then this nonce value is concatenated onto the user's token then run through the HMAC algorithm so that the client_secret_proof parameter cannot be replayed. The question here is that my PM thinks this extra protection is unnecessary and just terrible for Developer Experience, but I want to try and make it as difficult as possible to MITM the connection and do as much as I can to prevent the leaking of client secrets by sloppy programming on the part of our student developers. Am I wasting my time in toughening up OAuth here, or is OAuth 2.0 inherently weak when it comes to preventing … -
Exclude a field from Wagtail Page revisions
I have a Wagtail model that extends the base Page model. I am only updating the active field programmatically via daily API import script, so I want it excluded from the CMS entirely. I'm able to exclude the active field from the CMS edit view by not including it in the "content_panels", but a value is still always included in page revisions, which is overriding my imported value. How can I have a field that is excluded from page revisions? class EmployeePage(Page): active = models.BooleanField(blank=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) ... content_panels = [ FieldPanel('first_name'), FieldPanel('last_name'), ] -
How to update a form value and submit the updated form using JS
I have this form: <form name = "myform" method='POST' >{% csrf_token %} <div class="input-field col s6"> {{form.GenerateDate.as_hidden}}</div> <div class="input-field col s6"> {{form.Product.as_hidden}}</div> <div class="input-field col s6"> {{form.Link.as_hidden}}</div> <div class="input-field col s12"> <div class="input-field col s12"> <textarea id="textarea1" class="materialize-textarea" id="usercontent"></textarea> </div> </div> <div class="input-field col s6"> {{form.Status.as_hidden}}</div> <center><input type='submit' value='add' class="waves-effect waves-light btn" ></input></center> </form> I am loading the value in textarea using this script: <script type="text/javascript"> $('#textarea1').val('{{form.UserContent.value}}'); </script> The value is displayed as it is in the DB. But now I want to update this {{form.UserContent.Value}} in the form and using JS then POST it again using the submit button and let django save the new value. But it stores "None" instead! I am using materialize css and django 1.11 Textarea is a must for my use. -
Error when starting Django application from VSCode
I am trying to debug an Django application using VSCode. I made sure the launch.json has the right Django setting, opened the manage.py file, then start debugging session. But the console always shows that the manage.py does not take the argument "runserver" from the launch.json and failed as it cannot find any argument. The code I tried to debug won't be hit until the user click a button to trigger the action, so I am not sure if I can open that file as the starting point when I start the debugging session. When I tried that, I got a bunch of other errors : File "C:\Python34\lib\site-packages\django\conf__init__.py", line 42, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Not sure what is the problem, but I thought this should be a very common scenario that everyone using VSCode+Django will have. Any advise is highly appreciated. Thanks. -
A folder for multiple django apps
I'm trying to change the structure of my project. In fact, I would like to have an apps folder where I can stock all my project's apps. In this case I making a member app into the given folder. If I try to run the project I have this error: django.core.exceptions.ImproperlyConfigured: Cannot import 'member'. Check that 'apps.member.apps.MemberConfig.name' is correct. In my settings.py I configured my INSTALLED_APPS as follow: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.member.apps.MemberConfig', ] Basically, I just want to have the following folder structure: project_folder/ ___ apps/ ___ config/ For the rest of the settings folder here is the GIST More information: Django version : 1.11 Python version: 3.5.2 OS: Ubuntu 16 -
Python-ldap can connect to active directory from python console but not application
I am trying to connect to an active directory using Python-ldap library. I have the following bind code: def bind_connection(): ldap_password = ******* ldap_url = 'ldaps://*******:636 ldap_login = "CN=***, CN=Users, DC=***, DC=local" ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) l = ldap.initialize(ldap_url) l.set_option(ldap.OPT_REFERRALS, 0) l.set_option(ldap.OPT_PROTOCOL_VERSION, 3) l.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND) l.set_option(ldap.OPT_X_TLS_DEMAND, True) l.set_option(ldap.OPT_DEBUG_LEVEL, 255) l.simple_bind_s(ldap_login, ldap_password) return l Importing and running this in the python console works fine. I can search, create users, etc with this bind. Trying to use this class in an Django application returns : SERVER_DOWN: {'info': 'SSLHandshake() failed: misc. bad certificate (-9825)', 'errno': 2, 'desc': "Can't contact LDAP server"} All code is being run from the same development environment. Why would it work in one instance and not the other? -
How to set password to staging env for a django app on Heroku?
I'd like to password-protect my staging environment so it's not accessible to the public. Also, the password protection should not be tied to Django's authentication backend, so that I can test features (e.g. creating an account for user, logging in / out, etc.). How best to achieve that? -
Django admin custom field not showing
I'm trying to put a custom field in django admin, but It's looking like I'm missing something. I tried put code below in admin.py: class PhoneNumberAdmin(admin.ModelAdmin): list_display = ['company', 'carrier', 'area_code', 'number', 'status', 'hello_world'] def hello_world(self): return "<h1>Hello World!</h1>" admin.site.register(PhoneNumber, PhoneNumberAdmin) All fields are shown, except hello_world. What am I missing? -
POST request done successfully but data not saved in database
I'm trying to save form data in database by POST request, request successfully done but data not saved in database. models.py class Image(models.Model): user = models.ForeignKey(User, related_name='images') tagName = models.CharField(max_length=255) instance = models.CharField(max_length=255) forms.py class BuildImageForm(forms.ModelForm): class Meta: fields = ('user', 'tagName', 'instance') model = Image views.py class BuildImage(LoginRequiredMixin, CreateView): form_class = BuildImageForm model = Image template_name = 'images/buildImage.html' success_url = 'user/gui' def get(self, request, *args, **kwargs): objectlist = request.user.instances.all() return render(request, 'images/buildImage.html', {'form': forms.BuildImageForm, 'objectlist': objectlist}) def form_valid(self, form): instance = form.save() instance.user = self.request.user instance.tagName = self.request.tagName instance.instance = str(self.request.instance_name) instance.save() return HttpResponse(status=200) -
Django Angular cors error: access-control-allow-origin not allowed
I have implemented auth in my django app using django-rest-auth. My settings in settings.py: ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', 'corsheaders', 'rest_framework_docs', 'tasks' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] ROOT_URLCONF = 'urls' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = ['*'] SITE_ID = 1 I am logged in from my frontend- I receieved a token with I have stored in my local storage. Now I making a simple GET request like following: getTasks(): Observable<Task[]> { let headers = new Headers({ 'Access-Control-Allow-Origin': '*' }); let options = new RequestOptions({ headers: headers, withCredentials: true }); return this.http.get(this.taskUrl, options) .map(this.extractData) .catch(this.handleError); } But it gives me : Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response. although I am including withCredentials. What am I doing wrong? P.S: If I remove options from POST then there is no error but I get incorrect data because my backend returns data for a specific user. -
Django-multiform with custom form field, input not being passed to view
I am using django-multiform to submit two forms to my class based view (FormView). The two forms consist of multiple custom fields that extend the BooleanField class. The trouble that I'm having is that all fields evaluate to false even if they're checked, and I don't have the same problem if I only submit one form without using the django-multiform. Here is the custom field, it's extends the boolean field to return False if unchecked, and a pre-determined list if checked. class RangeField(forms.BooleanField): def __init__(self, hand=None, *args, **kwargs): super(RangeField, self).__init__(*args, **kwargs) self.hand = hand def to_python(self, value): # Return hand as a list object to python if isinstance(value, six.string_types) and\ value.lower() in ('false', '0'): return super(RangeField, self).to_python(False) elif bool(value): return self.hand else: return super(RangeField, self).to_python(False) Here are my forms class RangeForm(forms.Form): aa = RangeField(required=False, label='AA', hand=[12, 25], widget=forms.CheckboxInput(attrs={ 'class': 'range-form-attr hidden'})) aks = RangeField(required=False, label='AKs', hand=[25, 24], widget=forms.CheckboxInput(attrs={ 'class': 'range-form-attr hidden'})) class FlopForm(forms.Form): twoc = RangeField(required=False, label='2c', hand=[0], widget=forms.CheckboxInput(attrs={ 'class': 'range-form-attr hidden'})) threec = RangeField(required=False, label='3c', hand=[1], widget=forms.CheckboxInput(attrs={ 'class': 'range-form-attr hidden'})) class RangeFlopForm(MultiForm): base_forms = OrderedDict([('range_form', RangeForm), ('flop_form', FlopForm)]) Here is my view, it does nothing but print the input in the server so I can see what's happening. class … -
Django-rest saving model against a specific user
I have a model which has user as a foreign key: class Task(models.Model): user = models.ForeignKey(User) what_task = models.CharField(max_length=100, ) #This helps to print in admin interface def __str__(self): return u"%s" % (self.what_task) It's serializer: class TaskSerializer(serializers.ModelSerializer): steps = StepSerializer(many=True) class Meta: model = Task fields = '__all__' def create(self, validated_data): steps_data = validated_data.pop('steps') task = Task.objects.create(**validated_data) for step_data in steps_data: Step.objects.create(task=task, **step_data) return task And in my view I have a function that handles GET and POST request. GET is correct it returns me all the tasks of a specific user-I use request.user.id for it. I am not sure about my POST, how can I save task against a specific user in this case: @api_view(['GET', 'POST']) def task_list(request): """ List all tasks, or create a new task. """ if request.method == 'GET': tasks = Task.objects.filter(user=request.user.id) serializer = TaskSerializer(tasks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = TaskSerializer(data=request.data) print(request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) Where I must make change, in serializer or in view? -
Django prefetch_related outputs None
I'm new to Django. I am making a simple store. Currently I am working on the Order section. Every Order has Order Items inside it. Every order item has some values and a product id. What I am trying to display on the index.html, is the orders and its items inside it. However order.items always outputs order.OrderItem.None views.py class IndexView(generic.ListView): template_name = 'order/index.html' context_object_name = 'all_orders' def get_queryset(self): return Order.objects.all().prefetch_related('items') def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) return context views.py # Create your models here. class Order(models.Model): user = models.ForeignKey(User, related_name='orders') created_at = models.DateTimeField(auto_now_add=True, null=True) #order_products = models.ManyToManyField(OrderProduct) #def __str__(self): # return self.id #def __str__(self): # return self.id class OrderItem(models.Model): product = models.ForeignKey(Product) order = models.ForeignKey(Order, related_name='items') #order = models.ForeignKey(Order, related_name='order_products', on_delete=models.CASCADE, null=True) item_name = models.CharField(max_length=255, null=True, blank=True) item_price_in_usd = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) def __str__(self): return self.product.name index.html {% for order in all_orders %} <tr> <td>{{ order}}</td> <td>{{ order.created_at}}</td> <td>{{ order.items}}</td> </tr> {% endfor %} -
The view didn't didn't return an HttpResponse object. It returned None instead
Here is my views.py views.py def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username = username , password = password) if user: if user.is_active: login(request , user) return HttpResponseRedirect('/zdorovo/') else: return HttpResponse('You dont have an account with us') else: print "Invalid Login Details: {0} , {1}".format(username , password) return HttpResponse('Invalid Login Details ') else: render(request , 'zdorovo/login.html' , {}) authenticate , login , HttpResponse , HttpResponseRedirect have been imported correctly. I also took care of Indentation , so the error is not raising from that end. Please help me understand the error. P.S.:- Update me if you need other scripts from my end. -
Django Custom User Registration
I want to create a Django webapp that has a Custom User Registration Model , i.e, a UserProfile Attached with the User Model and a Custom Template with User Registration form. What are the Simple Steps to Create the Model and the template and the registration form so that i can have my webapp working ?? -
Django Error: 'Reverse for 'guestlist' with arguments '('',)' not found.'
I'll start off by saying that I know that this question comes up a lot, but I wasn't able to find a solution in other topics. I'm getting this error while trying to load a page. The relevant views: def index(request): all_lists = GuestList.objects.all() guest_list = GuestList() for glist in all_lists: guest_list = glist return render(request, 'guestlist/base.html', {'guest_list': guest_list}) def guestlist(request, list_id): g_list = get_object_or_404(GuestList, pk=list_id) return render(request, 'guestlist/guestlist.html', {'g_list': g_list}) guestlist/urls.py: app_name = 'guestlist' urlpatterns = [ # /guestlist/ url(r'^$', views.index, name='index'), # /guestlist/#/ url(r'^(?P<list_id>[0-9]+)/$', views.guestlist, name='guestlist'), # /guestlist/#/isclose/ url(r'^(?P<list_id>[0-9]+)/isclose/$', views.isclose, name='isclose'), ] The HTML fragment that the error occurs at: <li class="active"> <a href="{% url 'guestlist:guestlist' guest_list.id %}"> <span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span>&nbsp; Guest List </a> </li> Everything seems to be in order. The id is passed and it gets to the function 'guestlist()' like it should but i still get the error. -
Django reverse and redirect after ajax request returns django.urls.exceptions.NoReverseMatch
I call a specific url from and ajax function which will calls the respective view function. In view function I want to redirect the page by calling another view (because I can't render after ajax request). Here are my urls: urlpatterns = [ url(r'^$', views.search, name='search'), url(r'^search_result/.+$', views.search_result, name='search_result'), url(r'^new_search_result/$', views.new_search_result, kwargs={'selected': '', 'keyword': ''}, name='new_search_result') ] And here is the search_result view: @csrf_exempt def search_result(request): keyword = request.POST.get('keyword') selected = request.POST.get('selected') url = reverse('new_search_result', kwargs={'keyword': keyword, 'selected': selected}) return HttpResponseRedirect(url) # return render(request, 'SearchEngine/search_result.html', {'all_results': result}) And here is the new_search_result view: def new_search_result(request, selected={}, keyword=''): # code blocks But in consul I get this error: django.urls.exceptions.NoReverseMatch: Reverse for 'new_search_result' with keyword arguments '{'selected': '{"PANTHER":"ftp.pantherdb.org","Pasteur Insitute":"ftp.pasteur.fr","Rat Genome Database":"ftp.rgd.mcw.edu"}', 'keyword': 'dfasdf'}' not found. 1 pattern(s) tried: ['searchengine/new_search_result/$'] [22/Jul/2017 12:52:12] "POST /searchengine/search_result/dfasdf HTTP/1.1" 500 16814 -
Force user for small letters input in django forms
How can I force user for a formated input name.extention Two formats I need to implement in my forms: User can put only small letters ( Not Capital letters allowed ) Need for tagName field For another field, User needs to put filename.extentio like ( server.js )Need for filename field How can I achieve these two scenarios in my Django forms OR Templates forms.py from django import forms class BuildImageForm(forms.Form): instances = forms.CharField(max_length=255) tagName = forms.CharField(max_length=255) buildImage.html <div class="form-group"> <span class="col-md-1 col-md-offset-2 text-center"><label for="package">Docker Image Tag Name:</label></span> <div class="col-md-8"> <input type="text" name="tagName" id="tagName" placeholder="e.g node_image/istiogui" class="form-control" required> /div> <div class="col-md-8"> <input type="text" name="filename" id="fileName" placeholder="e.g server.js" class="form-control" required> /div> </div> -
In Django, how to render both JSON data with api and info from context dictionary
In Django, I want to render a page that includes a Chart js chart that relies on data from my database. I believe I need to implement an API for this. The same page with the chart will contain other info from the database that I think is rendered with a context dictionary and {{ variable }}. I know how to do one or the the other, but not both on the same page. Here is what I have so far. In views.py: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.views import generic from django.views.generic import View from .models import Article from rest_framework.views import APIView from rest_framework.response import Response class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): articles = Article.objects.all() correlationlist = [] nocorrelationlist = [] for corr in articles: if corr.correlation_type == "Correlation": correlationlist.append(1) nocorrelationlist.append(0) elif corr.correlation_type == "No Correlation": correlationlist.append(0) nocorrelationlist.append(1) else: pass correlation_items = correlationlist nocorrelation_items = nocorrelationlist data = { "correlation_items": correlation_items, "nocorrelation_items": nocorrelation_items, } return Response(data) The Javascript I have on the page where the chart appears is: $(document).ready(function(){ var endpoint = 'api/chart/data/' var defaultData1 = [] var defaultData2 = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ … -
Override foreignkey fields to textarea in Django
i'm have a model: @python_2_unicode_compatible class TypologyItem(Base): ... action = models.ForeignKey( Action, null=True, on_delete=models.CASCADE, verbose_name=_('action')) subject = models.ForeignKey( Subject, null=True, on_delete=models.CASCADE, verbose_name=_('subject')) brand = models.ForeignKey( Brand, null=True, on_delete=models.CASCADE, verbose_name=_('brand')) ... def save(self, *args, **kwargs): if not self.id: self.name ='{} {} {}'.format( self.action.name, self.subject.name, self.brand.name ) self.slug = slugify(self.name, allow_unicode=True) super(TypologyItem, self).save(*args, **kwargs) def __str__(self): return self.name And it is necessary, for convenience, to make a form in which each field corresponding to the related model is a Textarea. The data entered in these fields should be parsed line by line, and for each of the lines you need to create an instance of the corresponding model, and only then create the number of objects represented by this form equal to the multiplied number of each Textarea field. That is, if action1, action2, action3 was entered in the action field, subject1, subject2, subject3 was entered in the subject field, and in the brand field, respectively, brand1, brand2, brand3, then the output should look something like this: <Typology: Action1 subject1 brand1>, <Typology: action2 subject1 brand1>, <Typology: action3 subject1 brand1>, ... <Typology: action3 subject3 brand3>. Initially, I thought about the modelForm and did try to do something like this: class TypologyForm(forms.ModelForm): class Meta: … -
Handling GET and POST for a complex Django app using REST Framework
I have a django application that consists of the following models: class Subject(models.Model): subject_id=models.CharField(max_length=20,primary_key=True) subject_name=models.CharField(max_length=20) class Chapter(models.Model): chapter_id=models.CharField(max_length=20,primary_key=True) chapter_name=models.CharField(max_length=20) subject=models.ManyToManyField(Subject) class Question(models.Model): question_id=models.CharField(max_length=20,primary_key=True) question_value=models.CharField(max_length=255) chapter=models.ManyToManyField(Chapter) grades=models.ManyToManyField(Grades) class Grades(models.Model): grade_id=models.CharField(max_length=20) grade_type=models.CharField(max_length=20) self_grade=models.BooleanField(default=True) class Rating(models.Model): subject=models.ForeignKey(Subject) chapter=models.ForeignKey(Chapter) question=models.ForeignKey(Question) class Data(models.Model): rating=models.ForeignKey(Rating) grade=models.ForeignKey(Grades) value=models.TextField(blank=True,null=True) Subject > Chapter > Question > Grades Rating > Data This is a schema for an exam paper. And the grades are specific to students. As it is apparent form the models, Subject contains chapter, Chapter consists of Questions. Each question can have multiple grades. All the values for the grades are stored in the Rating table which in turn is connected to the Data table using foreign key. I am using django rest framework for creating the APIs. Now for fetching I have to hit the Rating Table to get the schema as well as the data. For updating the fields my json is like this: { "subject_id":"S01","chapter_id":"C01", "question_id":"Q01","grade_id":"G01", "value":"This is my answer" } My main queries are: 1.Initially if the user has not completed the form, then the ratings will not have all the grades and questions. How do I make sure to fetch the whole schema with current values. I was thinking I could do something … -
Serve media files in Django as seekable (with HTTP PartialResponse)
I know that it will be easier to serve these video files with another server like Apache, but I can't use it now. I have some uploaded videos in the media folder using Django (using those FileField models). Now, I have set up a way to stream those videos, but the problem is, the video is not seeking. This can be fixed by implementing some sort of Streaming Response (maybe this, but I am unsure and don't know how to do.) that implements HTTP PARTIAL RESPONSE. Any way to implement this? I'm using media files as specified here (see the MEDIA_ROOT, MEDIA_URL parts.) My settings.py - MEDIA_ROOT = os.path.join(BASE_DIR, "media/") MEDIA_URL = "media/" ... 'context_processors': [ 'django.template.context_processors.media', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ] My urls.py - urlpatterns = [...] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)