Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove [ ] closed bracket in djagno rest framework output
Is there any way to remove [] in the output when we run server using django. I need output only in json format, I dont need open and closed bracket in start and end position of output Here is my output after run the server : http:127.0.0.1:8000/WBCIS/wbcis/ [ { "id": 1, "fruit": "Pomegranate", "district": "Pune", "taluka": "Haveli", "revenue_circle": "Uralikanchan", "sum_insured": 110000.0, "area": 12200.0, "farmer": 1836 }, { "id": 2, "fruit": "Guava", "district": "Pune", "taluka": "Haveli", "revenue_circle": "Uralikanchan", "sum_insured": 50000.0, "area": 1150.0, "farmer": 10 } ] this is my current output, but i want data in this format, like : { { "id": 1, "fruit": "Pomegranate", "district": "Pune", "taluka": "Haveli", "revenue_circle": "Uralikanchan", "sum_insured": 110000.0, "area": 12200.0, "farmer": 1836 }, { "id": 2, "fruit": "Guava", "district": "Pune", "taluka": "Haveli", "revenue_circle": "Uralikanchan", "sum_insured": 50000.0, "area": 1150.0, "farmer": 10 } } Any idea how to remove [ ] brackets ? -
How can I translate dynamic variable with trans tag in Django?
I want to translate variable which is coming from database like page_title. {% page_info as page_list %} {% for page in page_list|slice:'10:14' %} <li> <a href="{% url "uniwissen:get_page" page.slug %}"> {{ page.title }} </a> </li> {% endfor %} In this code block, I try to translate {{ page.title }} part. But .po django files dont see this variable. How can I solve? Thank you. -
Getting Error While installing MYSQL-python
I'm using python 2.7 and django 1.9.4 i want to integrate my django application with mysql database i executed pip install MySQL-python on windows 7 machine And getting Error : F:\Djangoproject\mysite>pip install MySQL-python Collecting MySQL-python Using cached MySQL-python-1.2.5.zip Building wheels for collected packages: MySQL-python Running setup.py bdist_wheel for MySQL-python ... error Complete output from command c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\chandra\\appdata\\local\\temp\\pip-build -3qbbxo\\MySQL-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__ , 'exec'))" bdist_wheel -d c:\users\chandra\appdata\local\temp\tmpoytuplpip-wheel- --python-tag cp27: running bdist_wheel running build running build_py creating build creating build\lib.win32-2.7 copying _mysql_exceptions.py -> build\lib.win32-2.7 creating build\lib.win32-2.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-2.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-2.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-2.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-2.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-2.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-2.7\MySQLdb creating build\lib.win32-2.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-2.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-2.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-2.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-2.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-2.7\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-2.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-2.7\MySQLdb\constants running build_ext building '_mysql' extension creating build\temp.win32-2.7 creating build\temp.win32-2.7\Release C:\Users\Chandra\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info =(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -Ic:\python27\include -Ic:\python27\PC /Tc_mys ql.c /Fobuild\temp.win32-2.7\Release\_mysql.obj /Zl _mysql.c _mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory error: command 'C:\\Users\\Chandra\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\cl.exe' … -
Django: csrf_exempt doesn't work when other server send request?
views.py class OrderPayCheckView(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(OrderPayCheckView, self).dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): return redirect(reverse("home")) I used 3rd-party service (I'm client) and it sends sort of Notification request(POST) to OrderPayCheckView. Since this POST request is not from my application, I thought that this view should be decorated with csrf_exempt so that it doesn't require csrf token anymore. When I tested with POSTMAN it works very well: it shows redirected template page as a response body. However, when this 3rd-party service(server) tried sending POST request to this view, it shows an csrf-token authentication errors like this: (Since errors are in Korean, I translate it) REQUEST HTTP BODY : imp_uid=imp_1234567890&merchant_uid=merchant_1234567890&status=ready REQUEST HTTP STATUS : 403 REQUEST HTTP BODY : <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> </head> <body> <div id="summary"> <h1>Forbidden <span>(403)</span></h1> <p> CSRF authentication failed. </p> <p> The reason this message shown up is that this https site require "reference header" from your browser, but didn't receive anything abuout it. This header is required for security.</p> </div> </body> </html> What's wrong with it? Do sender have to add specific reference header to its request? -
django set context in template and pass it to different template
I am calling one template from another template using the following code <a class="admin" href={% url "manage_cases" %}>Manage cases</a> Now the page that gets loaded has something like this <script> $(document).ready(function(){ {% if foo == "val" %} .... {% endif%} }); </script> My question is in the code <a class="admin" href={% url "manage_cases" %}>Manage cases</a> -->I want to pass foo="val" as a dictionary context to that page How can I set the value of a parameter in the context and pass it in the above statement. I know i could pass a parameter from the view that calls the template but i am not sure how I can set a value through a template that calls that template ? -
Django restframework serializer response custom message
I'm trying to override the response message(return data) of the serializer. Below is my sample code. models.py from django.db import models class MyModel(models.Model): name = models.charField() email = models.EmailField() phone = models.charField() serializer.py from rest_framework import serializers class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('id', 'name', 'email', 'phone') def validate(self, data): ''' Some validation here ''' return data views.py from rest_framework import generics class MyModelList(generics.ListCreateAPIView): queryset = MyModel.objects.all().order_by('-id') serializer_class = MyModelSerializer Here, when I try to post the data, the serializer return the response in the json format like this { 'id': 2, 'name': 'myname', 'email': 'mayname@example.com', 'phone': 8569874587, } But I want to return the custom json response like this if the post is success. { 'success' : 'data posted successfully', } Guys how can I override this for the custom message, please help me for this, it will be very great-full, Thanks in advance. -
Django client side validation on decimal field limit
I wanted to limit django model decimal field to 4 places in client side itself meaning field should not allow user to enter more than 4 digits. I tried below code but its get validate only after save but i need to limit while user entering digits. unit_price = models.DecimalField(db_column='UNIT_PRICE', max_digits=4, decimal_places=2) -
How to create a custom entry style for field in django admin
I have this project where i have to store two dates (month and year) in the hebrew calendar in a model and get the model if the current date is between the two. My solution to this is to store them as SmallIntegerFields in the database in the MMDD format so that I can do a quick search after converting the date. Is there any way for me to modify the admin display of this field to show two dropdowns one for the months and one for the dates? (and convert them back and forth on load and save) -
Django cms select instead list in admin filters
I'm using Django 1.7 and need to make filter in admin page so class CityFilter(admin.SimpleListFilter): title = _("Cities") parameter_name = "cities" def lookups(self, request, model_admin): return ( ((c.id, _(c.name)) for c in City.objects.all()) ) def queryset(self, request, queryset): if not self.value(): return queryset objs = User.objects.filter( city=self.value() ).values_list('user__id', flat=True) return queryset.filter(id__in=objs) And I have + 200 cities and it looks not good in admin (as list) How can I change this list to something like select2? -
django reverse match problems
I have been trying to figure out why I'm having trouble with this. Everything seems to be fine, and I have no problems with other urls reversing. When I enter the URL manually, the page comes up fine. This is the template tag that causes the problems: {% url 'schedule:calendar' %} Here is urls.py: app_name = 'schedule' urlpatterns = [ url(r'^$', login_required(views.CalendarView.as_view(), login_url='/login/'), name='calendar'), ] I don't think it's necessary, but my views file has only this in it: class CalendarView(TemplateView): template_name = 'schedule/index.html' def get_context_data(self, **kwargs): context = super(CalendarView, self).get_context_data(**kwargs) context['template'] = 'calendar_view' return context I don't see naming conflicts at all, yet when I put {% url 'schedule:calendar' %} in my template, anywhere, it throws the error, even if that is the only thing in the template page. Here is the error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/schedule/ Django Version: 1.10.3 Python Version: 3.5.2 Installed Applications: ['footables', 'floppyforms', 'djangobower', 'custom_user', 'bootstrap3_datetime', 'widget_tweaks', 'schedule.apps.ScheduleConfig', 'customers.apps.CustomersConfig', 'employees.apps.EmployeesConfig', 'jobs.apps.JobsConfig', 'frontend.apps.FrontendConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'mptt'] 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'] Template error: In template /home/poduck/PycharmProjects/mobileautorepair/schedule/templates/schedule/index.html, error at line 0 Reverse for '' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) … -
use single-sign-on/remote-user authentication with django restframework to get authentication token
I have a django application implementing a REST API using the django-rest-framework. The authentication is to be implementated using apache/single-sign-on/remote-user method, for the non-API part of the URL Tree. and for the API portion of the tree we would like to use token based authentication. What is the simplest way to retrieve the authentication token, through a restframework APIview under the non-SSO protected part of the URL subtree. Using rest_framework.authtoken.views.obtain_auth_token seems to look for user/password in the json data. What is the best way of doing this using single-sing-on/remote_user, where the authentication is taken care of the apache. I was thiking there should be an existing authentication class that should help. But can't seem to find it. -
Django CSRF Error for Registration
I've thoroughly searched and applied code to the best of my current ability fixes to what solved other peoples similar problems, except I still get a 403 CSRF error when the user presses 'register' on my registration form, but admin login works. If any one can point me in the right direction it would be much appreciated. The things Ive tried and checked so far is: to put the CSRF middleware at the top of the middleware list, make sure the html registration form has {% csrf_token %}, make sure the register view contains render_to_response with RequestContext, and now im at a loss of what to try next. My project is called mysite, with the app login. Using django 1.10.5 and python 3.5 mysite/urls.py: from django.conf.urls import url, include from django.contrib import admin from login.views import home, logout_page, register_success, register import django from django.contrib.auth import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^webapp/', include('webapp.urls')), #url(r'^', include('personal.urls')), url(r'^contact/', include('personal.urls')), url(r'^blog/', include('blog.urls')), url(r'^$', django.contrib.auth.views.login), url(r'^home/$', home), url(r'^register/$', register), url(r'^register/success/$', register_success), url(r'^accounts/login/$', django.contrib.auth.views.login), url(r'^logout/$', logout_page), ] mysite/settings.py: INSTALLED_APPS = [ 'webapp', 'personal', 'blog', 'login', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] import django.contrib.auth django.contrib.auth.LOGIN_URL = '/' MIDDLEWARE = [ 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', … -
Django-allauth send emails in English when language is set to es-ES
i am using django-allauth and since a big update in my dependencies for some reason all the emails are being sent in English and one it is mixed, a sentence it is in Spanish and the rest in English, even when LANGUAGE_CODE it is defined with my lang (es-ES, i tried only "es" too) at my project settings file. The settings (base.py): ########## GENERAL CONFIGURATION TIME_ZONE = 'America/Argentina/Cordoba' LANGUAGE_CODE = 'es-ES' SITE_ID = 1 USE_I18N = True USE_L10N = True USE_TZ = True ########## END GENERAL CONFIGURATION ########## SOCIALACCOUNT CONFIGURATION SOCIALACCOUNT_EMAIL_VERIFICATION = 'optional' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_AUTO_SIGNUP = True SOCIALACCOUNT_EMAIL_REQUIRED = True SOCIALACCOUNT_PROVIDERS = \ {'facebook': {'SCOPE': ['email',], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'METHOD': 'js_sdk', 'LOCALE_FUNC': lambda request: 'es-ES', 'VERIFIED_EMAIL': True}} ACCOUNT_AUTHENTICATION_METHOD = "username_email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "optional" ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_USERNAME_MIN_LENGTH = 5 ACCOUNT_PASSWORD_MIN_LENGTH = 6 ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True ACCOUNT_SIGNUP_FORM_CLASS = 'algo.forms.SignupForm' ########## END SOCIALACCOUNT CONFIGURATION I am using django 1.10.2 and allauth 0.27.0, i have uninstalled allauth and re-installed but the problem it is still there. What can be the issue? Thanks a lot! -
Process all the template questions in django view at once
Hi Everyone! i am a newbie.Using the django documentation example, how do i process all the questions in #the views.py Template: <html> <body> {% for question in latest_question_list %} <h1>{{ question.question_text }}</h1> {% if error_message %} <p><strong>{{ error_message }}</strong> </p> {% endif %} <form id="qform" action="{% url 'polls:vote' question.id %}" method="post">{% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="{{ question.id }}" id=”choice{{ forloop.counter }} " value="{{ choice.id }}” /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label> <br/>{% endfor %} </form> {% endfor %} <input form="qform" type="submit" value="Vote" /> </body> </html> views.py(this is not working!) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST[question.id]) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return render(request,'polls/results.html', {'question':question, 'selected_choice': selected_choice, 'error_message': error_message}) Kindly tell me what i am missing; i need help badly. Thank you all! -
Can you have two of the same regex but point to them to different url files
For example is the following allowed? If so, is it not recommended or is it okay? urlpatterns = [ url(r'^$', include('login.urls')), url(r'^$' include('register.urls')), url(r'^admin/', admin.site.urls), ] -
Difference between `self` & `request`
I'm currently learning how to make a website with django. I have a little issue when I create a function. Could anyone be able to tell me what it is the difference between def function(self) and def function(request)? Thanks in advance -
Django template structure issues
I have a base.html template that every page on my site will be extending. However, from what I've gathered, Django requires that templates should be in the app directory. From an app, how can I extend a template that I have located in my project's basedirectory/templates/ ? Here is how my directories are ordered: project/ |----templates/ | |----base.html | |----app1/ | |----templates/ | |----app1/ | |----base.html | |----index.html | |----app2/... Currently, I have index.html extending app1/base.html: {% extends 'welcome/base.html' %} However, this is not ideal, because I want to extend project/templates/base.html. Logically, my app1 shouldn't have a template in it. -
How do I add the username to the url right after login in django?
When a user clicks 'login' I want them to be logged in and redirected to i.e., www.exampledomain.com/accounts/usernameGoesHere/ Here are my top level urls: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('accounts.urls')), ] and here are the urls for accounts: urlpatterns = [ url(r'^(?P<username>\w+)/$', login_required(views.IndexView.as_view()), name = 'index'), url(r'^login/', login_view, name='login'), url(r'^logout/', logout_view, name='logout'), url(r'^register/', register_view, name='register'), ] This is my login view: (I'm showing the full view but most of it can be ignored) class IndexView(FormView): template_name = 'accounts/index.html' form_class = PtoRequestForm success_url = '/accounts' # Function runs when form is submitted. Do whatever needed to the form before it's saved to the db. def form_valid(self, form): new_form = form.save(commit=False) new_form.user = self.request.user new_form.title = self.request.user.first_name new_form.save() return super(IndexView, self).form_valid(form) # Function runs on page load. Gather any information needed for the template. def get_context_data(self, **kwargs): # Initialize context context = super(IndexView, self).get_context_data(**kwargs) # Grab all ptoHistory records from the database, selecting only the values desired. pto_history = PtoHistory.objects.values('title', 'start', 'end', 'pk', 'user_id') # Convert the django queryset to json so that fullcalendar can work with it on the frontend. json_pto_history = json.dumps(list(pto_history), cls=DjangoJSONEncoder) # Save the converted json to the context to be returned to the front end. context['ptoHistory'] = … -
FileNotFoundError after deployment
I have written a web app in Django that works fine locally. After deploying it, trying to access a pdf throws an error FileNotFoundError. settings.py PDF_DIR = os.path.join(BASE_DIR, 'report/static/media/pdfs') model.py pdf = models.filePathField(path=settings.PDF_DIR) How can I solve this error? -
Django not searching templates directory defined in DIR setings
I got a templates directory in same level as my project directorry so I put in settings.py DIR = [BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ] but Django is not searching that templates directory that is outside of any apps meaning it is ame level as the project directory. -
Logging with email/password not with username using djangorestframework-jwt and django-rest-framework
I'm using rest-framework-jwt and just wanna know a few things. First, I make the login with the email and password, and I get the token. It works well. but I also wanna create a token in my register. so, I use this function: def create_token(user): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) return token The problem is that I don't have an username. So, it doesn't work. :) I thought, if it works with the login, it should work with the register. But not. :smiley: Even if I wrote this USERNAME_FIELD = 'email' in my model. It always asks for a username in my "create_token" function. But second, I would like to create the token with just the email, password, and uuid And third... Is the same token from my register and from my login? To make the requests, it should be the same. Thank you! -
ValueError: Found wrong number (0) of constraints for
While using Django 1.7 migrations, I came across a migration that worked in development, but not in production: ValueError: Found wrong number (0) of constraints for table_name(a, b, c, d) This was caused by an AlterUniqueTogether rule: migrations.AlterUniqueTogether( name='table_name', unique_together=set([('a', 'b')]), ) Reading up on bugs and such it seems to be about the existing unique_together in the db not matching the migration history. How can I work around this? -
Django sum and filter does not work
What i am trying to do is Sale.objects.values('pro').annotate(total_value = Sum('effective_price')).filter(total_value__gt=Decimal('600.00')).order_by('total_value'); In orm it does not return anything but when i takes it query in sql and then execute in sql it returns results as i want. There is a problem with filter as far as i know. I don't know why it is not working even count is working properly when i filter using the annotate variable. Please help me out. I will be very thankful to you. -
How to use Http headers in django? [on hold]
how I can configure and secure my site with HTTP Headers in django and how to use request.META.get('HTTP_AUTHORIZATION') -
Django Open and View a PDF(stored in AWS) in a new Tab
I have a model that stores a PDF file. On the DetailView of that Model I would like to have a link to view the PDF in a new tab. There are similar questions on here that I've used to get this far, but it looks like they're for local PDFs. My PDFs are stored as Media on AWS. This is what I have right now: plans/models.py class PlanSet(PlanModel): ... class PlanSetPDF(models.Model): planset = models.ForeignKey(PlanSet) PDF = models.FileField(upload_to='planPDFs') created = models.DateField(auto_now_add=True) added_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True) plans/views.py class PlanSetDetailView(DetailView): model = PlanSet template_name = "plan_detail.html" def get_context_data(self, **kwargs): context = super(PlanSetDetailView, self).get_context_data(**kwargs) context['now'] = timezone.now() return context def view_pdf(request, pk): pdf = get_object_or_404(PlanSetPDF, pk=pk) image_data = open(pdf.PDF.url, "rb").read() return HttpResponse(image_data, contenttype='application/pdf') plans/urls.py urlpatterns = [ url(r'^(?P<pk>\d+)/$', plan_detail, name='detail'), url(r'^(?P<pk>\d+)/pdf/$', view_pdf, name='view_pdf'), ] urls.py: url(r'^plans/', include(plan_sets.urls, namespace='plans')), template: {% for pdf in object.plansetpdf_set.all %} <a href="{% url 'plans:view_pdf' pdf.pk %}"> <span class="glyphicon glyphicon-file" aria-hidden="true"></span>PDF</a> {% endfor %} I'm recieving a builtin.OSError:[Errno 22] Invalid Argument: 'https://link_to_PDF_file_on_amazon' It looks like Python can't open the file. I've looked around and I can't find any answers. Can one of you show me where I'm going wrong? Thanks.