Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx serve HTTPS response redirects
Django + Nginx + uWSGI environment. I'm stuck trying to solve the following problem: The django application ensures the user is logged in before accesing resources through the @login_required decorator. In browser after the user session expires, if the user still attempts the access some resources the Django behaviour (through login_required) is to return a HttpResponseRedirect to the LOGIN_URL mentioned in settings.py The url format constructed in the HttpResponseRedirect object is like : /login/?next=/api/resource%3F_%3D1529658942988 The browser receives a HTTP 302 status code with the Location header like : http://some.ip.address/login/?next=/api/resource%3F_%3D1529658942988 Since this is Http (not Https) the browser blocks is due to active mixed content. How could I instruct the Nginx to serve the browser these redirects using Https ? -
Django getting foreign-key object list
I have model like this: class A: .... class B: .... a = model.ForeignKey(A, related_name='a') .... Let's assume there is an B object. I can get A object like this: b = B() a = b.a Then what is the simplest way to get all B object related with A? Additionally, I can get a list of A. list_a = A.objects.filter() Then how I can get a list of B which relates with A object list? -
Django: How to add email/password authentication to OAuth using REST
I can be able to setup separated OAuth provider server(PS) and Resource Server(RS). I can use username/password and get the bearer token from the PS normally. But I would like to extend the feature by let user be more convenient by accepting his email/password I had dig the issue and found the RFC. However, I am new to this thing. Attempt: The endpoint View is this, but I zoom to the inside and not understand it. @method_decorator(csrf_exempt, name="dispatch") class TokenView(OAuthLibMixin, View): """ Implements an endpoint to provide access tokens The endpoint is used in the following flows: * Authorization code * Password * Client credentials """ server_class = oauth2_settings.OAUTH2_SERVER_CLASS validator_class = oauth2_settings.OAUTH2_VALIDATOR_CLASS oauthlib_backend_class = oauth2_settings.OAUTH2_BACKEND_CLASS @method_decorator(sensitive_post_parameters("password")) def post(self, request, *args, **kwargs): url, headers, body, status = self.create_token_response(request) if status == 200: access_token = json.loads(body).get("access_token") if access_token is not None: token = get_access_token_model().objects.get( token=access_token) app_authorized.send( sender=self, request=request, token=token) response = HttpResponse(content=body, status=status) for k, v in headers.items(): response[k] = v return response class OAuthLibMixin(object): @classmethod def get_oauthlib_core(cls): """ Cache and return `OAuthlibCore` instance so it will be created only on first request """ if not hasattr(cls, "_oauthlib_core"): server = cls.get_server() core_class = cls.get_oauthlib_backend_class() cls._oauthlib_core = core_class(server) return cls._oauthlib_core def create_token_response(self, request): … -
Angular Routing not working with Django
I am building a project in Django and Angular. I have out the following code to provide routing after including/loading the angular routing library in my main html page. (function(){ 'use strict'; angular.module('scrumboard.demo') .config (['$routeProvider', config]) .run(['$http',run]); function config($routeProvider) { $routeProvider .when ('/', { templateUrl: '/static/html/scrumboard.html', controller: 'ScrumboardController', }) .when ('/login', { templateUrl: '/static/html/login.html' }) .otherwise('/'); } function run($http) { $http.defaults.xsrfHeaderName = 'X-CSRFToken'; $http.defaults.xsrfCookieName = 'csrftoken'; } })(); My urls.py looks like this urlpatterns = [ path('admin/', admin.site.urls), url(r'$', ensure_csrf_cookie(TemplateView.as_view(template_name="home.html"))), path(r'scrumboard/', include('scrumboard.urls')), path(r'auth_api/', include('auth_api.urls')), ] and I have included following in the settings.py 'DIRS': [os.path.join(BASE_DIR, 'templates')], STATIC_URL = '/static/' STATICFILES_DIRS =( os.path.join(BASE_DIR, 'static'), Yet, when I load localhost:8000/login then no page gets loaded but when I load localhost:8000/static/html/login.html then the page loads correctly. It seems angular routing is not working correctly. -
Tree in generic template
I am new with Django but i understand that the aim is to never reinvent the wheel. I am developing an application to supervise a factory, and in all the views I need to implement a tree represent the structure of the factory. In the template folder of the project, I did a html file, but i can't find a way to put the tree's element with a render or something like that Is there a solution to fix it, or is it mandatory to copy-paste the code of the tree in all views ? Thanks, Baptiste. -
Can't connect to my AWS Database Instance | psql: could not connect to server: Operation timed out
I created a postgres DB instance on AWS RDS. I am trying to connect this DB instance to my django zappa add so I can perform AWS Lambda functions. I've added a new security group to my DB instance so I can allow my django app to connect to it: My DB details show that the new security group is active: However when I try to connect to it, either by running psql --host="*************.us-east-2.rds.amazonaws.com" --port="5432" --username="*********" --password --dbname="*****" via my terminal, or via my pgadmin interface, it returns this error: psql: could not connect to server: Operation timed out Is the server running on host "***********.us-east-2.rds.amazonaws.com" (18.191.94.44) and accepting TCP/IP connections on port 5432? Any idea why it does this? -
How to send an email from different from address in django
I want send emails from my django app with different from address.My settings are EMAIL_BACKEND = 'post_office.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'outlook.office365.com' EMAIL_HOST_USER = 'mymail@domain.ae' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = 'Marketing<mymail@domain.ae>' SERVER_EMAIL = 'mymail@domain.ae' DEFAULT_BCC_EMAIL = 'mymail@domain.ae' DEFAULT_REPLY_TO_EMAIL = 'mymail@domain.ae' I could able to send email from 'mymail@domain.ae' .But if I'm using another from address it is going to spam mail.Is there any other way to avoid this? -
authenticate and login user with GET request
I've got a task of logging in user in GET request with specified login and password as arguments in url string. I've done it like this: def login_view(request): username = request.GET.get('login') password = request.GET.get('passwd') print('Is authenticated', request.user.is_authenticated) user = authenticate(request, username=username, password=password) if user is not None: login(request, user) print('Is authenticated', request.user.is_authenticated) return redirect('home') return HttpResponse("Login failed") and it must be working as it seemingly complies with documentation except the request method. In documentation it's POST but i've to make it for GET. So now it's not authenticated: Is authenticated False Is authenticated False and I'm sure it's due to wrong method type. Do you have any suggestions on how to work around this issue? -
django how to serialize fields into DateTimeRangeField
I'm having a bit of trouble serializing fields into DateTimeRangeField. The request currently has to have the following format: data = {"time": { "lower": timeThing, "upper": laterTimeThing } } What I would like it to look like on the request is this: data = { "start": timeThing, "end": laterTimeThing } So I can then serialize start/end into lower/upper. Here is my model: class Example(models.Model): time = DateTimeRangeField() user = models.ForeignKey('user.User') class ExampleAPI(ListCreateAPIView): serializer_class = ExampleSerializer pagination_class = None queryset = Example.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) class ExampleSerializer(serializers.ModelSerializer): time = DateTimeRangeField(write_only=True) user = serializers.ReadOnlyField(source='user.id') class Meta: model = Example exclude = ['user'] I've tried creating a custom field but it doesn't seem to go into the overriden to_representation or to_internal_value. The error message I got was {'time': ['This field is required.']} -
Django - Multi filtering queryset return empty queryset
I have problem with queryset in Django 2.0, after some research I don't find any problem looks like mine. I think it's because of my very old legacy database create by someone i didn't now. So, I have a sqlite database who looks like this: Has you can see, the Table Properties don't have primary_key, so i made a models with django inspectdb command who looks like this: from django.db import models class Record(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) class Meta: db_table = 'Records' def __str__(self): return "%s" % self.id class Propertie(models.Model): id = models.ForeignKey(Record, models.DO_NOTHING, db_column='ID', primary_key=True) item = models.CharField(db_column='Item', max_length=500) value = models.CharField(db_column='Value', max_length=500) class Meta: db_table = 'Properties' def __str__(self): return '[%s]- %s -> %s' % (self.item, self.value, self.id) I set Properties.id as primary_key but it's a ForeignKey and Django say to set this field as OneToOneField and it's normal and logic, but 1 Record is link to 9 Properties so Porpertie.id can't be unique this is my first problem because i can't alter the database. My second and real problem is when I run this query: def my_view(request): epoch = datetime.date(1970, 1, 1) period_from = stat_form.cleaned_data.get("period_from") period_to = stat_form.cleaned_data.get("period_to") product = stat_form.cleaned_data.get("kit") timestamp_from = period_from - epoch … -
How to specify the parameter for GET requests in django-rest-swaggerd for rendering serielizer with GenericAPIVIew
In the latest version on Django REST Swagger (2.1.0) YAML docstrings have been deprecated. I want to know how get swagger parameters to show GET response. class BizDay(GenericAPIView): """ get: Check whether this day is a business day in a specified timezone """ authentication_classes = (authentication.SessionAuthentication,) serializer_class = BizDayReq def get(self, request, version): serializer = BizDayReq(data=request.query_params) serializer.is_valid(True) data = serializer.validated_data regions = data['regions'] base_region = regions[0] days_offset = data['days_offset'] cutoff_region = data['cutoff_region'] cutoff_hour = data['cutoff_hour'] calendar = TradingCalendar(*regions) #Business logic #.... resp = { 'date': dt_next.strftime('%Y-%m-%d'), 'tz_region': base_region } return Response(resp) My serializer class BizDayReq(serializers.Serializer): base_date = serializers.IntegerField(required=False) regions = serializers.CharField(min_length=2) days_offset = serializers.IntegerField(required=False, default=1) cutoff_hour = serializers.IntegerField(required=False, default=20) cutoff_region = serializers.CharField(required=False, default='HK') def validate_regions(self, value): return value.split(',') Result of swagger rendering How can I specify the parameters. I tried to follow the advice from this question, but as you see it didn't help I'll appreciate any help. -
python-Django; How would one Left join ALL entries of 3 Models and then access them in Templates
I found some QA about Left joins and Django but all where (as the Docs) about filtered joins. I would like to do a Left join from Time to Card to Person (models below). For what I know I would use select related but I couldn't wrap my head arround how I would do this for 3 Models without filters (like seen in the Doc). I have 3 Models: class Person(models.Model): id = models.IntegerField() name = models.Charfield(max_length=32) class Card(models.Model): id_person = models.Foreignkey(Person) class Time(models.Model): id_card = models.ForeignKey(Card) time = models.Charfield(max_length=32) I tried: person = Card.objects.select_related('person') timestamp = Time.objects.select_related('card', person) And then of course I would like to use it my templates. I tried: {% for timestamp in time %} {{ timestamp.time }} {{ timestamp.card.id_person }} {{ timestamp.person.name }} {% endfor %} But that doesn't work for more and less obvious reasons. All hints appreciated. -
Method Not Allowed (POST) - search
The quest: add simple search on top of a django-table to filter it's values. Problem: f^tup somewhere and getting this error when passing request after putting value in search window: Method Not Allowed (POST): /warscrolls/ [22/Jun/2018 10:27:17] "POST /warscrolls/ HTTP/1.1" 405 0 My url is like this: url(r'^warscrolls/$', ScrollListView.as_view(filter_class=ScrollListFilter, template_name='scroll_list.html'), name='warscrolls'), My search form in html template looks like this: <form method="post" class="form-inline form-search pull-right"> {% csrf_token %} <div> <input id="search_form_id" name="search" type="text" class="form-control col-md-3" placeholder="ID, Name, Account #, ZIP"{% if search %} value="{{ search }}"{% endif %}> <button type="submit" class="btn btn-small btn-dark"><i class="fa fa-search"></i> Search</button> </div> </form> What am I missing? -
error connecting mysql 8 with django
I am using python 3.6, mysql-community-server-8.0.11-1 and using fedora 28 I am trying to setup mysql for my django application But I am receiving Segmentation fault (myblogvenv) [saurabhkumar@localhost myblog]$ python manage.py runserver Performing system checks... Segmentation fault (core dumped) If I use the default sqlite3 database, server comes up Also when I run django-admin dbshell I get the following error this is my project structure (myblogvenv) [saurabhkumar@localhost myblog]$ ls db.sqlite3 manage.py myblogvenv mysite (myblogvenv) [saurabhkumar@localhost myblog]$ cd mysite (myblogvenv) [saurabhkumar@localhost mysite]$ ls init.py pycache settings.py urls.py wsgi.py Database section in settings.py looks like DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'blog', 'USER': 'bloguser', 'PASSWORD': 'Blog#user1', 'HOST': '/var/lib/mysql', 'PORT': '3306', } } Using the following packages (myblogvenv) [saurabhkumar@localhost mysite]$ pip list Package Version ----------- ------- Django 2.0.6 mysqlclient 1.3.12 pip 10.0.1 pytz 2018.4 setuptools 39.2.0 wheel 0.31.1 Any pointer on how to debug/fix the issue will help me proceed. -
Have updated the django-rest-framework to last version, why there still have the `No module named 'django.core.urlresolvers'` error?
Have updated the django-rest-framework to last version, why there still have the error? ImportError: No module named 'django.core.urlresolvers' From the post: https://stackoverflow.com/a/47330759/7646621 I have update the djangorestframework to the version 3.8.2. But the issue still exists. File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/rest_framework_docs/urls.py", line 2, in <module> from rest_framework_docs.views import DRFDocsView File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/rest_framework_docs/views.py", line 3, in <module> from rest_framework_docs.api_docs import ApiDocumentation File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/rest_framework_docs/api_docs.py", line 3, in <module> from django.core.urlresolvers import RegexURLResolver, RegexURLPattern ImportError: No module named 'django.core.urlresolvers' my Django version is Version: 2.0.6. -
How to add security questions in Django based web server using Custom User(derived from AbstractBaseUser)?
Can someone help me with code for forms.py views.py and urls? views.py def PasswordRecover(request): if request.method=='POST': form=UserGet(request.POST) user= form.save(commit=False) if(user.is_active): return redirect('password_reset/security',pk=user.pk) else: form = UserGet() return render(request, 'passwordreset.html', {'form':form}) def Security(request): return HttpResponse('what do we add here??') forms.py: class UserGet(forms.ModelForm): class Meta: model = CustomUser fields = ('username',) urls.py: from django.urls import path from . import views app_name='users' urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), path('password_reset',views.PasswordRecover,name='password_recovery'), path('password_reset/security',views.Security,name='SecurityRecover'), ] Error I am getting: Exception Value:The CustomUser could not be created because the data didn't validate. -
Django Mongoengine Authentication
I have managed to connect django 2.0 with mongoengine. Every other thing is working fine apart from the authentication part. in my settings.py I have the following: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', #For Mongo Authentication 'mongoengine.django.mongo_auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', ] AUTH_USER_MODEL = 'mongo_auth.MongoUser' MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User' and am getting the following error core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/user/virtualenvs/project/lib/python3.5/site-packages/django/contrib/auth/checks.py", line 74, in check_user_model if isinstance(cls().is_anonymous, MethodType): AttributeError: 'MongoUser' object has no attribute 'is_anonymous' From the error above I see that the problem is at the declaration of the AUTH_MODEL_USER . I have not created any Custom User Model as I want to be able to user the django.uath User model....I need idea on how I can set it up and be able to create users and have them login. how should I go about?? -
Django on_delete=CASCADE not working, can't delete parent row using raw SQL
Django models: class Parent (Model): name = CharField (max_length = _MAX_NAME_LENGTH, unique = True) class Child (Model): name = CharField (max_length = _MAX_NAME_LENGTH, unique = True) parent = ForeignKey (Parent, on_delete = CASCADE) Create some data: p = Parent (name='parentname') p.save () c = Child (name='childname', parent=p) c.save () Delete parent, expecting child to be deleted via cascade: DELETE FROM `basedb_parent` WHERE `basedb_parent`.`id` = 1 #1451 - Cannot delete or update a parent row: a foreign key constraint fails (idat_prealpha_0_1.basedb_child, CONSTRAINT basedb_child_parent_id_d6f3ee55_fk_basedb_parent_id FOREIGN KEY (parent_id) REFERENCES basedb_parent (id)) Although running p.delete() in the Python code does delete the Parent and Child rows. I know this is actually happening in the underlying MySQL database because the AUTO_INCREMENT table attribute increases (so it's not being shortcutted by any kind of fancy cache in Django). Why doesn't my DELETE FROM query work, while p.delete() does work? -
Django Error "XXXForm" object has no attribute "XXX"
I use Django to build a web app and when I submit a form, I got error: AttributeError at /CustomerInfo/ 'CustomerForm' object has no attribute 'first_name' The project name is zqxt_views and app name is calc. I create a file named forms.py in the calc folder, see below: calc/forms.py: from django import forms class CustomerForm(forms.Form): customer_id = forms.IntegerField(label="Customer ID") first_name = forms.CharField(label="First Name", max_length=30) last_name = forms.CharField(label="Last Name", max_length=30) calc/views.py: # -*- coding: utf-8 -*- #from __future__ import unicode_literals #from django.shortcuts import render from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect import MySQLdb from calc.models import Customer from calc.forms import CustomerForm from django.db import connection ... def show_save_customer(request): # if this is a POST request we need to process the form database if request.method == 'POST': # create a form instance and populate it with data from the request: form = CustomerForm(request.POST) cursor = connection.cursor() query = """ insert into customers (first_name, last_name) values (%s, %s) """ cursor.execute(query, [form.first_name, form.last_name]) # check whether it's valid: if form.is_valid(): #process the data return HttpResponseRedirect('AddressTableMaintain/'); else: form = CustomerForm() return render(request, 'CustomerInfo.html', {'form': form}) # Create your views here. the form page like below: calc/templates/CustomerInfo.html: {% extends 'base.html' %} … -
Django slice of content
i would like to display a "... more" lable after the 100 slice to dsiplay the full comment content, can anybody help? template: <div class="comment"> {% for comment in post.comment_set.all %} <p>{{ comment.content| linebreaks}}</p> <p>{{ comment.content|slice:":100"|linebreaksbr}} {% if comment.content|length > 100 %} ???? {% endif %}</p> -
Django access model data in flatpages
Is it possible to access data from the DB and use it on a flatpage? I want to access the values stored in my table and display it on the flatpage. I've already created templates/flatpages/default.html under my app's directory. -
Django- Change Username field to BigAutoField?
I'm designing an Application where username will be an IntegerField(optional can be a typecasted to string) and unique. Here's my model. class ModelA(models.Model): username = models.BigAutoField(primary_key=True, db_index=False) user_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) Initially, I wanted user_id to be a primary_key, but I can't create an AutoField which is not primary_key. As a result, I'd to let go off user_id as primary_key and assigned username as the primary key. Now, when I run the migrations, it throws an error saying, django.db.utils.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type bigint -
Two part form on single page in django
How would I go about making a two part form on a single page? As in the form would have different tabs to switch between different views of the the form all while on the same page? could this be done with AJAX? I'm using Django and python 3.4 currently. Example -
Django how to show available item only in CBV List view?
I have two models car and booking. A car is ForeignKey field in booking model if car is booked then in car list its still showing. I have is_available_car model field in car model default=True. If car is booked then it will not show till it's unbooked. i am having booking form and if car is booked user cannot book it and it doesnt shown in CArlistview . Help me please. Thank you. Models class Booking(models.Model): booking_name = models.CharField(max_length=240, null=False) customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='book_customers' ) book_car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name='book_car') booking_start_date = models.DateTimeField(auto_now_add=True, blank=False) booking_end_date = models.DateTimeField(blank=True, null=True) rental_price = models.IntegerField(blank=False, null=False) times_pick = models.TimeField(blank=True) is_approved = models.BooleanField(default=False) def __str__(self): return self.booking_name def get_absolute_url(self): return reverse("buggy_app:detail",kwargs={'pk':self.pk}) Views.py class BookingView(FormView): template_name = 'buggy_app/booking.html' form_class = BookingForm models = Booking def form_valid(self, form): form.save() return super(BookingView, self).form_valid(form) success_url = reverse_lazy('index') def get_context_data(self, **kwargs): # kwargs['car'] is the car booking now! try: kwargs['car'] = Car.objects.get(id=self.request.GET.get('car', '')) except (Car.DoesNotExist, ValueError): kwargs['car'] = None return super(BookingView, self).get_context_data(**kwargs) def get_initial(self): initial = super(BookingView, self).get_initial() if 'car' in self.request.GET: try: initial['book_car'] = Car.objects.get(id=self.request.GET['car']) except (Car.DoesNotExist, ValueError): pass return initial class CarListView(ListView): context_object_name = 'cars' model = models.Car def get_queryset(self): qs = super(CarListView, self).get_queryset() qs = qs.filter(is_available_car=True) … -
How can I add a field's length for the sort in Model?
How can I add a field's length for the sort in Model ? I have a IPv4Manage model: class IPv4Manage(models.Model): """ ipv4 """ ip = models.GenericIPAddressField(help_text="ip") ... class Meta: ordering = ['ip'] in the Meta we can set ordering the fields. but I have a question, can I set the ip's length for order in the Model? I know if in the APIView we can use Prefetch or extra for length the ip and order it. ...extra(select={'length':'Length(ip)'}).order_by('length', 'ip') But whether we can set the length of field param of order in the Model?