Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I share with facebook the respective post?
I have a django blog on the web and I finally put the facebook share plugin in the one. But everytime I share, I can share the same image, the image is a static image from the head of base.html. I am using django 1.10,python3.6 and no one share plugin. How can I share respective image from my respective page? Very thanks! ps: I think any others code is be unnecessary. views.py def index(request): posts = Evento.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') return render(request, 'core/index.html', {'posts': posts}) from urllib.parse import quote_plus def post_detail(request, pk): post = get_object_or_404(Evento, pk=pk) share_string = quote_plus(post.apresentacao) context = { "title": post.nome, "instance": post.foto, "share_string": share_string, } Evento.objects.get(pk=pk) return render(request, 'core/post_detail.html', {'post': post}) def index(request): posts = Evento.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') return render(request, 'core/index.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Evento, pk=pk) share_string = quote_plus(post.apresentacao) context = { "title": post.nome, "instance": post.foto, "share_string": share_string, } Evento.objects.get(pk=pk) return render(request, 'core/post_detail.html', {'post': post}) models.py class Evento(models.Model): nome = models.CharField(max_length=200, null=False, blank=False) apresentacao = models.TextField(null=False, blank=False) foto = CloudinaryField('foto', null=True, blank=True) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.nome def get_absolute_url(self): #return reverse("detalhe", kwargs={"pk": self.pk}) return "/post/%s" %(self.pk) and post_detail.html <div class="post"> <div class="fb-share-button" data-href="{{ … -
How to set the default value of a dropdown menu in Django?
Currently, I have the following 2 Drop-Down menus to display the years and weeks but I want to display the current year and current week, respectively, inside of these menus. Django form from django import forms class DropDownMenuForm(forms.Form): week = forms.ChoiceField(choices=[(x,x) for x in range (1,53)]) year = forms.ChoiceField(choices=[(x,x) for x in range (2016,2021)]) Template to display the menus <form id="search_dates" method="POST" action="{{ action }}"> {% csrf_token %} <div class="row"> <div style="display:inline-block"> <h6>Select year</h6> <select name="select_year"> <option value={{form.year}}></option> </select> </div> <div style="display:inline-block"> <h6>Select week</h6> <select name="select_week"> <option value={{form.week}}></option> </select> </div> <button type="submit">Search</button> </div> </form> Display the current week and year from datetime import date date.today().isocalendar()[1] date.today().year How can I connect the Display the current week and year code with the template, so I can see the current year and week selected in the dropdown menus? -
django models.DoesNotExist: mahching query does not exist
I am using Django 1.11 and typed below codes in models.py. It works fine when makemigrations, but it notices the error of "models.DoesNotExist" when do migrate. The code in models.py: class RecordType(models.Model): name = models.CharField(max_length=100, default='out',blank=True, verbose_name="name") def get_record_type_default(): return RecordType.objects.get_or_create(pk=1)[0].id class PrimaryCategory(models.Model): type = models.ForeignKey(RecordType, on_delete=models.PROTECT, default=get_record_type_default, verbose_name="type") def get_primary_category_default(): return PrimaryCategory.objects.get_or_create(pk=1)[0].id class SecondaryCategory(models.Model): primary_category = models.ForeignKey(PrimaryCategory, on_delete=models.PROTECT, default=get_primary_category_default, verbose_name="1st category") def get_secondary_category_default(): return SecondaryCategory.objects.get_or_create(pk=1)[0].id class Record(models.Model): secondary_category = models.ForeignKey(SecondaryCategory, on_delete=models.PROTECT, default=get_secondary_category_default, verbose_name="2nd category") And here is the error message while doing migrate: File "C:\Users\myname\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 464, in get_or_create return self.get(**lookup), False File "C:\Users\myname\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 380, in get self.model._meta.object_name datacore.models.DoesNotExist: SecondaryCategory matching query does not exist. -
Alternative ways of styling class-based form fields
In Django, one applies CSS styling to class-based form fields in forms.py (or equivalent). My question: is it impossible to do it any other way inside a Django project? I'll accept the answer even if the answer is "it's impossible". Hacks and tricks are acceptable as well. Illustrative examples would be great. I've been a Django developer since a few years. It's worth it to know tricks, hacks or patterns experienced Djangonauts have been using. This question has been one of my pet peeves for a while. So I thought I'd pose it as a question to the community. p.s. here's an example of a Django form where I've styled in the class-based form: class SampleForm(forms.Form): description = forms.CharField(max_length=250) def __init__(self,*args,**kwargs): super(SampleForm, self).__init__(*args,**kwargs) self.fields['description'].widget.attrs['class'] = 'btn bcg' self.fields['description'].widget.attrs['style'] = 'background-color:#F8F8F8; width:98%; color: #1f8cad;' self.fields['description'].widget.attrs['autocomplete'] = 'off' -
AJAX update variable in html django
I'm trying to update a variable in an html page after it has been updated using an AJAX call: {% for q in questions %} {% if qdelete == forloop.counter %} <div align= Center> <button type="submit" class="btn btn-primary btn-small" id="qyesbtn" name="qyesbtn" value="qyesbtn_{{q.id}}">Yes &raquo;</button> </div> <div align= Center> <button type="submit" class="btn btn-primary btn-small" id="qnobtn" name="qnobtn" value="qnobtn">No &raquo;</button> </div> {% else %} <button type="button" id="qbtn" class="btn btn-primary btn-large" name="qid" value="{{forloop.counter}}" onclick="SetDeleteNum({{forloop.counter}})">Delete &raquo;</button> {% endif %} {% endfor %} <script> function SetDeleteNum(d) { var num = -1 num = d console.log('num: '+num) var page = $(this) $.ajax({ type: "POST", url: "{% url 'home' %}", data: { 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), 'qid': num }, dataType: 'json', success: function (data) { console.log('aa'+JSON.stringify(data)) page.html(data); }, error: function(e){ console.log('err: '+JSON.stringify(e)) } }); } </script> The value qdelete should be updated to 'num' after the AJAX call but it is still as before although I can see from the logs that the qdelete has the new value assigned but it simply not displayed in the page. I also tried to put the new 'data' in the new html using the line 'page.html(data);' but no luck. Any idea? -
Django Rest Framework HyperLinkedRelatedField: allow id instead of url for POSTS requests
I would like to allow a HyperLinkRelatedField to accept just an id instead of requiring a hyperlink to create a new instance of an object, but for get requests I would like to return the hyperlink not just an id but it appears to be either one or the other. Is this possible? class Blog(serializers.HyperlinkedModelSerializer): class Meta: model = Blog fields = ('url', 'id') class Comment(serializers.HyperlinkedModelSerializer): blog = serializers.HyperlinkedRelatedField(view_name='blog-detail', queryset=Blog.objects.all()) class Meta: model = Comment fields = ('url', 'text', 'blog') GET Request for Comment returns (This is perfect): {'url': 'mysite.fake/comments/1', 'text': 'test text', 'blog': 'mysite.fake/blog/1'} POST Request requires: {'text': 'test text', 'blog': 'mysite.fake/blog/1'} I want to also be able to pass: {'text': 'test text', 'blog': '1'} -
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