Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Swagger Documention for Nested Object?
I am trying to programatically add json input field in swagger using dango_rest_swagger but I am having trouble nesting object in array or another object. It only let me to one level of json. Here is what I have. class MySchemaGenerator(SchemaGenerator): title = 'REST API Index' def get_link(self, path, method, view): link = super(MySchemaGenerator, self).get_link(path, method, view) print(path) print(method) print("----") link._fields += (coreapi.Field( name='categories', location='form', required=True, description='stuff in array', type='array', ), coreapi.Field( name='stuff', location='form', required=True, description='stuff in object', type='object', )) return link I am unable to specify what goes into the object nor array, please help!! -
Django CMS Plugin: Can't see model fields in interface
This is my first attempt making Django CMS plugin. I have following files ready: cms_plugins.py from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.models import CMSPlugin from . import models class SurveyPluginPublisher(CMSPluginBase): """Show Polls entered by Admin.""" cache = False # model = models.QuickAidPluginModel module = "Survey" name = "Awesome Survey v1.0" render_template = 'survey/_hello.html' def render(self, context, instance, placeholder): return context plugin_pool.register_plugin(SurveyPluginPublisher) models.py # encoding: utf-8 from cms.models import CMSPlugin, python_2_unicode_compatible from django.db import models from django.core.exceptions import ValidationError from cms.models import CMSPlugin class Survey(models.Model): name = models.CharField(max_length=400) description = models.TextField() def __unicode__(self): return (self.name) def questions(self): if self.pk: return Question.objects.filter(survey=self.pk) else: return None @python_2_unicode_compatible class SurveyPluginModel(CMSPlugin): name = models.CharField("Survey Name", max_length=255, default='Survey Name', help_text='Enter Survey Name') description = models.CharField("Survey Description", max_length=500, blank=True, help_text='Write Description here') def __str__(self): return "Returning some Survey Text" template file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>Hi Survey</h2> </body> </html But when I got Edit Page option and try to add Plugin it shows this screen -
Form password field behave as if empty when filled automatically by Chrome
When Google chrome auto-fills the password field with saved credentials info and that I submit the form, the data for the password is an empty string. Because of this I get a "field is required" kind of error, even thought there is something in the field. I am using django-allauth but I did some test and the issue seems to also happen when I use basic django Forms. Any idea what could cause the issue? Ultimately, I could just try to deactivate the autocomplete for this field but I'd rather not. -
Cannot get subprocess output in Django view
I want to emulate command line call of my script (TensorFlow neaural chatbot model) in Django view and get output from console to variable. When i do manually in terminal of my server: python3 var/www/engine/chatbot/udc_predict.py --model_dir=var/www/engine/chatbot/runs/1486057482/ the output is good and printed out. So in my Django view i do: import subprocess answer = subprocess.check_output(['python3', 'var/www/engine/chatbot/udc_predict.py','--model_dir=var/www/engine/chatbot/runs/1486057482/'], shell=True, stderr=subprocess.STDOUT, timeout=None) print('answer', answer) And answer variable is printed as b'' in Apache error log. I cannot figure out what's wrong in my call. -
i am using drop down list and want to display its value on next page
i am using drop down list and want to display its value on next page but it is displaying id insted of it's name if i write code like below and if i take both in value means value="{{operator.id}}{{operator.operators_name}}" then it is printing output like this 1xyz but i want only xyz to display and 1 for passing another java script function <select class="form-control" id="sel1" name="oprator" data-live-search="true" onchange="getOprInfo(this.value)" > <option value="">Select Operator</option> {%for operator in operators%} <option value="{{operator.id}}">{{operator}}</option> {%endfor%} </select> -
How to read the data which is coming from front end?
I am getting the json response from front end like Object {distict: "bangalore", taluka: "vijaypura", taluka2: "rural", distict1: "vijaypura", taluka3: "singagi"} how to read the data to the backend and save into the database I am fresher so it would be helpful for me -
Django Memcached timeout setting ignored
I have configured Django per site caching, using memcached. I discorevered that the expire time is always 10 minutes, no matter what timeout setting I use. Here is my settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'TIMEOUT': 60, 'KEY_PREFIX': 'mykey', } } The low timeout value is just for testing (I would like to use option "never expire") Here is the output of memcached-tool: Last-ModifiedUSat, 11 Feb 2017 09:58:06 GMT�UexpiresUExpiresUSat, 11 Feb 2017 10:08:06 GMT�U I use Django 1.8.17 with python-memcached I tried many timeout settings, like None or 86400 The other setting KEY_PREFIX works. -
Django differentiate between the first time user and returning user
I am using django registration redux for login and auth purposes. I want to do the following. if the user logs in for the first time i want to redirect to URL-"profile/create" if the user is a returning user i dont want the user to access the URL-"profile/create" and i want the user to be redirected to another URL. -
Rewriting DRF token auth
I wanted to allow a user to have multiple tokens so decided to rewrite the Token model. As result created class TokenAuthentication(rest_framework.authentication.TokenAuthentication): model = Token In my settings added to REST_FRAMEWORK 'DEFAULT_AUTHENTICATION_CLASSES': ( 'users.authentication.TokenAuthentication', ) Also modified class ObtainAuthToken(APIView): authentication_classes = () throttle_classes = () permission_classes = () parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) renderer_classes = (renderers.JSONRenderer,) serializer_class = AuthTokenSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] name = serializer.validated_data['name'] token, created = Token.objects.get_or_create(user=user, name=name) return Response({'token': token.key}) obtain_auth_token = ObtainAuthToken.as_view() and AuthTokenSerializer to return the name Finaly in the urls got url(r'^token-auth/', obtain_auth_token), I think all is correct but keep getting the errors File "/home/me/code/python/OCManager/core/users/authentication.py", line 4, in <module> from rest_framework.views import APIView ImportError: cannot import name 'APIView' and ImportError: Could not import 'users.authentication.TokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'APIView'. Any hint what it could be? The Token class modification is this: class Token(rest_framework.authtoken.models.Token): # key is no longer primary key, but still indexed and unique key = models.CharField(_("Key"), max_length=40, db_index=True, unique=True) # relation to user is a ForeignKey, so each user can have more than one token user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='auth_tokens', on_delete=models.CASCADE, verbose_name=_("User") ) name = models.CharField(_("Name"), max_length=64) class Meta: … -
Ace editor sometimes doesn't work?
I made a project for myself. https://github.com/easytrader/StrategyWebsite It should login with username:leo But I meet some problems on ace editor. I use <div id="editor1"></div>for Ace editor. and use below code to set modes for ace edior. <script> var editor1 = ace.edit("editor1"); editor1.setTheme("ace/theme/twilight"); editor1.getSession().setMode("ace/mode/python"); editor1.setFontSize(15); editor1.setValue("{{strategy.strategy}}"); </script> But in my sqlite database, it only works fine in id 2 and 3. id 5,6,7,8's ace editor don't work. Below is the page working fine . Below is the page working wrong . Someone understand the ace editor well that can help me? Thank you very much -
django shoping-cart size of product
I want to add size to my product. I create shoping cart (it works good) but now i want to add size to it. I don't have idea how i can do it. I know i must do somthing with def add in cart.py and edit vies but i don't know how. This is my cart.py class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # pusty koszyk w sesji cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'size': None, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item This is my views.py in app cart @require_POST def cart_add(request, product_id, size): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart[item_id] = size form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def … -
Django multiselect dropdown value using Django Smart Select
I am using Django Smar Select over model. It is working fine but what i need is selecting multiple value from drop-down and populate related data in chained drop-down. Is there any way to do it? I did google but did not get any specific answer. Please help Thanks in advance -
Django how to reuse views functionality common to all views
I have a Django template, let's call it index.html which is divided in 3 parts (header, content and footer). In the header section I have a search bar that includes a drop-down menu which allows the user to select an option from it and search things based on the selected option. I want that header section to be include in all my future views/templates and still display the drop-down menu with all the options. This is what I currently have in my view file def index(request): return render( request, 'home.html', {'categories': get_all_categories()} ) def cart(request): return render(request, 'cart.html', {'categories': get_all_categories()}) def help(request): return render(request, 'help.html', {'categories': get_all_categories()}) def about(request): return render(request, 'about.html', {'categories': get_all_categories()}) def contact(request): return render(request, 'contact.html', {'categories': get_all_categories()}) def search(request): return render(request, 'search.html', {'categories': get_all_categories()}) def get_all_categories(): return Category.objects.all() This is what I have cart.html {% extends "index.html" %} {% block content %} <div> <h1> My Cart </h1> </div> {% endblock %} This is what contact.html has {% extends "index.html" %} {% block content %} <div> <h1> Contact </h1> </div> {% endblock %} This is what home.html contains {% extends "index.html" %} {% block content %} <div> <h1> Home </h1> </div> {% endblock %} This works right … -
Django tutorial : TypeError at /polls/3/vote/ reverse() takes no keyword arguments
I've been working on django project with tutorials and I got this message. When I click radio box to vote, the count in admin goes up but site shows error message instead of loeading templates.It seems like there is something wrong in model.py so I added it. TypeError at /polls/3/vote/ reverse() takes no keyword arguments Request Method: POST Request URL: http://127.0.0.1:8000/polls/3/vote/ Django Version: 1.10.5 Exception Type: TypeError Exception Value: reverse() takes no keyword arguments Exception Location: C:\Users\jeon hyun joo\workspace\ch3\polls\views.py in vote, line 33 Python Executable: C:\Python27\python.exe Python Version: 2.7.13 Python Path: ['C:\\Users\\jeon hyun joo\\workspace\\ch3', 'C:\\Users\\jeon hyun joo\\workspace\\ch3', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages', 'C:\\Python27\\lib\\site-packages\\django-1.10.5-py2.7.egg', 'C:\\WINDOWS\\SYSTEM32\\python27.zip', 'C:\\Python27\\lib\\plat-win'] views.py from audioop import reverse from gc import get_objects from django.http.response import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.template.context_processors import request from polls.models import Question, Choice # Create your views here. def index(request): latest_question_list = Question.objects.all().order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', { 'question' : question }) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) 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 … -
Django library: define custom settings
I am working on a Django library, something released on Pypi as a plugable component. Some settings in this plugin should be customized by users, simply by setting values in settings.py. Currently I use this logic: # config.py import django.conf class DefaultValues(object): SETTING_1 = [] SETTING_2 = 42 class SettingsWrapper(object): def __getattr__(self, item): result = getattr(django.conf.settings, item, None) if result: return result return getattr(DefaultValues, item) settings = SettingsWrapper() And in my library, when I need to get the setting value, I do: from mylib.config import settings [...] settings.SETTING_1 It works fine, but I feel I reinvent the wheel. Recently, digging into Django code, I discovered the django.conf module, with the classes LazySettings, BaseSettings and Settings. In particular, the doc for BaseSettings say: Common logic for settings whether set by a module or by the user. My question is: can I transform my comule conf to use django classes to perform the same work (maybe better) ? -
DJANGO upload images without store
i want to create a django app with the base64 help where the users can upload images(specific ".tiff" ext) using DJANGO forms without model and without that images store in my server. and i will the users can be see the upload image in the new html template. but my problem is my app work only with "PNG" images and not with "TIFF" on the return render_to_response("blog/success.html", {"image_file":base64_string}) dislplay only PNG images and not TIFF on html template. How to fix that ? i rename to "data:image/tiff;base64,"+base64_string and not work again : here the code : forms.py from django import forms class ImageUploadForm(forms.Form): """Image upload form.""" image = forms.ImageField() views.py def convert_to_base64(image_file): base64_string = base64.encodestring(image_file) return "data:image/png;base64,"+base64_string @csrf_exempt def index(request): form = ImageUploadForm(request.POST or None, request.FILES or None) if request.method == "POST" and form.is_valid(): image_file = request.FILES['image'].read() base64_string = convert_to_base64(image_file) return render_to_response("blog/success.html", {"image_file":base64_string}) return render_to_response('blog/calc.html', {'form': form}, RequestContext(request)) i try this change without success : my_str = base64_string.decode("utf-8") and try this change this without success again: bytes = str.encode(base64_string) imgString = base64.decodestring(bytes) i show me Incorrect padding error in browser. and i try this with PIL without success again : import cStringIO import PIL.Image # assume data contains your decoded … -
Django Audiofield Package installation
Complete Django newbie here, I'm currently trying to add the django-audiofield package into my project, and I have 2 questions: 1. Do I just do a pip install django-audiofield in the directory where my manage.py file is? The documentation mentions a installation script and I'm assuming thats it. 2. At a certain point the docs say to "If you are not using the installation script, copy following template file to your template directory": cp audiofield/templates/common_audiofield.html /path/to/your/templates/directory/ . Does this just mean I should just make an html file named common_audiofieled.html in my existing template directory for the app? Any help is much appreciated! -
If Bed assigned to patient then that bed disable and remaing bed show in list in Django?
I am Working on Hospital ERP and I am currently working on assign patent to be I have the problem with when BED No 1 is assign to the first Patient then when the second patient also shows the BED No 1 in Bed Drop Down list how to solve this? -
Django registration Redux Redirect after login
settings.py LOGIN_REDIRECT_URL = "profile:view_profile" urls.py(main urls.py) url(r'^', include('user_profile.urls', namespace="profile")) user_profile.urls.py url(r'^(?P<pk>[0-9]+)/$', views.ViewProfileId.as_view(), name='view_profile'), user_profile_views.py class ViewProfileId(generic.DetailView): model = Profile template_name = 'profile/profile_view.html' I get this error? Reverse for 'view_profile' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P[0-9]+)/$'] Any Solutions? -
ElasticSearch with django haystack
I am new to Elastic search . Please help me in finding the filter/query to be written to match the exact records with autocomplete using django haystck. Below is the example suppose /?q=Mel ---> it should returns records with mel__(eg.meluha).it does not return other records with m__ and me__.As per my knowledge autocomplete has Ngram field.By using this i am not able to complete my functionality -
Django failed to load templates in eclipse
I just tried to test app I made in localhost and it keep gives me a message that templates does not exit even though I made it in eclipse. When I checked it was trying to load templates where those are not exist. Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\contrib\admin\templates\polls\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\contrib\auth\templates\polls\index.html (Source does not exist) It seems like I have to change the path to the eclipse > workspace > ch3 > polls where html is in. I would like to know how can I edit this path and is it right solution for this error? -
Django tables manytomany field links
Django newbie here. I'm trying to use django-tables2 to display a model with a m2m field, and display the m2m field as an hyperlink through to the related record for each record found. In this case, for each device, I want to display related applications. The applications are displaying but are not hyperlinked to their related record. I know I'm missing something. Please point me in the right direction: device/models.py: from django.db import models from django.utils import timezone from django.template.defaultfilters import slugify # Create your models here. class Device(models.Model): device_name = models.CharField(max_length=200, unique=True) def __str__(self): return self.device_name description = models.TextField(max_length=500, blank=True) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.device_name) super(Device, self).save(*args, **kwargs) class Meta: verbose_name = 'Device' verbose_name_plural = 'devices' ordering = ['id'] # Related applications related_apps = models.ManyToManyField('application.Application', verbose_name = u'Applications', blank=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) application/models.py from django.db import models from django.utils import timezone from django.template.defaultfilters import slugify # Applications: many (Applications) to many (Devices) class Application(models.Model): application_name = models.CharField(max_length=200, unique=True) def __str__(self): return self.application_name description = models.TextField(max_length=500, blank=True) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.application_name) super(Application, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'applications' created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) def … -
Django - Allowing multiple files to be uploaded
I managed to allow users to upload an image with their posts now on the blog I am building. However, I am currently trying to allow them to upload multiple files. Here is my views.py: def post_create(request): if not request.user.is_authenticated: return(redirect("posts:post_timeline")) form = PostForm(request.POST or None, request.FILES or None) if form.is_valid() and request.POST: instance = form.save() return(HttpResponseRedirect(instance.get_absolute_url())) context = { "form": form, } return render(request, "post_form.html", context) Here is my models.py: def upload_location(instance, filename): try: id_ = Post.objects.all().latest('id').id + 1 except ObjectDoesNotExist: id_ = "first_post" return ("{}/{}".format(id_, filename)) class Post(models.Model): post_title = models.CharField(max_length = 120) post_content = models.TextField() last_updated = models.DateTimeField(auto_now=True, auto_now_add=False) post_date = models.DateTimeField(auto_now=False, auto_now_add=True) post_image = models.FileField(upload_to=upload_location, null=True, blank=True) def __unicode__(self): return self.post_title def __str__(self): return self.post_title def get_absolute_url(self): return reverse("posts:post_display", kwargs= {'post_id': self.id}) And here is my forms.py: class PostForm(forms.ModelForm): post_image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Post fields = ["post_title", "post_content", "post_image"] Thanks for any help or suggestions on how I could do this. I know that there have been questions asked like this before and I have tried their solution but nothing will work for me. Thanks, -Will -
Django - How can I iterate over the options with modelform?
I'm having a problem here I hope you could help.. Here's what I'm trying to achieve. Basically I have a little web application where I have 3 forms. one main form where I'm asking for name and age one form for an old man and one more form for a young man the first form I'll see in template will be the first form, where I'll enter the name and select if it's an old or young man. to make it work as expected once I select young or old it will show with Jquery the corresponding form if I enter old I'll see form for old man and if I enter young I'll see the form for young man. Jquery and everything works ok except by the first form.. All I need is to show my first form in template as a modelform. I know I can make it work perfect with a normal form, but I need to save age and name in my database. Here's my models : AGES = ( ('OLD', 'OLD'), ('YOUNG', 'YOUNG '), ) class Person(models.Model): name = models.TextField() age = models.CharField(max_length=128,choices=AGES, default=True) def __str__(self): return self.name class Questions_old(models.Model): person = models.ForeignKey(Person) country = … -
how to add two numbers on views.py in django?
i am trying to add two numbers on views.py but it concatenating two number new_bal = request.POST.get('wallet_bal') old_bal = request.POST.get('old_bal') update_bal = int(new_bal + old_bal ) wallet.balance = update_bal