Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Changing innodb_page_size in my.cnf file does not restart mysql database
Hope you have a great day. I have a table with 470 columns to be exact. I am working on Django unit testing and the tests won't execute giving the error when I run command python manage.py test: Row size too large (> 8126). Changing some columns to TEXT or BLOB or using ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED may help. In current row format, BLOB prefix of 768 bytes is stored inline To resolve this issue I am trying to increase the innodb_page_size in MySQL my.cnf file. When I restart MySQL server after changing value in my.cnf file, MySQL won't restart. I have tried almost every available solution on stackoverflow but no success. MYSQL version=5.5.57 Ubuntu version = 16.04 Any help would be greatly appreciated. Thank you -
django - calculating total average based on user inputs
i have my website setup where users can vote on the blogs on 4 separate categories. i have set up their individual averages as a function in my model and am trying to get their total averages combined to show in a template models.py class Post(models.Model): STATUS_CHOISES = ( ('draft', 'Draft'), ('published', 'Published'), ) category = models.ForeignKey(Category) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) content = models.TextField() seo_title = models.CharField(max_length=250) seo_description = models.CharField(max_length=160) author = models.ForeignKey(User, related_name='blog_posts', default=settings.AUTH_USER_MODEL) published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=9, choices=STATUS_CHOISES, default='draft') def get_absolute_url(self): return reverse('blog:post_detail', args=[self.slug]) # This was given to me by another StackOverflow user # def avg_ratings(self): return self.comments.aggregate( Avg('difficulty_rating', output_field=FloatField()), Avg('workload_rating', output_field=FloatField()), Avg('book_rating', output_field=FloatField()), Avg('attendance_rating', output_field=FloatField()), ) # This I tried to do myself based on the above # def avg_ratings_total(self): difficulty_average = self.comments.aggregate(Avg('difficulty_rating', output_field=FloatField())) workload_average = self.comments.aggregate(Avg('workload_rating', output_field=FloatField())) book_average = self.comments.aggregate(Avg('book_rating', output_field=FloatField())) attendance_average = self.comments.aggregate(Avg('attendance_rating', output_field=FloatField())) total_of_averages = difficulty_average + workload_average + book_average + attendance_average total_average = float(total_of_averages / 4) return self.total_average def __str__(self): return self.title class Comment(models.Model): difficulty_rating_choices = ( (1, 'Very Easy'), (2, 'Easy'), (3, 'Moderate'), (4, 'Hard'), (5, 'Very Hard'), ) workload_rating_choices = ( (1, 'Very Light'), (2, 'Light'), (3, 'Moderate'), (4, β¦ -
Django Rest Framework apply a filter to a string using SerializerMethodField
somebody know if can i apply a filter to a string field that i recovered from a foreign key using a SerializerMethodField? When i try to use the filter field on the filter option in the api-list page, i get on the field the tag: [invalid name]: And if i try to use it, i get the error: Cannot resolve keyword 'proceso_sitio' into field. Choices are: cerrado, create_by, create_by...... I have the following My models are: class ProcesoAuditoria(models.Model): auditoria = models.ForeignKey(Auditoria) proceso = models.CharField(max_length=160) auditor_nombre_completo = models.CharField(max_length=240) sitio = models.CharField(max_length=200) class HallazgoProceso(models.Model): titulo = models.CharField(max_length=40) proceso = models.ForeignKey(ProcesoAuditoria) requisito_referencia = models.ManyToManyField(RequisitoProceso, blank=True) falla = models.ManyToManyField(Falla, blank=True) tipo_hallazgo = models.CharField(max_length=11) observacion = models.CharField(max_length=400, blank=True) cerrado = models.CharField(max_length=2) My Serializer: class HallazgoProcesoSerializer(serializers.HyperlinkedModelSerializer): proceso_sitio = serializers.SerializerMethodField() class Meta: model = HallazgoProceso fields = ( 'pk', 'titulo', 'proceso', 'proceso_sitio', 'estado', 'tipo_hallazgo', 'cerrado', ) def get_proceso_sitio(self, obj): try: return obj.proceso.sitio except: return "" and my filters: class HallazgoProcesoFilter(filters.FilterSet): titulo = CharFilter( name="titulo", lookup_expr="icontains" ) proceso = CharFilter( name="proceso", lookup_expr="exact" ) proceso_sitio = CharFilter( name="proceso_sitio", lookup_expr="exact" ) estado = CharFilter( name="estado", lookup_expr="exact" ) tipo_hallazgo = CharFilter( name="tipo_hallazgo", lookup_expr="exact" ) cerrado = CharFilter( name="cerrado", lookup_expr="exact" ) class Meta: model = HallazgoProceso fields = [ 'titulo', 'proceso', 'proceso_sitio', β¦ -
ImportError : import dj_database_url ImportError: No module named 'dj_database_url'
I am attempting to use Django + Heroku + all necessary dependencies to create my app. After following these steps : migrating an existing django project However I keep getting this error when I ran python3 manage.py runserver: import dj_database_url ImportError: No module named 'dj_database_url' I have tried to fix it with these instructions and this THIS is my code : I imported the dj-database-url import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) I added the follow STATIC assets necessitities PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' THIS is in my requirements.txt file dj-database-url==0.4.2 gunicorn==19.7.1 whitenoise==3.3.0 I am still getting the ImportError. How do I fix this? -
Django and APScheduler on the same Postgres failed to run test
In my project code. I have Django 1.11 and APScheduler 3.3.1 running with Postgres 9.6 The problem is during the full testcaes. APScheduler hits database Postgres before Django finish the migrations. On my OSX Laptop does not has that problem. Any technique I can avoid this problem? Any help would be appreciated -
Incorrect Django path to templates folder in settings.py
I am newly learning Django and was following the Learn Django 1.11 Tutorial. Here is my current project tree: βββ manage.py βββ muypicky β βββ __init__.py β βββ old_settings.py β βββ settings β β βββ base.py # Contains the settings (like shown in the tutorial) β β βββ __init__.py β βββ urls.py β βββ wsgi.py βββ requirements.txt βββ restaurants βββ templates # Templates Folder βββ index.html I am trying to add the path to the tempelates folder in the settings folder. But the error shown django.template.loaders.filesystem.Loader: .../muypicky/templates/index.html (Source does not exist) Current setting.py file TEMPLATES = [{ 'DIRS': [os.path.join(BASE_DIR, 'templates')], },] Looking at the error, the file path is wrong because it goes into /muypicky/tempelates which is incorrect. So how do I get to root folder and then into tempelates folder with the given file tree in setting.py (base.py). Any further queries, just ask and many thanks in anticipation. -
Django admin backend UI does not update from 1.8 to 1.11 version
I have the latest version of Django: >>> import django >>> django.VERSION (1, 11, 4, u'final', 0) but my http://[IP Address]/admin, is still clearly showing the old design. Removed/changed static files, ran service gunicorn restart, made migrations, cleared cookies, tried a new browser, and everything else I could find on this topic. However, for some reason, I can not get the old Django admin backend design to change to the new one. The original default DigitalOcean "I click Install" Where am I going wrong.. -
Iterate through a Dictionary in Python 3, Django 1.11 to print Key, Value in the Template
Using Django 1.11 and Python 3, how can I iterate through a dictionary in order to show a list of key, value in the Template? Here is my function (in the Model): def status(self): queryset = Event.objects.filter(ticket__queue=True, service__in=self.services.all()).values('service').annotate(total=models.Count('service')) for items in queryset: for iten in itens.items(): print(iten) The above for returns me: ('service', 2) ('total', 6) How can I print this in the Template, like: Tickets for Service A : 3 Tickets for Service B : 5 and so on? Thank you! -
ImproperlyConfigured DeletePost's select_related property
So I'm trying to enable the currently logged in user to delete their own post on my site. I'm using a DeleteView with select_related mixing. I keep getting an error that says it's improperly configured and needs to be a tuple or a list. Here is the error, my post models, and views. Not really sure where to go from here, and this doesn't seem to be a very popular error as I'm not really able to find much with a Google search. Error: ImproperlyConfigured at /colorsets/delete/7/ DeletePost's select_related property must be a tuple or list. App Views.py from django.shortcuts import render from colorsets.forms import ColorForm from colorsets import models from colorsets.models import ColorSet from django.utils import timezone from django.contrib.auth import authenticate,login,logout from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse,reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from braces.views import SelectRelatedMixin from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) # Create your views here. #def index(request): # return render(request,'index.html') class PostListView(ListView): model = ColorSet def get_queryset(self): return ColorSet.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class CreateColorSetView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'index.html' form_class = ColorForm model = ColorSet def form_valid(self,form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class DeletePost(LoginRequiredMixin,SelectRelatedMixin,DeleteView): model = models.ColorSet select_related = β¦ -
Rewrite query from postgresql to Django ORM
I am trying to find all polygons that fit within a big polygon with the ID -52822. This query does exactly what I am looking for: select kid.* from location as kid, location as dad where dad.osm_id = -52822 and ST_Within(kid.way, dad.way) and kid.admin_level = 3; However, I can not wrap my head around how I should approach this using Django without ending up using two queries. Any help is greatly appriciated. Thank you! -
ImportError: cannot import name 'WSGIServer'
I am trying to install bots in Centos 7.2 all the software is installed, cherryfy,bots,Ganeshi,Django with the latest version, when trying to execute using bot-webserver.py I get the above error, tried downgrading, but no use tried to change "import wsgiserver" in /usr/lib/python2.7/site-packages/bots/webserver.py but no use, can anyone guide me in this? -
Django 1.8 How to filter an object by id of current generic Detail View
I am struggling (due to being new to django) with how to filter an object by the current details views ID. For example, I am writing a test app that allows "venues" to have their own detail page and on that page they can display their "Menu" items, "OpeningHours" etc. Here is what I am sending from the view to the template: class DetailView(generic.DetailView): model = Venue template_name = 'nmq/detail.html' def get_queryset(self): return Venue.objects.all() def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) context['OpeningHours'] = OpeningHours.objects.all() context['Menu'] = Menu.objects.all() context['Venue'] = self.queryset return context I can easily manage to get all OpeningHours from that model but this is shared across all users. I am trying to filter this by the id of the current page. I can access this on the detail page by using {{ venue.id }} but I cannot seem to manage to pull this together with anything else to just get menu items of opening hours for that particular id. -
django redirect to the prevoius page within a class [duplicate]
This question is an exact duplicate of: django CreateView class return to the Previous page i know how to do it in a function but not in a class like this: class updateTask(UpdateView): .... success_url = # code that redirect to the previous page -
How to correctly render multiple apps on the main page
So I'm currently learning to use Django, and I'm wondering how to correctly split up parts of the functionality while still displaying it on the main page. For example, I want the header + navigation, a calendar and recent blog articles on the main index page. On the view article page I'd for example have the header + nav, the calendar and a single article with a comment section. Now reading the tutorials, if I understand them correctly, I'd split the functionality in a header app, a calendar app and the blog app itself while glueing it together with a core app. But what I don't understand is how to render apps/other views in the main app. All the ways I found only specify templates itself or look very hacky, so apparently that doesn't seem to be the common way to go. -
Add warning message in django-rest-framework
I am new to django-rest-framework. I am building an employee scheduling application where I have a REST Api built with drf and frontend in angular. Below is one of my models and it's corrsponding serializer and viewset. model: class Eventdetail(models.Model): event = models.ForeignKey(Event, models.DO_NOTHING, blank=True, null=True) start = models.DateTimeField(blank=True, null=True) end = models.DateTimeField(blank=True, null=True) employee = models.ForeignKey(Employee, models.DO_NOTHING, blank=True, null=True) location = models.ForeignKey(Location, models.DO_NOTHING, blank=True, null=True) is_daily_detail = models.BooleanField def __str__(self): return self.event serializer: class LocationTrackSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) super(LocationTrackSerializer, self).__init__(many=many, *args, **kwargs) location = serializers.SlugRelatedField(slug_field='location_name', queryset=Location.objects.all() ) location_color = serializers.CharField(source='location.location_color', read_only=True) class Meta: model = Eventdetail fields = ('id','employee','location','location_color','start','end') viewset: class LocationTrackViewSet(viewsets.ModelViewSet): queryset = Eventdetail.objects.all() serializer_class = LocationTrackSerializer def create(self, request, *args, **kwargs): self.user = request.user listOfThings = request.data['events'] serializer = self.get_serializer(data=listOfThings, many=True) if serializer.is_valid(): serializer.save() headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) As you can see, this exposes event details of all employees. Now when new events are posted, I want to be able to find if the start and end times of posted events overlap with existing events and throw a warning message with info of overlapping events after creation. I still want to allow save but only return β¦ -
Django - Custom Form Field Example
I have a project in which I need to add a custom form field to a form (or formset) in which depending on the choice in the custom field selected, an integer in a database field is changed. I can't seem to find any examples or prior questions which imply how to modify a database field via a custom field. I suspect it is done by overwriting the save() function in a ModelForm but cannot work out how. Any advice on solving this problem would be greatly appreciated. -
Django: AJAX query returns intersection of the current and previous ResultSet
Okay, so I'm trying to display relevant search results in a HTML datalist tag as a user enters text into a HTML text input. To achieve this, I have the following JS: <script type="text/javascript"> jQuery.curCSS = function(element, prop, val) { return jQuery(element).css(prop, val); }; function searchOpen() { var search = $('#txtSearch').val() var data = { search: search }; $.ajax({ url: 'ajax/search_suggestions/', data: data, dataType: 'jsonp', jsonp: 'callback', minLength: 3, jsonpCallback: 'searchResult' }); } function searchResult(data) { var dataList = document.getElementById('suggestions'); data.forEach(function(item) { var option = document.createElement('option'); option.value = item; dataList.appendChild(option); }); }; </script> Sending an AJAX request to this Class Based View in Django: class SearchSuggestions(View): def get(self, request): search_term = self.request.GET['search'] query_set = Names.objects.filter(name__istartswith=search_term)[:5] results = [] for r in query_set: results.append(r.name) results = json.dumps(results) # print(results) resp = self.request.GET['callback'] + '(' + results + ');' return HttpResponse(resp, content_type='application/json') Say I have a database table with the following entries: { 'aa', 'ab', 'ac', 'ad', 'ae', 'af' } If I type a letter, for example 'a'. I get the first 5 results that start with 'a': { 'aa', 'ab', 'ac', 'ad', 'ae' } which is the expected behavior. However, when I type the second letter, it is further slicing the β¦ -
Displayin the elements inside for loop inline html
I'm trying to display the elements in thumbnail using bootstrap in a single line but whenever I execute it in a for loop it gets printed in different lines. My code: {% for book in all_books %} <div class="row"> <div class="clearfix"> <div class="col-md-2"> <div class="thumbnail"> <a href="https://en.wikipedia.org/wiki/Inferno_(Dan_Brown_novel)" target="_blank"><img src="{{book.book_cover}}" alt="Book1" style="width:60%"> <div class="caption"> <p>{{book.title}} - {{book.author}}</p> </div> </a> </div> </div> </div> </div> {% endfor %} -
Django tests broken when I have two database in settings
I have a Django (1.9.2) application with two databases (Postgres) in the settings. And I have migrations with migrations.RunPython. When I try to run the tests (manage.py test), migrations run twice breaking the tests. On the second execution, the database already updated to the latest version and the code called on the RunPython raise an exception. Someone have some tip to solve this? Thanks -
django summernote error "success is not a function"
I got error jquery.js:3860 jQuery.Deferred exception: imageInput.fileupload(...).success is not a function TypeError: imageInput.fileupload(...).success is not a function at HTMLDivElement.onImageUpload (http://localhost:8000/test/:87:22) at Context.triggerEvent (http://localhost:8000/static/django_summernote/summernote.min.js:3:13474) at Editor.insertImagesOrCallback (http://localhost:8000/static/django_summernote/summernote.min.js:4:19085) at Context.invoke (http://localhost:8000/static/django_summernote/summernote.min.js:3:14766) at http://localhost:8000/static/django_summernote/summernote.min.js:5:23000 at mightThrow (http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js:3583:29) at process (http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js:3651:12) undefined and my html head <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet"> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> <script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script> <link href="/static/django_summernote/summernote.css" type="text/css" media="all" rel="stylesheet" /> <link href="/static/django_summernote/django_summernote_inplace.css" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/static/django_summernote/summernote.min.js"></script> <script type="text/javascript" src="/static/django_summernote/jquery.ui.widget.js"></script> <script type="text/javascript" src="/static/django_summernote/jquery.iframe-transport.js"></script> <script type="text/javascript" src="/static/django_summernote/jquery.fileupload.js"></script> <script type="text/javascript" src="/static/django_summernote/ResizeSensor.js"></script> and this is file related with success function <script> $(function() { var id_desc_textarea = window.document.getElementById('id_desc-textarea'); var id_desc_src = window.document.getElementById('id_desc'); var id_desc_settings = {"width": 720, "height": 480, "url": {"upload_attachment": "/summernote/upload_attachment/"}, "toolbar": [["style", ["style"]], ["font", ["bold", "italic", "underline", "superscript", "subscript", "strikethrough", "clear"]], ["fontname", ["fontname"]], ["fontsize", ["fontsize"]], ["color", ["color"]], ["para", ["ul", "ol", "paragraph"]], ["height", ["height"]], ["table", ["table"]], ["insert", ["link", "picture", "video", "hr"]], ["view", ["fullscreen", "codeview"]], ["help", ["help"]]], "lang": "en-US"}; var csrftoken = getCookie('csrftoken'); // include summernote language pack, synchronously if( id_desc_settings.lang != 'en-US' ) { $.ajaxSetup({async:false}); $.getScript('/static/django_summernote/lang/summernote-' + id_desc_settings.lang + '.min.js'); $.ajaxSetup({async:true}); } $(id_desc_textarea).hide(); function recalcHeight(nEditor) { var nToolbar = nEditor.find('.note-toolbar'); var nStatusbar = nEditor.find('.note-statusbar'); var nEditable = nEditor.find('.note-editable'); var height = parseInt( parseInt(id_desc_settings.height) // default - nToolbar.outerHeight() // toolbar height including margin,border,padding - nStatusbar.outerHeight() // statusbar β¦ -
My virtual environment is having access to global packages
I have virtualenv 15.1.0 installed. The problem is that when I create a virtual environment with virtualenv venv and then activate it, it will have access to packages installed globally (django-admin for example). This happens although it is mentioned in virtualenv reference guide here that: Not having access to global site-packages is now the default behavior. Also, I want to mention that running pip3 freeze while the virtual environment is activated prints nothing. -
Django Haystack: is there a way to search in choices representation of a field that has choices as model field options?
I have a model that has choices as options for a field. class TMSDeviceSetting(models.Model): PULSE_STIMULUS_TYPES = ( ("single_pulse", "Single pulse"), ("paired_pulse", "Paired pulse"), ("repetitive_pulse", "Repetitive pulse") ) tms_setting = models.OneToOneField(TMSSetting, primary_key=True, related_name='tms_device_setting') tms_device = models.ForeignKey(TMSDevice) pulse_stimulus_type = models.CharField(null=True, blank=True, max_length=50, choices=PULSE_STIMULUS_TYPES) coil_model = models.ForeignKey(CoilModel) I'm using haystack/elasticsearch in my Django project. What I'd like to know is if I can make Haystack to search in the field choice representation: "Single pulse", "Paired pulse", "Repetitive pulse". My search index to this model is: class TMSDeviceSettingIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) tms_setting = indexes.CharField(model_attr='tms_setting__id') def get_model(self): return TMSDeviceSetting def index_queryset(self, using=None): experiments = Experiment.lastversion_objects.filter( status=Experiment.APPROVED ) tms_settings = TMSSetting.objects.filter(experiment__in=experiments) return self.get_model().objects.filter(tms_setting__in=tms_settings) -
Django CreateView: set user before validation
I have a model that uses different validation for its name field depending on whether the object was created by a user or by the system. class Symbol(models.Model): name = models.CharField(_('name'), unique=True, max_length=64) creator = models.ForeignKey('User', null=True, on_delete=models.CASCADE) def is_system_internal(self): """ whether or not this Symbol belongs to the system rather than having been created by a user """ return (self.creator is None) def clean(self): """ ensure that the Symbol's name is valid """ if self.is_system_internal(): if not re.match("^_[a-zA-Z0-9\-_]+$", self.name): raise ValidationError( _("for system-internal symbols, the name must consist of letters, numbers, dashes (-) and underscores (_) and must begin with an underscore."), params = { 'value' : self.name }, ) else: if not re.match("^[a-zA-Z][a-zA-Z0-9\-_]*$", self.name): raise ValidationError( _("the symbol name must consist of letters, numbers, dashes (-) and underscores (_) and must begin with a letter."), params = { 'value' : self.name }, ) I want to create a Form and a CreateView with which users can create the objects. When a user creates such an object, the user should be used as the value for the value of the 'creator' field. Currently it looks like this: class SymbolCreateForm(forms.ModelForm): name = forms.CharField(max_length=Symbol._meta.get_field('name').max_length, required=True) class Meta: model = Symbol fields β¦ -
Archive MonthYear widget not working in django
I have an app in Django where I want to create an archive where events will be displayed. I want to filter the archive after a month and a year. Unfortunately, my solution does not work - we do not see the current events and there are no events before 2017. Please help. Here is my view: class BookingListView(ListView, FormView): model = models.Booking form_class = BookingForm queryset = models.Booking.objects.order_by('-date_start') paginate_by = 80 template_name = 'events/archive_list.html' context_object_name = 'object_list' date_field = 'date_start' allow_future = True success_url = '/' def get_context_data(self, **kwargs): context = super(BookingListView, self).get_context_data(**kwargs) context['form'] = BookingForm() return context Here is my url: url('^$', views.BookingListView.as_view(), name="list"), Here is my form: from django import forms from django.forms.extras.widgets import SelectDateWidget from archive.models import Booking class BookingForm(forms.ModelForm): date_start = forms.DateField(widget=SelectDateWidget()) class Meta: model = Booking fields = ('date_start', ) widgets = {'date_start': SelectDateWidget()} -
Django filtering objects by repeats in each month
I have a model like this: class Event(models.Model): user = models.CharField() event_date = models.DateTimeField() I want to get the user ids who have an event (or events) each month from the minimum event_date to the maximum event_date. Is this possible using Django aggregations? Or should I do it manually with a loop or something?