Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - 'ascii' codec can't encode character u'\u0105' in position 17: ordinal not in range(128)
UnicodeEncodeError at /admin/blog/post/add/ 'ascii' codec can't encode character u'\u0105' in position 17: ordinal not in range(128) When i try to add content via Django admin, i have problem when i using polish letters like śźó... -
How to use pymssql with Django?
This is mssql: https://pypi.python.org/pypi/pymssql/2.1.3 would I use it on django?? DATABASES = { 'default': { 'ENGINE': 'pymssql', 'NAME': 'XXXXX', 'HOST': 'XXXXX', 'USER': 'XXXXXXX', 'PASSWORD': 'XXXXX', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } now i get this error Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: No module named 'pymssql' is there anyway to fix it? thanks a lot -
django queryset custom annotate(counting)
i'm trying to query in django. my model is below class Game(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) my situation: Game(name='League of Legend') Game(name='StartCraft') Game(name='OverWatch') word_list = ["league", "over", "craft", "legend"] games = Game.objects.annotate(word_count=blablabla).order_by('-word_count') desired result queryset: Gmae('League of Legend', 2) Game('StartCraft', 1) Game('OverWatch', 1) there is solution?? :) -
Conversion of SQL to Django
Below are my django models class SourceFile(models.Model): full_path = models.TextField(unique = False) project_name = models.TextField(blank = True) def __str__(self): return self.full_path class Coverage(models.Model): line_pct = models.IntegerField(default = 0, blank = True) source_file = models.ForeignKey(SourceFile, related_name = 'coverage', null = True) date_generated = models.DateTimeField(default = timezone.now, blank = True) def source_file_full_path(self): return self.source_file.full_path Now i want count of distinct id of source file table present in coverage table based on project_name. I wrote a sql query for the same but unable to write django equivalent for the same. select count(distinct(sf.id)), sf.project_name from coverage c inner join sourcefile sf on c.source_file_id = sf.id group by sf.project_name; Please help with this -
Django: how get a fresh connection to the database
I have built a web server with django. And use a thread to run task, which save data sent from clients to the database. while True: ... try: self.dbTarget, created = ClientMonitor.objects.get_or_create(Machine_code=own_MachC) data = self.workQueue.get() #from client sent self.dbTarget.setValue(data) #Custom method assigning self.dbTarget.save() #django ORM except InterfaceError as ee: pass The thread is long-running, but it will except a InterfaceError after a long time because the mysql server disconnect as eight-hours timeout. Especially it can not auto-reconnect to the db. Creating a new thread will be OK, but it will increase resource occupation. So I want to reconnect db when connection closed in the same thread. Also Django each request gets a fresh connection. How I can get a fresh connection to the database in the same thread? Thank you!!! -
Django-Haystack results object filtering featured items
I want to display only 'Featured Products' in a carousel display. I've have a Model with featured choice of 'YES' and 'NO'. If the choice is 'YES' I want the object to displayed as below. Nothing is being returned at this point. I'm using django-haystack ES2. models.py FEATURED_CHOICES = ( ('YES', 'YES'), ('NO', 'NO'), ) class Product(models.Model): title = models.CharField(max_length=255, db_index=True, default='') price = models.DecimalField(max_digits=10, decimal_places=2, default="2") description = models.TextField(db_index=True) retailer = models.CharField(max_length=255) image = models.CharField(max_length=1000) url = models.URLField(max_length=800, unique=True, default='') location = models.CharField(max_length=255, db_index=True, choices=LOCATION_CHOICES, default='Unknown') featured = models.CharField(max_length=255, db_index=True, choices=FEATURED_CHOICES, default='NO') home.html {% for result in page_obj.object_list %} {% if result.object.featured == 'YES' %} <div class="item"> <a href="{{ result.object.url}}"> <span class="item-carousel-thumb"> <img class="img-responsive" src="{{ result.object.image }}" alt="img"> </span> <span class="item-name"> {{ result.object.title }} </span> <span class="price"> £ {{ result.object.price }} </span> <span class="retailer"> {{ result.object.featured }} </span> </a> </div> {% endif %} {% endfor %} I've tried this with a boolean field, with and without parenthesis... Any thoughts? -
django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist by testing django form
I have the following model: class Damage(models.Model): kind = models.ForeignKey(Kind, on_delete=models.PROTECT) region = models.ForeignKey(Region, on_delete=models.PROTECT) def clean(self): if self.region not in self.kind.regions.all(): raise ValidationError('not possible') and the corresponding form: class DamageForm(forms.ModelForm): class Meta: model = Damage fields = ['kind', 'region'] when I run the following tests, I always get the django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: Damage has no region failure. def test_empty_input(self): data = { 'kind': None, 'region': None, } form = DamageForm(data) self.assertFalse(form.is_valid()) def test_invalid_input(self): data = { 'kind': self.test_kind, 'region': self.test_region, } form = DamageForm(data) self.assertFalse(form.is_valid()) -
How to use a loop inside datapool django chartit
I have to create a chat where I need to plot multiple data items. I have multiple option and term in my datapool I want to use then in loop so that I can have this dynamic -
AttributeError: 'module' object has no attribute 'Bussiness'
This is the /app03/views.py: def business(request): v = models.Bussiness.objects.all() # this is the line10 # QuerySet # [obj(id, caption, code), obj,obj...] return render(request, '/app03/business.html', {'v':v}) This is the traceback information in my PyCharm CE: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/luowensheng/Desktop/TestIOS/TestPython/pyProject/app03/views.py", line 10, in business v = models.Bussiness.objects.all() AttributeError: 'module' object has no attribute 'Bussiness' [14/Aug/2017 09:27:27] "GET /app03/business/ HTTP/1.1" 500 64817 In my /app03/models.py: class Bussiness(models.Model): caption = models.CharField(max_length=32) code = models.CharField(max_length=32, default='SA') and, I have done this operation: python manage.py makemigrations python manage.py migrate and in the db.sqlite3, have generated the app03_bussiness table: Why there is no attribute 'Bussiness'? -
Can't coalesce extents with geodjango
When I try to coalesce extent aggregations I get a string instead of the right type. So this works >>> Community.objects.annotate(extent=Extent('geometry')).get(...).extent (2726459.05875, 1220672.3825, 2736397.89, 1227645.2375) and this works >>> Community.objects.annotate(extent=Extent('potential__geometry')).get(...).extent (2726687.04049593, 1221917.0, 2732056.725, 1223760.94563836) but this doesn't >>> Community.objects.annotate(extent= ... Coalesce(Extent('potential__geometry'), Extent('geometry'))).get(...).extent 'BOX(2726687.04049593 1221917,2732056.725 1223760.94563836)' and neither does this >>> Community.objects.annotate(extent= ... Coalesce(Extent('potential__geometry'), Extent('geometry'), ... output_field=ExtentField())).get(...).extent 'BOX(2726687.04049593 1221917,2732056.725 1223760.94563836)' Is this a bug, or am I doing something wrong? -
How to expose some specific fields of model_b based on a field of model_a?
I want to create a ModelForm which gonna show some specific field of ControlInstruction if device_type of Device is equals DC. Otherwise show all fields. Suppose, if device type == 'DC': show these filed in form-> on_off_flag, speed_flag, direction_flag else: show all How can I do that? class Device(models.Model): DEVICE_TYPES = ( ('AC', 'AC MOTOR'), ('DC', 'DC MOTOR'), ) user = models.ForeignKey(User, on_delete=models.CASCADE) device_id = models.CharField(max_length=64, unique=True, blank=False) device_name = models.CharField(max_length=100, blank=False) device_model = models.CharField(max_length=10) device_type = models.CharField(max_length=2, choices=DEVICE_TYPES, blank=False) location = models.CharField(max_length=150) def __str__(self): return self.device_name class ControlInstruction(models.Model): DIRECTION_CHOICES = ( ('FW', 'Forward'), ('BW', 'Backward'), ) # OneToOneField is is similar to a ForeignKey with unique=True, but the “reverse” # side of the relation will directly return a single object. device = models.OneToOneField(Device, on_delete=models.CASCADE, primary_key=True) on_off_flag = models.BooleanField(default=False) voltage_flag = models.FloatField(max_length=20, default=0) current_flag = models.FloatField(max_length=20, default=0) speed_flag = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100)]) direction_flag = models.CharField(max_length=2, choices=DIRECTION_CHOICES, default='FW') frequency_flag = models.IntegerField(default=0) -
what is the fastest web framework to make a medium scale website (developement time)?
What is the fastest web framework to make a medium website (Django , .net core , Ruby on Rails , php frameworks ) ? I mean here fastest to develop & then if possible please state the average execution time leader also Please assume moderate knowledge in programming in C++ & java & algorithms , but I am very willing any of them -
AuthKEY REST - Role service from REST endpoint
I'm trying to setup Geonode and Geoserver advance security. I'm currently doing setup for the Geoserver. I'm stuck at this step Setup of the GeoNode REST Role Service. I cannot add new role service as i did not have AuthKEY REST - Role service from REST endpoint in the role service option. AuthKEY REST - Role service from REST endpoint. currently using Django (1.6.11) Geoserver 2.4.7 GeoNode (2.4.dev20170302183855, /vagrant/geonode) django-oauth-toolkit (0.7.2) -
How to change the rendered field in Django's ModelForm queryset?
I want to change the rendered field shown in a model form choicefield, based on some user selected feature, which is language in my case. I've got a two models. Of the two, the 'Vastausvaihtoehto' model saves an answer in both english and finnish, saving it to the database. It also returns the finnish answer by default, because that's how I've defined the unicode function: Model class Vastausvaihtoehto(models.Model): ... vastaus_fi = models.CharField( verbose_name=_(u'Vastaus'), max_length=256, null=True, blank=True, ) vastaus_en = models.CharField( verbose_name=_(u'Vastaus_en'), max_length=256, null=True, blank=True, ) ... def __unicode__(self): return u'%s' % (self.vastaus_fi) class Valinta(models.Model): organisaatio = models.ForeignKey( Organisaatio, related_name=_(u'valinta'), null=True, blank=True, on_delete=models.CASCADE, ) kysymys = models.ForeignKey( Kysymysvaihtoehto, related_name=_(u'valinta'), null=True, blank=True, ) vastausvaihtoehto = models.ForeignKey( Vastausvaihtoehto, related_name=_(u'valinta'), null=True, blank=True, ) def __unicode__(self): return u'%s' % (self.kysymys) I also have a ModelForm, that I use to select the correct choices Form class ValintaForm(ModelForm): class Meta: model = Valinta fields = '__all__' widgets = { 'organisaatio':forms.HiddenInput(), 'kysymys':forms.HiddenInput(), 'vastausvaihtoehto':forms.RadioSelect(), } And here's my view: View class kysymys(View): template_name = 'mytemplate.html' success_url = 'something' def get(self, request, pk, question_id, *args, **kwargs): kysymys = Kysymysvaihtoehto.objects.get(kysymys_id=int(question_id)) vastausvaihtoehdot = Vastausvaihtoehto.objects.filter(kysymysvaihtoehto=kysymys) if request.LANGUAGE_CODE == 'fi': # What do I put here? else: # What do I put in here? … -
How to use Pagination in a Non-Generic View/Viewset?
Prologue: I have seen this question arising in more than one posts: Django Rest Framework - APIView Pagination Pagination not working in DRF APIView and can also be applied here: Combine ListModelMixin with APIView to show pagination I have composed an example on SO Documentation to unify my answers in the above questions but since the Documentation will get shutdown on August 8 2017, I will follow the suggestion of this widely upvoted and discussed meta answer and transform my example to a self-answered post. Of course I would be more than happy to see any different approach as well!! Question: I am using a Non Generic View/Viewset (eg: APIView) on a Django Rest Framework project and I cannot add pagination to my get method results. I have tried to override the method as follows: from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger class ItemsAPIView(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request, format=None): """ Return a list of all items of this user. """ reply = {} page = request.GET.get('page') print ('page is', page) try: products = BaseItem.objects.owned_items().filter(owner=request.user) reply['data'] = OwnedItemSerializer(products, many=True).data items = BaseItem.objects.filter(owner=request.user) paginator = Paginator(items, 1) items_with_pagination = paginator.page(page) if page is not None: reply['data'].extend( ItemSerializer(items_with_pagination, many=True).data ) reply['data'].extend(ItemSerializer(items, many=True).data) … -
How to display records belongs to categories in django
I have a models.py from django.db import models from django.utils import timezone class Kategorie(models.Model): glowna = models.CharField(max_length=150, verbose_name='Kategoria') slug_kat = models.SlugField(max_length=255, verbose_name='Odnośnik', default='') class Meta: verbose_name='Kategoria' verbose_name_plural='Kategorie' def __str__(self): return self.glowna class Witryna(models.Model): nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony') adres_www = models.CharField(max_length=70, verbose_name='Adres www') slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url', unique=True) email = models.CharField(max_length=100, verbose_name='Adres e-mail') text = models.TextField(max_length=3000, verbose_name='Opis strony') kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria') data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji') class Meta: verbose_name='Strona www' verbose_name_plural = 'Strony www' def publikacja(self): self.data_publikacji=timezone.now() self.save() def __str__(self): return self.nazwa and i have created view : def detale_kat(request, slug_kat): konkretna_kategoria = Witryna.objects.annotate(cnt_witryna=Count('kategoria')).order_by('kategoria') return render(request, 'firmy/detale_kat.html', {'konkretna_kategoria': konkretna_kategoria}) on the end in html fil i have a django tags like: {% extends 'firmy/index3.html' %} {% block kategoria %} {%for konkret in konkretna_kategoria%} {{ konkret.cnt_witryna }} {% endfor %} {% endblock %} In my app on the main html file I have a view of 56 categories whos were added by the Kategorie class. The list of display categories is the detail view. How to use definition when I click in link of for example category "Business", and I want to display all websites whos were added in that category. The annotate is … -
I want to know how many orders are placed by each of the customer
I am having the following models.py from django.db import models class Customer(models.Model): Person_Id=models.IntegerField() Person_Name=models.CharField(max_length=100) Address=models.CharField(max_length=500) Email=models.EmailField(null=False, default="") def __str__(self): return self.Person_Name class Items(models.Model): Item_Code=models.IntegerField() Item_Name=models.CharField(max_length=200) def __str__(self): return self.Item_Name class Orders(models.Model): Order_Id=models.ForeignKey(Customer, on_delete=models.CASCADE) Item_Name=models.ManyToManyField(Items) Order_date=models.DateField() Comment=models.CharField(max_length=1000, blank=True) def __str__(self): return str(self.Order_Id) admin.py is as follow from django.contrib import admin from .models import Customer, Orders, Items class CustomerDetails(admin.ModelAdmin): list_display = ('Person_Name', 'Address', 'Email','total','count') readonly_fields = ('total',) search_fields = ('Person_Name', 'Email') list_filter = ('Address',) ordering = ('-Person_Name',) class OrderDetails(admin.ModelAdmin): filter_horizontal = ('Item_Name',) admin.site.register(Customer, CustomerDetails) admin.site.register(Items) admin.site.register(Orders, OrderDetails) Now, I want to know how many orders are placed by each customer. I know that reverse lookup of foreign keys would be used but I am not getting the proper way. -
Error running django with gunicorn and circus
I want to run django on an ubunu 14.04 machine , using gunicorn and circus. when I start gunicorn manually, it works fine, but when I try to run it with circus , this error occurs: Traceback (most recent call last): File "/path_to_my_app/venv/bin/gunicorn", line 7, in <module> from gunicorn.app.wsgiapp import run File "/path_to_my_app/venv/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 10, in <module> from gunicorn.app.base import Application File "/path_to_my_app/venv/lib/python3.5/site-packages/gunicorn/app/base.py", line 9, in <module> import traceback ImportError: No module named 'traceback' I have tried deleting virtual environment and creating it again, I have tested the ini file ... any ideas? -
python - subtract a field value with an .aggregate(Sum()) result
I have 2 fields, total annual leaves and annual leaves taken, using .aggregate(Sum()) I've calculated the of total annual leaves taken for an employee. but now I want to calculate the remaining leaves available for the user, which is total annual leaves - total annual leaves taken but I'm having trouble doing it because the annual_taken is a string and not a float Its giving me this error : unsupported operand type(s) for -: 'float' and 'str' How can I fix this? Any help is much appreciated Below is my view.py : def my_leaves_view(request): annual = LeavesEntitlement.objects.all().filter(employee=request.user.profile.employee.id, type=1) annual_taken = Leave.objects.all().filter(employee=request.user.profile.employee.id, type=1).aggregate(Sum('duration')) for annual_field in annual: for field in annual_taken: annual_available = annual_field.days - field context = {'form': form, 'annual': annual, 'annual_taken': annual_taken, 'annual_available': annual_available } return render(request, 'hrm/my_leaves/my_leaves_content.html', context) -
How can use another module place of HTMLParser in django
I have appearing error of HTMLParser, In terminal showing this :- from django.utils.html import format_html, format_html_join, escape File "/usr/local/lib/python3.5/dist-packages/django/utils/html.py", line 16, in <module> from .html_parser import HTMLParser, HTMLParseError File "/usr/local/lib/python3.5/dist-packages/django/utils/html_parser.py", line 12, in <module> HTMLParseError = _html_parser.HTMLParseError AttributeError: module 'html.parser' has no attribute 'HTMLParseError' Python 3.5 django 1.7.7 Using pip3 According to communities , they saying HTML parser is removed on the Python 3.5 version , on my this old application.. What should I do :- 1. Replace HTMLParser with another similar then How??? OR 2. Downgrade python version I have tried this but it taking by default lib -> /usr/lib/python3.5 How to change this path Please help on this. my requirement file requirements/common.txt is like this # Core Stuff # ------------------------------------- django>=1.7.7,<1.8 whitenoise==2.0.6 # Authentication # ------------------------------------- django-facebook==6.0.3 PyJWT==1.4.0 # Notifications # ------------------------------------- django-twilio-sms-2==1.0.2 hashids==1.1.0 apns==2.0.1 # Extensions # ------------------------------------- django-extensions==1.6.1 Werkzeug==0.11.3 pytz==2015.7 django-sampledatahelper==0.3 arrow==0.7.0 requests==2.9.1 django-flat-theme==1.1.3 # Configuration # ------------------------------------- django-sites==0.9 django-secure==1.0.1 python-dotenv==0.3.0 django-environ==0.4.0 # Models # ------------------------------------- django-model-utils==2.4 django-uuid-upload-path==1.0.0 django-versatileimagefield==1.3 django-jsonfield==0.9.15 # Images # ------------------------------------- Pillow==3.1.1 # For the persistance stores # ------------------------------------- psycopg2==2.6.1 # Celery # ------------------------------------- celery==3.1.20 # Unicode slugification # ------------------------------------- unicode-slugify==0.1.3 django-autoslug==1.9.3 # Django Rest Framework # ------------------------------------- djangorestframework==3.3.2 django_filter<=0.11.0 # Do not … -
How to check the permissions as per authenticated user using Django and Python
I need one help. I need to check the permission required as per authenticate user Using Django and Python. I am explaining my code below. class Permission(models.Model): """docstring for Permission""" user_id = models.ForeignKey(User) class Meta: permissions = ( ("view_reactor", "1"), ("find_reactor", "1"), ("controll_reactor", "0"), ) Views.py: from django.contrib.auth.decorators import permission_required def view_reactor(request): """ This function for to get serch screen. """ return render(request, 'plant/view_reactor.html', {'count': 1}) Here I need to check @permission_required decorator function as per proper userid. Suppose the logged in user has permission ("view_reactor", "1"), then that view_reactor function can access if ("view_reactor", "0") then it can not be accessed. Please help me. -
django.core.wsgi and mysql db connection (2006,'MYSQL server has gone away')
I have written a server script in python to connect to Mysql database using get_wsgi_application in django.core.wsgi. But the server often gets idle for long hours and after that I get an error(2006,'MYSQL server has gone away'), when server tries to query the database. I have found one possible solution to this, and that is by increasing the value of wait_timeout in Mysql server, but this keep others connections alive for long intervals as well. Is there any other way to resolve this issue or a way to re-establish the Mysql connection after it goes down? -
Pagedown app always converts first line at <code> tag?
I added scirpt for converting text to markdown display. Added "content-markdown" class to my div of content but my first line of the text always is being surrounded by <pre> and <code> tags. <script type="text/javascript"> $(document).ready(function(){ $(".content-markdown").each(function(){ var content = $(this).text() var markedContent = marked(content) console.log(markedContent) $(this).html(markedContent) }) What's the problem? -
how to filter data in model forms according to fields in form in Django
I am trying to filter data according to selected fields in forms. I have created a model and imported it to forms.py from django import forms from django.forms import ModelForm from .models import Student_Detail, Student_Education class StudentDetailForm(forms.ModelForm): class Meta: model = Student_Detail fields = ['name', 'surname' , 'sex', 'birth_date', 'area', 'state' , 'city' , 'pincode'] def to_python(self, value): if not value: return [] return value.split(',') and my modles are ` from __future__ import unicode_literals from django.db import models # Create your models here. class State(models.Model): state = models.CharField(max_length=50) slug = models.SlugField(unique=True, null=True, blank=True) def __str__(self): return self.state class City(models.Model): state = models.ForeignKey('State', on_delete=models.CASCADE) city = models.CharField(max_length=70) slug = models.SlugField(unique=True, null=True, blank=True) def __str__(self): return self.city class Student_Detail(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50, blank=True, null=True) sex = models.CharField(max_length=4) birth_date = models.DateTimeField() area = models.CharField(max_length=100, blank=True, null=True) state = models.ForeignKey('State', on_delete=models.CASCADE) city = models.ForeignKey('City', on_delete=models.CASCADE) pincode = models.IntegerField() slug = models.SlugField(unique=True, null=True, blank=True) def __str__(self): return self.name + " " + self.surname` Now I want to filter cities in form according to a state selected in the same form. My View is from django.shortcuts import render from .models import City, Student_Detail, State, Student_Education from django.http import HttpResponseRedirect from .forms import StudentDetailForm, … -
How to do with that if I want to pass the data from the input, and also want user can not edit the id input?
This is the template html: <form action="/app02/user_edit-{{obj.id}}/" method="post" > <input type="text" name="id" value="{{obj.id}}" disabled> <input type="text" name="username" value="{{obj.username}}"> <input type="text" name="password" value="{{obj.password}}"> <input type="submit" value="Submit"> </form> I have a form in the template, and the input for id I don't want it is editable for user, so I set it to disabled, but however if set if to disabled, I can not pass the data to the action now. In the views.py: nid = request.POST.get('id') # there will get "None" How to do with that if I want to pass the data from the input, and also want user can not edit the id input ? please ignore the form tag param's obj.id, I just want to pass data from the input.