Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URL patterns to serve external webpack bundle
I'm writing a django rest framework API (backend) with a react SPA frontend. For the production environment, the front end is served up via nginx at http://example.com/ and the backend is proxied to gunicorn and served from the same domain with a different path - http://example.com/api/ This is all working fine in production, there are no CORS issues as the frontend and backend are both served up under the same domain via nginx. For local development, I want to be able to replicate a similar setup using ./manage.py runserver and have django serve up the frontend from project/frontend/dist (built by npm build seperately). Has anyone got any urlpattern wizardry that will allow this to happen and also let the react-router play nicely? I just can't figure it out and it's starting to drive me nuts... The project structure is something like this if it helps in any explanations. Project | ── backend │ ├── apps │ ├── config | | ├── settings.py | | ├── settings_local.py | | ├── urls.py │ ├── manage.py │ ├── requirements.txt │ └── venv ├── frontend │ ├── dist (contains the npm build webpack) │ ├── node_modules │ ├── package.json │ ├── package-lock.json │ ├── … -
Django - include a child template cannot find template
I am trying to include a page into another one like this <div id="past_comments"> {% include 'comment_block.html' %} <!--{% for comment in comments %}--> <!--<p>{{comment.content}}</p>--> <!--{% endfor %}--> </div> and the structure of my directory is like: |-post |----comment_block.html |----detail.html |----index.html screenshot of structure in picture However, I get an exception: Exception Type: TemplateDoesNotExist Exception Value: comment_block.html Can any body help me with this? Thanks in advance! -
How to copy files from a directory to a new sub domain
I am developing a basic website builder like wix.com using Django, I have a default template in folder which contains css, html and js files in my Django project, Once the user fills the registration form and submits i want to create a new folder with all the files from template folder. Once the folder is created with template files i will use wild cards to create a sub domain. Kindly help me to achieve this -
django staticfiles collection error
I started a new project in django and created a development and a testing environment with their settings in the same folder as the custom settings.py everything is going well till I created a static file directory and I tried to collect static files but got error. raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. this is my directory BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if DEBUG: MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only") MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media") STATICFILES_DIRS = ( os.path.join(os.path.dirname(BASE_DIR), "static", "static"), ) -
Django ORM - MySQL query count optimization for related models
I have two related models, that looks like below: class Enterprise(models.Model): id = models.AutoField(primary_key=True) subsystem_id = models.IntegerField() name = models.CharField(max_length=255, unique=True) modif_date = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Project(models.Model): id = models.AutoField(primary_key=True) subsystem_id = models.IntegerField() name = models.CharField(max_length=255) modif_date = models.DateTimeField(auto_now=True) enterprise = models.ForeignKey('Enterprise' on_delete = CASCADE) active = models.BooleanField(default=True) In my view, need to get all active Enterprises and list them. I'm doing it this way: enterprise_list = Enterprise.objects.annotate(project_count=Count('project')).filter( Q(active=True) | Q(subsystem_id=-1), project_count__gt=0 ) serializer = EnterpriseSerializer(enterprise_list, many=True) Then, my serializer is displaying project list with some additional query: class EnterpriseSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) name = serializers.CharField(max_length=255, required=False) project_list = serializers.SerializerMethodField() def get_project_list(self, enterprise): project_list = Project.objects.filter(Q(active=True) | Q(subsystem_id=-1), enterprise=enterprise) serializer = ProjectSerializer(project_list, many=True) return serializer.data class Meta: model = Enterprise fields = ('id', 'name', 'project_list') This code is working fine, but it has very serious issue - performance. The first query for Enterprise returns list of ~1500 object. Then, for every object, serializer executes single query to fetch additional data for project which results to ~1500 queries. I've tried prefetch_related and select_related but either I'm doing something wrong or it doesn't work in my case. In the other hand I can get list of project first. This could … -
DJango pagination error, staticfiles
Hi guys (I'm newbie in DJango)! I'm having a problem with DJango. When i go to 127.0.0.1/blog i have an error which looks like this: image Here are some lines from settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog',] STATIC_URL = '/static/' Here is head from base.html: {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static 'css/blog.css' %}" rel="stylesheet"> </head> -
MultiValueDictKeyError at /accounts/upload_save/
I got an error, MultiValueDictKeyError at /accounts/upload_save/ "'image'" . I am making file upload system.It is that if i select file and put "SEND" button,selected image is sent to model.But now,when i select no image and put "SEND" button,the error happens.I wanna make a system that if i select no image and put "SEND" button,<p>You should select at least one photo</p> message is shown. I wrote in photo.html <div class="container" id="photoform"> {% if form.errors %} <div class="alert alert-danger" role="alert"> <p>You should select at least one photo</p> </div> {% endif %} <form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group"> <label class="input-group-btn" style="width: 30%;"> <span class="btn btn-primary btn-lg"> File Select1 <input type="file" name="image"> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label class="input-group-btn" style="width: 30%;"> <span class="btn btn-primary btn-lg"> File Select2 <input type="file" name="image2"> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label class="input-group-btn"> <span class="btn btn-primary btn-lg"> File Select3 <input type="file" name="image3"> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </form> </div> I wrote in views.py @login_required @csrf_exempt def upload_save(request): if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if form.is_valid(): data = … -
django rest api for advance search
i want to create a api using django rest framework which will do some advance search, say a list of grocery item is saved in database and user want to create a list of grocery and he enters first 2 or 3 letters and then my api will do query to get rest of the item name and will suggest to user I have seen the documentation of drf haystack but not sure whether will it fulfill my requirement. Also it does not support django LTS version 1.11 . Can you please give me some suggestion? is django rest framework itself provide any support to create such a api which will do such advance search which i mentioned above? i just need some suggestion as i am new in django rest framework. -
subprocess not work in django with apache
This probelm confused me many days, i can't figure it out, please help. windows django 1.7.8 + python 2.7.8 requirment: copy file to s3 with aws cli process = subprocess.Popen( r'C:\Program Files\Amazon\AWSCLI\aws.exe s3 cp e:\test\p001.zip s3://bucketsname',stdout=subprocess.PIPE, universal_newlines=True) This code can be successful in A,B,C, and file copied to s3. A. run in directly in python cmd B. run in python manage.py shell C. run in django default http server D. django + apache wsgi The only problem is that D, if i use apache in django, the cmd not work, file not copied. So how to deal with apache in this case? Thank you! -
why does it renders django administration site instead of custom log out page
I create my own template for logout page, but it loads default django logout page instead of it. according to this solution I need to put django.contrib.admin after my app name in setting.py. I've already tried this but doesn't work for me. -
Django CSS takes time to refresh
When I make a change in css, it takes time to be seen in browser. Often I just leave it and get back to do some backend stuff and while I'm doing that, suddenly and unexpectedly, the css changes are applied. I have seen some solutions on the internet, like clear browser's cache, but it doesn't work every time. What is the reason behind it? It gets annoying when you want immediate results. -
already made a website, now i need it to convert it into an android/ios app
i've been learning and building websites for 5 months. Currently i use js (angular2); html5 css(foundation); and python (django).I've already created a basic website [blog] and considering turning it into an app {android / ios} native apps isn't in my interests (the development takes too long, ecspecially when i have to learn java AND swift). So, i am taking "the hybrid app" approuch. i've read that foundation doesn't work well with ionic (the framework i want to use).the reason i am using ionic instead of foundation for apps is because ionic gives far more acsess to mobile features (bluetooth, photo, data, etc). i read that servers that work for desktop aren't good with moble applications. here are my questions: how do i convert a website into an app? since i can't use foundation and ionic at the same time, do i create a seperate project where i use ionic instead of foundation? then if my app and my website files are seperate, do i have to make seperate servers and one database(i will use database mirroring) or connect them to one server? if i connect them to one server how do i handle mobile requests from desktop ones? -
Django/rest: When I'm trying to select a user, I get error `(1048, "Column cannot be null")`
I'm using django 1.11.5 and python 3.5. Using rest-framework, I want to search a patient having uid. When I'm trying to have a serializer with only one field I get the error (1048, "Column 'yearofbirth' cannot be null"). I don't want to save anything, I just want to get all user's info having the given uid. Is there any solution to fix this? serializers.py class GetUserSerializer(serializers.ModelSerializer): id = serializers.CharField(source='uid') class Meta: model = User fields = ('id', ) views.py class GetUser(CreateAPIView): permission_classes = () serializer_class = GetUserSerializer def get(self, request): serializer = GetUserSerializer(data=request.data) # Check format and unique constraint if not serializer.is_valid(): return Response(serializer.errors, \ status=status.HTTP_400_BAD_REQUEST) data = serializer.data if User.objects.filter(uid = data['id']).exists(): user = User.objects.get(uid = data['id']) resp = {"user":{"uid":user.uid, "firstname":user.firstname, "yearofbirth": user.yearofbirth, \ "lastnames": user.lastname, "othernames": user.othernames}} return Response(resp, status=status.HTTP_200_OK) else: resp = {"error": "User not found"} return Response(resp, status=status.HTTP_404_NOT_FOUND) models.py class User(models.Model): uid = models.CharField(max_length=255, unique=True,default="0") firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255, blank=True) othernames = models.CharField(max_length=255, blank=True) yearofbirth = models.SmallIntegerField(validators=[MinValueValidator(1900), MaxValueValidator(2018)], null = False -
django/rest: Can I have serializer with only one field?
I'm using django 1.11.5 and python 3.5. Using rest-framework, I want to search a patient having uid. When I'm trying to have a serializer with only one field I get the error Thefieldsoption must be a list or tuple or "__all__". Got str.. Is there any solution to have only one field to search a user? serializers.py class GetUserSerializer(serializers.ModelSerializer): id = serializers.CharField(source='uid') class Meta: model = User fields = ('id') views.py class GetUser(CreateAPIView): permission_classes = () serializer_class = GetUserSerializer def get(self, request): serializer = GetUserSerializer(data=request.data) # Check format and unique constraint if not serializer.is_valid(): return Response(serializer.errors, \ status=status.HTTP_400_BAD_REQUEST) data = serializer.data if User.objects.filter(uid = data['id']).exists(): user = User.objects.get(uid = data['id']) resp = {"user":{"uid":user.uid, "firstname":user.firstname, "yearofbirth": user.yearofbirth, \ "lastnames": user.lastname, "othernames": user.othernames}} return Response(resp, status=status.HTTP_200_OK) else: resp = {"error": "User not found"} return Response(resp, status=status.HTTP_404_NOT_FOUND) models.py class User(models.Model): uid = models.CharField(max_length=255, unique=True,default="0") firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255, blank=True) othernames = models.CharField(max_length=255, blank=True) yearofbirth = models.SmallIntegerField(validators=[MinValueValidator(1900), MaxValueValidator(2018)], null = False -
Django transfer files from local host to web server
I am very new to Python, just did a tutorial on it where I created a small website with a blog. It works fine on the local host http://127.0.0.1:8000/ but when I want to upload the files on my subdomain I created on siteground, my browser then tells me "No matching DirectoryIndex". So I added "Options +Indexes" into the .htaccess. Now I can see the directory "Index of /" and the list of my files when I go the website, Instead of the actual website like I can when using the local host. Is there anything I am missing? Thanks! What I get when I enter the website in my browser on the URL of my subdomain: -
Extended User model in django not saving profile image
Am trying to create a chat forum in django . but to do this i needed to extend the User Model, But after extending it the profile image does not save This is my model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField() img = models.FileField(upload_to='media/', blank=True, null=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() My View: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.profile.email = form.cleaned_data.get('email') user.profile.img = form.cleaned_data.get('img') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'tforum/signup.html', {'form': form}) My Forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(help_text='Required.') img = forms.FileField(help_text='Upload Image') class Meta: model = User fields = ('username', 'email', 'img', 'password1', 'password2', ) Signup.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> The problem is that the user … -
django blog: A server error occurred. Please contact the administrator
I run the code last it's well,but taday when i input http://127.0.0.1:8000/,it show A server error occurred. Please contact the administrator.but I can't find anyerror in settings.py,and i revised the urls.py,then it show enter image description here it seems like there are two question my urls.py from django.conf.urls import url,include,patterns from django.contrib import admin from blog.views import * #admin.autodiscover() urlpatterns = patterns('', url(r'^archive/$',archive), url(r'^admin/',include(admin.site.urls)), ) my setting.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.9.8. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'zzwayk(+k0m-+docu%uigkuymxlde34fx3$=syx#*3-i)8hlel' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ … -
Auto create objects with ForeignKey when save in Django
I got problem with Django auto create objects.Please help me. I have a model Avatar that: class Avatar(models.Model): owner = models.ForeignKey(User, related_name='avatar_owner') photoset = models.ForeignKey(PhotoSet, null=True) image = models.ImageField(max_length=1024, upload_to=avatar_file_path) and model class PhotoSet(models.Model): title = models.CharField(_('title'), max_length=200, null=True) I want to create a def when saving model Avatar with a null photoset, it will auto get_or_create a Photoset with a certain title. I made a def like this but it's not work. @transaction.atomic def create_default_photoset(self, *args, **kwargs): if self.photoset is None: self.photoset, _ = Photoset.objects.get_or_create(title=self.id) super(Avatar, self).create_default_photoset(*args, **kwargs) Am I wrong with this def? How can I fix that? Thank you in advance! -
Django ; NameError: name 'pbkdf2' is not defined
hye i just want to ask why i keep getting this error . i dont understand why it says pbkdf2 is not defined and i already install pbkdf2 and also import PBKDF2PasswordHasher. i have been trying to fix this error for almost 4 hours . hashers.py : def encode(self, password, salt, iterations=None): assert password is not None assert salt and '$' not in salt if not iterations: iterations = self.iterations hash = pbkdf2(password, salt, iterations, digest=self.digest) hash = base64.b64encode(hash).decode('ascii').strip() return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash) can someone help me ? im really desperate :( -
What is a strategy of deploying Django + Vue with docker?
I don't fully understand how should I build and deploy the docker container with my app. I have an app which has two parts - REST API with Django REST Framework and SPA with Vue.js. API is connected to Postres. The question is, should I build a single container where I install SPA, API and database, or have app-container linked with a separate database container. I plan to build containers with gitlab ci and deploy to heroku. Or what is the best practice? -
guys i have a issue while migrating my data from models.py
guys i'm getting an error as you should have a default value to models:author,body,created,updated and here is my models.py configuration from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class post(models.Model): STATUS_CHOICE=( ('draft','DRAFT'), ('published','Published'), ) title=models.CharField(max_length=250) slug=models.SlugField(max_length = 250,unique_for_date=1) author=models.ForeignKey(User,related_name='blog_posts') body=models.TextField() publish=models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices = STATUS_CHOICE, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title and this is the error while migrating the database: You are trying to add a non-nullable field 'body' to post without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option i'm not sure what are the default values for those models and the configuration is same as it is mentioned in book but i'm still getting an error any kind of help is appreciated thanks in advance NOTE:this is a blog application and when i tried to add random default values to the models i'm getting this error: … -
How to hide button/form using django templates?
I want to hide form if user already pushed on the button. I tried to use a bit of JS code, it works well, but after refreshing page, button on form stay valid. It not a huge surprise for me)) I want hide form using Django templates, but it is not so easy as I thought. my html : <div class="who_come"> <p>Who come : </p> {% for u in who_come %} {%if u.visitor.username != request.user.username %} <form class="form-inline" role="form" method="post" id="joinToEventForm"> {% csrf_token %} <p align="left"><b ><button type="submit">I want join</button></b></p></b></p> </form> {% endif %} {% endfor %} <div id="who_come_links"> {% for u in who_come reversed %} <p><a href="profile/{{u.visiter.username}}" title="{{u.visiter.first_name}} {{u.visiter.last_name}}">{{u.visiter.username}}</a></p> {% endfor %} </div> <script> $('#joinToEventForm').submit(function() { $(this).find("button[type='submit']").prop('disabled',true); }); </script> <script> $('#joinToEventForm').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") // sanity check $.ajax({ type:'POST', data:{ action: 'joinEvent', csrfmiddlewaretoken:'{{ csrf_token }}' }, success : function (data) { //console.log(data); var usernames = JSON.parse(data); var html_str = ''; for (var i=0; i < usernames.length; i++) { html_str += '<p><a href="profile/' + usernames[i] + '">' + usernames[i] + '</a></p>'; } $('#who_come_links').html(html_str); } }); }); </script> </div> my model : class WhoComeOnEvent(models.Model): visiter = models.ForeignKey(User, related_name='WhoComeOnEvent') which_event = models.ForeignKey(Topic, related_name='WhoComeOnEvent') in this place : <p>Who come : </p> … -
Unable to install mysqlclient on Ubuntu LTS 16.04 LTS on Python3.6
I installed and created a virtual environment on my Linux Ubuntu LTS 16.04 server. MySQL database is successfully installed and the database server is working. While trying to migrate django I get error that mysqlclient is not installed. When I try to install mysqlclient using the below command, pip install mysqlclient I am getting the below error, Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Building wheels for collected packages: mysqlclient Running setup.py bdist_wheel for mysqlclient ... error Complete output from command /home/ubuntu/django_project/bin/python3.6 -u -c "import setuptools, tokenize;file='/tmp/pip-build-m44_w0__/mysqlclient/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 /tmp/tmprdsdub84pip-wheel- --python-tag cp36: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.6 copying mysql_exceptions.py -> build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/init.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb creating build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants running build_ext building 'mysql' extension creating build/temp.linux-x86_64-3.6 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,3,12,'final',0) -D__version=1.3.12 -I/usr/include/mysql -I/home/ubuntu/django_project/include -I/usr/include/python3.6m -c _mysql.c -o build/temp.linux-x86_64-3.6/_mysql.o … -
django rest api for autosuggest search
i am relatively new in django rest framework(DRF).i want to create a auto suggest api to create a list of objects, do i need to do anything more for auto sugestion or just create a create api and rest of the job will be done in front end, FYI, i am using react native for my front end. This is my model.py, class Item(models.Model): item_id = models.IntegerField(null=True, blank=True) item_name = models.CharField(max_length=100, null=True, blank=True) quantity = models.CharField(max_length=5, null=True, blank=True) unit = models.CharField(max_length=50, null=True, blank=True) and serializers.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' and the api view class ItemList(APIView): """ List all item, or create a new item. """ permission_classes = [permissions.IsAuthenticated] def get(self, request, format=None): bazarerlist = Item.objects.all() serializer = ItemSerializer(bazarerlist, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and urls.py from django.conf.urls import url from . import views urlpatterns = [ # api endpoints url(r'^items/$', views.ItemList.as_view()), ] now what should i do more if i want o add a auto suggest while creating list item ? -
Start developer server in django
After update code I have problem with runserver. Could You help me? After typing python manage.py runserver I have following exception. Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0xb615d89c> Traceback (most recent call last): File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/amich/virtualenvs/problemondo/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'url_tools' Thank You