Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I wanna set minlength&maxlength in template of input tag
I wrote in index.html <div class="heading col-lg-6 col-md-12"> <h2>New account registration</h2> <form class="form-horizontal" action="regist_save/" method="POST"> <div class="form-group-lg"> <label for="id_username">username</label> {{ regist_form.username }} </div> <div class="form-group-lg"> <label for="id_email">email</label> {{ regist_form.email }} </div> <div class="form-group-lg"> <label for="id_password">password</label> {{ regist_form.password1 }} </div> <div class="form-group-lg"> <label for="id_password">password(conformation)</label> {{ regist_form.password2 }} <p class="help-block">{{ regist_form.password2.help_text }}</p> </div> <div class="form-group-lg"> <div class="col-xs-offset-2"> <button type="submit" class="btn btn-primary btn-lg">SUBMIT</button> <input name="next" type="hidden"/> </div> </div> {% csrf_token %} </form> </div> I wanna set minlength&maxlength in template of username&password input tag.If i wrote in html stye,it is <form class="form-horizontal" action="regist_save/" method="POST"> <div class="form-group-lg"> <label for="id_username">username</label> <input id="id_username" name="username" type="text" value="" minlength="5" maxlength="12" placeholder="username" class="form-control"> </div> <div class="form-group-lg"> <label for="id_email">email</label> {{ regist_form.email }} </div> <div class="form-group-lg"> <label for="id_password">password</label> <input id="id_password1" name="password1" type="password1" value="" minlength="8" maxlength="12" placeholder="password1" class="form-control"> </div> <div class="form-group-lg"> <label for="id_password">password(conformation)</label> <input id="id_password2" name="password2" type="password2" value="" minlength="8" maxlength="12" placeholder="password2" class="form-control"> <p class="help-block">{{ regist_form.password2.help_text }}</p> </div> <div class="form-group-lg"> <div class="col-xs-offset-2"> <button type="submit" class="btn btn-primary btn-lg">SUBMIT</button> <input name="next" type="hidden"/> </div> </div> {% csrf_token %} </form> in forms.py class RegisterForm(UserCreationForm): class Meta: model = User fields = ('username', 'email','password1','password1',) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' in views.py @require_POST def regist_save(request): regist_form … -
How to install django spirit ? I am getting the error command not found: spirit
I tried install django spirit using mkvirtualenv env -p /usr/bin/python3 pip install django-spirit spirit startproject mysite - it says spirit command not found Any solutions ? -
How to set up ALLOWED_HOSTS in digital ocean
I successfully hosted my Django code in digital ocean with DNS.After hosted I'm getting weird output in my browser. when I enter example.com.i'm getting the login page after logged in I'm reached my home page.all works fine.But when I enter www.example.com I'm redirected to my login page.then again I test example.com it shows homepage, not the login page. I don't know what I'm doing wrong here. my ALLOWED_HOSTS look like this initially ALLOWED_HOSTS = ['www.example.com','example.com'] Then I changed it to: ALLOWED_HOSTS = ['.example.com'] last try ALLOWED_HOSTS = [*] I changed multiple things but the result is same.Any help really appreciate :) -
Issue in migrating database from pyhton-mysql in OSX
I am running this command to migrate my database. I am unable to do so. Whenver I run this command I am getting error: bin/django migrate Error: raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/rm/Documents/GitHub/project/lib/python2.7/site-packages/_mysql.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/rm/Documents/GitHub/project/lib/python2.7/site-packages/_mysql.so Expected in: flat namespace in /Users/rm/Documents/GitHub/project/lib/python2.7/site-packages/_mysql.so MySql Version: mysql Ver 14.14 Distrib 5.7.19, for osx10.12 (x86_64) using EditLine wrapper Python Version: Python 2.7.14 -
How to convert the UTC time to Shanghai +8 timezone time in template?
From the database, I query out the created_date and put in the template: You see, it is UTC time, how can I in the template shows the +8 timezone time? I tried use the custom template-filter to change, but failed: from django import template from django.template.defaultfilters import stringfilter import datetime, time register = template.Library() ### function def utc2local(utc_st): """UTC时间转本地时间(+8:00)""" now_stamp = time.time() local_time = datetime.datetime.fromtimestamp(now_stamp) utc_time = datetime.datetime.utcfromtimestamp(now_stamp) offset = local_time - utc_time local_st = utc_st + offset return local_st @register.filter def convert_utc_to_shanghai(value): """ UTC->Shanghai :param value: :return: """ local_time = utc2local(value) print local_time.strftime("% Y - % m - % d % H: % M: % S") return local_time.strftime -
Django Querying database based on the user input.
I just started learning python/django and I'm working on a small project. I have models and an html form build. How can I query my database and filter all the names of the drivers that matches the destination city the user entered. My models class Drivers(models.Model): first_name = models.CharField(max_length=30, null=True, blank=False) last_name = models.CharField(max_length=30, null=True, blank=False) destination_one = models.CharField(max_length=50, null=True, blank=False) My HTML form <form id="searchform" method="get" action="" accept-charset="utf-8"> Search destination: <input id="searchbox" name="search_res" type="text" placeholder="Search"> <input type="submit" value="OK"> </form> {% for dr in results %} {{dr.first_name}} {{dr.last_name}} {{dr.destination_one}} <br> {% endfor %} <br> My View def newpage(request): querry = request.GET.get('search_res') if request.method == 'GET': results = Drivers.objects.filter(destination_one=querry) context = RequestContext(request) return render_to_response(request,'busapp/newpage.html',{'results': results}) Models and HTML are fine. I'm having trouble building a simple def in views.py. -
How can i Access the JWT_AUTH variables in my models for creating JWT token
in my settings.py JWT_AUTH = { 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_response_payload_handler', 'JWT_SECRET_KEY': settings.SECRET_KEY, 'JWT_GET_USER_SECRET_KEY': None, 'JWT_PUBLIC_KEY': None, 'JWT_PRIVATE_KEY': None, 'JWT_ALGORITHM': 'HS256', 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_LEEWAY': 0, 'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1), 'JWT_AUDIENCE': None, 'JWT_ISSUER': None, 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'JWT', 'JWT_AUTH_COOKIE': None, } api_settings = APISettings(JWT_AUTH) And this code block is in my Models.py def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') All i want to replace settings.SECRET_KEY, algorithm='HS256' from the JWT_AUTH (settings.py) I have tried these following from rest_framework.settings import api_settings api_settings.JWT_AUTH['JWT_SECRET_KEY'] and from django.conf import settings settings.JWT_AUTH['JWT_SECRET_KEY'] -> This works but no idea this is the proper way. -
'invalid_grant: Invalid JWT: Google Translation Api
when I am trying to run this on my server I am getting following error but is working on my local machine. RefreshError: ('invalid_grant: Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values and use a clock with skew to account for clock differences between systems.' -
Password is not saved
Password is not saved in new user registration.I wrote in views.py def regist(request): regist_form = RegisterForm(request.POST or None) context = { 'regist_form': regist_form, } return render(request, 'registration/regist.html', context) @require_POST def regist_save(request): regist_form = RegisterForm(request.POST) if regist_form.is_valid(): user = regist_form.save(commit=False) password = regist_form.cleaned_data.get('password') user.set_password(password) user.save() login(request, user) context = { 'user': request.user, } return redirect('detail') context = { 'regist_form': regist_form, } return render(request, 'registration/regist.html', context) in regist.html <div class="heading col-lg-6 col-md-12"> <h2>New account registration</h2> <form class="form-horizontal" action="regist_save/" method="POST"> <div class="form-group-lg"> <label for="id_username">username</label> {{ regist_form.username }} </div> <div class="form-group-lg"> <label for="id_email">email</label> {{ regist_form.email }} </div> <div class="form-group-lg"> <label for="id_password">password</label> {{ regist_form.password1 }} </div> <div class="form-group-lg"> <label for="id_password">password(conformation)</label> {{ regist_form.password2 }} <p class="help-block">{{ regist_form.password2.help_text }}</p> </div> <div class="form-group-lg"> <div class="col-xs-offset-2"> <button type="submit" class="btn btn-primary btn-lg">SUBMIT</button> <input name="next" type="hidden"/> </div> </div> {% csrf_token %} </form> </div> in forms.py class RegisterForm(UserCreationForm): class Meta: model = User fields = ('username', 'email','password1','password1',) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' Username&email is registered normally.So I really cannot understand why password is not registered.I read Django tutorial and I think my code is ok.How should I fix this?What should I write it? -
Django: How to write Mixin for queryset for logged in User's data
I am using Generic Class based views for my Project like: ListView (Queryset returning all the objects) DetailView (Queryset for single object) CreateView (Foreignkey data in select boxes) UpdateView (Foreignkey data in select boxes) How to write a generic Mixin for CBV so that the queryset returns only the data owned by the logged in user. -
Invalid geometry value with PostGis
I am using PointField of gis for storing the latitude and longitude in the location field. I dont want to show that field in the ui because I am using google autocomplete places where when user selects the address, i get the lat and lng which I want to fetch it and save to the location field. However I could not do that but I tried to change the field type to TextInput but that did not work as well. How can I do it so? Here is what I have tried class Restaurant(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='restaurant' ) name = models.CharField(max_length=500) phone = models.CharField(max_length=500) location = gis_models.PointField(blank=True, null=True, geography=True) gis = gis_models.GeoManager() objects = models.Manager() class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant widgets = {'country': forms.HiddenInput(attrs={'id': 'country'}), 'location': forms.HiddenInput(attrs={'id': 'location'}), 'city': forms.HiddenInput(attrs={'id': 'locality'}), 'state': forms.HiddenInput(attrs={'id': 'administrative_area_level_1'}), 'postal_code': forms.HiddenInput(attrs={'id': 'postal_code'}), } fields = ( "logo", "name", "cuisine", "phone", "location", "country", "city", "state", "postal_code", ) def clean_location(self): print('self', self.cleaned_data) coordinates = self.cleaned_data['location'] lat, lng = coordinates.split(', ', 1) return GEOSGeometry('POINT(' + longitude + ' ' + latitude + ')') if request.method == "POST": restaurant_form = RestaurantForm(request.POST, request.FILES) if restaurant_form.is_valid(): print(request.POST.get('location')) new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = request.user new_restaurant.save() return redirect(restaurant_order) … -
Create a Django model instance concurrent with the creation of another Django model instance
I'm creating a simple record keeping app in Django 1.11 that keeps track of what happens in games turn by turn. What I'd like to do is when I create an instince of Game automatically create the first dependent Turn instance. class Game(models.Model): name = models.Charfield(param) active = models.BooleanField(param) def __init__(self, *args, **kwargs): super(Game, self).__init__(*args,**kwargs) Turn(game=self, turn=1).save() class Turn(models.Model): turn = models.IntergerField(param) please suggest a better method becuase I get ValueError on the save method. -
Django form httpresponse
I want to submit form and return to topics page,but it doesn't work.Here is the page before submit. page before submit I enter something and click the button,it does't return to the page I want.Error shows as follow: error page It seems like the views.py can't find the right url,how can I fix it? view.py: def new_topic(request): if request.method != "POST": form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('leraning_log:topics')) context = {'form':form} return render(request,'learning_logs/new_topic.html',context) urls.py: urlpatterns = [ url(r'^topics/$',views.topics,name='topics'), url(r'^topics/(?P<topic_id>\d+)/$',views.topic,name='topic'), url(r'^new_topic/$',views.new_topic,name='new_topic'), ] -
How to join table in django?
Assumes, I have two tables below : enter image description here I've made the models.py: class Score(models.Model): Student_Id = models.CharField(max_length=20, primary_key=True) Grade = models.CharField(max_length=30) Status= models.CharField(max_length=3) class Meta: db_table ='T_Score' class Student(models.Model): Student_Id = models.CharField(max_length=20, primary_key=True) Student_Name = models.CharField(max_length=30) Student_Class = models.CharField(max_length=3) def __str__(self): return { "id" : self.Student_Id, "name" : self.Student_Name, } class Meta: db_table ='T_Student' Is it possible to join the table if Student.Student_Id just as primary key (not as foreign too)? And how should I make the view.py and template which represent Student ID, Student Name, and Grade? Thank you in advance. -
Web analytic with python
I want to build a web analytic as google analytic. My requirement for this system that is high throughput,scalability, low latency and efficient ETL. And If it's ok, can we use django to develop. But I don't know which technique is suitable with my case. For detail, I need to answer these questions: With Django, which open source is the best for: 1) Which framework can help me build high throughput,scalability, low latency service? 2) Which database is better for realtime as google's analytic: High Performance, Security & Permissions, Low Latency Storage, Fully Managed, Redundant Autoscaling Storage, Seamless Cluster Resizing, HBase Compatible. 3) Which Framework for ETL with high performance? Without Django/python, which language is the best and which is suitable question for these question above Thanks & Best Regards, Phuong Hoang -
Django Rest Framework Token authentication with Social auth login
In my Django Rest Framework application, a Token is generated for every user that logs in for the first time into the application using signals. Now I can use this token (By manually going to database and grabbing the token) to make API calls to the view that have authentication_classes = (TokenAuthentication,). Can someone explain me how can I provide this token to the user securely when the (OpenID) login was successful. Django Rest Framework supports something like: from rest_framework.authtoken import views urlpatterns += [ url(r'^api-token-auth/', views.obtain_auth_token) ] But, this obtain_auth_token view only supports post request which takes username and password, which is not the case with my application. Please correct me if there are any flaws in my workflow. -
Can't find any modules in Django project
I've been following a Django tutorial and initially had created virtualenv and a requirements file in it. Project was halfway and in working state. Today I activated virtualenv successfully and tried python manage.py runserver to get error ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I realized it's not finding Django and just to be sure checked my requirements.txt file (which confirmed right Django version). Tried to reinstall it from the file using pip3 install -r requirements.txt (tried using just pip too) to get another error -- ModuleNotFoundError: No module named 'pip' It seems the environment is unable to find any of the modules. I tried to reinstall pip also just to be sure, but then it couldn't find apt-get command. OS: Mac OSX El Capitan 10.11.6 Python: 3.6.2 Django: 1.10.3 (in requirements file) -
Integrate oscar to existing app
Is there a way I can integrate Oscar to an existing app? I installed oscar, created an app in my existing folder. I changed the settings in my shop app according to Oscar. Then I added the new shop to my existing app's settings in the installed app. It said no module name shop. Is this right way to go about it? -
Send template form data to view via URL
I'm trying to build a wiki search app in django and am having trouble creating a MVC link with a template that has a form with POST method. Essentially, my search form, search_form.html looks like this: {% extends 'layout.html' %} {% block title %}Wiki Search | Search {% endblock title %} {% block content %} <form action = "{% url 'search_results' search_term %}" method="post"> Search for:<br> <input type="text" name="search_term" value=""> <br> <input type="checkbox" name="is_date" value="date">I'm searching for a date (e.g. 02/10) <br><br> <input type="submit" value="Search"> </form> {% endblock content %} The end view needs to evaluate the checkbox value (name=is_date) and the text input (name=search_term). I am passing it to URL named 'search_results' which is defined in my urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'search/(?P<search_term>[.\-\_\w\d\s]+)/$', views.search_results, name='search_results'), url(r'search/$', views.search_form, name='search_form'), url(r'^$', views.index, name='index'), ] my search_results url has a regex with a named capture of search_term. I am assuming that this is filled by me referencing the template's form's text input (named search_term). Finally, this URL references views.py's search_results function which is: from django.shortcuts import render from django.http import HttpResponse, HttpRequest from .models import Search # Create your views here. def index(request): #return render(request, … -
New user registration cannot be done
New user registration cannot be done. I wrote in views.py def regist(request): regist_form = RegisterForm(request.POST or None) context = { 'regist_form': regist_form, } return render(request, 'registration/regist.html', context) @require_POST def regist_save(request): regist_form = RegisterForm(request.POST) if regist_form.is_valid(): user = form.save() login(request, user) context = { 'user': request.user, } return redirect('detail') context = { 'regist_form': regist_form, } return render(request, 'registration/regist.html', context) in forms.py class RegisterForm(UserCreationForm): class Meta: model = User fields = ('username', 'email','password1','password1',) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' in regist.html <div class="heading col-lg-6 col-md-12"> <h2>New account registration</h2> <form class="form-horizontal" action="regist_save/" method="POST"> <div class="form-group-lg"> <label for="id_username">username</label> {{ regist_form.username }} </div> <div class="form-group-lg"> <label for="id_email">email</label> {{ regist_form.email }} </div> <div class="form-group-lg"> <label for="id_password">password</label> {{ regist_form.password1 }} </div> <div class="form-group-lg"> <label for="id_password">password(conformation)</label> {{ regist_form.password2 }} <p class="help-block">{{ regist_form.password2.help_text }}</p> </div> <div class="form-group-lg"> <div class="col-xs-offset-2"> <button type="submit" class="btn btn-primary btn-lg">SUBMIT</button> <input name="next" type="hidden"/> </div> </div> {% csrf_token %} </form> </div> No error happens and when I put SUBMIT button,it send detail.html,so it is ok.But when I see admin site,no user is registered. I really cannot understand why this happens.I cannot understand what is wrong.I read Django tutorial,so I think this way of … -
Django production get Service Unavailable
I'm trying to setup my app with django but unfortunately I can't I just got a Service Unavailable message. I'm using vestacp The apache configuration works in the same ubuntu 14 without vestacp but using vestacp I can not achieve to work. settings.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] it suppose to work using "*" apache2.conf <VirtualHost 172.31.2.45:80> ServerName ip-172-31-2-45.us-west-1.compute.internal ServerAlias www.ip-172-31-2-45.us-west-1.compute.internal ServerAdmin info@ip-172-31-2-45.us-west-1.compute.internal DocumentRoot /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/public_html ScriptAlias /cgi-bin/ /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/cgi-bin/ Alias /vstats/ /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/stats/ Alias /error/ /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/document_errors/ #SuexecUserGroup admin admin CustomLog /var/log/apache2/domains/ip-172-31-2-45.us-west-1.compute.internal.bytes bytes CustomLog /var/log/apache2/domains/ip-172-31-2-45.us-west-1.compute.internal.log combined ErrorLog /var/log/apache2/domains/ip-172-31-2-45.us-west-1.compute.internal.error.log <Directory /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/public_html> AllowOverride All Options +Includes -Indexes +ExecCGI php_admin_value open_basedir /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/public_html:/home/admin/tmp php_admin_value upload_tmp_dir /home/admin/tmp php_admin_value session.save_path /home/admin/tmp </Directory> <Directory /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/stats> AllowOverride All </Directory> <IfModule mod_ruid2.c> RMode config RUidGid admin admin RGroups www-data </IfModule> <IfModule itk.c> AssignUserID admin admin </IfModule> IncludeOptional /home/admin/conf/web/apache2.ip-172-31-2-45.us-west-1.compute.internal.conf* </VirtualHost> <VirtualHost 172.31.2.45:80> ServerName mensajeriadf.com ServerAlias www.mensajeriadf.com ServerAdmin info@mensajeriadf.com DocumentRoot /home/admin/web/mensajeriadf.com/public_html WSGIDaemonProcess sampleapp python-path=/var/www/sampleapp/sampleapp:/var/www/sampleapp/env/python2.7/site-packages WSGIProcessGroup sampleapp WSGIScriptAlias / /var/www/sampleapp/sampleapp/sampleapp/wsgi.py ScriptAlias /cgi-bin/ /home/admin/web/mensajeriadf.com/cgi-bin/ Alias /vstats/ /home/admin/web/mensajeriadf.com/stats/ Alias /error/ /home/admin/web/mensajeriadf.com/document_errors/ #SuexecUserGroup admin admin CustomLog /var/log/apache2/domains/mensajeriadf.com.bytes bytes CustomLog /var/log/apache2/domains/mensajeriadf.com.log combined ErrorLog /var/log/apache2/domains/mensajeriadf.com.error.log <Directory /home/admin/web/mensajeriadf.com/public_html> AllowOverride All Options +Includes -Indexes +ExecCGI php_admin_value open_basedir /home/admin/web/mensajeriadf.com/public_html:/home/admin/tmp php_admin_value upload_tmp_dir /home/admin/tmp php_admin_value session.save_path /home/admin/tmp </Directory> <Directory /home/admin/web/mensajeriadf.com/stats> AllowOverride All </Directory> … -
Getting AttributeError at /gitstack/ 'str' object has no attribute 'resolve' in Django 1.11
I am modifying Gitstack, a 32bit Python2.7-based Git Web Application (available here) for my 64bit Python installation. In the process, I also had to modify all the Django codes e.g. urlpatterns, etc. While I managed to adapt it to my Apache/PHP environment, I ended up with this Django issue. The error is as below while trying to access /gitstack location AttributeError at /gitstack/ 'str' object has no attribute 'resolve' Request Method: GET Request URL: https://localhost/gitstack/ Django Version: 1.11.6 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'resolve' The traceback below seems to be useless Environment: Request Method: GET Request URL: https://localhost/gitstack/ Django Version: 1.11.6 Python Version: 2.7.13 Installed Applications: ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'gitstack') Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 172. resolver_match = resolver.resolve(request.path_info) File "C:\Python27\lib\site-packages\django\urls\resolvers.py" in resolve 364. sub_match = pattern.resolve(new_path) Exception Type: AttributeError at /gitstack/ Exception Value: 'str' object has no attribute 'resolve' Below is my modified app\urls.py: from django.conf.urls import url, include from django.contrib.auth.views import login # Uncomment the next two lines to enable the admin: # from django.contrib import admin … -
how to use ajax with graphql using get method?
I am trying to follow this documentation about django and graphql https://www.techiediaries.com/django-graphql-tutorial/graphene/ I am only half way to where we can do testing with the graphql view and make our queries. Then I stopped and trying to do some front end work to make query with ajax been reading https://blog.graph.cool/how-to-use-graphql-with-jquery-51786f0a59cb Even though in that blog, it's using post. I believe using get shouldn't be too much different. So I tried making query into a string then JSON.stringify them to pass it over to the backend django but I keep on getting error this is the error I have XMLHttpRequest cannot load localhost:8000/graphql/?{"query":"query { allProducts {id sku title description } }"}. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. this is the html + jquery <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <button class="graphql-test">CLICK</button> </body> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script> $(function(){ $('.graphql-test').on('click', function(e){ e.preventDefault(); var query = "query { allProducts {id sku title description } }"; $.ajax({ method: 'get', url: 'localhost:8000/graphql/', data: JSON.stringify({"query": query}), contentType: 'application/json', success: function(data){ console.log(data); }, error: function(data){ console.log(data); } }) }) }); </script> </html> -
How to define a subclass of ListBlock with fixed contents?
Is there a better way than this to make a subclass of ListBlock with fixed contents? class MixedMediaCarouselBlock(blocks.ListBlock): """ A hghly streamlined CarouselBlock which displays only Images and/or Videos. """ def __init__(self, child_block=None, **kwargs): child_block = blocks.StructBlock([ ('image', ImageChooserBlock(required=False)), ('video', EmbedBlock( label="Video URL", help_text="Paste the video URL from YouTube or Vimeo." " e.g. https://www.youtube.com/watch?v=l3Pz_xQZVDg" " or https://vimeo.com/207076450.", required=False ) ), ]) super(MixedMediaCarouselBlock, self).__init__(child_block, **kwargs) class Meta: template = 'core/blocks/mixed_media_carousel_block.html' label = 'Mixed Media Carousel' icon = 'media' It feels really hacky to do it this way, but I can't find any other obvious method, because ListBlock requires that child_block argument to its constructor, while other block types do not. The reason I want a ListBlock subclass is to use it as the single block type in a StreamField in one of my Pages: class News(Page) assets = StreamField( MixedMediaCarouselBlock(), help_text='Pick one or more images/videos to place in the sidebar of this article.' ) Maybe I'm just doing this wrong? -
Access related ManyToManyField data pre-save in the Django Model.save method
We would like to access related ManyToManyField data pre-save within the Model.save method, however the data isn't available yet via the Django ORM because it's related ManyToManyField data and doesn't get set until post-save of the primary record. Here's some example code of the relationship and where the related ManyToMany records are accessed in Model.save class Friend(models.Model): name = models.CharField(max_length=50) class Person(models.Model): name = models.CharField(max_length=50) friends = models.ManyToManyField(Friend) def save(self, *args, **kwargs): friends = self.friends.all() # 'friends' is an empty QuerySet at this point # I'd like to do something with friends here, # but it gets set after save super(Friend, self).save(*args, **kwargs) Example use case where friends are passed in on save: friend = Friend.objects.all()[0] friend2 = Friend.objects.all()[1] friends = [friend, friend2] Person.objects.create(friends=friends)