Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access excel data in django response for testing?
I have used xlwt for export some data to the client in django. Now i am testing the function and hence i want to verify that the data in response are matching with expected result. How to read the excel data from the response object. The excel data is added to response something like w.save(response) and how to retrieve this data with the response in response=self.client.get(reverse("create"))? -
How catch callback after new page was loaded?
I use pagination on scroll by Django EL(Endless) Pagination library in my project. Question: Is there any way to catch callback that will fire at the end of the request cycle, after new items have been appended to the container?! I need to refresh one script which don't work for added items. Do you have any ideas? -
How to insert seperate python scripts in django
i have created a webscraper in python and now i want to insert this file into my views.py and execute them using the html button create on html page. my scrper name is maharera.py and it is saved in same folder where i have saved views.py My views.py looks like this: from django.shortcuts import render from django.conf.urls import url from django.conf.urls import include from django.http import HttpResponse # Create your views here. def index(request): first = {"here":"will enter more details"} return render(request, "files/first-page.html", context=first) #return HttpResponse("<em>Rera details will be patched here</em>") After inserting it in views.y i want to execute that file using html button i create. How can i do that? -
Attribute Error - Where to start
i'm still a newb at django slowly figuring it out. Although ive run into this error and i dont really know where to start debugging it since the trace back doesnt tell me the location. I think i have to look at the views.py or models.py and then figure out where the nonetype is with the filter on it but after that, idk. Any insight would be appreciated. Request Method: GET Request URL: http://127.0.0.1:8000/questions/by/test1/3/ Django Version: 1.11 Python Version: 3.5.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'accounts', 'posts', 'groups', 'questions', 'django_extensions'] Installed 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'] Traceback: File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/views/generic/detail.py" in get 115. self.object = self.get_object() File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/views/generic/detail.py" in get_object 38. queryset = queryset.filter(pk=pk) Exception Type: AttributeError at /questions/by/test1/3/ Exception Value: 'NoneType' object has no attribute 'filter' Here is my views.py gist for questions: class QuestionDetail(generic.DetailView): model = models.Question def get_queryset(self): queryset = super().get_queryset() class UserQuestions(generic.ListView): model = models.Question … -
Issues with django-allauth 0.34.0 with django 2.0, how do i update my package
i have problems using django-allauth in my project, like viewing/editing the socialaccount. im getting AttributeError at /en/admin/socialaccount/socialaccount/2/change/ 'JSONField' object has no attribute '_get_val_from_obj' Request Method: GET Request URL: http://localhost:8000/en/admin/socialaccount/socialaccount/2/change/ Django Version: 2.0.1 Exception Type: AttributeError Exception Value: 'JSONField' object has no attribute '_get_val_from_obj' i tried getting the latest version but still get 0.34.0 pip install django-allauth --upgrade i've reviewed the github code and it looks like it's already fixed. https://github.com/pennersr/django-allauth/pull/1878 how do i fix this? or do i need to wait for someone to update the installer? The latest version in https://pypi.python.org/pypi/django-allauth is version 0.34.0 - last updated - Oct 29, 2017 -
Authenticate users in sleekxmpp
I am accepting a username in an html page and sending the name as a post to Django which in turn connects to the xmpp server. I need to authenticate the user and take action accordingly. Right now, I do not have a problem with the users already created but I am not able to handle non-authenticated users. I am getting the following error - INFO Negotiating TLS INFO Using SSL version: TLS 1.0 INFO Authentication failed: not-authorized INFO Authentication failed: not-authorized ERROR No appropriate login method. INFO Waiting for from server ERROR Error reading from XML stream. -
Customize show_more tag in django-endless-pagination?
I use pagination on scroll by Django EL(Endless) Pagination library in my project. By default show_more tag show loading word. I want customize it. I use next code but it work incorrect. It show me 9 icons and at the end don't disappear. I am little bit confused. How to fix it? settings.py: EL_PAGINATION_LOADING = """<i class='fa fa-cog fa-spin fa-3x fa-fw text-info text-justify endless_loading'>""" -
Error: BadZipFile: File is not a zip file when install django-libsass
I create a virtual env with python3. I install django and some packages. It works. But when install django-libsass, It raise an error BadZipFile: File is not a zip: Collecting django-libsass Exception: Traceback (most recent call last): File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/commands/install.py", line 335, in run wb.build(autobuilding=True) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/req/req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/download.py", line 809, in unpack_url unpack_file_url(link, location, download_dir, hashes=hashes) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/download.py", line 715, in unpack_file_url unpack_file(from_path, location, content_type, link) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/utils/__init__.py", line 599, in unpack_file flatten=not filename.endswith('.whl') File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/utils/__init__.py", line 484, in unzip_file zip = zipfile.ZipFile(zipfp, allowZip64=True) File "/usr/lib/python3.5/zipfile.py", line 1026, in __init__ self._RealGetContents() File "/usr/lib/python3.5/zipfile.py", line 1093, in _RealGetContents raise BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a zip file I don't know why, anyone help me! Thanks! -
How to write testcases in python-django testing?
Consider a code below, dev=request.POST['device'] stat=request.POST['type'] For the front i have used two drop down options. <select name="device" id="dev"> <option value="device1">device1</option> <option value="device2">device2</option> </select> <select name="type" id="typ"> <option value="auto">Automatic</option> <option value="manual">Manual</option> </select> Can you please tell me how to write white box test cases for the above python code. Please find my testcases below. def test_post_device_keyerror(self): postdata={'type':'manual'} self.client.login(username='vishnu',password='vishnu@12345') with self.assertRaises(MultiValueDictKeyError): response=self.client.post(reverse("create"),postdata) def test_post_type_keyerror(self): postdata={'device':'device1'} self.client.login(username='vishnu',password='vishnu@12345') with self.assertRaises(MultiValueDictKeyError): response=self.client.post(reverse("create"),postdata) def test_post_valid_data(self): postdata={'device':'device1','type':'manual'} self.client.login(username='vishnu',password='vishnu@12345') response=self.client.post(reverse("create"),postdata) self.assertEqual(response.status_code,200) Is this test cases enough? or whether my sequence of tests is wrong? -
django import-export work with django smart-selected
i want to create function export and import model from xls my model.py class LegalDocumentField(models.Model): name = models.CharField(max_length=255, default="default" class LegalDocumentType(models.Model): linhvuc = models.ForeignKey(LegalDocumentField, on_delete=models.CASCADE) name = models.CharField(max_length=255, default="default") class LegalDocument(models.Model): linhvuc = models.ForeignKey(LegalDocumentField, on_delete=models.CASCADE, verbose_name="Lĩnh vực") loai = ChainedForeignKey( LegalDocumentType, chained_field="linhvuc", chained_model_field="linhvuc", show_all=False, auto_choose=True, sort=True,) LegalDocument model use django smart-selected format and now i want to import-export LegalDocument model in admin i have already tried that: in admin.py @admin.register(LegalDocument) class LegalDocAdmin(ImportExportModelAdmin): pass my xls after exported exported xls file but when i import from this file it have error: "LegalDocument.loai" must be a "LegalDocumentType" instance. Please save me thanks -
Django 'python manage.py runserver' has from config import* error
I have an error when i use django. Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/ghk/djangoprojects/myvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/ghk/djangoprojects/myvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/Users/ghk/djangoprojects/myvenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/ghk/djangoprojects/myvenv/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Users/ghk/djangoprojects/myvenv/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/ghk/djangoprojects/lab-in-the-wild/labinthewild/settings.py", line 18, in <module> from config import * ModuleNotFoundError: No module named 'config' If I command 'python manage.py runserver', it show this error. -
Serializing User model
I have the following code that should return me all the Users that are registered in my site, but for some reason it just returned me the last signed user, I need all the users in my JSON. from django.shortcuts import render, redirect import json from django.http import HttpResponse from rest_framework.response import Response from rest_framework.views import APIView from profiles.serializers import ProfileSerializer from django.contrib.auth.models import User from rest_framework.decorators import api_view class ProfilesAPI(APIView): serializer = ProfileSerializer def get(self, request, format=None): users = User.objects.all() response = self.serializer(users, many=True) for j in range(0,len(response.data)): dictionary = response.data[j] myresponse = "" for i, (val, v) in enumerate(dictionary.items()): myresponse = [{"text":v} for v in dictionary.values()] print(myresponse) return HttpResponse(json.dumps({'messages': myresponse}), content_type='application/json') and throws me this, even I have more than one user registered. My JSON -
most django/pythonic way to find the most popular choice in queryset
there is a model field with choices: class MyModel(models.Model): your_choice = models.CharField(choices=('A', 'B', 'C', 'D')) what is the most compact way to get the most popular choice from the queryset? If for example, the queryset is: qs = MyModel.objects.all() -
Django test failing only when its module is run individually
I'm running tests in a Django project called lucy-web. If I run a simple python manage.py test, all tests pass: (venv) Kurts-MacBook-Pro:lucy-web kurtpeek$ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). ........................ ---------------------------------------------------------------------- Ran 24 tests in 22.097s OK Destroying test database for alias 'default'... However, if I try to run a particular test defined in lucy_web/tests/test_schedule_request.py, it fails: (venv) Kurts-MacBook-Pro:lucy-web kurtpeek$ python manage.py test lucy_web.tests.test_schedule_request Creating test database for alias 'default'... System check identified no issues (0 silenced). .F ====================================================================== FAIL: test_send_schedule_request (lucy_web.tests.test_schedule_request.ScheduleRequestTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/freezegun/api.py", line 495, in wrapper result = func(*args, **kwargs) File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/lucy_web/tests/test_schedule_request.py", line 44, in test_send_schedule_request self.assertEqual(mail.outbox[0].body, expected_body) AssertionError: 'Hi!\[17 chars]ily 1) wants to schedule a Birth Preparation a[102 chars] AM.' != 'Hi!\[17 chars]ily 12) wants to schedule a Birth Preparation [103 chars] AM.' Hi! - Test Test (family 1) wants to schedule a Birth Preparation and Preferences session within the next day or two. + Test Test (family 12) wants to schedule a Birth Preparation and Preferences session within the next day or two. ? + Test requested this session on 01/01/12 at 09:00 AM. ---------------------------------------------------------------------- Ran 2 tests in 2.365s … -
Why can't we mix named groups and non-named groups in Django URLconf?
In Django, when you need to capture some string in a matching URL to pass to its corresponding view (i.e. if you have /year/2011 as a URL and you need to pass 2011 to the view), you would need to use a capture group in the URL pattern so that Django can pass the captured string to it associated view. If you have the following URL pattern: url(r'^time/(\d{1,2})/$', some_view) Django would call some_view as some_view(request, the_captured_string) where the_capture_string is whatever string matches (\d+{1,2}) in the URL. The capture group in the URL pattern is called a non-named group. You could also do named groups. URLs using named groups would look like this: url(r'^time/(?P<some_string>\d{4})/$', some_view) For this pattern, Django would call some_view as some_view(request, some_string=some_value where some_value is whatever string matches (?P<some_string>\d{4}) in the URL. So I attempted to mix non-named and named groups together (for curiousity reasons) in this URL pattern: urlpatterns = [ ... url(r'^mixed/(\w+)/(?P<named>\d{4})/$', mixed_test) ... ] def mixed_test(request, non_named, named): return HttpResponse('Non_named: {0} | Named: {1}'.format(non_named, named)) Based on my previous readings, I was expecting that Django would call mixed_test as mixed_test(request, 'positional', named='keyword'), assuming that I accessed the URL, /mixed/positional/keyword. However, I get a TypeError: mixed_test() … -
Listing existing objects and objects search results on Django
I have the following LodgingOffer model with their respective models.Manager with the order of perform some searches using solr and haystack The LodgingOfferManager perform the active() function to retrieve the LodgingOffer active objects which are active if those have the is_taked = True class LodgingOfferManager(models.Manager): def active(self, *args, **kwargs): return super(LodgingOfferManager, self).filter(is_taked=False).filter(pub_date__lte=timezone.now()) This is the LodgingOffer model with some of their more representative fields related to my case/question def get_images_search_path(instance, filename): return '/'.join(['lodging_offer_images', instance.slug, filename]) class LodgingOffer(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ad_title = models.CharField(null=False, blank=False, max_length=255, verbose_name='Título de la oferta') photo = models.ImageField(upload_to=get_images_search_path, blank=False, verbose_name='Fotografía', null=False) pub_date = models.DateTimeField(auto_now_add=True) is_taked = models.BooleanField(_('Oferta tomada'), default=False,) objects = LodgingOfferManager() def __str__(self): return "%s" % self.ad_title To perform my searchs I have this form: class LodgingOfferSearchForm(forms.Form): query = forms.CharField(label='', widget=forms.TextInput()) In my views I have the LodgingOfferSearch view to perform the searches of this way: class LodgingOfferSearch(FormView): template_name = 'hosts/lodgingoffer_search.html' form_class = LodgingOfferSearchForm() def get(self, request, *args, **kwargs): form = LodgingOfferSearchForm(self.request.GET or None) return self.render_to_response(self.get_context_data(form=form)) # We get the active object records # I think that this is not necessary ... ? def get_queryset(self): qs = LodgingOffer.objects.active() return qs def get_context_data(self, **kwargs): context = super(LodgingOfferSearch, self).get_context_data(**kwargs) user = self.request.user form = LodgingOfferSearchForm(self.request.GET or … -
How to create multiple inner joins using Django ORM
I'm really struggling to find documentation and examples to solve the following dilemma. I have two tables, Results (which contain results of a race) and Photos (where each photo contain runners in that race). Both tables contain entrant_numbers, i.e. the number of the runner in the race and the number of the runner in the photo. In SQL I joined them like so to get the total number of photo captures per runner. SELECT * FROM photos p INNER JOIN results r ON p.EntrantNumber=r.EntrantNumber AND p.raceyear=r.raceyear WHERE r.userid=123 My models are structured like so; class Photo(models.Model): photo_id = models.AutoField(primary_key=True) url_pre_string = models.CharField("URL pre-string", max_length=255) filename = models.CharField("Filename", max_length=100) extension = models.CharField("File extensions", max_length=4) race_year = models.PositiveIntegerField("Race year", default=0) entrant_number = models.PositiveIntegerField("Entrant number", default=0) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) class Result(models.Model): results_id = models.AutoField(primary_key=True) position = models.PositiveIntegerField("Position", default=0) entrant_number = models.PositiveIntegerField("Entrant number", default=0, null=True, blank=True) firstname = models.CharField("Firstname", max_length=255) surname = models.CharField("Surname", max_length=255) team_name = models.CharField("Team name", max_length=255, null=True, blank=True) registration_number = models.PositiveIntegerField("Registration number", default=0, null=True, blank=True) category = models.CharField("Category", max_length=50, null=True, blank=True) gender = models.CharField("Gender", max_length=50, null=True, blank=True) date_of_birth = models.CharField("Date of birth", max_length=30, null=True, blank=True) no_mail = models.BooleanField("No mail", default=False) finish_time = models.CharField("Finish time", max_length=50, null=True, blank=True) chip_time … -
ValueError: invalid literal for int() with base 10 seems to be related to ForeignKey
Trying to get to the bottom of this error. Several SO questions on the subject and the answers range from: deleting previous migrations, setting default value in the model for the field, or using a GenericForeignKey. None have resolved my issue thus far. I am fairly certain the issue is related to ForeignKey and have read it uses int() by default even if the field is CharField. Here is the field in question in the model I am trying use: product_code = models.ForeignKey(Products, null=False) Here is the field in the parent model it is referring to (Products): code = models.CharField(unique=True, max_length=16) And here is the query where the issue is occurring: # returns 'A_17' product_code = Products.objects.get(id=data['product_id']).code # error triggered here: print(ProductPositions.objects.filter(product_code=product_code)) # ValueError: invalid literal for int() with base 10: 'A_17' So it appears to be string from end-to-end, but I guess with the ForeignKey "defaulting" to integer or something the issue is related to that. Not sure how to override that as something like default='' doesn't work. Not sure how to clear up the issue so thanks for the feedback. -
Doesen't work LIKE icontains
Try do search with ajax requests. prefix = str(request.POST.get('prefix')) colors = UserDataCsv.objects.filter(material__icontains=prefix).values('color') print(colors.query) But i don't get response, coz: SELECT `users_userdatacsv`.`color` FROM `users_userdatacsv` WHERE `users_userdatacsv`.`material` LIKE %ff% ORDER BY `users_userdatacsv`.`id` ASC I haven't quotes in mysq SQL reqyest %ff%, how i can fix it? Use django 1.9 -
Django/PIL: AttributeError: 'Image' object has no attribute 'read'
I'm testing example code validate image field (Django custom validation in model form for imagefield (max file size etc.)): models.py from django.db import models from filer.fields.image import FilerImageField class Event(models.Model): # (...) banner = FilerImageField(verbose_name='Banner') admin.py from django.contrib import admin from django import forms from PIL import Image from .models import Event class EventForm(forms.ModelForm): class Meta: model = Event fields = '__all__' def clean_banner(self): image = self.cleaned_data.get('banner', False) if image: img = Image.open(image) img.load() width, height = img.size max_width = 879 max_height = 392 if width > max_width or width < max_width or height > max_height or height < max_height: raise forms.ValidationError('Imagem está com dimensão incorreta: %s x %s pixels. Insira uma imagem com %s x %s pixels.' %(width, height, max_width, max_height)) # Máx 3MB if len(image) > (3 * 1024 * 1024): raise forms.ValidationError('Arquivo de imagem muito grande (máximo 3MB).') name_type, ext = image.content_type.split('/') if not (name_type == 'image' and ext.lower() in ['png', 'jpg', 'jpeg']): raise forms.ValidationError('Por favor, use imagem em formato JPG, JPEG ou PNG.') else: raise forms.ValidationError('Não foi possível ler a imagem carregada.') return image error when registering image not django-admin. Version: Pillow==4.3.0, Python==3.6 Traceback (most recent call last): File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\PIL\Image.py", line 2534, in open fp.seek(0) … -
Finding someone to build simple Django Website
I want to create a simple website and turns out my basic html knowledge won't get the job done. I learned some basic python/django through youtube/internet research and was able to build a basic site that looks decent. The problem is I am trying to give the site search functionality and after a week of research I can't figure this part out. I wan't to be able to create multiple databases that can be searched with a search box. You enter your search keyword, it searches all databases and prints results on your screen. I got as far as creating one database but I am having trouble getting the search box to work with it. I also couldn't figure out how to add new databases. Now I've come to the realization that it might be best to have someone build a skeleton site with just the functionality that I need. I can then take care of the site's appearance. Whats the best way to go about hiring somebody and where can I find them. I'm using a windows pc not a mac therefore I would need the site to be pc friendly for editing. Using Django 2.0 and python 3.0. -
How does django testing work with running both the client and the server at once?
I'm wondering, it seems that when you run django tests, you have access to a client, which is hitting a running copy of your server. How does this work? Is it all done in a single thread? My question is motivated by the request_finished signal. I'm wondering, when you're running django tests, will request_finished call its functions before the response returns, or after? Or not at all? Please let me know if I can expand on this question in any helpful way -
refer to last available historical data
In a django project backed by a postgresql db I have two models,: class Asset(models.Model): name = models.CharField(...) class AssetHistory(models.Model): asset = models.ForeignKey('Asset', ...) timestamp = models.DateTimeField(...) value = models.IntegerField(...) Periodically some data are added to AssetHistory for some specific asset. What is the best practice to refer to the last value in AssetHistory for a specific asset? I was thinking to add 2 extra fields in Asset model and update them when a new entry is added to AssetHistory class Asset(models.Model): name = models.CharField(...) timestamp = models.DateTimeField(...) value = models.IntegerField(...) but i'm not sure this is the best choice. -
Django rest framework URL Filter - Edit/Update Instance returned via filter method
I've had success using filter_fields to return a single filtered result list. I want to update to this result. Is there a way to update a filtered single result? via a URL pattern like the below? LocalHost:8080/PriceMaster/?ISIN=aaa&valuedate=2018-01-01 I know if i use the primary key at the end of the URL instead of the filter I can update the instance. I feel I may have to make a second view (inheriting from one of these API views) with a a new url? RetrieveUpdateAPIView, RetrieveDestroyAPIView, RetrieveUpdateDestroyAPIView Is there a way to keep it within the 1 ViewSet and what might it look like? This is my current views.py class OptionMasterViewSet(TemporalModelViewSet): queryset = OptionMaster.objects.filter(vflag=1) lookup_field = 'django_id' filter_backends = (DjangoFilterBackend,) filter_fields = ('ISIN', 'ValueDate',) model = OptionMaster When I make a PUT or POST within Postman to the URL I get the error "Method Not Allowed" Thanks -
MongoDB with Django Rest Elasticsearch?
Following the Basic Usage example at http://django-rest-elasticsearch.readthedocs.io/en/latest/ from app.serializers import BlogSerializer from app.models import Blog from rest_framework_elasticsearch import (es_views, es_client, es_pagination, es_filters) from .search_indexes import BlogIndex class BlogView(es_views.ListElasticAPIView): es_client = es_client es_model = BlogIndex es_pagination_class = es_pagination.ElasticLimitOffsetPagination es_filter_backends = ( es_filters.ElasticFieldsFilter, es_filters.ElasticFieldsRangeFilter, es_filters.ElasticSearchFilter, es_filters.ElasticOrderingFilter, ) es_ordering = 'created_at' es_filter_fields = ( es_filters.ESFieldFilter('tag', 'tags'), ) es_range_filter_fields = ( es_filters.ESFieldFilter('created_at', 'created_at'), ) es_search_fields = ( 'tags', 'title', ) Gives me the stacktrace: `Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10de071e0> Traceback (most recent call last): File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File …