Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 'Key(field)=() is duplicated'
This question had been asked before here, but for a different scenario. I am working on a Django/Wagtail project. At some point I had to modify a model, and add some fields. Accidentally I included a flag unique=True for a new field. This way: title = models.CharField(max_length=100, unique=True, blank=True, null=True, verbose_name=_('Category Title')) When making migrations and migrating, it yelled this issue: Then I realized the mistake, removed the unique=True and left it like this: title = models.CharField(max_length=100, blank=True, null=True, verbose_name=_('Category Title')) I made the migrations and migrated again, expecting the issue to go away. However I get the same issue. How can I solve this? This is the last migrations: class Migration(migrations.Migration): dependencies = [ ('distributed', '0029_remove_blogcategory_title'), ] operations = [ migrations.AddField( model_name='blogcategory', name='title', field=models.CharField(blank=True, max_length=100, null=True, verbose_name='Category Title'), ), ] And this is the trace: Microsoft Windows [Versión 6.1.7600] Copyright (c) 2009 Microsoft Corporation. Reservados todos los derechos. C:\Windows\system32>cd C:/ C:\>cd distributed C:\distributed>cd distributed C:\distributed\distributed>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). You have 6 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): distributed. Run 'python manage.py migrate' to apply them. April 26, 2017 - 12:40:45 Django … -
Django 1.10 - Form fields ignore attributes when rendered as hidden
I have declared form, which contains DateInput. DateInput has specified format attribute. This will format field's date value. At the same time, the form will expect the same format upon validation. My Form: class CoolForm(forms.ModelForm): class Meta: model = Event fields = ['day', 'time_from', 'time_to', 'type'] widgets = { 'day': forms.DateInput(format=('%d--%m--%Y')) } Template: {{ field.as_hidden }} <!-- is rendered with wrong format: --> <input id="id_day" name="day" type="hidden" value="2017-04-30"> {{ field }} <!-- is rendered with correct format: --> <input id="id_day" name="day" type="text" value="30--04--2017"> Problem: In template when I print form using field.as_hidden, format remains unaffected from form setting. It even ignores attr attribute. How can I render field as hidden, while keeping its specified date format? -
Invalid static folder with django and Heroku
I try to publish a django project on Heroku but I have problems with static files. This my my configuration: BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' But Heroku returns: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_02a3e2abd7f176139303f077e32a2e9b/static' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... I'm out of solution, I understand the issue but do not know how to fixe it :( My project structure looks like: ├── Procfile ├── manage.py ├── my_project │ ├── __init__.py │ ├── settings │ │ ├── __init__.py │ │ ├── base.py │ │ ├── dev.py │ │ └── prod.py │ ├── urls.py │ └── wsgi.py ├── requirements.txt ├── runtime.txt ├── static └── staticfiles Documentation about Django or Heroku don't explain when settings are splitted … -
Wagtail Form Builder doesn't support translations?
I am using wagtail translations outlined here for some of my page models. They are working as expected. I am adding a form via the form builder I can access the forms via the url www.domain.com/slug but when I fill it out the url redirects to a None url. Also in the admin, if I click on the LIVE button, it directs to a None url as well. I assumed it had to do with not being hooked up to the translations because, by default, that is adding a url slug for each language in the promote panel of a page. So I hooked up the form model to the translations and the content panels are getting the correct translations, but the promote panel still only receives a slug field. There is no other fields for the different languages. The LIVE button still gives a None and when I submit the form on the page, it redirects to a None page with an error. Again, all my other pages that are hooked up with the translations work as expected. I'm assuming the Wagtail forms don't fully support the translations. With internationalization like this, is it an all or nothing deal? … -
Django UserPassesTestMixin, Looping error in get_absolute_url?
Views.py class ProfileEdit(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = User form_class = ProfileForm template_name = "profile/profile_new.html" slug_field = "username" def test_func(self): a = self.request.user.username b = self.kwargs['slug'] x = self.get_object().full_name y = '' if a == b: if x != y: return True else: print("failing") def get_absolute_url(self): return reverse('profile:profile_view', kwargs={"slug": self.request.user.username}) Explanation The LoginRequiredMixin forces the user to login. UserPassesTestMixin checks 1. if full_name is ''(empty) 2. if the loggedin user's username is same as the slug field The test_func() is all correct when it returns True, but in the elseloop ie., if the test condition fails the view should redirect to 'profile_view' but it does not do so. i get the output "failing" in the terminal. only when i do the same inside the get_absolute_url() function it does not work. The complete get_absolute_url() function does not work. What am i doing wrong here? note: the total process seems to be in a loop here GET /user1/edit/ HTTP/1.1" 302 0 GET /as/login/?next=/user1/edit/ HTTP/1.1" 302 0 these two URLS keep looping. -
invalid literal for int() with base 10 Django with valid integer timestamp
I have a charting library which requires my data in the epoch/Unix timestamp timestamp. So I convert it like this: ydm = 20170101 ymd = ms['dimensions'][0] + '-' + '235959' d = datetime.datetime.strptime(ymd,'%Y%m%d-%H%M%S') date = d.strftime('%Y-%m-%d') ts = int(d.strftime("%s")) * 1000 This works fine and as a result I get a human readable field 2017-04-08 and I timestamp 1491695999000 I'm trying to save both fields in my db, I first tried with a IntegerField, but I was getting the above error, I thought that it was because of the timestamp being such a big number so I also tried a BigIntegerField but I keep getting the error with a random(?) number near like: invalid literal for int() with base 10: '100.0' The number has always a dot and I guess that's why django rightly is not accepting it. My view looks something like this: print('time stamp is: '+str(ts)) # This is an int and the result is something like this: `time stamp is: 1491868799000` # Save Metrics to DB gp = GoogleProperty.objects.get(google_email=current_user) user_id = int(gp.user_id) property_id = gp.property_id property_name = gp.property_name obj, created = GaCountries.objects.get_or_create(property_id=property_id, date=date, country=country, defaults={ 'owner':user_id, 'property_id':property_id, 'date':date, 'property_name':property_name, # Remove Later 'country':country, 'sessions' : sessions, 'users' … -
Django+Angular CORS not working with POST
My Angular4 app (running on http://127.0.0.1:4200 development server) is supposed to access a django REST backend on the web. The backend is under my control and is available only via HTTPS (running Apache that tunnels the request to a gunicorn server running on an internal port). Let's say that this is https://example.com/. For historical reasons, logging the user in is done using sessions, because I want the users to be able to also use Django's admin interface after they logged in. The workflow is as follows: Users opens http://127.0.0.1:4200, I perform a GET request to https://example.com/REST/is_logged_in which returns a 403 when the user isn't logged in via sessions yet, 200 otherwise. In the former case, the user is redirected to https://example.com/login/, rendered by Django's template engine, allowing the user to log in. Once logged in, the user is redirected to http://127.0.0.1:4200 When clicking on some button in my Angular UI, a POST request is performed. This post request fails with 403, even though the preflight OPTIONS request explicitly lists POST as allowed actions. Here is my CORS configuration in Django: NG_APP_ABSOLUTE_URL = 'http://127.0.0.1:4200' # adapt Django's to Angular's presumed XSRF cookie/header names CSRF_COOKIE_NAME = "XSRF-TOKEN" CSRF_HEADER_NAME = "HTTP_X_XSRF_TOKEN" CORS_ORIGIN_WHITELIST = … -
Django- Changing Page Background with Session Variables
I am trying to have my application randomly select a background and use a session variable to keep it fixed as long as the session is open. This is the process I am using to set up the background: def bg_path(self): if self.request.session.get('background', None): background = self.request.session['background'] else: background = self.request.session['background'] = random.randint(1, 14) return "images/backgrounds/bg{}.jpg".format(background) If I place this in the view, I have trouble displaying the background because I can't call it in a static tag like so: {% static {{view.background}} %} I thought about moving the entire function into a template tag, but then accessing the session variable becomes increasingly complicated. I could also perhaps load the static functionality into the view and somehow deliver the converted string to the template. What is the cleanest solution? -
Django: icontains over unicode string
My client is asking something very weird but that makes sense in everyday operations. I have an user with the first name Nicolás and i am filtering through first name with the value Nicolas. Is there a way to show up the results? Thanks! The code i have so far q = request.GET['q'] q_res = Member.objects.filter( Q(first_name__icontains = q)| Q(last_name__icontains = q) ) -
Django LOGIN_REDIRECT_URL doesn't work
I want to use django login framework to my first application in django. This is my django url file from django.contrib.auth import views as auth_views ... url(r'^$', auth_views.login, {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name="logout"), In my settings file, I defined these variables: LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = '/conceptos' My django login view doesn't work propertly, always redirect to localhost:8000/index.html. But it shows the login form in localhost/. Why is this happening? -
How do I get the user object from Django middleware?
I have the following middleware: class TestMiddleware(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print(getattr(request, "user", None)) return self.get_response(request) The print function always prints None. I added the middleware both before and after the django.contrib.auth.middleware.AuthenticationMiddleware line in settings.py, but in either case, I get None. Also, I'm logged in as a user. What else can I try? I'm using Django 1.11. -
Django write to csv in views not working
In my views I have: import csv outputfile = open("test.csv", 'w') I am getting a [Errno 13] Permission Denied So I tried just opening the file: outputfile = open("test.csv") I am getting a [Errno 2] No such file or directory: 'test.csv' when I try to open it. When I run the same line of code using python manage.py shell, the file opens without an error. test.csv is in the same folder as my views. Why am I getting these errors and how do I go about fixing them? -
how to configure django form to create select option with query specific?
how to configure django form to create select option with query specific. Example1, i need create a select with user below a group but if i use just model i have every user, and just need the users specific. Example2. i have this models: class Fruit(models.Model): name = models.CharField(max_length=150) color = models.CharField(max_length=150) I Have this datas [apple, red], [banana, yellow], [strammberry, red], [orange, orange]... when i create my form i need select field that show me fruits color red. apple, strammberry. but show me all fruit. apple, banana, strammberry, orange what is the form to this do? -
Django: "Model" matching query does not exist
For the record, I've scoured this website for similar answers, but I'm still beating my head against a wall trying to figure this out. I'm using Django version 1.10, and I'm running MySQL as the database engine. I wish to simultaneously update a OneToOneField within a related model when saving information to my database (via my view), but an error is thrown "IndividualEmp" matching query does not exist. Here are the models: class IndividualEmp(models.Model): name = models.CharField(max_length = 100, db_column = 'name', primary_key = True) department = models.CharField(db_column='department', max_length=30, blank=True, null=True) emp_type = models.CharField(db_column='emp_Type', max_length=15, blank=True, null=True) class Meta: managed = False db_table = 'individual_emp' app_label = 'users' class IndividualDetails(models.Model): d_name = models.OneToOneField(IndividualEmp, models.DO_NOTHING, db_column = 'd_name', primary_key = True) gender = models.CharField(max_length=1, blank=True, null=True) email = models.CharField(max_length=20, blank=True, null=True) phone = models.CharField(max_length=9, blank=True, null=True) class Meta: managed = False db_table = 'individual_details' app_label = 'users' And here is my views.py file: from users.forms import Register from users.models import (Attendee, IndividualDetails, IndividualEmp) # Create your views here. def signup(request): form = Register(request.POST) if request.method == 'POST': if form.is_valid(): obj = Attendee() obj_1 = IndividualDetails() obj_2 = IndividualEmp() obj.attendee_ID = form.cleaned_data['attendee_ID'] obj_1.name = form.cleaned_data['name'] obj_1.department = form.cleaned_data['department'] obj_1.emp_type = form.cleaned_data['emp_type'] obj_2.gender … -
Integration testing of React front end with Django REST backend
Does anybody know how to do integration testing of a (React) frontend with Django REST backend. I was able to write functional tests for the frontend with Nightwatch.js and with a fake server API. I am also able to separately test Django REST API - Django offers a LiveServerTestCase that can start a test server for you with a test database and destroy it at the end. I'm wondering if it's possible to somehow use/setup Django's test server that can be called by the front end (i.e. Nightwatch tests). I'm open to other ideas on how I can approach this problem. -
Passing django variable to slide function in django template
I know that Django template allow this structure {% for i in paginator.page_range|slice:":10" %} It means just 10 element from paginator.page_range list. But how can instead passing 10, want to passing a variable, like this: {% for i in paginator.page_range|slice:":page_obj.number" %} -
NoReverseMatch at /blog/
I am following the <> and i met the problem but i don't know what causes it. The following is the error page: NoReverseMatch at /blog/ Reverse for 'post_detail' with arguments '('', '', '')' not found. 1 pattern(s) tried: ['blog/(?P\d{4})/(?P\d{2})/(?P\d{2})/(?P[-\w]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Django Version: 1.11 Exception Type: NoReverseMatch Exception Value: Reverse for 'post_detail' with arguments '('', '', '')' not found. 1 pattern(s) tried: ['blog/(?P\d{4})/(?P\d{2})/(?P\d{2})/(?P[-\w]+)/$'] Exception Location: E:\workspace\pycharm\djangobyexample\mysite\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 497 Python Executable: E:\workspace\pycharm\djangobyexample\mysite\env\Scripts\python.exe Python Version: 3.5.2 Python Path: ['E:\workspace\pycharm\djangobyexample\mysite', 'E:\workspace\pycharm\djangobyexample\mysite\env\Scripts\python35.zip', 'E:\workspace\pycharm\djangobyexample\mysite\env\DLLs', 'E:\workspace\pycharm\djangobyexample\mysite\env\lib', 'E:\workspace\pycharm\djangobyexample\mysite\env\Scripts', 'c:\users\richard\appdata\local\programs\python\python35\Lib', 'c:\users\richard\appdata\local\programs\python\python35\DLLs', 'E:\workspace\pycharm\djangobyexample\mysite\env', 'E:\workspace\pycharm\djangobyexample\mysite\env\lib\site-packages'] Main URLConfiguration urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), ] blog/url.py from django.conf.urls import url from . import views urlpatterns = [ # post views # url(r'^$', views.post_list, name='post_list'), url(r'^$', views.PostListView.as_view(), name='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), #url(r'^(?P<post_id>\d+)/share/$', views.post_share, name='post_share'), ] views.py from django.shortcuts import render, get_object_or_404 from .models import Post from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.views.generic import ListView from .forms import EmailPostForm from django.core.mail import send_mail # Create your views here. class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html' def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) models.py … -
Ul radio buttons disappear on hover
I am using CharField in a django form. The form element is rendered using {{ form.elementName }}. It shows a list of radio buttons for options specified for the field. However, the radio buttons disappear when selected or hovered. (see second option below): Same happens for a multi select field (https://github.com/goinnn/django-multiselectfield). I am using Bootstrap 3 for frontend. I tried but couldn't find any reason for it. No js errors were there. -
File upload in django giving IntegrityError
I have made some custom fields in my user model of django,what i was trying to do is to offer the user to set his/her profile by submitting those fields.although my custom model is working fine.since I can edit or add those fields in my admin site mode. But when I try to submit that form as a user, it gives an error like this:- Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: blog_profile.user_id my models.py:- class Profile(models.Model): user = models.OneToOneField(User,unique=True,on_delete=models.CASCADE,default=1) bio = models.TextField(max_length=500,null=True,blank=True) location = models.CharField(max_length=30,null=True,blank=True) birth_date = models.DateField(null=True,blank=True) pic=models.FileField(default='/user.png',null=True,blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py:- class ProfileForm(forms.ModelForm): class Meta: model=Profile fields = ['bio','location','birth_date','pic'] views.py:- def set(request): if request.user.is_authenticated(): if request.method == 'POST': form=ProfileForm(request.POST,request.FILES) if form.is_valid(): item=form.save(commit=False) item.pic=request.FILES['pic'] item.save() return redirect('/blog') else: return HttpResponse('Invalid') else: form=ProfileForm() return render(request,'blog/set.html',{'form':form}) My template for set is:- {% extends 'blog/base.html' %} {%block body%} <div class="container"> <div class="row">{{hell}} <div class="col-md-6 col-md-offset-3"> <div class="alert alert-success" role="alert"><strong>Well Done!</strong> {{user.username}} You Have Succesfully Registered!</div> </div> </div> <form method="POST" enctype="multipart/form-data">{% csrf_token %} {{form.as_p}} <input type="submit" value="Edit"> </form> </div> {%endblock%} This is my attempt please help me i am new to all of these stuffs thanks in … -
How can I get data argument from serializer?
I'm using Django and django-restframework. I don't know How to access Serializer's argument. I can access full json data from serializer.data. But when I tried to get argument like id, then it return error. serializer.data.id. How can i get it? I used lots of time for search this, but failed. I do this because update model based on user input. e.g. user input id. get data with that id. save that data to database. I'm very very thanks for reading this. views.py class CareerViewSet(viewsets.ModelViewSet): queryset = Career.objects.all() serializer_class = CareerSerializer permission_classes = (IsCreateable,) def perform_create(self, serializer): serializer.save(nickname='test') print(serializer.data) print(serializer.data.id) Error {'id': 14, 'created': '2017-04-26T12:39:58.249038Z', 'modified': '2017-04-26T12:39:58.249538Z', 'battle_tag': 'Fortune-1130', 'nickname': 'test', 'quick_eliminations': None, 'quick_damage_done': None, 'quick_deaths': None, 'quick_final_blows': None, 'quick_healing_done': None, 'quick_objective_kills': None, 'quick_objective_time': None, 'quick_solo_kills': None, 'competitive_eliminations': None, 'competitive_damage_done': None, 'competitive_deaths': None, 'competitive_final_blows': None, 'competitive_healing_done': None, 'competitive_objective_kills': None, 'competitive_objective_time': None, 'competitive_solo_kills': None, 'games_won': None, 'competitive_rank': None, 'level': None} Internal Server Error: /career/ Traceback (most recent call last): File "E:\Development\Venv\20170420\myvenv\lib\site-packages\django\core\handlers\exception.py", line 42, in inner response = get_response(request) File "E:\Development\Venv\20170420\myvenv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\Development\Venv\20170420\myvenv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Development\Venv\20170420\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "E:\Development\Venv\20170420\myvenv\lib\site-packages\rest_framework\viewsets.py", line 83, … -
Django: how to emulate a slow server?
The production server my work is pushed to performs significantly worse than my local development environment, where everything runs fast and smoothly, so I cannot figure out if any change I make may or may not have a bad performance in production. In that server, responses take a lot of time, mostly I assume because of the database queries, rather than the server's processing power and memory capacity. I wonder if there is any way to set up a server configuration to emulate these bad conditions: how can I reduce the power of my local Django server so that responses take longer, processing power is low and, most importantly, database connection is slow? I hope this is not a crazy ask, but it is something I really need to figure out how my code will behave in production, since I have no way of telling that from my local environment. -
django upload file, process pandas and download as csv
I built an app which allows the user to upload a file. On the other hand, I have some python script which takes a text file, convert it to CSV and do pandas. This script works perfectly when running in the terminal. Now I want to apply that python script to the file upload in Django and show that file in httpResponse and make available to download it. python script import csv import pandas as pd df = pd.read_csv('raw_df.txt', delimiter = '\t' , usecols=['Sample','Cohort','Metabolite Name','Intensity']) df = df[df['Cohort'].str.contains("std")] df = df.groupby(['Cohort', 'Metabolite Name'])['Intensity'].sum().reset_index() df = df[['Cohort','Intensity']] c = 'Cohort' s = df.set_index([c, df.groupby(c).cumcount() + 2]).Intensity df = s.unstack().add_prefix('Intensity').reset_index() df.to_csv() print df; views.py from django.shortcuts import render, redirect from django.conf import settings from django.core.files.storage import FileSystemStorage from uploads.core.models import Document from uploads.core.forms import DocumentForm def home(request): documents = Document.objects.all() return render(request, 'core/home.html', { 'documents': documents }) def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() return render(request, 'core/model_form_upload.html', { 'form': form }) Models.py class Document(models.Model): document = models.FileField(upload_to='documents/') template-upload page {% extends 'base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> <p><a … -
TypeError Object id is not JSON serializable
I have a link (in a form submit) on one of my Django views where the url uses an id. When the template tries to render I get the following error: TypeError: is not JSON serializable The error is triggering on this line: <form id="a-form" method="POST" action="{% url 'app:form_submit' model1_id=model1object.id %}" class="" enctype="multipart/form-data">{% csrf_token %} In this view I have passed the variable model1object to the template. def view(request, variable): # this works fine model1object = Model1.objects.get(pk=variable) # ... context = { "model1object": model1object, .... } return render(request, 'app/template.html', context) Here is the url where I need the model1_id: url(r'^(?P<model1_id>[0-9]+)/.../$', views.form_submit, name='form_submit' ), I can't figure out the problem. It's just an id that I'm passing...??? Here's my model for Model1: class Model1(models.Model): date_field = models.DateField() another_field = models.CharField(max_length= 50, default="...") def __str__(self): return unicode(self.id) or u'' def get_absolute_url(self): return reverse('app:model1', kwargs={'id': self.id}) thanks -
Upgrade to Django 1.9 or 1.11 (from 1.6) - Error when calling the metaclass bases
i am upgrading to django 1.9 (from 1.6) mysql-connector-python 2.1.6 is installed when i am trying to run my app, i get: TypeError: Error when calling the metaclass bases 'NoneType' object is not callable does anyone had this issue? stacktrace: /Library/Python/2.7/site-packages/django/core/handlers/wsgi.pyc in __init__(self, *args, **kwargs) 149 def __init__(self, *args, **kwargs): 150 super(WSGIHandler, self).__init__(*args, **kwargs) --> 151 self.load_middleware() 152 153 def __call__(self, environ, start_response): /Library/Python/2.7/site-packages/django/core/handlers/base.pyc in load_middleware(self) 55 for middleware_path in settings.MIDDLEWARE_CLASSES: 56 print middleware_path ---> 57 mw_class = import_string(middleware_path) 58 try: 59 mw_instance = mw_class() /Library/Python/2.7/site-packages/django/utils/module_loading.pyc in import_string(dotted_path) 18 six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) 19 ---> 20 module = import_module(module_path) 21 22 try: /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.pyc in import_module(name, package) 35 level += 1 36 name = _resolve_name(name[level:], package, level) ---> 37 __import__(name) 38 return sys.modules[name] /Library/Python/2.7/site-packages/django/contrib/auth/middleware.py in <module>() 2 from django.contrib import auth 3 from django.contrib.auth import load_backend ----> 4 from django.contrib.auth.backends import RemoteUserBackend 5 from django.core.exceptions import ImproperlyConfigured 6 from django.utils.deprecation import MiddlewareMixin /Library/Python/2.7/site-packages/django/contrib/auth/backends.py in <module>() 2 3 from django.contrib.auth import get_user_model ----> 4 from django.contrib.auth.models import Permission 5 6 UserModel = get_user_model() /Library/Python/2.7/site-packages/django/contrib/auth/models.py in <module>() 2 3 from django.contrib import auth ----> 4 from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager 5 from django.contrib.auth.signals import user_logged_in 6 from django.contrib.contenttypes.models import ContentType /Library/Python/2.7/site-packages/django/contrib/auth/base_user.py in <module>() 50 … -
how to overwrite RetrieveAPIView response django rest framework
I am fetching data from RetrieveAPIView I want to overwrite it. class PostDetailAPIView(RetrieveAPIView): queryset = Post.objects.all() serializer_class = PostDetailSerializer lookup_field = 'slug' http://127.0.0.1:8000/api/posts/post-python/ it return me result { "id": 2, "title": "python", "slug": "post-python", "content": "content of python" } I want to overwrite this with some extra parameters like [ 'result': { "id": 2, "title": "python", "slug": "post-python", "content": "content of python" }, 'message':'success' ]