Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework add custom validator to many=True serializer class
below serializer class has one many=True field which is for ItemSerializer class DataSerializer(serializers.Serializer): items = ItemSerializer(many=True) now I want to apply some validation on this field items, So I tried items = ItemSerializer(many=True, validators=[my_custom_validator]) below is the validator(function based) def my_custom_validator(value): # do some check and validation and raise appropriate validation error but the problem is that this validator will be applied to each item one by one instead of whole list at once. so for example I want to check the length of items list and if it exceed the predefined length, I should be able to raise error before executing any validation on each item. NOTE that ItemSerializer can be a nested serializer itself, I mean using another serializer as a field and so on. -
Exclude an app from Django migrations
Is there a way to exclude models of an app from Django migrations? I know changing the model meta options with managed = False is an option but that's a lot of models to edit every time. Is there a way to specify an app whose models I don't want to migrate? -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcd in position 0: invalid continuation byte
I faceing a strange issue!I use Pycharm to build a new Django project,I have no modify any on new project , but it appear a problem: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcd in position 0: invalid continuation byte please help me ! -
Valid OAuth redirect URIs for facebook - Django Social Auth
I am referring tutorials to implement django social-auth, I hace successfully implemented it for Twitter and Google+ . But, in case of facebook , I am not seeing "Valid OAuth redirect URIs" which has to provided for facebook. I assume that the new developer console of facebook has this new field. By leaving the field empty, I am still able to login but I am not getting relevent details from FB. It might be because of this "redirect URI". I followed below tutorials Tutorial 1 Tutorial 2 I guessed that "http://localhost:8000/oauth/complete/facebook/" could be the URI looking at google+ and twitter pattern but I am still not getting email ID of user. Can someone please confirm the redirect URI that has been used by them for Facebook in their Django App -
django multiple submit buttons
I have many buttons in my django template. Each button has a different name {{transaction.id}}. How can I refer to (submit) a single button in my view? base.html <h3>Open transactions</h3> {% for transaction in transactions_open %} {{ transaction.id }} {{transaction.timestamp}} {{ transaction.currency }} {{ transaction.sell_or_buy }} {{ transaction.bid }} {{ transaction.date_add }} <form action="" method="POST"> {% csrf_token %} <button type="submit" name={{ transaction.id }} value="close">Close</button> </form> </p> {% endfor %} views.py class MainView(View): def get(self, request): transactions_open = DealModel.objects.filter(open_or_closed='OPEN') transactions_closed = DealModel.objects.filter(open_or_closed='CLOSED') content_dict = {'transactions_open': transactions_open, 'transactions_closed': transactions_closed} return TemplateResponse(request, 'base.html', content_dict) def post(self,request): if request.method == 'POST': transactions_open = DealModel.objects.filter(open_or_closed='OPEN') transactions_closed = DealModel.objects.filter(open_or_closed='CLOSED') if request.POST.get('name???') == 'close': content_dict['answear'] = "Closed!!!" return TemplateResponse(request, 'base.html', content_dict) -
Techniques to Avoid Problems with Django Migrations?
I'm building an e-commerce website with Django 1.8 and PostgreSQL 9.4. I'm interested in learning what techniques I can use when I change my database to avoid having problems with Django migrations, particularly in the event that I can't get migrations to run and I have to delete my migrations, rebuild my database, and restore from backups. In development, I've found that when I change my database schema and re-run migrations, they only run successfully about 50% of the time. Clearly I'm doing some things wrong. What's worse is that when migrations don't work, it's not always easy to understand exactly why they failed and how to modify my migration files so that they will run. In those situations, I always have to delete the database and start over. This is acceptable in development but it's not a good strategy when I go into production. What are some "best practices" or "do's and don'ts" you follow when you modify your model classes/database schema so as to increase the probability that your Django migrations will run? And are there any steps you take to ensure that you can restore your database in the event that your migrations won't run and you … -
Display callable attribute from another model in Django admin
I have next models: class BaseModel(models.Model): def admin_link(self): url = reverse( 'admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=(self.pk, ) ) return '<a href="{url}">{name}</a>'.format( url=url, id=str(self) ) admin_link.allow_tags = True admin_link.short_description = _('Admin Link') class Account(BaseModel): pass class Order(BaseModel): account = models.ForeignKey( 'base.Account', on_delete=models.DO_NOTHING, related_name='orders', verbose_name=_('Account'), null=False ) And I created admin model for Order model: class OrderAdminModel(admin.ModelAdmin): fieldsets = [ (_('Order'), {'fields': [ 'account__admin_link', ]}) ] When I go to order change page, I getiing error: FieldError at /admin/base/order/1475d5d6-135f-454e-bec4-a801183dfc5f/change/ Unknown field(s) (account__admin_link) specified for Order. Check fields/fieldsets/exclude attributes of class OrderAdmin. I don't want write many identical functions in different admin models. Can i use one function but display it in fields and fields sets? -
Django, Nginx, Gunicorn. Ubuntu 16.04 error
i'n trying to run server with this - https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04#create-a-gunicorn-systemd-service-file When i try to run some commands, i get this error - sudo: unable to resolve host giver.local what can be the problem? -
Avoiding existence errors
def clean_bank_account(self): import ipdb; ipdb.set_trace() ssn = self.form.cleaned_data.get('ssn') customer = CustomerProfile.objects.filter(ssn=ssn) bank_account = self.form.cleaned_data.get('bank_account') bank = self.form.cleaned_data.get('bank') bank_transit = self.form.cleaned_data.get('bank_transit') qs = FinancialProfile.objects.filter( bank=bank, bank_transit=bank_transit, bank_account=bank_account) if customer.count() == 1: for cust in customer: qs = qs.exclude(customer_id=cust.id) if qs.count() > 0: # The concatenation of bank transit, the bank account and the bank # number must be unique. Hence, the following message would be # displayed if it is already in use. raise ValidationError( _('The bank, the bank transit and the bank are already in use.') ) if bank not in (None, ''): # Check bank account format for specific banks length = settings.LOANWOLF_BANK_ACCOUNTS_LENGTH.get(bank) if length: if bank_transit not in (None, ''): if not bank_account.isnumeric() or length != len(bank_account): raise ValidationError( _('Bank account number must contain %d digits') % length # noqa ) else: raise ValidationError( _('Cannot validate bank account without a valid bank transit') # noqa ) return bank_account I would like to improve the structure of this code. I can't do CustomerProfile.objects.get(ssn=ssn), because it will give me an error if the object doesn't exist. Instead I decided to create a list with a filter which returns me a queryset. with the lines if customer.count() == 1: for cust … -
DRF file.read() contains HTML header info and not just file content
I'm not sure where the problem is, but file.read() should only give me file content. I'm printing out the first 200 chars and get content headers instead of just the uploaded file data. Uploader local_file = os.path.join(basedir, 'a.jpg') url = baseurl + 'a.jpg' files = {'file': open(local_file, 'rb')} headers = {'Authorization': 'Token sometoken'} r = requests.put(url, files=files, headers=headers) print(r.status_code) View class FileUploadView(BaseAPIView): parser_classes = (FileUploadParser,) def put(self, request, filename): file_obj = request.FILES['file'] data = file_obj.read() print(data[:200]) return Response(status=HTTP_204_NO_CONTENT) And the output printed is: b'--139822073d614ac7935850dc6d9d06cd\r\nContent-Disposition: form-data; name="file"; filename="a.jpg"\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xe1!(Exif\x00\x00II*\x00\x08\x00\x00\x00\r\x00\x0b\x00\x02\x00\r\x00\x00\x00\xaa\x00\x00\x00\x00\x01\t\x00\x01\x00\x00\x00x\x03\x00\x00\x01\x01\t\x00\x01\x00\x00\x00\xe8\x03\x00\x00\x0f\x01\x02\x00\x04\x00\x00\x00HTC\x00\x10\x01\x02\x00\x0b\x00\x00\x00\xb8\x00\x00' How come I see all this extra data and not just the file content? Dis has been driving me bonkers and is probably going to be something simple. -
Pip is rolling back uninstall of setuptools
I am using this Ansible-Django stack to deploy my Django project to an AWS EC2 instance. It worked fine for a long time, but now suddenly, I get the error below when deploying. It seems like there is a new setuptools build that is not properly updated. Why does it rollback the uninstall of setuptools? Why does it not install setuptools 36.2.2? Specifying explicitly the version of setuptools in my requirements solves this issue, but since I am only indirectly dependent on setuptools, it should not be my responsibility to know which version to keep. Installing collected packages: shared-django, setuptools Found existing installation: shared-django 0.1.0 Uninstalling shared-django-0.1.0: Successfully uninstalled shared-django-0.1.0 Running setup.py install for shared-django: started Running setup.py install for shared-django: finished with status 'done' Found existing installation: setuptools 36.2.0 Uninstalling setuptools-36.2.0: Successfully uninstalled setuptools-36.2.0 Rolling back uninstall of setuptools :stderr: Exception: Traceback (most recent call last): File \"/webapps/CatalogService/lib/python3.5/site-packages/pip/basecommand.py\", line 215, in main status = self.run(options, args) File \"/webapps/CatalogService/lib/python3.5/site-packages/pip/commands/install.py\", line 342, in run prefix=options.prefix_path, File \"/webapps/CatalogService/lib/python3.5/site-packages/pip/req/req_set.py\", line 784, in install **kwargs File \"/webapps/CatalogService/lib/python3.5/site-packages/pip/req/req_install.py\", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File \"/webapps/CatalogService/lib/python3.5/site-packages/pip/req/req_install.py\", line 1064, in move_wheel_files isolated=self.isolated, File \"/webapps/CatalogService/lib/python3.5/site-packages/pip/wheel.py\", line 247, in move_wheel_files prefix=prefix, File \"/webapps/CatalogService/lib/python3.5/site-packages/pip/locations.py\", line 140, in distutils_scheme … -
Access specific element of array from list django
I have queryset like this in my view.py: SomeValue = list(a.objects.filter(x=x_number, timestamp__gte=a_time, timestamp__lte=b_time) \ .order_by('timestamp').values_list('timestamp', 'some_index').annotate( some1=dosomething('some_index'), some2=dosomething('some_index_2'), combined_some=(F('some1') + F('some2')) )) So SomeValue looks like this: SomeValue = [(datetime.datetime(2017, 7, 20, 23, 53, 51, tzinfo=<UTC>), 2L, 10.1, 2.4, 12.5), (datetime.datetime(2017, 7, 20, 23, 54, 51, tzinfo=<UTC>), 8L, 5.5, 6.4, 11.9), (datetime.datetime(2017, 7, 20, 23, 55, 51, tzinfo=<UTC>), 4L, 7.2, 2.0, 9.2),...] My goal is to access SomeValue and get combined_some like this: combined_some = [(datetime.datetime(2017, 7, 20, 23, 53, 51, tzinfo=<UTC>), 12.5), (datetime.datetime(2017, 7, 20, 23, 54, 51, tzinfo=<UTC>), 11.9), (datetime.datetime(2017, 7, 20, 23, 55, 51, tzinfo=<UTC>), 9.2),...] -
Passing data to bootstrap modal Django template
The view passes a list of elements to the template, for example a list of movies, and they are rendered in a table. And each element has its detail and one specif element has a list. The content of this list I wanna put them inside a modal. I'm doing this with two for loops like the following: <table> <thead> <tr> <td>title</td> <td>description</td> <td>hours</td> </tr> </thead> <tbody> {% for key in movies %} <tr> <td>{{ key.title }}</td> <td>{{ key.description }}</td> <td> <!--This button calls my modal--> {% for hour in key.hours %} <li>{{ hour }}</li> {% endfor %} <button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal"></button> </td> </tr> {% endfor %} </tbody> </table> My modal is under my table outside the div that wraps my table. I would like to pass the values of the second for loop to my modal. And when de user click on the button the values appear inside the modal How can I do this? -
django admin: changing the way a field (w/ relationship to another model) is submitted on a form so that it can be submitted multiple times
Struggling to find exact wording for this so I need to use an images. I have a model called Statements and I want to change the way the admin page for editing or submitting a Statement looks. This is particularly for a field that Statement has called statement-contexts. Right now, it doesn't accurately represent what the field is supposed to be and doesn't accomodate for multiple entries. statement-contexts draws a many-to-many relationship with another model called Context. Context consists of two fields that pair two words: the word field and the keyword field which draws a many to many relationship with the model Keyword, a pool of keywords in my database. This drop down menu doesn't really accomodate for submitting the pair of words that's actually supposed to comprise statement-contexts, beyond just selecting two words (which I hope would indicate the Context's word field and keyword field respectively. It also isn't user friendly since people will likely have to submit MANY pairs of contexts and keywords. More than one drop down menu is needed, and a way to actually see the many different pairs of words that someone would need to add. So I need to figure out how to … -
Duplicate static_placeholder makes placeholders uneditable
My site has a newsbanner which is displayed on every page, thus I have created static_placeholders to manage the content of it. However, the banner has a different look on mobile, which means I've created 2 sections, where one displays the large screen newsbanner and the other section displays the mobile version. The content, however, is the same, so I have duplicated the static_placeholder from the large screen section to the mobile section like this: <div class="section no-padding"> <div class="row hide-on-large-only hide" id="announcement-mobile" style="background: linear-gradient(to bottom, #26a69a 0%, #26a69a 50%, #ffffff 50%, #ffffff 100%); "> <div class="col s12"> <div class="card"> <div class="card-image"><a class="btn-floating btn-flat waves-effect waves-default transparent hide-announcement" href="#!" style=""><i class="material-icons">close</i> </a> {% static_placeholder "CTA billede" %} <span class="card-title"><i class="material-icons">fiber_new</i> {% static_placeholder "CTA overskrift" %}</span></div> <div class="card-content"> <p class="teal-text text-lighten-1 left-align">{% static_placeholder "CTA tekst" %}</p> </div> <div class="card-action"> {% static_placeholder "CTA links" %} </div> </div> </div> </div> </div><!-- end mobile --> <div class="section no-padding"> <div class="row hide-on-med-and-down hide" id="announcement" style="background: linear-gradient(to bottom, #26a69a 0%, #26a69a 50%, #ffffff 50%, #ffffff 100%); "> <div class="col s12 m8 offset-m2"> <div class="card horizontal hoverable"> <div class="card-image"> {% static_placeholder "CTA billede" %} </div> <div class="card-stacked"> <a class="btn-floating btn-flat waves-effect waves-default transparent hide-announcement" href="#!"><i class="material-icons blue-grey-text">close</i> … -
Installing wordpress on Azurewebsites running Django
We are running Django application on Azure websites. We would like to install a blog on www.example.com/blog. We uploaded wordpress into root directory, www.example.com/blog. But Django URL handler is stopping the request to the subdirectory and issuing an 404 page. How to solve this issue? -
Select a specific object from a queryset django
Is there any way to select a specific object that is found in the results of a queryset like selecting an item in an array. In arrays, you can select a specific item based on its position: arrayName = {55, 33, 34, 23} arrayName[2] result = 34 I want to accomplish the same thing with queryset results Users in database = {Steve, Chris, Jame, Cole, Casper, Courtney} Query will filter the names that start with c result = {Chris, COle, Casper, Courtney} After I get the results, I want to select Casper from the results... is there a way to do it like an array. something like results[2] -
Sign-in with Google using python django
I want to add sign-in with Google in my web application and generate the refresh token and access token for accessing the Google street view publish API using django. I have followed this link using this documentation I'm able to generate authorization code but here is a problem with authorization code that is the The life span of authorization code is only 10 mins and showing below error : {'error_description': 'Code was already redeemed.', 'error': 'invalid_grant'} Any help would really be appreciated! Thanks! -
How to get a data from form in django?
I have a form in my template django that was ok, it saves ok in a model. Well, now, i want create a new form inside this form. This form, i create inside the template, but now, i want get de data to save in another model. (I can't use the formset, i'm ready using it). This form are create with javascript when user click in the option inside the list. I'm using Class-based view to create a view. My question is, how can i get this data from this form that was created dynamically by the user? <div class="form-group"> <label class="col-sm-2 control-label">{{form.name.label}}</label> <div class="col-sm-10"> {{form.name}} {% if form.name.errors %} <span class="glyphicon glyphicon-remove form-control-feedback"></span> <span class="help-block">{{form.name.errors.as_text}}</span> {% endif %} </div> <label class="col-sm-2 control-label">{{form.date_max.label}}</label> <div class="col-sm-10"> {{form.date_max}} {% if form.date_max.errors %} <span class="glyphicon glyphicon-remove form-control-feedback"></span> <span class="help-block">{{form.date_max.errors.as_text}}</span> {% endif %} </div> <label class="col-sm-2 control-label">{{form.demand_desc.label}}</label> <div class="col-sm-10"> {{form.demand_desc}} {% if form.demand_desc.errors %} <span class="glyphicon glyphicon-remove form-control-feedback"></span> <span class="help-block">{{form.demand_desc.errors.as_text}}</span> {% endif %} </div> <div class="optional-imege-form">{{formset}}</div> <div id="create-new-image-button">Add</div> </div> <div class="format-list"> <h3>Lista de formatos:</h3> <ul> {% for key, value in format_names_fields_dict.items %} <li class="format-create" data-format-name-id='{{key}}' data-fields-value='{% for i in value %}{{i}},{% endfor %}'>{{key}}</li> {% endfor %} </ul> </div> <div class="col-sm-12 container-with-format-forms"> </div> <div class="ground-light-popup"></div> … -
html js voice recorder not working in django python implementation
i have tried to implement a django application wherein the user can record a voice message pass it ti watson api and receive back the transcribed data and show the result to the user on a separate page. The recorder is not working as i am not able to save the file also what changes should be made if i want to deploy the application to heroku and have the voice recording saved there and then pass that audio file to watson api? Code: STT/STT/settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'my-secret-key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'record', ] 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', ] ROOT_URLCONF = 'STT.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'STT.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES … -
Django condition aggregation, count when entry exists
What i want to do is something like this: Foo.objects.all().annotate(c=Count(Case(When(bar_set= exists,then 1)))) That is, count the cases where bar_set is not empty. # should not be counted foo.bar_set() >>> [] # should be counted foo.bar_set() >>> [<Bar: Bar object>] How can this be done? -
Refresh only the table content in a Template with new items (Django)
I am implementing a table with filters. None of the existing libraries (such as DataTables) work for me because they are based on client pagination and I cannot bring all the data from my DB and paginate it in the client side since it has more than 5 million items. So, the thing is that I want to be able to write something in an input field and filter the items in the table accordingly. The URL where it all starts is: http://127.0.0.1:8000/es/view-containing-the-table/ This url has the html cointained in custom_table.html (see the file below), which includes a sub-template called table_rows.html, which is the one I want to refresh To do it I have done the following: Structure of my project: project |-app |-static | |-javascript | |-myJS.js | |-templates | |-templates1 | |-custom_table.html | |-table_rows.html | |-views | |-__init__.py #Gathers all the views from othe files) | |-ajaxCalls.py | |-modelViews.py | |-urls.py urls.py url(r'^table_rows/$', views.tableRows, name='tableRows'), custom_table.html #extend and loads here {% block content %} <table id="myTable""> ... <thead> #headers and filters for each column </thead> <tbody id="table_body"> {% include "templates1/table_rows.html" %} </tbody> </table> {% endblock %} inside the of the table table, there is an input in every … -
How can i add pdf file to the email with the email template?
from django.core.mail import EmailMultiAlternatives subject, from_email, to = 'hello', 'from@example.com','to@example.com' text_content = 'Hello' html_content = 'Hello' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() -
Need to download 90MB+ xlsx file, cannot save it on the server. Can I stream it to a client
I have Django running on an Nginx Webserver, with uwsgi as application server. I need to generate a large .xlsx file by combining multiple smaller ones. Then that file needs to be downloaded to a client. After googling a lot, I have not been able to find anything that really answers my question, so I am asking here. I am using an openpyxl WriteOnly Worksheet. Upon trying to save the worksheet the process always gets killed. My question is, whether I can stream the workbook to the client via a uwsgi socket and save it there. It would be greatly appreciated if someone could provide some sample code for an implementation, that can save or stream the file to a client! -
How to disable migrations for specific Django 1.7 apps?
How do you disable migrations for specific apps in Django>=1.7? I'm trying to upgrade from Django 1.6 to 1.7, and I made some trivial changes to Django's auth app to change labels, but a design flaw in Django>=1.7 now treats all attributes as part of the database schema, triggering a new migration. Moreover, running manage.py makemigration myapp generates a migration for all other apps touching myapp, so even though I'm not explicitly trying to create a migration for auth, it's forcing me to do so, and I see no way to turn this off. This is creating havoc, since I have a dozen apps that touch auth, so this is causing Django to create over a dozen pointless migrations. I tried creating a custom auth migration directory using MIGRATION_MODULES, but doesn't seem to work. Any app that relies on auth now throws an error like: ValueError: Lookup failed for model referenced by field helpdesk.Queue.group: auth.Group If I try to migrate auth. How do I fix this? Ideally, the simplest solution would be to just "turn off" migrations for auth, since I'm not actually making any changes to it.