Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: QuerySet evaluation
Django 1.11.2 In the example, below I have got a QuerySet "arts". I iterate through it in the view (that list comprehension). The transmit the queryset to the template. Ant in the template I again iterate through it in the for loop. In the documentation I can read that QuerySets are evaluated in case of iteration. This is the documentation: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#when-querysets-are-evaluated But I organized a log file for PostgreSQL. And try to control database hits: tail -f postgresql-2017-07-20_120840.log Well, there is only one hit in this case. Could you comment on this. As far as I can understand the QuerySet was evaluated when that list comprehension worked. Then it remembered it state: it is already evaluated. And in the template it just worked without evaluation. Could you comment on this: am I right. If I'm wrong, then why only one evaluation happened? views.py class AsciiView(View): def get(self, request): arts = Art.objects.all() if arts: points = [(art.lat, art.lon) for art in arts if (art.lat and art.lon)] else: points = [] return render(request, "ascii_chan/ascii_chan.html", {"arts": arts, "points": points}) ascii_chan.html {% for art in arts %} <div class="art"> <h2 class="art-title">{{ art.title }} {{ art.created }}</h2> <pre class="art-body">{{ art.art }}</pre> </div> {% empty %} … -
I'm confused with django project root and the virtualenv. Please guide
I'm new to django and have a virtualenv outside my django project directory. When I download open source django apps like python_social_auth using pip install, the apps reside in the virtualenv's site-packages directory and not in the project root. But I import them in my projects. Should I keep a copy of the downloaded apps in my projects root? Would that be necessary if I wanted to deploy the project? -
Is it possible to save multiple type of data in a single field in django model?
I have some question with options as checkboxes, textfield, radio buttons and text area.Can there is a way to accomodate answer value in one field in django? Thanks in advance. -
Where is the declaration of objects of django model?
In django documentation, it say that we can retrieve data entry as below entry = Entry.objects.get(pk=1) Entry is a model class in models.py. I tried to find the declaration of objects, but I can't find its declaration in manager.py, just know it is a instance of Manager. So, where is the declaration of objects? Does it represent a set of Entry instances? -
Open Layers 3: Create source from paginated API
How do you create an ol.source.Vector from a paginated url? Using the code below, only the first 100 (size of page) objects are rendered on the map: var source = new ol.source.Vector({ url: "{{ url }}", format: new ol.format.GeoJSON() }); Sample data: { "type": "FeatureCollection", "count": 16241, "next": "http://0.0.0.0:8000/api/bikeshare/station/?page=2", "previous": null, "features": [ { "id": 6346, "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 16.387084722519, 48.291809541369 ] }, "properties": { "name": "10vorWien / Strebersdorferhof", "capacity": 5, "address": null, "installed": null, "open": null, } }, ... ]} -
pip install mysqlclient through s ,failed to import Cython: DLL load failed: %1 is not a valid Win32 application.
Hi iam following Django documentation, earlier i thought of using oracle db,but not got right documentation thus decided to use mysql db. Iam following with django version 1.8 and python 2.7.12(both are compatible).I have installed mysql 5.7.19.0 . When i run pip install mysqlclient,iam getting below error, copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-2.7\MySQLdb\constants running build_ext failed to import Cython: DLL load failed: %1 is not a valid Win32 application. error: Cython does not appear to be installed But i can see that Cython is already installed,when i type pip install cython.I am using 64 bit windows machine and installed python 2.7.2(64 bit).How can i resolve this? Please let me know any other documentation available for setting MySql db with(django version 1.8+python 2.7.12)?Serched over web but could not able to resolve this. -
Deploying multiple django sites with mod_wsgi apache linux
I wish to deploy multiple Django sites (say 2 for now - www.example.com, www.example2.com) using apache2 mod_wsgi. Here are the steps I followed in a fresh Ubuntu 16.04 installations. I've set alias python=python3 in my .bashrc as I am working in python3 packages installed: apache2 - sudo apt-get install apache2 mod_wsgi - sudo apt-get install libapache2-mod-wsgi-py3 Django(V1.11) - sudo apt-get install python3-django Then I've created two projects inside /var/www/ django-admin startproject example django-admin startproject example2 then I did the followings for both the projects (I've mentioned only one, the other one is exactly the same except replacing example with example2) /var/www/example/example/settings.py ALLOWED_HOSTS = ['example.com', 'www.example.com'] /var/www/example/example/wsgi.py #os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings") os.environ["DJANGO_SETTINGS_MODULE"] = "example.settings" /etc/apache2/sites-available/example.conf <VirtualHost *:80> ServerName www.example.com ServerAlias example.com ServerAdmin admin@example.com DocumentRoot /var/www/example WSGIScriptAlias / /var/www/example/example/wsgi.py ErrorLog /var/www/example/error.log </VirtualHost> Also, I've added /etc/apache2/apache2.conf WSGIPythonPath /var/www/example I've called a2ensite for both example.conf and example2.conf Once I restart apache I could now access www.example.com successfully, but www.example2.com gives an internal server error(500). I thought that's because I've only included one path for WSGIPythonPath in apache2.conf and changed it as /etc/apache2/apache2.conf WSGIPythonPath /var/www/example:/var/www/example2 But however, I now get an internal server error(500) for both. in both cases, the error message is ImportError: No module … -
MySQL query with list of values
I have a table with over then 50kk rows. trackpoint: +----+------------+-------------------+ | id | created_at | tag | +----+------------+-------------------+ | 1 | 1484407910 | visitorDevice643 | | 2 | 1484407913 | visitorDevice643 | | 3 | 1484407916 | visitorDevice643 | | 4 | 1484393575 | anonymousDevice16 | | 5 | 1484393578 | anonymousDevice16 | +----+------------+-------------------+ where 'created_at' is a timestamp of row added. and i have a list of timestamps, for example like this one: timestamps = [1502744400, 1502830800, 1502917200] I need to select all timestamp in every interval between i and i+1 of timestamp. Using Django ORM it's look like: step = 86400 for ts in timestamps[:-1]: trackpoint_set.filter(created_at__gte=ts,created_at__lt=ts + step).values('tag').distinct().count() Because of actually timestamps list is very very longer and table has many of rows, finally i getting 500 time-out So, my question is, how to for it in ONE raw SQL query join rows and list of values, so it looks like [(1502744400, 650), (1502830800, 1550)...] -
python manage.py migrate KeyError: 255
Server environment configuration Ubuntu 14 Django 1.11.3 Python 3.6.1 MySql 8.0.1 When I execute python manage.py dbshell command everything works ok. But when I execute python manage.py migrate command, I get a KeyError: 255. Here is the traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 110, in handle loader.check_consistent_history(connection) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 282, in check_consistent_history applied = recorder.applied_migrations() File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 254, in cursor return self._cursor() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 229, in _cursor self.ensure_connection() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 274, in get_new_connection conn = Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/pymysql/__init__.py", line 90, in Connect return Connection(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 706, in __init__ self.connect() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 931, in connect self._get_server_information() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1269, in _get_server_information self.server_charset = charset_by_id(lang).name File "/usr/local/lib/python3.6/site-packages/pymysql/charset.py", line 38, in by_id return self._by_id[id] KeyError: 255 -
Django Search not working
I've made an Application containing List of trainers. My Index View Displays these trainer profiles from the database. I intend to implement a sear bar to filter these results. I am not getting what i'm doing wrong. As soon as i mention the url in action of the search for, it displays reverse match error url's.py : url(r'trainer/search/$', views.search, name='Search'), views.py def search(request): query = request.GET['q'] trainer= Trainer.objects.filter(name__icontains=query) return render(request,'trainer/index.html', {'trainer': trainer}) search form in my base template <form class="navbar-form navbar-left" method="get" action="{% url 'trainer:Search' %}"> <div class="form-group"> <input type="text" id="searchBox" class="input-medium search-query" name="q" placeholder="Search"> </div> <button type="submit" class="btn btn-default">Search</button> </form> -
Django adding new model to a ManyToManyField
I am trying to create a forum like dialog where every topic has a ManyToManyField that links to its posts. Here I am trying to create a new topic, meaning a new topic model is created and so is its first post: # views.py topic_form = NewTopicForm(request.POST) post_form = NewPostForm(request.POST) if topic_form.is_valid() and post_form.is_valid(): topic_form = topic_form.save(commit=False) post_form = topic_post_form.save(commit=False) post_form.posted_by = request.user post = post_form.save() topic_form.posts.add(post) topic = topic_form.save() However I am having trouble finding the correct way to save both forms and add the post to the topic. -
RuntimeError: Model class models.AuthGroup doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got: command prompt- (orahienv) somya@somya-Inspiron-15-3555:~/Desktop/backup/admin_python$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7fa8ce735de8> Traceback (most recent call last): File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/somya/Desktop/backup/admin_python/admin_python/urls.py", line 21, in <module> url(r'', include('admin_app.urls', namespace = 'admin_app')), File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/somya/Desktop/backup/admin_python/admin_app/urls.py", line 26, in <module> exec "from {0} import {1}".format(dir_name + files.split(".")[0], files.split(".")[0].title()) File "<string>", … -
How to GET from a model, showing its related models' details in the JSON response?
I am writing a small system of which a Transaction has an Account and Category related to it. Currently I'm using PrimaryKeyRelatedField in the TransactionSerializer. I need to, when GETing all the transactions or just one, to return the related Account and Category details in the JSON response. By using PrimaryKeyRelatedField, the response is alike this: class TransactionSerializer(serializers.ModelSerializer): account = serializers.PrimaryKeyRelatedField(read_only=True) category = serializers.PrimaryKeyRelatedField(read_only=True) # output: [ transaction: { id: 1, account: 1 category: 3, ... }, ... ] To bring the details the related account and category, I've done the following in the TransactionSerializer: class TransactionSerializer(serializers.ModelSerializer): account = AccountSerializer() category = CategorySerializer() # output: [ transaction: { id: 1, account: { id: 1, name: "Foo", ... } category: { id: 3, name: "Bar", ... }, ... }, ... ] But then I cannot create a new Transaction. It shows an error saying account and category are expected to be a dictionary but got str. I've tried moving the fields to read_only within the serializer, but then another error says these fields should be within fields list. So this is my problem. How do I create a new Transaction, assigning an account and category by ID, and yet when retrieving … -
Finding and logging dynamic text that needs to be translated in django
When django begins translating the page, I would like to find the texts that were marked for translation, but django did not find the msgid for the same in the po/mo file If I can find it, I would then log it for further processing Example, message_to_be_translated = _("Hello") this_message_is_marked_but_wont_be_translated = _(some_variable_name_whose_value_we_dont_know_now) I would like to log the value of "some_variable_name_whose_value_we_dont_know_now" during run time to a file or something. The reason we wont know the value before hand is it could be from a third party api it could come from a user request -
How to write urls and views when a OneToOne field is a lookup field?
I have a situation where I'm storing the user profile in a different django model. class Profile(models.Model): user = models.OneToOneField(User, primary_key=True) address = models.CharField(max_length=1000) Using default Model ViewSet I get the following URL to GET/UPDATE a particular instance of the profile /api/profile/user Now, since I'm using token authentication, the client only has a token and is not aware of the user. How can a write a URL of the following form /api/profile This seems more natural to me as a user can have only one Profile object and hence his token should be sufficient to do all the operations in his API calls. Writing custom views is one option but is there any way I can leverage DRF to achieve the same with minimal manual implementation? -
django group by aggregate
I have the following query set in django query_set = JoineryLabour.objects.filter(quote_no = qt.quote_no).values("Hours", "Aspect", "JoineryID") This gives me the following output |Hours|Aspect|JoineryID |100 |Load |123 |50 |Cut |123 |300 |Load |123 |50 |Load |234 What I want is that, hours will be added with the same JoineryID and grouped by Aspect. Like the following: |Hours|Aspect|JoineryID |400 |Load |123 |50 |Cut |123 |50 |Load |234 is it possible to do it in query? The aspect list is dynamic and can be long. I can manage to do it if it's of the fixed size, however, the list is dynamic and I am using nested loops for that. Any advice will be highly appreciated. -
Adding newrelic to a python stack (django) deployed via dokku
I'm trying to add newrelic to a django website deployed via dokku. I've installed newrelic and added to the requirements and also created the newrelic.ini file and added to the repo. I've aslo changed the command of my Procfile, so it reads like: NEW_RELIC_CONFIG_FILE=newrelic.ini newrelic-admin run-program gunicorn config.wsgi:application Whe I deloy however I get a strange error, with the daemon complaining the file is not present: (ticker_env) mattions@apollo:ticker(add_newrelic*)$ git push dokku add_newrelic:master Counting objects: 8, done. Delta compression using up to 4 threads. Compressing objects: 100% (8/8), done. Writing objects: 100% (8/8), 4.21 KiB | 0 bytes/s, done. Total 8 (delta 3), reused 0 (delta 0) remote: master -----> Cleaning up... -----> Building ticker from herokuish... -----> Adding BUILD_ENV to build environment... -----> Warning: Multiple default buildpacks reported the ability to handle this app. The first buildpack in the list below will be used. Detected buildpacks: multi nodejs python -----> Multipack app detected =====> Downloading Buildpack: https://github.com/heroku/heroku-buildpack-python.git =====> Detected Framework: Python -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput DEBUG 2017-07-20 06:55:42,979 base 529 139977271977792 Configuring Raven for host: <raven.conf.remote.RemoteConfig object at 0x7f4ef31a7a90> 111 static files copied to '/tmp/build/staticfiles', 111 post-processed. Using release configuration from last framework … -
How to fetch a Django urls while clicking on google geo chart api?
I have one template as given bellow: {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/table_2.css' %}"> <table> <thead> <tr> <th> Country </th> </tr> <thead> <table/> <html> <body> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> var j = "{{ind}}".replace(/&quot;/g,"\"") var c_names = {{c_list|safe}} //var c_details = {% url country_details %} google.charts.load('current', { callback: function () { var data = google.visualization.arrayToDataTable([ ['Country', 'Popularity', 'Domain'], [c_names[1], j, 'www.google.com'], // [c_names[1], j, c_details], ]); var view = new google.visualization.DataView(data); view.setColumns([0, 1]); var options = {}; var chart = new google.visualization.GeoChart(document.getElementById('regions_div')); google.visualization.events.addListener(chart, 'select', function () { var selection = chart.getSelection(); if (selection.length > 0) { console.log(data.getValue(selection[0].row, 2)); window.open('http://' + data.getValue(selection[0].row, 2), '_blank'); } }); chart.draw(view, options); }, packages:['geochart'] }); </script> <script src="https://www.gstatic.com/charts/loader.js"></script> <script src="https://www.google.com/jsapi"></script> <div id="regions_div" style="width: 600px; height: 500px;"></div> </head> </body> </html> I am trying to build a basic application that uses google geo chart api and when I clicked on a specific country (implemented on "select" event of api) it will render an associated url to render my Django template. But its showing error which you could find at the last of this post. I have declared a variable "c_details"as javascript variable and stored url as (which i have comment out in this … -
Django login suddently error, even though the last time it's doesn't error
I don't understand what the error i got. The last time i running my code, it's working. But suddently it' error. i don't understand why. The case is i build a form for login and signup for new user. Signup it;s working so well, but when i was try to login, it's doesn't work, but when i was try to login as admin, it's working, i can login. views.py def newCat(request): if request.method == 'POST': form = NewCatForm(request.POST) if form.is_valid(): newcat = form.save(commit=False) username = form.cleaned_data.get('username') passwd = form.cleaned_data.get('password') newcat.save() user = authenticate(username=username, password=passwd) auth_login(request,user) return redirect('/') else: form = NewCatForm() return render(request, 'girl/signup.html', {'form':form}) def login(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: auth_login(request,user) return redirect('/') else: error = " Sorry! Username and Password didn't match, Please try again ! " print(error) return render(request, 'login', {"error":error}) else: form = LoginForm() return render(request, 'girl/login.html', {"form":form}) forms.py class NewCatForm(forms.ModelForm): class Meta: model = User fields = ('username', 'password', 'email') class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput()) login.html {% extends 'girl/base.html' %} {% block content %} <h1>Login</h1> {% if error %} {{ … -
Django heroku deployment Server Error Due to Staticfiles
With DEBUG = True the page loads from Django without css and js as expected. When DEBUG = False a server 500 error is thrown. The heroku sentry addon says this is due to Missing staticfiles manifest entry for 'css/base.css' When base.css is removed, the same error is thrown for the next static file linked via {% static 'filename' %} Once I set the STATICFILES_STORAGE to django.contrib.staticfiles.storage.StaticFilesStorage in settings, I had the same functionality as when DEBUG = True. i.e. templates load (and cdn linked bootstrap) but none of the custom staticfiles in the /static/ of my apps. Why is this the case? I want to be able to serve the static files with AWS but if this isn't functioning properly (throwing Server Errors because of Missing staticfiles manifest errors) then I'm unsure if it will work properly when the files are served from AWS. -
When i learn django document chapter5,I encountered a mistake.Here it is
(python35) E:\pythonProject\mysite>python manage.py test polls Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: test_was_published_recently_with_future_question (polls.tests.QuestionModelTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "E:\pythonProject\mysite\polls\tests.py", line 12, in test_was_published_recently_with_future_question self.assertls(future_question.was_published_recently(),False) AttributeError: 'QuestionModelTests' object has no attribute 'assertls' ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (errors=1) Destroying test database for alias 'default'... -
django rest framework order listview by serializer specific field
So I currently have a Drink serializer built using django rest framework. It has a field count_need that i obtain using a SerializerMethodField, which is not part of the Drink model. It also has a timestamp field that is part of the model. How can I order the ListAPI view by either timestamp or count_need based on parameters from a get request like /api/drink/?ordering=timestamp. Currently, i have ordering fields specified in the ListAPI view ordering_fields = ('count_need', 'timestamp', ) but it doesnt seem to be ordering the apiview on either query. I can order it by timestamp through the get_queryset method but this doesnt work for count_need because it is not part of the model. -
Food Ordering Website Process (Django)
apologies if this question is not suitable on stackoverflow. I'm making an food ordering website through Django (one restaurant only). I want to be able to identify who ordered what (through user accounts) So please correct me if I am wrong on the process here: Create an app (for "Menu") Create an app (for UserAuth?) Create a model (for "MenuItems") inside "Menu" app User needs to be able to add MenuItems to their "Basket" (how do I do this?) Admin should be able to remove MenuItems from the "Basket" of specific users after the food has been collected (how do I do this?) Make views for home (sitename/), lists of MenuItems (sitename/menu), "Basket" (sitename/basket - this would have an order button), Make a checkout view (sitename/checkout) after pressing Order button - this should add the "MenuItems" in "Basket" to the basket database..? Are there things I am missing, or things I am doing completely wrong? Thank you in advance for all answers! -
when to map http methods to view methods django rest framework
I have seen viewsets implemented like this: can we expand on this line of code in the django rest frameworks docs: "If we need to, we can bind this viewset into two separate views, like so:" user_list = UserViewSet.as_view({'get': 'list'}) user_detail = UserViewSet.as_view({'get': 'retrieve'}) where would user_list and user_detail be connected to / used? more so when would you map the http methods while using viewsets or generic views? Because I have seen examples like this for view sets not using the mapping and using them. Example of using can we talk about how this works and how it is connected? task_list = TaskViewSet.as_view({ 'get': 'list', 'post': 'create' }) task_detail = TaskViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) task_router = DefaultRouter() task_router.register(r'tasks', TaskViewSet) and also what is up with this: @detail_route(methods=['post']) def set_password(self, request, pk=None): if we have the route decorators why do we have in url mapping? What is the difference between them? -
exception handling while using django and django rest framework
While using django and django rest framework and strictly using the frame work code. Example, using a router connected to a view set to a serializer into a model. What I mean is no custom code, other than what is required to feed into the django rest frameworks code, do we not need exceptions? I ask because in all the code examples I have seen, I have yet to see a try catch block. thank you