Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Catch adding Django admin inline from js
I want to catch moment of adding new inline element and do some manipulation, but can't find any jquery way for this. But in admin page source I'm find this code: (function($) { $(document).ready(function() { $('.add-another').click(function(e) { e.preventDefault(); var event = $.Event('django:add-another-related'); $(this).trigger(event); if (!event.isDefaultPrevented()) { showAddAnotherPopup(this); } }); }); })(django.jQuery); How I understand it custom jquery event, but I'm can't understand how catch them. -
How to run a local python script from django project hosted on aws?
I have a requirement to run a local python script which takes arguements and will run on local windows computer from python code hosted on aws. -
Failed: WebSocket is closed before the connection is established
I'm using django channels and recently encountered this error while connecting to the WebSocket: "Failed: WebSocket is closed before the connection is established". This error resulted from updating some packages as follow: channels (0.17.3) -> channels (1.0.3) daphne (0.15.0) -> daphne (1.0.2) My other related packages are: django(1.10.4) asgiref (1.0.0) asgi-redis (1.0.0) django-redis (4.6.0) redis (2.10.5) Twisted (16.6.0) When I use runserver I only see: "WebSocket HANDSHAKING" "WebSocket DISCONNECT" -
DRF and django-mptt pagination
I'm using django-mptt 0.8.7, Python 3.5, Django 1.10.5, and Django Rest Framework 3.5.3. class CommentViewMixin(object): def get_queryset(self): id_related_object = self.kwargs.get(self.qs_related_object_pk) try: return self.model.objects.select_related('user').filter(**{self.related_object_field: id_related_object}) except (self.model.DoesNotExist, ValueError): raise exceptions.NotFound() def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) # cached using MPTT get_cached_trees if page is not None: serializer = self.get_serializer(get_cached_trees(page), many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(get_cached_trees(queryset), many=True) return Response(serializer.data) def retrieve(self, request, *args, **kwargs): raise exceptions.MethodNotAllowed() Using get_cached_trees I cache the comments and it works great, I have always 3 queries instead of 50 or more*, but when I apply the pagination I clearly have: serializer = self.get_serializer(get_cached_trees(page), many=True) _('Node %s not in depth-first order') % (type(queryset),) ValueError: Node <class 'list'> not in depth-first order Because the DRF pagination I suppose cut the get_cached_trees list dividing root and elements. A solution could be to override the DRF pagination and returns always an entire node+children, but how? Thanks, D -
Delete action not working in Django rest framework tutorial 7 schemas and client libraries
I followed the Django rest framework tutorial. I got an error on tutorial 7 while trying to delete the snippets through command line. I installed coreapi and command line client. But while I'm trying to delete a snippet using the command $ coreapi action snippets delete --param id=7 I got the given below error <Error: Forbidden> detail: "You do not have permission to perform this action." And also corejson representation is not available as an option in GET request while visiting the API root endpoint in a browser. How can I solve these problems? -
Django Models Multifile causes django.contrib errors
It's my first question on stackoverflow (but not my first visit! hahaha). I'm actually working on Django project and I issue a problem with django.contrib import with multifile models. My environnement is Python 2.7 Virtual Env with Django 1.10.5 Here is the stacktrace Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/vbrice/Projects/Pro/labs/Puffin/app/__init__.py", line 1, in <module> import views File "/Users/vbrice/Projects/Pro/labs/Puffin/app/views/__init__.py", line 3, in <module> from login import login_view File "/Users/vbrice/Projects/Pro/labs/Puffin/app/views/login.py", line 4, in <module> import models File "/Users/vbrice/Projects/Pro/labs/Puffin/models/__init__.py", line 1, in <module> from .category import Category File "/Users/vbrice/Projects/Pro/labs/Puffin/models/category.py", line 3, in <module> from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation File "/usr/local/lib/python2.7/site-packages/django/contrib/contenttypes/fields.py", line 5, in <module> from django.contrib.contenttypes.models import ContentType File "/usr/local/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 138, in <module> class ContentType(models.Model): File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 105, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I can't … -
create desktop app (in windows 7 by .EXE format) by django (and python 3.4)
I am tring to create windows app by Django and find this: link But it's not usefull for me. is there any way to create desktop (windows .exe formatted) app by Django? -
Django serializer not returning all fields
My serializer is not returning all fields from the model. Just the nested serializer. serializer.py class IndicatorSerializer(serializers.ModelSerializer): class Meta: model = Indicator class QuoteSerializer(serializers.ModelSerializer): class Meta: model = Quote class VWAPSerializer(serializers.ModelSerializer): vwap = serializers.SerializerMethodField() class Meta: model = Quote fields = ('vwap',) def get_vwap(self, obj): indicators = Indicator.objects.filter(quote__in = obj) return IndicatorSerializer(indicators,many=True).data views.py def get_vwap(request): """ List all vwap for a date """ quotes = Quote.objects.filter(date__gt = '2016-05-05') serializer = VWAPSerializer(quotes) return Response(serializer.data) models.py class Quote(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now_add=True) symbol = models.ForeignKey(Symbol, on_delete=models.CASCADE) date = models.DateField(blank=True, null=True) open = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) high = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) low = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) close = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) last = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) prevclose = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) tottrdqty = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) tottrdval = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) total_trades = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) class Meta: index_together = [ ["symbol", "date"], ] class Indicator(models.Model): quote = models.ForeignKey(Quote, on_delete=models.CASCADE) indicator = models.ForeignKey(IndicatorDefinition, on_delete=models.CASCADE, db_index=True) value = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) class Meta: unique_together = ('quote', 'indicator') Response "vwap": [ { "id": 311743, "value": "1188.98", "quote": 77437, "indicator": 1 }, { "id": 311742, "value": "1185.52", "quote": 77437, "indicator": 2 }, What im … -
Django/bootstrap form : how to set and get btn-group value
I'm beginner and use Python/Django/bootstrap. I googled and didn't find really the full answer to my question (code example) ;-) On a form, I would like to use 3 buttons grouped to display and select the status of an alarm system which can be : Armed/Home/unarmed I use the below HTML code: `<div class="btn-group btn-group-lg"> <button class="btn btn-default" type="button"> <em class="glyphicon glyphicon-lock"></em> Armed </button> <button class="btn btn-default" type="button"> <em class="glyphicon glyphicon-lamp"></em> Home </button> <button class="btn btn-default" type="button"> <em class="glyphicon glyphicon-home"></em> Unarm </button> </div>` The question is how to: 1) highlight on of the 3 button to show the alarm status when entering the form 2) get the button status (armed/home/unarmed) modofied by the user when leaving the form Would it be possible you provide me the HTML code updated and the code of the urls.py and views.py to be added Thanks a lot for your help MMGG -
manage.py runserver returns immediately
I have an existing django project which was working fine until I added a new app & models which makemigrations wouldn't detect. As a newbie, I assumed the problem was that I'd missed a step somewhere. So I decided to go back and do do the tutorial again to refresh my memory. And now, I can't even get runserver to run properly python manage.py runserver just returns immediately with no output. And this is on a project that consists only of the code django-admin startproject has generated. I am at a loss how to work out where things are going wrong. I have had to reinstall my computer and am running python 3.6 and django 1.10.4, so maybe there's some system config issues somewhere. This is a windows 7 environment running git bash and virtualenv, if that's relevant. Any advice on how to proceed? -
Unable to get correct FileField.url from django ModelForm instance when saving without committing
I have a model, and a model form by which to save instances: class Cat(models.Model): image = models.ImageField(upload_to="the_image_directory") css_file = models.FileField(upload_to="the_image_directory") class CatForm(forms.ModelForm): image = forms.FileField( label=_("Cat image"), widget=forms.FileInput() ) class Meta: model = Cat exclude = ('css_file',) The css file template contains styling for the cat image: background-image: url("{{ cat.image.url }}"), which is obviously replaced with the image url when run through the context processor. In pseudocode (for brevity): cat = form.save(commit=False) cat.css_file = render_to_file("base.css", {"cat": cat}) cat.save() My problem is that I need to get a Cat instance's image in order to create its css_file, but the cat.image.url parameter is incorrect when I call form.save(commit=False). Instead of cat.image.url being /media/the_image_directory/some_cat.jpg, it is /media/some_cat.jpg. The upload_to seems not to be recognised until I actually call .save(commit=True). Is there a way around this, or do I have to commit twice to accomplish what I'm trying to do? -
A method in python not working which is imported from other py file
I have a python class which has to use a function in another python file. I imported the class and there in no import error but it gives an error about attribute not present My files re combact.py and monster.py. I have imported combat. This is combact.py import random class Combat(): dodge_limit = 6 attack_limit = 6 def dodge(self): roll = random.randint(1,self.dodge_limit) return roll > 4 def attack(self): roll = random.randint(1,self.attack_limit) return roll > 4 This is monster.py import random from combact import Combat COLOR = ['blue', 'red', 'green', 'yellow'] class Monsters(Combat): max_hitpoints = 1 min_hitpoints = 1 max_experience = 1 min_experience = 1 weapon='sword' sound = 'roar' def __init__(self, **kwargs): self.hit_points = random.randint(self.min_hitpoints,self.max_hitpoints) self.color = random.choice(COLOR) self.experience = random.randint(self.min_experience,self.max_experience) for key,value in kwargs.items(): setattr(self,key,value) def __str__(self): return '{} {} HP: {} XP: {}'.format(self.color.title(),self.__class__.__name__,self.hit_points,self.experience) def battlecry(self): return self.sound.upper() class Goblin(Monsters): max_experience=2 min_hitpoints = 2 max_hitpoints = 3 sound = 'Squek' class Troll(Monsters): max_experience = 5 min_experience = 2 max_hitpoints = 8 min_hitpoints = 5 sound = 'Wiggling' class Dragon(Monsters): max_hitpoints = 10 min_hitpoints = 7 max_experience = 10 min_experience = 8 weapon = 'fire' sound = 'raaaaaaar' When I run monsters.py Output is: This is another file character.py with same … -
django : OneToOne field links to id and not to email
How to change the linking of OneToOne Field See the bottom for my problems Output in terminal : In [21]: profile = User.objects.get(email='jlennon@beatles.com') In [22]: profile Out[22]: <User: jlennon@beatles.com> In [23]: profile = User.objects.get(email='jlennon@beatles.com').profile In [24]: profile Out[24]: <Users: Aniket> In [25]: profile = User.objects.get(id=2).profile In [26]: profile Out[26]: <Users: Aniket> In [27]: User.objects.get(id=2) Out[27]: <User: jlennon@beatles.com> In [28]: User.objects.get(id=4) Out[28]: <User: AniketYadav> models.py : class Users(models.Model): user = models.OneToOneField(User, related_name='profile') user_Id = models.BigAutoField(primary_key=True) user_name = models.CharField(max_length=25) user_fname = models.CharField(max_length=40, blank=True, null=True) user_lname = models.CharField(max_length=40, blank=True, null=True) user_email = models.CharField(max_length=60) user_password = models.CharField(max_length=255) joining_date = models.DateTimeField() user_dob = models.DateField() user_country = models.CharField(max_length=3, blank=True, null=True) user_gender = models.CharField(max_length=1) user_pic = models.CharField(max_length=255, blank=True, null=True) user_about = models.CharField(max_length=512, blank=True, null=True) class Meta: verbose_name = 'Users' verbose_name_plural = 'Users' managed = False db_table = 'tbl_users' def __unicode__(self): return self.user_name def __str__(self): return self.user_name settings.py AUTH_PROFILE_MODULE = 'myWebsite.Users' my database : mysql> select id, username, email from auth_user where id=1 or id=2 or id=4; +----+---------------------+---------------------+ | id | username | email | +----+---------------------+---------------------+ | 1 | admin | admin@admin.com | | 2 | jlennon@beatles.com | jlennon@beatles.com | | 4 | AniketYadav | aniket@gmail.com | +----+---------------------+---------------------+ 3 rows in set (0.00 sec) My Users table (tbl_users): … -
How to use webrtc for recognation in Django with Opencv?
Is it possible to make a streaming camera with facedetection on the client (with use Django as axample) as it is possible to do in a usual Python+OpenCV? -
render page is wrong
When I accessed upload_save method,basic.html was showed. I wrote in view.py like def upload_save(request): photo_id = request.POST.get("p_id", "") if (photo_id): photo_obj = Post.objects.get(id=photo_id) else: photo_obj = Post() files = request.FILES.getlist("files[]") photo_obj.image = files[0] photo_obj.save() return render(request,"registration/accounts/photo.html") So,I naturally thought when I accessed upload_save method,photo.html would be showed. In photo.html,I wrote {% extends "registration/accounts/base.html" %} {% block body %} <div class="container"> {% for photo in photos %} <h2 class="page-header">{{ photo.title }}</h2> <div class="row"> <div class="col-xs-4"> <img class="img-responsive" src="/media/{{ photo.image1 }}"> </div> <div class="col-xs-4"> <img class="img-responsive" src="/media/{{ photo.image2 }}"> </div> <div class="col-xs-4"> <img class="img-responsive" src="/media/{{ photo.image3 }}"> </div> </div> <a class="btn btn-primary" href="{% url 'accounts:upload' photo.id %}">UPLOAD</a> {% endfor %} </div> {% endblock %} I wrote base.html in photo.html ,but I cannot understand why photo.html's content is not show.How can I fix this? -
Django-OpenCV: img is None in views and I cannot save modified img
Img is None and cv2.imwrite doesn't work. How to correct this? Also PyCharm writes "Cannot find reference 'imread' in init.py" and "Cannot find reference 'imwrite' in init.py". from django.shortcuts import render import os import numpy as np import cv2 from django.contrib.staticfiles.templatetags.staticfiles import static from django.utils import timezone from .models import Post def post_list(request): img = cv2.imread(static('blog' + os.sep + 'misdyxcgAo4.jpg'), 0) print static('blog' + os.sep + 'misdyxcgAo4.jpg') print img cv2.imwrite(static('blog' + os.sep + 'messigray.png', img)) posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) -
Scrapy + django-item + postgresql (sqlalchemy), how mapping items?
I use this stack, and have problem sqlalchemy.orm.exc.UnmappedInstanceError: Class news_scrap.items.NewsItem' is not mapped. I do not really know how to relate sqlalchemy with Django-item. I understand problem, but do not know how to deal with it. I can not do it, Without your help. Items.py from scrapy_djangoitem import DjangoItem from main.models import News class NewsItem(DjangoItem): django_model = News __tablename__ = "main_news" Models.py from sqlalchemy import * from sqlalchemy.engine.url import URL from . import settings def db_connect(): """ Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance """ return create_engine(URL(**settings.DATABASE)) Pipelines.py from sqlalchemy.orm import sessionmaker from .items import NewsItem from .models import db_connect class NewsScrapPipeline(object): def __init__(self): """ Initializes database connection and sessionmaker. Creates deals table. """ #log.INFO('First Point') engine = db_connect() self.Session = sessionmaker(bind=engine) def process_item(self, item, spider): session = self.Session() news = NewsItem(**item) #log.INFO('This Point') try: session.add(news) session.commit() except: session.rollback() raise finally: session.close() return item If you need other parts of the code, please tell me. -
Why am i getting '500 (Internal Server Error jQuery.min.js:4) ' error in the following ajax code?
I am trying to login the user by opening the bootstrap login modal and filling it with username and password but the movement i hit 'Login' button i get the following error message in the browser's console: ajax: $('#loginForm').on('submit',function(e){ e.preventDefault(); $.ajax({ type: "POST", url: "/librarysystem/login/", data: { 'username':$("username").val(), 'password':$("password").val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, dataType: 'json', success: function(data){ if (data.response) { alert("Invalid"); } else alert("Valid"); } }); }); urls.py: from django.conf.urls import url from .import views urlpatterns = [ url(r'^register/$',views.create_user), url(r'^$', views.index, name="Index"), url(r'^validate/$',views.validateForm), url(r'^article/$', views.article, name="Article"), url(r'^Login/$',views.loginUser, name="Login") ] views.py: from forms import signupForm from django.http import JsonResponse from django.contrib.auth import authenticate, login from django.contrib.auth.models import User def loginUser(request): data = {} if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username,password=password); if user is None: data['response'] = False else: data['response'] = True return JsonResponse(data) -
Group by dictionary value in for loop
I'm trying to group by dictionary value inside for loop in an django template. My template is as follows : <div id="engines-rows"> {% for engine in engines %} <h3>{{ engine }}</h3> {% endfor %} </div> Result that I get is as follows : {'id': 8, 'name': '2.0 TFSI', 'fuel_type': 'PETROL', 'displacement_cc': 1984, 'power_hp': 188, 'power_ps': 190, 'power_kw': 140} {'id': 7, 'name': '2.0 TDI', 'fuel_type': 'DIESEL', 'displacement_cc': 1968, 'power_hp': 181, 'power_ps': 184, 'power_kw': 135} {'id': 6, 'name': '2.0 TDI', 'fuel_type': 'DIESEL', 'displacement_cc': 1968, 'power_hp': 148, 'power_ps': 150, 'power_kw': 110} {'id': 5, 'name': '1.6 TDI', 'fuel_type': 'DIESEL', 'displacement_cc': 1598, 'power_hp': 109, 'power_ps': 110, 'power_kw': 81} {'id': 4, 'name': '1.4 TFSI g-tron', 'fuel_type': 'CNG', 'displacement_cc': 1395, 'power_hp': 109, 'power_ps': 110, 'power_kw': 81} {'id': 3, 'name': '1.4 TFSI e-tron', 'fuel_type': 'ELECTRICITY', 'displacement_cc': 1395, 'power_hp': 148, 'power_ps': 150, 'power_kw': 110} {'id': 2, 'name': '1.4 TFSI', 'fuel_type': 'PETROL', 'displacement_cc': 1395, 'power_hp': 148, 'power_ps': 150, 'power_kw': 110} {'id': 1, 'name': '1.0 TFSI', 'fuel_type': 'PETROL', 'displacement_cc': 999, 'power_hp': 114, 'power_ps': 116, 'power_kw': 85} I want to group by fuel_type, thus I want to see something like : Petrol Name: 2.0 TFSI -- displacement_cc: 1984 -- power_hp: 188 -- power_ps: 190 -- power_kw: 140 Name: 1.4 TFSI -- displacement_cc: … -
Django server 10054/10053 error when I tried to load video on ios
I tried to add a video in my django web app page with html5 video tag. The video can be viewed in ie/chrome/ff but it cannot be loaded from ios safari. The server side threw below errors but I could not figure out how can I fix it? Is it a safari problem or python/django problem or even a video encoding problem? Thanks a lot! [05/Feb/2017 00:49:48] "GET /static/testmovie.mp4 HTTP/1.1" 200 5832704 Traceback (most recent call last): File "C:\Python\Python27\lib\wsgiref\handlers.py", line 86, in run self.finish_response() File "C:\Python\Python27\lib\wsgiref\handlers.py", line 128, in finish_response self.write(data) File "C:\Python\Python27\lib\wsgiref\handlers.py", line 217, in write self._write(data) File "C:\Python\Python27\lib\socket.py", line 328, in write self.flush() File "C:\Python\Python27\lib\socket.py", line 307, in flush self._sock.sendall(view[write_offset:write_offset+buffer_size]) error: [Errno 10054] An existing connection was forcibly closed by the remote host [05/Feb/2017 00:49:48] "GET /static/testmovie.mp4 HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('192.168.1.8', 9097) Traceback (most recent call last): File "C:\Python\Python27\lib\SocketServer.py", line 599, in process_request_thread self.finish_request(request, client_address) File "C:\Python\Python27\lib\SocketServer.py", line 334, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python\Python27\lib\site-packages\django\core\servers\basehttp.py", line 99, in __init__ super(WSGIRequestHandler, self).__init__(*args, **kwargs) File "C:\Python\Python27\lib\SocketServer.py", line 657, in __init__ self.finish() File "C:\Python\Python27\lib\SocketServer.py", line 716, in finish self.wfile.close() File "C:\Python\Python27\lib\socket.py", line 283, in close self.flush() File "C:\Python\Python27\lib\socket.py", line 307, in flush … -
why post blog content get by comment?
hello i have a problem that when i post a Blog,it is got by both blog and comment, here is the specific: problems when i post a blog, the content goes to Model.Blog.content, but also goes to Model.Comments.content, and save in Mysql database, table Blog and Comments, show in front end either. i think it is there is some problem with the name"content",they are same in Blog and comment model, but not sense about that. so, pls help, with great appreciate!!! url.py urlpatterns = [ url(r'^admin/',admin.site.urls), url(r'^blogs/$',get_blogs), url(r'^detail/(\d+)/$',get_details,name='blog_get_detail'), url(r'^$', Register, name='register'), url(r'^register/$',Register,name='register'), url(r'^blog_post/$',Post_blog,name='blog_post'), models.py class Blog(models.Model): title = models.CharField(verbose_name='标题',max_length=150) author = models.CharField(verbose_name='作者',max_length=16,blank=True, null=True,default='adma') # abstract = models.TextField('blog_abstract',blank=True, null=True,max_length=150) content = models.TextField(verbose_name='内容',max_length=5000) created = models.DateTimeField(verbose_name='发布日期',default=datetime.datetime.now) catagory = models.ForeignKey(Catagory,related_name="blog_catagory",verbose_name="分类") tags = models.ManyToManyField(Tag,related_name="blog_tag",verbose_name="标签") class Comment(models.Model): blog = models.ForeignKey(Blog,verbose_name='文章') name = models.CharField(verbose_name='评论人',max_length=16,blank=True, null=True) # email = models.EmailField('email') content = models.TextField(verbose_name='评论内容',max_length=240) created = models.DateTimeField(verbose_name='评论时间',default=datetime.datetime.now) view.py def get_details(request,blog_id): try: blog = Blog.objects.get(id=blog_id) except Blog.DoesNotExist: raise Http404 if request.method == 'GET': form = CommentForm() else: form = CommentForm(request.POST) if form.is_valid(): cleaned_data = form.cleaned_data cleaned_data['blog'] = blog Comment.objects.create(**cleaned_data) ctx = { 'blog':blog, 'comments':blog.comment_set.all().order_by('-created'), 'form':form } return render(request,'blog_details.html',ctx) def Post_blog(request): if request.method == "POST": bf = BlogForm(request.POST) if bf.is_valid(): post = bf.save(commit=False) post.author = request.user post.save() return get_details(request,blog_id=post.id) else: … -
how to customize django admin panel model columns? django
By saying customize, I don't mean using list_display and things like that. My meaning of customizing is that I want a column which is not in the model. The idea is, I want to create a column saying download and there's no such attribute named download in the model. It's just a an url that I want to customize myself which would show up in each row. an easy example would be something like this in admin page in one of the random models. Let's say this is my Employee model. In my admin page it would show the name of the employee and at the right side I would like to create a download url myself which would export let's say the user's info. I do have the export codes ready and url ready too but I am not sure how to customize it in the admin page. Model Employee ------------------------------- name | download ------------------------------- Goerge | download Fluffy | download Techy | download Anyone got ideas how this can be done? Thanks in advance -
django - context processors return error
I've added the following function in context_processors.py. but when i go to index url, return me error. it's a natural error. because we do not have a date arguments in index. is there any way to prevent this error to be displayed? def one_day_foods_NOT_PAID(request): user = request.user path = request.get_full_path() date = path.strip('/').split("/", 2) if len(date) == 0: year, month, day = 0 else: year, month, day = date[1].split("-") foods = Reservation.objects.filter(order_date__startswith = datetime.date(int(year), int(month), int(day))).filter(user=user) return {'foods':foods} -
Django + PostgreSQL: creating a database (what privileges to grant)
Everything I have managed to find in the Internet looks like this: postgreSQL.app : create database https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-14-04 So, the first link say we have to create a database for Django like this: CREATE USER testfor_psl_user WITH password 'pass'; CREATE DATABASE testfor_psl ENCODING 'UTF8' TEMPLATE template0 OWNER testfor_psl_user; The second one is pretty similar: CREATE DATABASE myproject; GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser; In both cases we can see that all privileges are granted to the user. Why do they do that? Django uses two privileges: select and insert. Granting all privileges is not safe. I'm not thinking of making postgres the owner of the database. And granting select and insert privileges to myprojectuser. Could you comment on this question and share your experience of creating a database. Could you point at a useful link on this matter. -
How to serve templates for 2 different Django apps from the same folder?
The question is pretty self explanatory. Basically, I have 2 apps running in the same project. I want to serve all my templates from one single folder called templates, preferably placed in my project's root folder. However, Django serves templates from within the app's folders. How do I do this? Thanks.