Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get video duration in django
i would like to get video duration of video stored in database using django i have all video information title url pk def post(self, request,pk): instance = Video.objects.get(pk=pk) form = PhotoForm(self.request.POST, self.request.FILES,instance=instance) video_type = str(self.request.FILES.dict()["file"])[-4:] if instance.section.course.teacher.user == request.user and form.is_valid() and video_type == ".mp4": video_section = form.save() data = {'is_valid': True, 'name': video_section.file.name , 'url': video_section.file.url,"pk":video_section.pk} else: data = {'is_valid': False} return JsonResponse(data) -
Django and checkboxes
I've got some boolean fields on a model inside of my app. They default to false and I want to write a function that toggles them between true and false. Then on my template, I want that function to operate based on a checkbox. Then allow the checkbox to show checked if true and un checked if false. I'm just not sure should I be doing this with a URL and a view or is this a form? Here's what I've got so far: models.py class CarrierCompany(models.Model): rgn = models.BooleanField(default=False) van = models.BooleanField(default=False) power_only = models.BooleanField(default=False) step_deck = models.BooleanField(default=False) flatbed = models.BooleanField(default=False) reefer = models.BooleanField(default=False) hotshot = models.BooleanField(default=False) specialized = models.BooleanField(default=False) def rgn_equipment(self): if self.rgn == False: self.rgn = True else: self.rgn = False self.save() views.py def rgn_equipment_toggle(request, pk): carrier_company = get_object_or_404(CarrierCompany, pk=pk) carrier_company.rgn_equipment() return redirect('accounts:carrier_company_detail', pk=pk) urls.py urlpatterns = [ url(r'rgn_equipment_toggle/(?P<pk>\d+)/$', rgn_equipment_toggle, name='rgn_equipment_toggle'), ] template <div class="row"> <div class="col-md-4 col-xs-12"> <div class="x_panel tile fixed_height_235"> <div class="x_title"> <h3>Equipment Type <input type="checkbox" data-target="{% url 'accounts:rgn_equipment_toggle' pk=carriercompany.pk %}" /> </a> </h3> </div> <div class="x_content"> {{ carriercompany.rgn }} </div> <script type="text/javascript"> $(function(){ $('input[type="checkbox"]').change(function(){ var item = $(this); if (item.is(":checked")) { window.location.href = item.data("target") } }); }); </script> </div> </div> </div> I can get … -
How to sort the results of filtering with django-filter in a ListAPIView
I have a ListAPIView that uses the DjangoFilterBackend to filter rooms based on url parameters. The code below does this just fine. Now, I would like to sort the results based on a score calculated from other attributes of the Room object, another url parameter, and possibly what we know about the user issuing the request. The function itself does not matter. How can I sort the results after applying the filter I already have? If I were to do the filtering myself, I suppose I could do the filtering, calculate the score and sort the results in the get_queryset but I do not know how to do this after the filtering with django-filter. Example query For example, I would do this query to filter by price lower than 100. The other_field value would be used to compute the score for sorting: http://localhost:8000/api/search/rooms?price=100&other_field=200 Code class RoomFilter(filters.FilterSet): price = filters.NumberFilter(name="price", lookup_expr='lte') features = filters.ModelMultipleChoiceFilter( name="features", conjoined=True, queryset=Features.objects.all() ) class Meta: model = Room fields = ['price', 'features'] class RoomSearchView(generics.ListAPIView): queryset = Room.objects.all() serializer_class = RoomSearchSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = RoomFilter -
Django doesn't recognize DEBUG = False
I'm trying to develop 404 and 500 error custom templates for my Django project. When I change DEBUT to False, Django always returns me: You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. What am I doing wrong? Why Django does not recognize the variable? -
Django Formsets deletion is failing
I'm rendering manually form in formset, because I need to add data attributes in HTML for the fields. <input type="file" id="id_publication_image-0-image" name="publication_image-0-image" data-upload-file/> <input name="publication_image-0-id" value="12" type="hidden"> <input name="publication_image-0-DELETE" type="checkbox" data-upload-state /> Behavior Adding and Updating files is working with no issues. Deleting files is not working. I used a debugger to check why, so the POST is passing the data: and in the form changed_data = <class 'list'>: ['DELETE'] in the formset: self.can_delete = True self._should_delete_form(form) = False In Django code is defined this way: DELETION_FIELD_NAME = 'DELETE' def _should_delete_form(self, form): """Return whether or not the form was marked for deletion.""" return form.cleaned_data.get(DELETION_FIELD_NAME, False) and it fails. I don't understand why, because is appearing in form. -
How get param from URL after # in python
How can I get param from URL after #? Example: http://localhost/addAccount/#code=qwerty I tried use url = request.path and url.spit('/') but it isn't working becasuse request.path don't read string after # in url. -
Instance from post_save django signal
Before asking my question, I would like to give a small example. Assuming I have the following code: #models.py class A(models.Model): #something class B(A): #something class C(A): #something class D(models.Model): field = models.ForeignKey(A) Let's assume I have a post_save signal: @receiver(post_save, sender=D) def my_signal(instance, **kwargs): #do signal stuff and moreover, I have D as an Inline in the AdminModel for class B and C. According to the django documentation, the instance is the actual instance being saved. I am technically saving B or C in the admin panel, what would then the instance be? -
Django expression DateTime and Integer seconds
I want to annotate the difference between a DateTime and an Integer (seconds) on a legacy MySQL DB (so there is no chance to change the IntegerField to a DurationField) with Django 1.11 Report(Model): # time the report was sent time = DateTimeField() # seconds since the last reboot uptime = IntegerField() MyModel.objects.all().annotate( last_report=Max(time), last_reboot=ExpressionWrapper(F('last_report') - F('uptime')), output_field=DateTimeField()) ) This would work, if uptime was a DurationField(), but won't work with an integer. So I tried converting the seconds to a timedelta last_reboot=ExpressionWrapper( F('last_report') - F(timezone.timedelta(seconds=1)*F('uptime')), output_field=DateTimeField() ) which gives me AttributeError at ... 'CombinedExpression' object has no attribute 'split' Is there a way to calculate with a DateTimeField() and a IntegerField() in a query expression? -
Wagtail 2.0 site using WSGIDaemonProcess and virualenv will not run
Environment: Ubuntu 16.04 running on a Windows 10-hosted Vagrant box with port 8080 on the client mapped to port 80 on Ubuntu. Apache 2.4.18. This is my typical setup that works for other sites. Problem: I've been trying to migrate a Wagtail 1.13 site to 2.0 (within a virtualenv) without success, so I've created a fresh Wagtail example site to try to get it running and still can't get the site to come up (the 1.13 site was running fine). I first created a "Wagtail Sample" folder and then used pipenv --python 3.5 to create a virtualenv based upon Python 3.5. This placed a Pipfile in the "Wagtail Sample" folder and created the virtualenv at /root/.local/share/virtualenvs/Wagtail_Sample-Knqp_dtZ. I then installed wagtail (and psycopg2) using pipenv install. If I activate the virtualenv using pipenv shell and type python --version I get: Python 3.5.2, so I know that the virtualenv is set up correctly. The Django version within the virtualenv is 2.0.2 and the Wagtail version is 2.0.0. I am trying to run in daemon mode in order to be able to specify the virtualenv. Here is my VirtualHost file: <VirtualHost *:80> ServerAdmin me@me.com ServerName dev.wagtailsample.com ErrorLog ${APACHE_LOG_DIR}/wagtail_sample-error.log CustomLog ${APACHE_LOG_DIR}/wagtail_sample-access.log combined LogLevel info … -
best way to check if django can see method handler?
I am looking for a way to peel back the onion on a put request I am working on. For the sake of clarity, here is another question of mine that is currently open to get you up to speed on what is going on. Basicly I am sending a valid put request to a class which has a put acceptance handler but I am still geting method not allowed. put method not working on RetrieveUpdateDestroyAPIView Django Rest Framework Angular so now I am trying to figure out what is going on. Why isn't Django recognizing the put method? I am assuming this is the case, because The url is correct. the client side request is correct. The framework and the class I am inheriting from is correct. So I really don't know how to fix this. -
DRF serializer depth makes fields ignored on create
(project is available on github with that problem) For some reason serializer's depth option makes fields ignored on create. Serializer: class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('question', 'body',) depth = 1 View: class AnswerList(ListCreateAPIView): queryset = Answer.objects.all() serializer_class = AnswerSerializer When I try to create an answer with depth = 1 I get NOT NULL constraint failed: forum_answer.question_id, but when I comment out depth = 1 everything works. But of course I don't get a full Question object, only pk of it. -
Redirect from second view
Got a real problem here. I have got 2 views in backend and really need to redirect FROM second view Views like this: def first_function(request): """ Here is some stuff """ second_function(request) return render(request, 'first.html', context) def second_function(request) """ Check here something """ if ok: return else: return redirect('/') # this redirect does not work -
Django CreateView's form not re-rendering as expected
I'm trying to make a form in which a certain field, title, is pre-populated when another field, checkin_type, is selected from a drop-down menu. I'm trying to follow the approach outlined in Django: How to pre-populate FormView with dynamic (non-model) data? and have put a 'proof-of-concept' project here: https://github.com/khpeek/django-dynamic-form. In the view's template, I've made it such that when the checkin_type field has a .change(), an AJAX POST request is sent with the id of the selected check-in type: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <script> $(document).ready(function(){ var csrftoken = Cookies.get('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $(".auto-submit").change(function() { $.post({ url: "{% url 'checkin-create' %}", data: {id: $(".auto-submit option:selected").val()} }) }); }); </script> <form action="" method="post">{% csrf_token %} {% for field in form %} <div class="{% if field.name == 'checkin_type' %}auto-submit{% endif %}"> {{ field.errors }} {{ field.label_tag }} {{ field }} </div> {% endfor %} <input type="submit" value="Send message" /> </form> In views.py, I've tried the following: import logging import sys from django.views import generic from .models import CheckIn, CheckInType from django.http import HttpResponse def get_stdout_logger(name, level): … -
Django query exclude runtime
I'm wondering about SQL query performance. Let's say I'm doing the following query: MyModel.objects.exclude(indexed_field=list_of_field_values) list_of_field_values isn't a queryset -- it's an actual list. How will the performance change as list_of_field_values grows? What happens when it goes from 1000 to 2000 elements, for example? -
modelform id field being passed as REQUIRED field
The site I am building uses modelforms several times. Until now validation of the forms using is_valid has gone smoothly. Now, a new model I've created has decided that the id field (which is generated automatically for model forms) is a required field. I am rendering the fields manually in the template and am not rendering the id field. This has not been a problem with any of my modelforms until now, since it has never been registered as a required field. With this problematic model however, since I am not rendering the field, it gets returned empty and so doesn't pass validation. I realize that I could solve the problem by rendering the field, but I'd like to understand whats going on here. Why has it decided, seemingly randomly, that the id is required? Here is the problematic model: class Item(models.Model): budgetcatagory=models.ForeignKey(BudgetCatagory, on_delete=models.CASCADE) name=models.CharField(max_length=30) enName=models.CharField(max_length=30, default ="") detail=models.CharField(max_length=30) layout=models.CharField(max_length=30, default="normal") unit=models.CharField(max_length=30) unit_description=models.CharField(max_length=30, default="") unit_price=models.IntegerField(default=0) QTY=models.IntegerField(default=0) param1=models.CharField(max_length=30, blank=True) param2=models.CharField(max_length=30, blank=True) param3=models.CharField(max_length=30, blank=True) param4=models.IntegerField(default=0) parent=models.CharField(max_length=30, default = "0") cost_ave=models.IntegerField(default=0, blank=True) cost_min=models.IntegerField(default=0, blank=True) cost_max=models.IntegerField(default=0, blank=True) total_cost=models.IntegerField(default=0) choiceList=( ('choice1',param1), ('choice2',param2), ) ItemChoice=models.CharField( max_length=10, choices=choiceList, default='', ) objects=ItemManager() def __str__(self): return self.name Here is how I am populating the form before sending to template: … -
super(type, obj): obj must be an instance or subtype of type Django
I am making a registration form for users to signup using Django 1.8 and python 3.5 I have created a User(Extending User Model Using a Custom Model Extending AbstractUser)(ie I wanted to add custom fields to the default django's Users table like bio, date of birth etc) When I try to enter username and password I get an error TypeError at /signup/ This is my mainpage/models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) This is my signup/forms.py from django import forms from mainpage.models import User from django import forms from django.contrib.auth.forms import UserCreationForm class allusers1(forms.Form): username1=forms.CharField(label = "Username")#="USSSERRNAME",max_length=40) password1=forms.CharField(label="passwordwa",max_length=40) class Meta: model=User fields=( 'username', 'password', ) def save(self,commit=True): user=super(User,self).save(commit=False) user.username=self.cleaned_data['username1'] user.password=self.cleaned_data['password1'] if commit: user.save() return user this is signup/views.py from django.shortcuts import render from .forms import allusers1 def signup(request): form1=allusers1(request.POST or None) if form1.is_valid(): form1.save() context = { "form1": form1, } return render(request, "signup.html",context) Traceback Environment: Request Method: POST Request URL: http://localhost:8000/signup/ Django Version: 1.8 Python Version: 3.5.4 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainpage', 'signup', 'login', 'currency', 'rest_framework', 'corsheaders') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File … -
In Django Mezzanine, how to I prevent caching on a page_processor?
With the following I created a Page that handles a post request. Mezzanine 4.2.3 Django 1.10.8 Python 2.7.10 PostgreSQL 9.6.3 Darwin 17.4.0 Here is my models.py for the Page. from mezzanine.pages.models import Page from django.db import models class MyCustomPage(Page): a_field = models.CharField(max_length=100) Here is my page_processors.py for the Page. from django.views.decorators.cache import never_cache from django.contrib import messages from .forms import MyCustomForm from .utils import do_something_specific from .models import MyCustomPage from mezzanine.pages.page_processors import processor_for from django.shortcuts import redirect @never_cache @processor_for(MyCustomPage) def my_custom_page(request, page): if request.method == "POST": form = MyCustomForm(request.POST) if form.is_valid(): do_something_specific(form.cleaned_data) messages.success(request, "Your post request was a success!") return redirect(page.get_absolute_url()) else: return { "form": form, } else: # is GET request return { "form": MyCustomForm(), } The @never_cache decorator seems to prevent the python code from being cached, however the template is being cached. Meaning, if I post to the url, it will call do_something_specific(form.cleaned_data) and that will happen, and it even seems to set the messages.success. But then when I do a regular get request the next time on the page, it will use the cached template and the messages.success message will be there. For what it is worth, I am using redis as my caching backend. I … -
'User' object has no attribute 'is_valid' Django
I am making a registration form for users to signup using Django 1.8 and python 3.5 I have created a User(Extending User Model Using a Custom Model Extending AbstractUser)(ie I wanted to add custom fields to the default django's Users table like bio, date of birth etc) This is my mainpage/models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) this is signup/view.py from django.shortcuts import render from mainpage.models import User def signup(request): form1=User(request.POST or None) if form1.is_valid(): form1.save() context = { "form1": form1, } return render(request, "signup.html",context) Traceback Environment: Request Method: GET Request URL: http://localhost:8000/signup/ Django Version: 1.8 Python Version: 3.5.4 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainpage', 'signup', 'login', 'currency', 'rest_framework', 'corsheaders') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\vaibhav2\PycharmProjects\MajorProject\src\signup\views.py" in signup 12. if form1.is_valid(): Exception Type: AttributeError at /signup/ Exception Value: 'User' object has no attribute 'is_valid' SOME ADDITIONAL INFO I am refering to this blog for creating AbstractUser https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#abstractuser -
Lost Date and DateTime admin widgets (pickers) after Django upgrade (from 1.6 to 2.0)
I am trying to upgrade an old Django version 1.6 to the latest 2.0 (2.0.2) and on the Admin pages the old version shows (seemingly by default) a Date and Time picker for attributes of DateField and DateTimeFields in the models. For instance, let's take a model like this: class Order(BaseModel): preferred_date = DateField(null=True, blank=True) submit_date = DateTimeField(null=True, blank=True) In the old Django 1.6, it looks like this: A DateField model's field shows a little calendar icon that, when clicked, allows the user to choose a date, and a DateTimeField shows both the calendar icon (for the Date part) and a clock icon to choose a particular time (for the Time part). However, after upgrading to Django 2.0, these date and time pickers seem to have disappeared and I've been left with what it looks like a plain input text. I know I could always specify the widget to use by specifying the ModelForm (as explained in this other S.O. answer) and so something like class OrderForm(forms.ModelForm): preferred_date = forms.DateField(widget=AdminDateWidget()) but I was wondering if there's a more generic (and less intrusive than having to declare a Form for each model that has Date/Datetime fields). Also, if this is a … -
How to configure travis.yml to have coverage report in codeclimate for a Django project ?
I have troubles configuring my .travis.yml file to send coverage report to CodeClimate. I'm working on a Django project. Here is my .travis.yml file: language: python python: - "3.5" services: - postgresql # setup environment env: - DJANGO_VERSION=2.0.1 install: - pip install -r requirements.txt - pip install codeclimate-test-reporter script: - export DJANGO_SECRETKEY=secret - coverage run --source=my_project manage.py test - python manage.py test after_script: - codeclimate-test-reporter --file .coverage I've added an environment variable CODECLIMATE_REPO_TOKEN in my travis settings with the TEST REPORTER ID from CodeClimate. And everything seems to go well on Travis side : The command "export DJANGO_SECRETKEY=secret" exited with 0. 2.47s$ coverage run --source=my_project manage.py test ... ---------------------------------------------------------------------- Ran 3 tests in 0.439s OK Creating test database for alias 'default'... System check identified no issues (0 silenced). Destroying test database for alias 'default'... The command "coverage run --source=my_project manage.py test" exited with 0. 1.82s$ python manage.py test ... ---------------------------------------------------------------------- Ran 3 tests in 0.400s OK Creating test database for alias 'default'... System check identified no issues (0 silenced). Destroying test database for alias 'default'... The command "python manage.py test" exited with 0. after_script 0.31s$ codeclimate-test-reporter --file .coverage Done. Your build exited with 0. However, I can't see the test … -
Django REST ViewSet ordering for Null-able columns
Consider a table Person: | name | wealth | |------| ------ | |Abby | 12 | |Ben | Null | |Carl | 5 | |Diane | Null | We want to sort the rows by wealth, descending, i.e. to get (Abby, Carl, Ben, Diane), but Django's order_by function sorts them by Null first: class PersonViewSet(serializers.ModelViewSet): serializer_class = PersonSerializer queryset = Person.objects.all().order_by('-wealth) gives (Ben, Diane, Abby, Carl), i.e. it first lists the Null values then sorts by wealth. I tried redefining the get_queryset method: class PersonViewSet(serializers.ModelViewSet): serializer_class = PersonSerializer def get_queryset(): invalid_entries = Person.objects.filter(wealth=None) valid_entries = Person.objects.all().difference(invalid_entries).order_by('-wealth') return valid_entries.union(invalid_entries) This does return the desired behavior, (Abby, Carl, Ben, Diane) but messes up the detail view, and gives the get() returned multiple values error. Is there a way to get the desired behavior, by customizing the ordering functionality, or modifying get_queryset only for the list view? -
put method not working on RetrieveUpdateDestroyAPIView Django Rest Framework Angular
I am attempting to make a put request in django rest framework. My view is inheriting from the RetrieveUpdateDestroyAPIView class. I am using angular on the front end django rest on the back end. Here is the error: Failed to load resource: the server responded with a status of 405 (Method Not Allowed) ERROR detail:"Method "PUT" not allowed." Here is the full implementation of the put request from angular side to django rest editcity(index){ this.oldcityname = this.cities[index].city; const payload = { citypk: this.cities[index].pk, cityname: this.editcityform.form.value.editcityinput }; this.suitsettingsservice.editcity(payload, payload.citypk) .subscribe( (req: any)=>{ this.cities[index].city = req.city; this.editcitysucess = true; // will have changed this.newcityname = this.cities[index].city; } ); } the service being called editcity(body, pk){ const url = suitsettingscity + '/' + pk; return this.http.put(url, body); the url being mapped django side: url(r'^city/(?P<pk>[0-9]+)',SearchCityDetail.as_view()) the view class class SearchCityDetail(RetrieveUpdateDestroyAPIView): queryset = SearchCity.objects.all() serializer_class = SearchCitySerializer the RetrieveUPdateDestoryAPIView documentation: http://www.django-rest-framework.org/api-guide/generic-views/#updatemodelmixin RetrieveUpdateDestroyAPIView Used for read-write-delete endpoints to represent a single model instance. Provides get, put, patch and delete method handlers. Extends: GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin The RetrieveUpdateDestroyAPIView source code: class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, GenericAPIView): """ Concrete view for retrieving, updating or deleting a model instance. """ def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) … -
Django-CMS CMSPlugin doesn't trigger pre_save/post_save signals
Using Django 1.10, django-cms 3.42, I have this model (simplified for this question): from django.db import models from cms.models.fields import PlaceholderField from cms.models import CMSPlugin class NewsItem(models.Model): title=models.CharField(_('title'), max_length=200), content = PlaceholderField('news_content') I need to do some extra processing as soon as the model field 'content' is saved, and apparently the best way to check for that is to monitor the CMSPlugin model. So I look for saves using from django.db.models.signals.post_save like this: @receiver(post_save, sender=CMSPlugin) def test(sender, **kwargs): logger.info("Plugin saved.") Now, the problem is that post_save is not triggered as I thought it would. With normal CMS Pages, I noticed that post_save is only triggered when a Page is published, but there is no apparent way to publish a placeholder when used outside the CMS. The closest similar case I've found is Updating indexes on placeholderfields in real time with django/haystack/solr, but the suggested solution doesn't work. How could I go about resolving this? Thank you! -
Prefix all table names Django 1.11
I have a database that cannot use multiple schemas due to some legacy software on it, and it needs to share space with a new Django application. Django's built-in tables names conflict with some of the existing ones, so I wanted to add a prefix to all of the table names. I found various stackoverflow posts such as How to rename all django's default auth, permission,groups tables? Django Database Prefix and they mention a few plugins such as https://github.com/benslavin/django-db-prefix and https://pypi.python.org/pypi/django-table-prefix/0.0.5 - but all of these are ancient, and don't work from Django 1.8 and on (I'm running 1.11) Is there any solution for Django 1.11? I've looked everywhere, but the existing plugins don't work, and every feature request submitted to Django itself has been closed as wontfix. I tried updating the plugins to 1.11, but they are honestly way over my head. In case it matters, the database is Oracle. -
Creating RESTful API for Uploading and listing using Django and the Django Rest Framework
Create a small RESTful API that allows uploading and listing Android applications. The API should be built with Django and the Django Rest Framework. When uploading an application you should just provide the file and the API should be able to extract the “package name” and “package version code” from the apk file. strong text GET /api/applications/ [ { `"application": "/media/525db2b8-e9c9-46be- 8275-b93e285bfecd.apk", "package_name": "com.whatsapp", "package_vesion_code": "1234" }, ] Requirements: Use Django and Django Rest Framework Add an endpoint which allows listing and uploading Android application (GET and POST) When an application is uploaded the metadata of that application should be extracted (hint: have a look at “aapt” to get the metadata) Bonus: Run the Django app in a docker container with docker-compose.