Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF imagefield upload response with html template
I'm working with Django Rest Framework 3.5.4 Django 1.9 python 3.5 and Angular 1.4.5. I'm having an issue where I can upload/post to an image endpoint but the response I get is the DRF template instead of the JSON that I was expecting. models.py class BeforeImage(models.Model): job = models.ForeignKey(Job, related_name='before_images') before_image = models.ImageField(upload_to='images/', default='images/no-image.jpg') def __str__(self): return self.pk class Meta: db_table = 'before_images' serializers.py class BeforeImageSerializer(ModelSerializer): before_image = ImageField( max_length=None, allow_empty_file=False, use_url=True) class Meta: model = BeforeImage fields = ('id', 'job', 'before_image') views.py class BeforeImageViewSet(ModelViewSet): queryset = BeforeImage.objects.all() serializer_class = BeforeImageSerializer -
Django polls: NoReverseMatch with chartit
I am using chartit in Django and I want to integrate it on my polls application. I can display the graph by typing complete URL like http://127.0.0.1:8000/polls/chart/. But if I want to access using a button on the html page I get this NoReverseMatch error. What I have to do here to get it working? My url.py has url(r'^chart/$', views.model_property, name='column_chart'), views.py def model_property(request): ballot = Ballot.objects.all()[0] ds = DataPool( series=[{ 'options': { 'source': ballot.contestants.all(), }, 'terms': [ 'contestant_name', 'votes' ] }] ) cht = Chart( datasource=ds, series_options=[{ 'options': { 'type': 'column', 'stacking': False, 'stack': 0, }, 'terms': { 'contestant_name': [ 'votes' ] }}, ], chart_options={ 'title': { 'text': 'Ballot statistics' }, 'xAxis': { 'title': { 'text': 'Contestants' } } } ) # end_code return render_to_response('polls/graph.html', { 'chart_list': cht, 'title': "Test Chart"}) From html I have a boostrap button using which I would like to access this link <a href="{% url 'polls:chart' %}"> <button type="submit" class="btn btn-primary">{% bootstrap_icon "glyphicon glyphicon-info-sign" %} </button> </a> Chart looks like this -
Pass parameter from one link to another with jQuery or Django
I am not 100% sure how to explain my question and cannot provide a code example of things I've tried because I am not sure where to begin. I am building a carnival party rentals site and have built a custom backend that will allow my client to add a single product for multiple locations with multiple prices. The way I am do this is when someone hits the home page http://138.197.123.25/ the left sidebar links will simply launch a modal window and ask for location; when they choose a location, they will be taken to that url path for the location they chose; from there, I simply filter the prices based on the url parameter. The problem is if someone clicks on the side menu for Party Packages, then chooses say San Diego from the modal choice, they are taken to http://138.197.123.25/location/san-diego-rentals/, but what I would like is for them to go directly to the item and location they chose, so in this example, I would like them to go to directly to http://138.197.123.25/location/san-diego-rentals/party-packages/. The site is in Django, but this is probably a jQuery solution. Sorry for not providing code; thank you. -
Django 1.6 : Saving most fields of current object to a different table
I have a model A defined with bunch of fields. Here is what I want to do: Whenever a certain method say x() is called on model A, I want to create a new record in another model (say model B) with all the fields(except pk). Here is how I thought of solving it: 1. Make model B inherit from model A. So I will get all the fields setup automatically. 2. Serialize the current object whenever x() is called, prune the fields that I don't need, call B.save(**serialized_json) This way, every time the method is called, I would have a record for it in model B. Is there a better way of doing this? -
How to change context in Django TemplateView based on url
I am stuck with a automation problem in that I have a django project with multiple subdomains, one for each council model instance, all of my models have a forigenfield of 'council' and that is how i am filtering the context of the sites by creating a separate view view for each council that i add. However I would like to somehow create a way to automate adding a view class with the right filtered context each time I add a model instance (Council), also I will need to add another url in the urlpatterns which again i am stumped maybe a bit of python could help there but the views are my main concern. I hope i have explained this well enough any help would be much appreciated at this point! -
Foreign Key field always showing up as None in views.py, but not empty in database
I have a django app that I want set up to have a worksheet object that has a list of section objects, where each section object has a list of answers. In the excerpt from my views.py shown below, I am trying to pass the first section associated with a worksheet to the render function. Whenever I get an individual section object in the following function within my views.py file, the section object does not have any answers associated with it. However, I know that the section I have gotten does have answers associated with it, because when I do a GET request (or look using the browsable API that is automatically setup by django rest framework), I can see that the section with the same id as the one I have in the function shown below in views.py has a long answers list as one of its attributes. Despite this, when I print out section.answers as shown below, myapp.Answer.None is displayed. views.py def worksheet_detail(request, pk): worksheet = Worksheet.objects.get(pk=pk) sections = Section.objects.filter(worksheet=worksheet) sections = list(sections) section = sections[1] print(section.answers) print(section.id) return render(request, 'worksheets/worksheet_detail.html', { 'worksheet': worksheet, 'section': section, }) models.py class Worksheet(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, unique=True, default='') … -
TypeError: object of type 'NoneType' has no len() for a ClassBaseView
Is it normal to get the error : TypeError: object of type 'NoneType' has no len() when I typed def get_queryset(self): qs = super(PerceptionIndexView, self)\ .get_queryset().filter(loan__request__customer_id=205).values_list('loan__request__customer_id', flat=True)\ .distinct() In fact, when I execute In [71]: perc = Perception.objects.filter(loan__request__customer_id = 205).valu ...: es_list('loan__request__customer__user__last_name', flat=True).distinct ...: () In [72]: perc Out[72]: <QuerySet [u'Boyer']> everything looks fine. Why do I have such error? -
Display Contents of uploaded csv file in Django
I am not familiar with Django but I do have some practice with Python. I am attempting to display the csv file contents in a table using a template file. So far I am able to display the form for uploading the csv file. But, I am not sure exactly to display the csv contents in another template file. Does anyone have suggestions as to how I can display the uploaded csv contents. fileUpload.html {% extends "master.html" %} {% block content %} <h2>CSV File Upload</h2> <form action="{% url "csv_upload" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="submit" /> </form> {% endblock %} Incomplete Form file form.py class DataForm(forms.Form): data_file = forms.FileField(label="Please select a csv file") def clean_data_file(self): f =self.cleaned_data['data_file'] if f: fend = f.name.split('.')[-1] if fend != 'csv': raise forms.ValidationError('Can only use csv files') return f csvFormView.py from django.shortcuts import render from django.views.generic import FormView, DetailView, ListView from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from ..forms import DataForm from ..models import User class DataView(FormView): template_name = 'fileUpload.html' form_class = DataForm success_url = '/upload2/' def form_valid(self, form): form.process_data() return super().form_valid(form) -
Django MEDIA_ROOT, MEDIA_URL etc
This is my first time using MEDIA_ROOT/MEDIA_URL and I'm a little confused by the configuration. I have an image upload form which saves the original image plus a resized copy. I want to save both images to my MEDIA folder, but separate them. Current structure: project/ ----apps/ --------appOne/ ------------static/ ------------templates/ ------------__init__.py ------------models.py ------------urls.py ------------views.py --------__init__.py/ ----MEDIA/ ----project/ --------__init__.py --------settings.py --------urls.py ----manage.py I would like to save the original uploaded image to MEDIA/ and the resized image to a folder inside the MEDIA folder, like MEDIA/media/. Right now, it's nesting 3 times: original image goes to ---> MEDIA/media/ resized image goes to ---> MEDIA/media/media I'm almost positive I have my settings wrong but I've been fiddling with it for too long and nothing is working. It seems every tutorial configures things differently and I'm just not sure what the preferred structure is or why my current config isn't working the way I expect. Here is my settings.py: MEDIA_ROOT = os.path.join(BASE_DIR,'MEDIA') MEDIA_URL = "media/" models.py: from django.conf import settings from smartfields import fields from smartfields.dependencies import FileDependency from smartfields.processors import ImageProcessor class Image(models.Model): client = models.ForeignKey(Client, null=True, blank=True) model_pic = fields.ImageField(upload_to=settings.MEDIA_URL, dependencies=[ FileDependency(processor=ImageProcessor( format='PNG', scale={'max_width': 500, 'max_height': 500})) ]) views.py: def show_images(request): … -
invalid block of form is rendered
I want to show a form for invitation. I have created a form but when i go to the url /invitations/request, the invalid block is shown not the template with form. What might be the reason? url(r'^request/$', requestInvitation, name='request-invitation'), @csrf_exempt def requestInvitation(request): form = InviteForm(request.POST or None) response_data = {} if form.is_valid(): join = form.save(commit=False) email = form.cleaned_data.get('email') already_join, created = Invitation.objects.get_or_create(email=email) if created: already_join.invite_code = get_invite_code() already_join.save() response_data['result'] = "Thank you for your interest" response_data['email'] = email print ('response_data', response_data) return HttpResponse(json.dumps(response_data),content_type="application/json") else: return HttpResponse(json.dumps({'result': 'Error message'})) # return HttpResponseRedirect('/') context = {"form": form} return render(request, 'invitation/invitation.html', context) <form method="POST" class="invitation-form vcenter" action="."> {% csrf_token %} <div class="ui action input"> <input type="email" class="requested_email" name="email" placeholder="Email address"> <button class="ui button primary">Request Invite</button> </div> </form> -
Trying to access Django's extended UserProfile in a view
I'm creating a website which returns videos to users on the basis of their taste for example if a user selected 'Sports' as an option, it will return 'Sports' videos. So I've extended the django built in authentication system to store Profile information of the user, which is where the user is able to select his/her taste like 'sports'. What I'm trying to do now is to use the options selected by the User in a view to return different templates. For eg: If the user selected Sports: return Sports relevant template Elif the user selected Politics: return Politics relevant template I am particularly getting stuck at how to access this UserProfile field in the view. thanks. -
Store result to database from celery worker vs return result
I'm using Celery w/ Django to process a certain task which returns a JSON value that needs to be put in a Model record. Right now I see 2 options to persist it in the Django database: Passing in the id of the record as part of the task signature. Then Celery can use it to update the record. Alternatively, I can return the result from the task and enable the django-db result backend for Celery, which will live in Celery's own task_result table. This means I'll have to persist the AsyncResult Id inside the record, and whenever the client requests the record I'll look up and see if the process is done or not. To me it seems that option 1 is better, but since I haven't worked with Celery in recent years I want to know if there are downsides to it, and/or which situation would option 2 be better suited for. Thanks! -
All matches in one row
I have following database: class Person(models.Model): name = models.CharField(max_length=60) surname = models.CharField(max_length=60) class Place(models.Model): name = models.CharField(max_length=300) class Result(models.Model): place = models.ForeignKey(Place) person = models.ForeignKey(Person) votes = models.IntegerField() There are results of voting. There are 12 candidates in Person. In each Place there are always 12 matching results. I want to receive table: PlaceName | votesFor1 | votesFor2 | ... | votesFor11 | votesFor12 I don't see simple solution using annotate or aggregate. There is any? -
Django model save override not changing self
I'm stuck using a non-Django legacy MySQL database. I need to write code that generates a unique filename each time a model object is saved. The following doesn't work. It won't overwrite the filename field. It saves fine with whatever the filename field was set to. Is this because that field is set as the primary key? (I realize my code isn't creating a random filename--haven't gotten that far yet. Also, I know this will only save once since it needs to be unique, but it won't even save the first time). class Agenda(models.Model): type = models.IntegerField() filename = models.CharField(max_length=45, primary_key=True) date = models.DateField() class Meta: managed = False db_table = 'gbminutes' def save(self, *args, **kwargs): self.filename = 'ATESTFILE' super(Agenda, self).save(*args, **kwargs) -
Conda + Django: ImportError on everything when trying to load settings
I'm trying to get a Django app running on Windows with Conda, but importlib as called through Django isn't able to import… anything, it seems. For example, if I set my DJANGO_SETTINGS_MODULE=django (or another module that clearly exists, like os or importlib), I get this error: Traceback (most recent call last): File "./manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "C:\Anaconda2\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line utility.execute() File "C:\Anaconda2\lib\site-packages\django\core\management\__init__.py", line 303, in execute settings.INSTALLED_APPS File "C:\Anaconda2\lib\site-packages\django\conf\__init__.py", line 48, in __getattr__ self._setup(name) File "C:\Anaconda2\lib\site-packages\django\conf\__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "C:\Anaconda2\lib\site-packages\django\conf\__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Anaconda2\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named "django" But this only seems to happen when it's being called through Django; I'm able to import without issue from Python directly: Z:\>python Python 2.7.13 |Anaconda custom (32-bit)| (default, Dec 19 2016, 13:36:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import importlib >>> importlib.import_module("django") <module 'django' from 'C:\Anaconda2\lib\site-packages\django\__init__.pyc'> What's going on here? Why isn't Django able to import anything? -
convert python datetime with timezone to string
I have date time strings in the format of datetime.datetime(2010, 7, 1, 0, 0, tzinfo=<UTC>) How can I convert that into a date time string? I am really just getting held up on the tzinfo part. strftime("%Y-%m-%d %H:%M:%S") works fine without the tzinfo part -
How can I configure AWS SNS subscription in a Django Web server deployed on Beanstalk?
I plan to set the django web server subscribing to aws sns. So each time when there is a notification form sns, the django server can get the notification via http request. In this case, what should I do to make the server be able do handle the imcoming http request from sns all the time? -
How to share user information between wordpress and django website
I have two websites located on two different servers. One is based on Django and the other one is based on Wordpress. They both have some links that linked to each other. My current problem is, when I login on one website and I click the link which redirect me to the other website, I want to keep the login information with me in the other website.Therefore, I don't have to login in the other website again. In other word, I want the two website can share the session. How can I implement this? -
Django 1.10 makemigrations errors
I am having major problems getting a Django app installed on an Ubuntu machine running Django 1.10.6. I am used to using an older version of Django and now I cannot get my webapp to install. Here is the situation: I have a Django project called myproject. The file structure is: (BASEDIR)/manage.py (BASEDIR)/mycommon/ # I will discuss mycommon below (BASEDIR)/myproject/ (BASEDIR)/myproject/settings.py (BASEDIR)/myproject/urls.py (BASEDIR)/myproject/views.py (BASEDIR)/myproject/wsgi.py (BASEDIR)/myproject/models/ (BASEDIR)/myproject/models/__init__.py (BASEDIR)/myproject/models/models.py It turns out that for this project I need to put my models in a common package because there is another python application (using Twisted that bootstraps Django) that needs to access these models. I will call this package "mycommon". So my "real" models are here: (BASEDIR)/mycommon/ (BASEDIR)/mycommon/utils.py (BASEDIR)/mycommon/models/ (BASEDIR)/mycommon/models/__init__.py (BASEDIR)/mycommon/models/models.py So the Django settings file is in (BASEDIR)/myproject/settings.py and the INSTALLED_APPS parameter is set to this: INSTALLED_APPS = ( 'myproject.models', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', ) Finally, note that myproject/models/models.py is very simple, since it just uses the mycommon models: from django.db import models from mycommon.models.models import * So far so good, this is a structure that works fine on older Django versions. Anyway, I start with an empty MYSQL database (created but empty) and now I go back to (BASEDIR) … -
How do we convert field values to a numeric type in the Django ORM?
I have a CharField on my model, and I want to retrieve only the numbers in that CharField. For example: DEMO 025-SP 026 028 I want to retrieve this: 026 028 The padding zeroes are not necessary if that helps. -
Change items in database based on an array of values in Python Django
I have a string of values being posted to my python API ["7779987","5559098","2453987"] these numbers are unique identifiers of users in my database. These users have an 'amount' tuple. What I want to do is, when the array is received, in my code, I get all the users that have their IDs in the string and subtract 10 from their current amount value. This is what I tried but I know I'm doing something wrong. How do I go about this? class PayForTrips(APIView): def post(self, request): print(request.data) for index_number in request.data: print(index_number + "; ") user = User.objects.get(index_number=index_number) print("old user amount" + str(user.amount)) user.amount -= 1; print("new user amount" + str(user.amount)) serializer = UserSerializer(data=user) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to filter objects with many to many relationships in django
I am new at Django and I am trying to discover many to many relationships. I have a word model which has a many to many relationship with the default user model: from django.db import models from django.contrib.auth.models import User class Word(models.Model): definition = models.CharField(max_length=350) turkish = models.CharField(max_length=50) english = models.CharField(max_length=50) users = models.ManyToManyField(User) def __str__(self): return self.english def add_date_pretty(self): return self.add_date def summary(self): return self.definition[:50] + "..." I have an example word object belonging to two users and I want only these two users to see this word object on their feedpage. How should I correct the view function below? from django.shortcuts import render from django.contrib.auth.models import User @login_required def home(request): user = request.user small = user.username.title() words = Word.objects.filter(??????) #order_by('-english') return render(request, 'intro.html', {'words': words, 'small' : small}) Basicly, I want to check if a word object's user list contains authourized user, and if it contains, the word will be taken from database. How can I code this? -
What is the relationship between Celery and RabbitMQ?
Is Celery mostly just a high level interface for message queues like RabbitMQ? I am trying to set up a system with multiple scheduled workers doing concurrent http requests, but I am not sure if I would need either of them. Another question I am wondering is where do you write the actual task in code for the workers to complete, if I am using Celery or RabbitMQ? -
Use .distinct() with MySQL
In order to work with .distinct() in django in knowing that we work with MySQL, is there an alternative to In [48]: perc = Perception.objects.all() In [49]: perc Out[49]: <QuerySet [<Perception: Perception #0000001>, <Perception: Perception #0000002>, <Perception: Perception #0000003>, <Perception: Perception #0000004>]> In [50]: perc.filter(loan__request__customer=cust).distinct('loan__request__cust ...: omer__user__last_name') Out[50]: In fact, I read that ".distinct([*fields]) only works in PostgresSQL." The issue is related to the line which didn't return anything. Question : Is there an alternative in Django when we work with MySQL? Thanks in advance! -
Heroku-deployed Django webpage doesn't update when DB changes
I have deployed an app in Heroku using Django. The Django program uses a SQLite database db.sqlite3 on root directory to populate its page. Separately, there is also a Node.js scraper program that inserts to that database. The problem is that the hard-refreshed webpage shows the same data even after the content of the database changed. Curiously, this does not happen when it is tested locally with python manage.py runserver. How can I fix this problem? Thank you in advance! For reference, here is my requirements.txt file: Django==1.10.6 gunicorn==19.7.1 Pillow==4.0.0 selenium==3.3.1 whitenoise==3.3.0