Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django table2: Add row with the edittext field
I have designed the the table with the table2.is the screen shot of my table as shown below: This row of each column are read only i.e. screenshot.I want the row of each column should be editable.Can we have the "edittext" as column of each row in the table2 in django? Below is my model.py from django.db import models class Person(models.Model): date = models.CharField(verbose_name="Date",max_length=255) project = models.CharField(verbose_name="Project",max_length=255) release = models.CharField(verbose_name="Release",max_length=255) feature = models.CharField(verbose_name="Feature",max_length=255) module_name = models.CharField(verbose_name="Module Name",max_length=255) hours_spent = models.CharField(verbose_name="Hours spent",max_length=255) comment = models.CharField(verbose_name="Comment",max_length=255) Below is the table.py. import django_tables2 as tables from .models import Person class PersonTable(tables.Table): class Meta: model = Person # add class="paleblue" to <table> tag attrs = {'class': 'paleblue'} #fields = ('name') # fields to display How should I edit my model.py,table.py?Please help. -
Placement ordering
I'm using placements to implement m2m relations between pages and snippets, and I'ld like to order the results (aka the related snippetsà) in the page according to pre-defined "order". This order could be a date: class NewsTopic(Page): intro = RicheText() ... class NewsTopicPlacement(models.Model): page = ParentalKey(HomePage) news = ForeignKey(BewsTopicPage) class Meta: verbose_name = _('News topic in home page') order_by = ('news__go_live_at',) # Does not work ! class HomePage(Page): intro = RichText() ... I'ls like to order the results by news go_live_at dates, but I don't know how t implement that ? Thanks : -
Exception Value: context must be a dict rather than WSGIRequest
I'm making a web app using Django 1.11, Apache 2.2, and mod_wsgi all using Python 2.7. I'm having an issue rendering my page. The full traceback is, Environment: Request Method: GET Request URL: http://website.com/~user/irtf/ Django Version: 1.11.1 Python Version: 2.7.13 Installed Applications: ['irtf.apps.IrtfConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mod_wsgi.server'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/path/irtf_website/mysiteenv/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/path/irtf_website/mysiteenv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/path/irtf_website/mysiteenv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/path/irtf_website/mysite/irtf/views.py" in index 18. return HttpResponse(template.render(request)) File "/home/path/irtf_website/mysiteenv/lib/python2.7/site-packages/django/template/backends/django.py" in render 64. context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "/home/path/irtf_website/mysiteenv/lib/python2.7/site-packages/django/template/context.py" in make_context 287. raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__) Exception Type: TypeError at /irtf/ Exception Value: context must be a dict rather than WSGIRequest. My views.py is, def index(request): template = loader.get_template('irtf/index.html') return HttpResponse(template.render(request)) It might not matter but my template for this page just consists of text and links. -
Django rest framework how to return data field and success field
I using Django rest framework,and I hava a question: my model: class Store_Rotation(models.Model): store = models.ForeignKey(Stores) rotation = models.ImageField(upload_to='rotation/', verbose_name="轮播图") def __str__(self): return self.rotation.url my serializer: class Store_RotationSerializer(ModelSerializer): class Meta: model = Store_Rotation fields = '__all__' my view: class Store_RotationViewSet(ModelViewSet): queryset = Store_Rotation.objects.all() serializer_class = Store_RotationSerializer It return this: [ { "id": 1, "rotation": "http://192.168.33.10:8000/files/rotation/%E4%B8%9A%E5%8A%A1%E6%B5%81%E7%A8%8B%E5%9B%BE.png", "store": 1 } ] I want to return this: { data: [ { "id": 1, "rotation": "http://192.168.33.10:8000/files/rotation/%E4%B8%9A%E5%8A%A1%E6%B5%81%E7%A8%8B%E5%9B%BE.png", "store": 1 } ] } How to do this? It have some general method? -
JSON decode error while sending post request during testing
I am trying to test my signup url. When I do the following it gives me an error. from django.test import Client c = Client() response = c.post('/signup/', {'username': 'john', 'password': 'smith'}) Error: raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded -
Where To Modify The Code in Django Project
I've installed python and django. Everything is working fine. I can see the admin dashboard etc. But couldn't find where I can make the changes to html or play with the code. Can anybody point me in the right direction? Thanks. I've the following directory structure. -
why my tornado lost connection with mysql server for several hours?
I have a tornado project, in this project, I used Django model, everything is OK in my local development environment, but after I uploaded this project to server, I found each time after several hours(about 20 hours), this tornado project lost connection with MySQL service and throw errors:django.db.utils.InterfaceError: (0, ''). Then, each time after I restart this tornado project(use superviosr restart, I used supervisor to manage this project), everything went OK again. This is the main setting of this tornado project: import os import django from tornado.web import Application from tornado.ioloop import IOLoop from tornado.httpserver import HTTPServer os.environ.setdefault("DJANGO_SETTINGS_MODULE", "reserve.settings") django.setup() from servers.handlers import ReverseSubmit app = Application( [ (r"/reserve/(?P<game_id>\d+)", ReverseSubmit) ], autoreload=False ) if __name__ =="__main__": server = HTTPServer(app) server.listen(8889) IOLoop.current().start() I used python -m servers.index in supervisor config file to start this project, and servers.index is the position of this setting file. Other informations: in this project, I used py3.6/pymysql, and my mysql-serviceis running on the same server with my tornado project. -
Threading in Django is not working in production
I have a function in my Django views.py that looks like this. def process(request): form = ProcessForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.requested_by = request.user instance.save() t = threading.Thread(target=utils.background_match, args=(instance,), kwargs={}) t.setDaemon(True) t.start() return HttpResponseRedirect(reverse('mart:processing')) Here, I'm trying to call a function 'background_match' in a separate thread when ProcessForm is submitted. Since this thread takes some time to complete, I redirect the user to another page named 'mart:processing'. The problem I am facing is that it all works fine in my local machine but doesn't work on production server which is an AWS EC2 instance. The thread doesn't start at all. There's a for loop inside the background_match function which doesn't move forward. However, if I refresh (CTRL + R) the 'mart:processing' page, it does move by 1 or 2 iterations. So, for a complete loop consisting of 1000 iterations to run, I need to refresh the page 1000 times. If after, say, 100 iterations I don't refresh the page it gets stuck at that point and doesn't move to the 101st iteration. Please help! -
Radio-buttons are not displayed in the Class Based Views, its the check-boxes showing
Radio-buttons are not showing, its the check-boxes displayed in the Class Based Views. I want them to be showing the radio-buttons forms.py class ProductImagesForm(forms.ModelForm): media = forms.ImageField(label='Image') def __init__ (self, *args, **kwargs): super(PerstransForm, self).__init__(*args, **kwargs) self.fields['featured_image'] = forms.BooleanField( widget = forms.RadioSelect(choices=((0, 'False'), (1, 'True')) )) def add_prefix(self, field): if field == 'featured_image': return field else: return self.prefix and ('%s-%s' % (self.prefix, field)) or field class Meta: model = ProductImages fields = ['media', 'featured_image'] ImagesFormset = modelformset_factory(ProductImages, fields=('media', 'featured_image'), extra=1) models.py def product_download(instance, filename): return '%s/%s' %(instance.product.slug, filename) class ProductImages(models.Model): product = models.ForeignKey(Product) title = models.CharField(max_length=120) media = models.ImageField(upload_to=product_download, width_field='max_width', height_field='max_height', null=True, blank=True) max_width = models.CharField(max_length=100, null=True, blank=True) max_height = models.CharField(max_length=100, null=True, blank=True) featured_image = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return unicode(self.media) class Meta: verbose_name = "product image" verbose_name_plural = "product images" Views.py def get(self, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) formset = ImagesFormset(queryset=ProductImages.objects.none()) return self.render_to_response(self.get_context_data(form=form, formset=formset)) def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) formset = ImagesFormset(self.request.POST, self.request.FILES) form_valid = form.is_valid() formset_valid = formset.is_valid() if form_valid and formset_valid: seller = self.get_account() form.instance.seller = seller self.object = form.save() media = formset.save(commit=False) for img in … -
how to group_by a query by date and sum 2 others fields
My model looks like this : class PostMetric(models.Model): likes = models.IntegerField() comments = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) I would like to get the sum of likes and comments for each day (note that i need to transform the datetimefield to datefield (probably using Cast?): date engagement (likes+comments) 2/5/2017 26 3/5/2017 29 I tried to use : Cast, annotate, aggregate and even rawsql and extra/select functions but with no success. -
Selecting only active records django query
In my Django project, I have an is_active boolean column in every table of my database. Every time I or the framework accesses the database, I want only the active records to show up. What is the standard way to achieve this? Certainly I don't want to check for is_active in every queries I make. -
Which is better for Android backend - ME(a)N or Django
For Android backend , whether to use ME(a)N or Python Django or some other technology? I am new to Android Please help. -
Django filter limit objects
sorry for the stupid question. I don't know where to find this solution or any keyword reference for it. Let say, I have 2 models Place and Tips, and: # list of place id place_id_list = [...] How do I filter tips over the place_id_list that just retrieve <= 5 tips object for every place Here is the model: class Place: ... class Tip: # object_id is id of place object_id = models.PositiveIntegerField(editable=False) content_type = models.ForeignKey(ContentType) Right now, I just use for loop like: tip_list = [] for place_id in place_id_list: tip_list += Tip.objects.filter(object_id=place_id, content_type...)[0:5] But this query seem to slow. Is there any better solution? Thanks. -
(Django/HTML) How to create Live onClick Add to Favorite Function
I'm trying to create a Add to Favorite function, so far I manage to display an button with icon that based on if the field is_favorite is True or False. My Question is : How can I change the is_favorite state and update it into my database just by onClick the button without needing to refresh the page afterward? Optional Additional Question : If I add user authentication later on, how can i display a facebook like notification to public that notify "User A has favorite your project" Here's my code : model.py class ProjectProfile(models.Model): project_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) is_favorite = models.BooleanField(default=False) def __str__(self): return self.project_name views.py def index_view(request): context = { "table_list": ProjectProfile.objects.all(), "title": "Table_List" } return render(request, 'index.html', context) index.html <head> <meta charset="UTF-8"> <title>Favorite function</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <h1>Favorite Function</h1> <table> <thead> <tr> <th>Name</th> <th>Artist</th> <th>Favorite</th> </tr> </thead> <tbody> {% for data in table_list %}{% csrf_token %} <tr > <td>{{data.project_name}}</td> <td>{{data.artist}}</td> <!-- Favorite Album --> <td><a href="#" class="btn btn-default btn-sm btn-favorite" role="button"><span class=" {% if data.is_favorite %}glyphicon glyphicon-star {% else %} glyphicon glyphicon-star-empty{% endif %}"></span></a></td> </tr> {% endfor %} </tbody> </table> </body> I'm new to Web … -
Heroku I/O Error When Serving Media Files
I am trying to deploy a website to Heroku and I'm running into some trouble with Whitenoise and serving media when DEBUG=False. I have gotten the site to work when DEBUG is on but after adding Whitenoise the server throws and I/O error when trying to serve files that I know are there, even is DEBUG is on. My static files are configured as STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, '../pages/static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' When I try to load the front page, which contains an image that I know is stored in 'media' I get IOError at / [Errno 2] No such file or directory: u'/app/{appname}/media/{picture}.png' This is the first app I've ever deployed with Heroku and the first website I've written with Django so I'm still trying to understand how it all works. I thought I should be able to add the Whitenoise middlewear to the static files settings I had during development and it should pretty much just work but clearly I'm doing something wrong. -
Writing a reverse nested serializer in Django Rest Framework
Whats the best way to write reversed nested serializers? Example - I have a one-to-many Survey Model and SurveyReponse Models. What I done so far: I set up my SurveyReponse.create() method to be able to do is to post a SurveyResponse providing NO Survey, and for it to save to a default Survey. This works great. i.e., a POST of { "rating": 10 } creates a new SurveyReponse object and also Relates it to the Survey with name: "Default Survey Name" What else I want to do: I want to be able to POST providing a specific Survey to relate my SurveyReponse too. { "rating": 10, "survey": {"name": "Other Survey Name"} } This works fine with my current code if the Survey doesn't exist yet, however, if the Survey already exists, I hit the unique identifier duplication error { "survey": { "name": [ "survey with this name already exists." ] } } How do I get around this? by removing this line, survey = SurveySerializer(required=False) I'm able to do what I want, but I have to just provide the url to the resource, when I want to be able to just provide the name. (Unless this entire idea is an … -
Publishing JSON Data in Django templates
I am new to Django and Python so question might appear silly at first but after various attempts I am failing to get my desired result. The json data looks like this { "name":"Oliver", "age":"22", "About":{ "hobbies" : ["cricket","football","chess"], "dob":"1st_January_2000"} } I need to display all the information in a django template based table. I am comfortable in handling basic json with templates but cant frame a template for this one. -
ImportError: No module named 'oscar'
1.first: Install Oscar and its dependencies within a virtualenv: git clone https://github.com/django-oscar/django-oscar.git cd django-oscar ll virtualenv oscar . ./oscar/bin/activate sandbox/manage.py runserver python -m pip install django pip install --upgrade pip python -m pip install django sandbox/manage.py runserver pip install -r requirements.txt sandbox/manage.py runserver 2.this is my version: (oscar)[root@node02 django-oscar]# python --version Python 3.5.1 (oscar)[root@node02 django-oscar]# django-admin --version 1.11.1 (oscar)[root@node02 django-oscar]# 3.this is error: CentOS Linux release 7.1.1503 (Core) (oscar)[root@node02 django-oscar]# sandbox/manage.py runserver Traceback (most recent call last): File "sandbox/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/root/django-oscar/oscar/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/root/django-oscar/oscar/lib/python3.5/site-packages/django/core/management/__init__.py", line 307, in execute settings.INSTALLED_APPS File "/root/django-oscar/oscar/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/root/django-oscar/oscar/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/root/django-oscar/oscar/lib/python3.5/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/root/django-oscar/oscar/lib64/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 662, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/root/django-oscar/sandbox/settings.py", line 3, in <module> oscar? import oscar ImportError: No module named 'oscar' thank you -
Django Models Filefiled save according to query ID/pk
I am new to django and sqlite. From the code below i will upload my file to 'documents', since there is an overwrite storage function, if i upload the same file name with another query i will overwrite the old one which i dont wan it to be happend. So what I am thinking is to get the query id or pk as the directory.Its there anyway to store my upload file via their pk or id? eg. document/0/test.zip eg. document/1/test.zip -
Apache2 Django Keeps 500 and
So I have a virtual server where I'm running a Django application with different subdomains in one domain: Let's say subdomain1.domain.com subdomain2.domain.com subdomain3.domain.com Every few days, I have a 500 Internal Service Error, however nothing in my codes,apache2 files, etc has changed. When I restart apache2 with sudo service apache2 restart The subdomains fire up and it runs for a few days. Today I looked and I'm having a forbidden error (403) despite not changing anything from this morning when I checked my servers. I tried restart the apache2 server, updating the VPS, and checking my models, settings, and wsgi file. Currently there is no error in any of my apache2 log files or each individual log file despite all three being down. Any help pointing me in the correct direction would be appreciated. -
Django: How to remove the list that appears from raising a ValidationError
I want to raise a validation error so that the red box appears in the following image, but I do not want the list to appear. It would seem that forms.ValidationError("") forces you to input some text so that it can appear in this error list but I already handled that in my .html with {% if form.errors %} (display the red box). Is there a way to stop this list from appearing? ValidationError -
Django - How to create whitelist of files extensions for an ImageField?
I've created a Django website in which I allow users to upload Image files using Django's ImageField field. Django docs section about this mentions that there is a vulnerability involved in letting users upload files: Specifically, an HTML file can be uploaded as an image if that file contains a valid PNG header followed by malicious HTML. And it says that at the framework level there is no way to prevent this potential malicious behavior, and that one of the ways with which this can be prevented is by only allowing certain file extensions in the web-server's config: ... applications may choose to define a whitelist of allowable file extensions for user uploaded files and configure the web server to only serve such files. However, I'm using PythonAnywhere and I've found out that there is no way to whitelist file extensions at the server level with PythonAnywhere, and I'll have to use Python to do that in my app. I'm not sure how I would do that. My guess is that I will have to check for the uploaded file's extension in my Create and Update views, perhaps inside the def post or def form_valid methods, but I just don't … -
Linking directly to Wagtail modeladmin views
I'm successfully using Wagtail's wagtail.contrib.modeladmin to make a regular Django model editable from the Wagtail admin. I'd like to hyperlink to the modeladmin "create" and "edit" views from my template. What is the URL "name" I can use to reference these views? There appears to be no urls module in wagtail.contrib.admin and no documentation on this. Here's my directory app's models.py: from django.db import models class Organisation(models.Model): title = models.CharField(max_length=255) logo = models.ImageField(upload_to='logos', blank=True) ... And my project's urls.py: from django.conf.urls import include, url urlpatterns = [ url(r'^admin/', include(wagtailadmin_urls)), ... url(r'^directory/', include('directory.urls')), ] -
Industry standards for Django
I was wondering what the standards were for user groups under auth_user. The current debate is whether it would be better to create multiple files for static access and then direct users upon login to their group's profile page, or if it was better to create one large file with elements hidden to certain users. -
Django reversion fails to recover object after migration
I have this model: from django.contrib.auth.models import User from django.db import models import reversion @reversion.register() class BlogPost(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=32) content = models.TextField() Now I decided to add this field to the model: random_field = models.PositiveIntegerField(null=False, blank=False) I created migrations and choose default value: operations = [ migrations.AddField( model_name='blogpost', name='random_field', field=models.PositiveIntegerField(default=10), preserve_default=False, ), ] And migrate it. Now, I am using Django admin with reversion support, I modified the blog post few times before the migration and now I want to migrate to the version that did not have the random field. It says: Could not save BlogPost object version - missing dependency. Is there a way how to prevent this? I think its because the migration did not create the revision. Seems like the error is somewhere here: reversion/models.py#L21 I am using Django==1.11.1 django-reversion==2.0.8 with sqlite db. Is there a way to prevent this?