Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django utf-8 metatag not extending to inheriting templates
I have template inheritance set up with utf-8 metatag: layout.html would work fine with ä in it. <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>{{ title }}</title> {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'app/css/theme-default.css' %}" /> </head> <body> ääää {% block content %}{% endblock %} </body> I can use unicode charset in the layout.html with no problems. ä ü õ etc. But not in the inheriting templates. events.html like this would give a error: {% extends "app/layout.html" %} {% block content %} ä {% endblock %} UnicodeDecodeError at /events.html 'utf-8' codec can't decode byte 0xe4 in position 54: invalid continuation byte -
django removes image on update save
I have the following clean method by which I reduce an image if it is too large: class CompanyForm(forms.ModelForm): class Meta: model = Company exclude = ('limited') def clean_image(self): image_field = self.cleaned_data.get('image') if image_field: reduced_image = reduce_image(image_field, 550) return reduced_image else: raise forms.ValidationError('You must upload a square logo image') return image_field My reduce image looks like the following: def reduce_image(image_field, height_max): if image_field: try: image_file2 = BytesIO(image_field.read()) image = Image.open(image_file2).convert('RGB') print(image) except: #raise ValidationError('There was a problem with the image, please try another.') print('returning from image errror') return image_field w, h = image.size print('image width:'+str(w)) print('image height:'+str(h)) if h > height_max: print('height toolarge') ratio = h/float(w) new_height = ratio * height_max image = image.resize((int(height_max), int(new_height)), Image.ANTIALIAS) image_file = BytesIO() image.save(image_file, 'JPEG', quality=90) image_field.file = image_file print(image_file) return image_field The first time I save, it saves no problem. When I save a second time to update the model, it removes the image. Why might this be happening? -
Django aggregate avg price by product category
I have this view: def MainStatsView(request): leads = Leads.objects.all() university = University.objects.all() price = Leads.objects.aggregate(Avg('price')) context = { 'leads':leads, 'university':university, 'price':price, } return render(request,'stats/stats_main.html',context) I am trying to get the average price of properties (the product) that generated leads at each university (the category). I am having trouble finding the avg price based on university. I tried using a for loop but that doesn't seem to do the trick. Also here is my loop: {% for uni in university %} <tr> <td>{{ uni.u_name }}</td> <td>{{ price }}</td> <td>{{ lead.school }}</td> <td>{{ lead.featured }}</td> <td>{{ lead.price }}</td> </tr> {% endfor %} I'm a little all over the place here so that is why it looks overly messy. Here is an image of the result. It's giving me the avg on the price of all properties that have generated leads rather than for one school specifically (which is what I want). -
Static folder is not working on Django
I'm beginning at Django and I don't know why but it seems like Django can't find my static folder. Here's how I did it : # IN MY SETTINGS FILE STATIC_URL = '/static/' # IN MY APP "accounts", IN base.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'accounts/basic.css' %}"> # (MAIN FOLDER) -> (accounts (APP)) -> (static) -> (accounts) -> basic.css I tried to put some red color on my h2 but it's not working, and I see no mistakes. Sorry if this is a dupe but it seems like it has no mistakes for me and I'm lost.. Thanks ! -
python, django code doesn't work in html
This is my html file code part product.html <aside> <div id="news"> <h2 class="heading">News</h2> <div style="clear: both"><br></div> {% for articles in news_articles %} <div id="articles"> <div class="article"> <a href="{{ articles.article.get_absolute_url }}"> <img src="{{ articles.image }}"> <div style="clear: both"></div> <span></span><div style="clear: both"></div> </a> <em>{{ articles.article.created }}</em> <div style="clear: both"><br></div> </div> {% endfor %} </div> <a href="" title="View More Articles"> <div id="btn"> <span>View More</span> </div> </a> </div> </aside> This is my views.py file code part views.py def product(request, product_id): product_images = ProductImage.objects.filter(is_active=True, is_main=False, product=product_id) product = Product.objects.get(id=product_id) links = ProductDownload.objects.filter(is_active=True, product=product_id) return render(request, 'products/product.html', locals()) def new(request, product_id): news_articles = NewsImage.objects.filter(is_active=True, is_main=True) article = Article.objects.get(id=product_id) return render(request, 'news/article.html', locals()) This is my models.py file code part models.py class Product(models.Model): name = models.CharField(max_length=128, blank=True, null=True, default=None) description = models.TextField(default=None) processor = models.CharField(max_length=300, blank=True, null=True, default=None) video = models.CharField(max_length=300, blank=True, null=True, default=None) ram = models.CharField(max_length=300, blank=True, null=True, default=None) disk_space = models.CharField(max_length=300, blank=True, null=True, default=None) oS = models.CharField(max_length=300, blank=True, null=True, default=None) video_trailer = models.CharField(max_length=10000, blank=True, null=True, default=None) img = models.CharField(max_length=10000, blank=True, null=True, default=None) category = models.ManyToManyField(ProductCategory, blank=True, default=None) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField(primary_key=True, max_length=250, unique=True, default=None) def __str__(self): return '%s' % self.name def get_absolute_url(self): return reverse('product', args=[str(self.slug)]) class ProductImage(models.Model): product = models.ForeignKey(Product, … -
Getting a url to read the HTML output from a .fcgi file and not the contents of the .fcgi file (shared server using fastcgi)
My question is how do I get a browser to read the HTML output from a .fcgi file and not the contents of the .fcgi file. I am using a shared server, linux, Django 2.0, Python 3.6.4, flup6. Because fastcgi is deprecated post Django 1.8 and Bluehost doesn't use WSGI and only FastCGI (mod_fastcgi) I am using what NetAngels made available: https://github.com/NetAngels/django-fastcgi My .htaccess file is the project folder with my .fcgi file as is commonly recommended. My .htaccess reads: AddHandler fastcgi-script.fcgi RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)% app.fcgi/$1 [QSA, L] My .fcgi file reads: #!/homeX/user/python3.6/bin/python36 import sys, os project_name = "app" sys.path.insert(0, "homeX/user/python3.6/bin/python36") sys.path.append("directory/of/my/project/app") sys.path.append("directory/of/my/project/app/app") sys.path.append("directory/of/my/project/app/app/app") sys.path.append("directory/of/site-packages") sys.path.append("directory/of/site-packages/flup") sys.path.append("directory/of/site-packages/django") os.chdir("directory/of/my/project/app/app/app") os.environ['DJANGO_SETTINGS_MODULE'] = "settings" from django_fastcgi.servers.fastcgi import runfastcgi from django.core.servers.basehttp import get_internal_wsgi_application wsgi_application = get_internal_wsgi_application() runfastcgi(wsgi_application, method="prefork", daemonize="false", minspare=1, maxspare=1), maxchildren=1) I have made sure to: chmod 0755 app.fcgi I am able to type into the linux SSH: app.fcgi This is what comes up in the SSH terminal: WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI! WSGIServer: missing FastCGI param SERVER_NAME required by WSGI! WSGIServer: missing FastCGI param SERVER_PORT required by WSGI! WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI! Not Found: / Status: 404 Not Found Content-Type: text/html … -
django-taggit - display existing tags on the django-admin add record page
I have created a test vlog application using django/python and django-taggit. The vlog and tags are working as they should. However, I want to list all the existing tags in the django-admin interface for new and updated vlog entries - similar to displaying the tags as a filter on the django-admin list page. This will make the selection of new or existing tags for each new or updating vlog entry that much easier. Here is what I mean by adding the tags as help-text on the tags input field: My models.py code: class VlogDetails(models.Model): .... vlog_video_image_url = models.URLField(null=False, blank=False, max_length=250, unique=True, help_text='http://img.youtube.com/vi/You_Tube_URL/0.jpg') .... tags = TaggableManager(help_text='List all the available tags here.') Here is the django-admin input form interface: Is it possible to display the existing tags in another manner on the new / edit django-admin page? I have already listed the existing / existing tags on the django-admin list page as a filter as shown below. This filter display does not display on the new / update input forms. django-admin filter code: class VlogDetailsAdmin(BaseDetailsAdmin): .... list_filter = [ 'vlog_date_published', 'tags', 'vlog_timestamp_added', 'vlog_timestamp_updated' ] I have tried several things but none work and I cannot find any related ideas in the … -
Detecting if my page is being loaded in an iFrame in a Django view
How can I detect in a view function that the page is being loaded in an iFrame? I want to change the page slightly if that is the case. Is there any way to do this? Note, Im not looking for click jacking protection. I want to make changes to my view if the page is being loaded in an iframe. -
Django ORM - How to perform complex GROUP BY with values().annotate().values()
I'm trying to convert as much raw SQL to use the Django ORM as I can, and I've run into a snag. I'm trying to perform a query similar to this one: SELECT table.x, MAX(table.y) AS y, table.group_category, table.group_number, FROM table GROUP BY table.group_category, table.group_number So far, what I've been trying has been some permutation of this: q = MyModel.objects\ .filter(**filter_kwargs)\ .values('group_category', 'group_number')\ .annotate(y=Max('y'))\ .values('x','y','group_category','group_number') However, this doesn't seem to work. If I exclude the last values(), it produces the following (roughly): SELECT MAX(table.y) AS y, table.group_category, table.group_number, FROM table GROUP BY table.group_category, table.group_number It doesn't select table.x. But if I include the last values()... SELECT table.x, MAX(table.y) AS y, table.group_category, table.group_number, FROM table GROUP BY x, y, table.group_category, table.group_number It groups by x, y. So what clearly seems to be happening is that the all of the values are replaced and annotate uses whatever values the QuerySet is given (because it's evaluated lazily?). The docs on aggregation and values seem to suggest that doing the two values functions in this order would have the desired effect, and I found a writeup (from 2013) that also suggests this. Am I doing something wrong? Is this still possible in the Django … -
Django conn= connet(dsn, connetion_factory, async=async) django.db.utils.OperationalError psycopg2
I am working on the connection of postgresql 9.5 and Django 1.11 in wimdows 7, but it throws me an error install python 3.4.2, add path install postgresql 9.5.10, add path install virtualenv version 15.1.0 create virtualenv myenv run Scripts\myenv\activate install psycopg2-2.6.2.win32-py3.4-pg9.5.3-release.exe, add folder psycopg2 in C:\proyectos\myenv\Lib\site-packages install Django 1.11 create project Django => django-admin.py startproject redsocial in the folder redsocial => django-admin.py startapp goodpeople in Sublime text3 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'goodpeople', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'goodpeople', 'USER': 'postgresql', 'PASSWORD': 'postgresl', 'HOST': 'localhost', 'PORT': '5432', } } #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "redsocial.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) python manage.py migrate, python manage.py test, python manage.py runserver enter image description here enter image description here enter … -
What is the correct way to catch model object deleted time in django?
signal CODE : @receiver(post_save, sender=TestModel) def update_log(sender, instance, **kwargs): TestModelLog.objects.create(description=instance.description, datetime=instance.updated) @receiver(post_delete, sender=TestModel) def delete_log(sender, instance, **kwargs): TestModelLog.objects.create(description=instance.description, datetime=now()) model CODE: class TestModel(models.Model): description = models.CharField(max_length=34) updated = models.DateTimeField(auto_now=True) I made signal code like above one and which is to catch log of TestModel. As you can see, I can get update time using instance as datetime=instance.updated. And it is correctly the same as TestModel's updated time. When I want to get deleted time, datetime=instance.updated is not working. So I tried to catch deleted time using datetime=now(). But I'm curious about that there is other good way except datetime=now(). Would you let me know other good way of catching object's deleted time? -
Persisted data with Django and Algolia search model indexing
This is a curious one for Django+Algolia. I'm using the Algolia specific Django package: $ pip install algoliasearch-django I have the following model schema: import os import datetime from channels import Group from django.db import models from django.conf import settings from django.utils.six import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.core.files.storage import FileSystemStorage from django.contrib.humanize.templatetags.humanize import naturaltime BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SITE_UPLOAD_LOC = FileSystemStorage(location=os.path.join(BASE_DIR, 'uploads/site')) USER_UPLOAD_LOC = FileSystemStorage(location=os.path.join(BASE_DIR, 'uploads/user')) @python_2_unicode_compatible class Room(models.Model): """ This model class sets up the room that people can chat within - much like a forum topic. """ title = models.CharField(max_length=255) staff = models.BooleanField(default=False) slug = models.SlugField(max_length=250, default='') banner = models.ImageField(storage=USER_UPLOAD_LOC, null=True, blank=True) def last_activity(self): """ For date and time values show how many seconds, minutes, or hours ago a message was sent (i.e., persised to the database) compared to current timestamp return representing string. """ last_persisted_message = Messages.objects.filter(where=self.slug).order_by('-sent_at').first() if last_persisted_message is not None: # First we can store "last persisted message" time in ISO format (could be useful for sitemap.xml generation; SEO tasks etc) last_persisted_message_iso = last_persisted_message.sent_at.isoformat() # Use the natural time package form contrib.humanize to convert our datetime to a string. last_persisted_message = naturaltime(last_persisted_message.sent_at) return last_persisted_message else: return "No activity to report" Which is … -
Autofill database column after form submission in django
Using Django 2.0 I have a model class named Book that asks for title, author, year but I have another column in that row that requires for a unique id based on the authors name, book title, and random numbers. This is my model class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=50) year = models.PositiveSmallIntegerField() identification = models.CharField(max_length=50, blank=True) holder = models.ForeignKey('Person', related_name='book_holder', on_delete=models.PROTECT(), null=True, blank=True) available = models.BooleanField(default=True, blank=True) overdue = models.BooleanField(default=False, blank=True) and it will be used in a form that only asks for the title, author, and year but what im looking for is how can i fill the identification column after the user submits the form. So for example if the user enters Harry Potter for the title and J. K. Rowling for the author, I want identification to have a value of a combination of both plus an eight digit random number at the end something like JH28194637 but I also need this column to be unique for every book so if i had to of the same Harry Potter books, I would need both to be different so one could be JH28194637 while the other one could be JH39287104. I will be using ajax … -
Django admin shows dates in UTC time zone instead of TIME_ZONE
I run django 11 with the following timezone settings: USE_I18N = True USE_L10N = True USE_TZ = True TIME_ZONE = 'Europe/Kiev' The admin app shows all the dates using UTC timezone and doesn't use TIME_ZONE settings. What should I do to show the dates in admin using the settings.TIME_ZONE instead of UTC? -
Conditional validation depending on POST parameter Django
I have a form that I am trying to have some "conditional" validation on, depending on the button the user clicks. The fields should all be required if the user clicks "Submit", and none should be required if the user clicks "Draft". My models specify that no fields are required, to accomdate the draft. Then I tried to override it to require the validation only when a certain button is clicked, but I can't figure out for the life of me how to do it. I've simplified the code below. The form: class MOCForm(forms.ModelForm): facility = forms.CharField(required=False) def fields_required(self, fields): """Used for conditionally marking fields as required.""" for field in fields: if not self.cleaned_data.get(field, ''): msg = forms.ValidationError(" This field is required.") self.add_error(field, msg) def clean(self): self.fields_required(['facility']) return self.cleaned_data The view method: def post(self, request): if request.POST.get('_start') == '' or request.POST.get('_draft') == '': MOC_form = forms.MOCForm(request.POST, prefix="MOC_form", instance=MOC) if request.POST.get('_draft') == '' or MOC_form.is_valid(): MOC_form.save() if request.POST.get('_start') == '': MOC.submitted_date = timezone.now() if request.POST.get('_draft') == '': MOC.status = C.moc_status_draft() if request.POST.get('_start') == '' or request.POST.get('_draft') == '': MOC.creator = request.user MOC.save() if request.POST.get('_start') == '' or request.POST.get('_draft') == '': # If there is an activation (i.e. it is part of … -
django getting error about views.py
This is my views.py from django.shortcuts import render from . models import Houses def houses_list(request): house = Houses.objects.all().order_by('owner') return render('Houses.html',{'houses':house}) this my models.py from django.db import models class Houses(models.Model): owner = models.CharField(max_length=250) house_name = models.CharField(max_length=500) country = models.CharField(max_length=500) genre = models.CharField(max_length=100) def __str__(self): return self.house_name class house(models.Model): houses = models.ForeignKey(Houses, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) house_title = models.CharField(max_length=250) this my url.py from django.urls import path from . import views urlpatterns= [ path('', views.Houses, name='Houses'), ] this my html file {% load static %} <html> <head> <meta charset = "utf-8"> <title>Houses</title> </head> <body> <h1>House list</h1> <div class="house"> {% for house in houses %} <div class="house"> <h2><a href="#">{{Houses.house_name}}</a></h2> <p>{{Houses.owner}}</p> <p>{{Houses.genre}}</p> </div> {% endfor %} </div> </body> </html> I'm tring to get the data from my database but on the web getting attribute no object error.But I can see the all objects on the admin page do you have any idea what I'm doing wrong? -
Django Rest Framework - Authentication credentials were not provided when using renderer
I have a small company web service written in DRF. It uses basic authentication so I have this in my settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication' ), 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), } When I browse any pages there is a basic popup window provided by default that asks for username/password. It suits my needs as I don't have to deal with login forms ans so on and I only need very basic authentication anyway. It all worked great until I started creating my renderer: class MyRenderer(BaseRenderer): def render(self, data, media_type=None, renderer_context=None): logging.debug(data) return data At this point it prints in logs: {u'detail': u'Authentication credentials were not provided.'} If I browse any other page with a web browser it just asks for a username/password in popup window and remembers it for some time. So after authorising on another page if I come back to my page with renderer and it works. Why it doesn't behave like other pages? How can I make to ask for username/password like all the other pages? -
Django with AJAX - security concern
Sorry for not providing any code, but this is purely theoretical, so picture, for example, an application that sends Like/Dislike asynchronous requests with AJAX in Django. I got to a point with Django, where I can send requests containing cookies (sessionid, and csrftoken). My ajax functions aren't form based - they send a request without a form. I logged the requests I'm sending with chrome, copied the entire request body, and put it into Restlet Client to send them again. What I found is that when I change the sessionid, the request is completely broken for obvious reasons. I can change the csrf token all I want and it produces no complications. What that means is that csrf token is unused. How do I validate that token in a view (without a form), or should I not worry about it? By the way, is sessionid all that is required to make any requests on someone's behalf without knowing their passsword? Logging out doesn't kill the session and sessions have a long lifetime (default 2 weeks). -
missing 1 required positional argument 'request'
I would like to know why I have it wrong that is what I lack def user(request): User = User.objects.filter(empresa_area_id=request.user.empresa_area_id) return HttpResponse(User) -
Django crashign when using validator on model field
Why is django crashing (without error) when setting validators=[...] on my Image and File fields in my model? When I uncomment my import / validators settings everything works fine. It seems the validator is being hit and even setting the attributes on __init__ but then it just crashes after initializing all of the validators. My validator is: import magic from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from django.utils.translation import ugettext_lazy as _ @deconstructible class MimeTypeValidator(object): def __init__(self, valid_mime_types): self.valid_mime_types = valid_mime_types def __call__(self, value): try: mime_type = magic.from_buffer(value.read(1024), mime=True) if not mime_type in self.valid_mime_types: raise ValidationError(_('%s is not an acceptable file type.' % value)) except AttributeError as e: raise ValidationError(_('This file type of %s could not be validated.' % value)) I'm setting it on my fields by doing: field = models.ImageField(....., validators=[MimeTypeValidator(settings.VALID_IMAGE_MIME_TYPES)] and similarly for file fields. -
Django Rest Framework Example
I am having problems with the example in the documentation. When I try going to the default route "/", I keep getting a 404. The way the documentation example reads, I should be able to get a User list? Here is the urls.py code: from django.contrib import admin from django.conf.urls import url, include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('username', 'email', 'is_staff') # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'users', UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] I have the rest_framework added to my application, too. I can see the various User related routes when I look at the router object via the manage.py shell, but I keep getting the 404. I am implementing this in an existing new project, but I have yet to actually put anything in the project so I don't think the issue … -
Running django-pdb in post mortem mode for a test command
I'm trying to run a test suite using python manage.py test, but I run into an error which ends like this: return self.cursor.execute(sql) django.db.utils.ProgrammingError: type "hstore" does not exist LINE 1: ..., "options" varchar(255)[] NOT NULL, "conditions" hstore NOT... I'd like to drop into the debugger at this point in order to see the full sql statement. To this end, I've run pip install django-pdb and added the following lines to my settings.py (as per the instructions): # Order is important and depends on your Django version. # With Django 1.7+ put it towards the beginning, otherwise towards the end. INSTALLED_APPS = ( ... 'django_pdb', ... ) # Make sure to add PdbMiddleware after all other middleware. # PdbMiddleware only activates when settings.DEBUG is True. MIDDLEWARE_CLASSES = ( ... 'django_pdb.middleware.PdbMiddleware', ) Then I try to re-run the test with the --pm option: python manage.py test lucy_web.tests.notifications --pm However, this is not recognized: manage.py test: error: unrecognized arguments: --pm I've also tried to run this command with --ipdb instead of --pm, but it seems to not work: I simply get an error message without dropping into the debugger. Any ideas what the issue might be? Is post mortem debugging perhaps not … -
Django displaying blog posts on different pages
I'm rather new to Django and I've been following a tutorial on building a simple blog application. My application works fine so far (using Django 1.8.6). Here are my urls.py, views.py and models.py: urls.py urlpatterns = [ url('admin/', admin.site.urls), url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), blog/urls.py urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\ r'(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), url(r'^tag/(?P<tag_slug>[-\w]+)/$', views.post_list, name='post_list_by_tag'), ] blog/views.py def post_list(request, tag_slug=None): object_list = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) return render(request, 'blog/post/list.html', { 'posts': posts, 'tag': tag }) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids)\ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags'))\ .order_by('-same_tags','-publish')[:4] return render(request, 'blog/post/detail.html', {'post': post, 'similar_posts': similar_posts}) blog/models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. Now I would like to create 4 … -
How to make my JSON work with a Gijgo grid in Django/Python?
I tried the code below to be able to show my database records in a Gijgo grid. Unfortunately it doesn't work, because Gijgo by default expects JSON data without keys. As far as I know there are two options to solve this problem: Get rid of the keys (model, pk, fields) in JSON, which is accepted by Gijgo Configure Gijgo to understand my JSON structure (couldn't find any information about this approach) Any idea how I can solve this problem? Code demand = Demand.objects.filter(week__number=request.GET["weeknumber"], week__year=request.GET["weekyear"]) response = serializers.serialize("json", demand) return HttpResponse(response, content_type='application/json') [{"model": "demand", "pk": 4, "fields": {"week": 3, "model": 1, "product": 3, "type": 7, "build": 1, "sdna": 1234, "rcna": 234234, "sdeu": 3333, "rceu": 433, "ssd": 53, "src": 63, "notes": "fafd"}}] -
Difference Between Reset Done and reset Complete in Django 2.0 Authentication Views
I'm looking at implementing user authentication to a Django project. I'm reading through the documentation. It mostly seems straightforward, but there's one thing that I don't understand. Apparently the authentication includes eight views: accounts/login/ [name='login'] accounts/logout/ [name='logout'] accounts/password_change/ [name='password_change'] accounts/password_change/done/ [name='password_change_done'] accounts/password_reset/ [name='password_reset'] accounts/password_reset/done/ [name='password_reset_done'] accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm'] accounts/reset/done/ [name='password_reset_complete'] When implementing a password reset I assume that what I want to do implement accounts/password_reset/, which forwards the user an email. Then, I need to implement accounts/reset/<uidb64>/<token>/, which is where the user is directed to via the email. What I'm not clear on is what that should do when the user has updated their password successfully. What's the difference between accounts/reset/done/ (or password_resest_complete) and accounts/password_reset/done/ (or password_reset_done)?