Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Camel Case - Testing not using parser
I have a simple REST API in Django using rest_framework. I added the djangorestframework-camel-case plugin and updated my REST_FRAMEWORK configuration and the REST API outputs proper camelCase. However, when I test using unittest (python manage.py test app.test), the results are in snake_case instead of camelCase and cause my assertions to fail. Using this fork: https://github.com/rense/djangorestframework-camel-case REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.DjangoModelPermissions', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend', 'rest_framework.filters.OrderingFilter'), 'DEFAULT_RENDERER_CLASSES': ('djangorestframework_camel_case.render.CamelCaseJSONRenderer',), 'DEFAULT_PARSER_CLASSES': ('djangorestframework_camel_case.parser.CamelCaseJSONParser',), 'TEST_REQUEST_RENDERER_CLASSES': ('djangorestframework_camel_case.render.CamelCaseJSONRenderer',), 'TEST_REQUEST_PARSER_CLASSES': ('djangorestframework_camel_case.parser.CamelCaseJSONParser',), 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } Do I need to add some additional configuration? Is this a bug in djangorestframework? In djangorestframework-camel-case? -
Where do you put custom templates for django crispy forms?
For example, where would you put 'my_div_template.html' in your project structure? Layout( Div( 'field1', 'field2', template = 'my_div_template.html' ) ) (I am using the Bootstrap3 template pack) -
Django 1.11 - nested OuterRef usage
I recently updated Django to the bleeding-edge version 1.11rc1 because of the Subquery feature that was introduced there. Now, let's say this is my use case: I have following models - Users, Groups and Permissions. So, I have some Users whom I can group (e.g. Administrators group) and Permissions - which are lists of users that can do some things (e.g. I have User A, User B and Administrators who can create new users). What I want to do now is display all of the Permissions with a number of users inside them efficiently. So in other words, I want to make a QuerySet which would return all the information about the Permissions and calculate the number of the users for each Permission. The first, obvious way to work-around this would be to create a get_user_count method for the Permission model which would return all users from my ManyToMany relationships, but that would require at least 1 additional query per Permission, which is unacceptable for me, as I'm planning to have a lot of Permissions. This is where I want to use Subquery. So, to clarify things up - this is models.py: class User(models.Model): name = models.CharField(max_length=20) class Group(models.Model): users … -
Run pytest on vagrant ubuntu vm with windows as host. Import file mismatch
I guess that this is a quite specific situation but I will make the question since I didn't found a relevant answer and might be useful to someone else. The situation is this: Windows is the host OS. There is an Ubuntu VirtualBox (created with vagrant). My django project folder is shared between windows and ubuntu. I installed pytest (through pytest-django) both on ubuntu and on my virtualenv on windows. If I run the pytest command from the windows virtualenv the tests run just fine But in the ubuntu vm terminal I can't just run the pytest command since I get the error: The program 'pytest' is currently not installed. I can run it though with python -m pytest. But in this case I get import file mismatch errors: ========================ERRORS ======================= _____________ ERROR collecting my_django_app/tests.py ____________ import file mismatch: imported module 'my_django_app.tests' has this __file__ attribute: C:\virtualEnvs\my_env\project_src\my_django_app\tests.py which is not the same as the test file we want to collect: /vagrant/projects/project_src/my_django_app/tests.py HINT: remove pycache / .pyc files and/or use a unique basename for your test file modules The message is very clear but I don't know how to overcome this issue. I use python 2.7.9 and there is no pycache … -
Should I use wildcard for sub-domain in nginx server block or create virtualhost for each subdomain?
I am creating a SAAS app and I am wondering what architecture is good, Should I create a sub-domain wildcard or create separate nginx virtual host conf file for each sub-domain. -
All possibilities from Django's shell
I have the error name 'customer1' is not defined when I execute Request.objects.get(customer=customer1) in the interactive shell of Django. I would like to see all possibilities of customer I could pass in argument. I mean all possibilities of ? in Request.objects.get(customer=?). Is there an easy way to see that from the interactive shell? -
How to launch multiple test servers in a Django unittest
How would you simulate the running of multiple test servers in a Django unittest? I have a common code-base that powers two different sites with a separate database and settings.py file. I'm trying to unittest a tool that imports data from one site to another. The default unittest setup supports multiple sqlite3 databases, so I can confirm the data on one site gets into the other's database, but I'm not sure how to confirm the data in the UI on the other site, since the default client only seems to support a single server/port. -
'Pedido_Extra' object has no attribute 'update'
I have problems updating the fields of an object that was saved, first capture the id with ped.id and then pass it to get (id = ped.id) to then do the .update and that is the error, Which is tested in several ways is why I need your help please, thank you in advance! def IngresarExtra(request, id_especialidad, cod_experto): especialidad = Especialidad.objects.get(id=id_especialidad) articulo = Articulo.objects.get(pk=cod_experto) if request.method == 'GET': form = ExtraForm() else: form = ExtraForm(request.POST) if form.is_valid(): ped = form.save() ped.id ped_ex = Pedido_Extra.objects.get(id=ped.id).update(articulo_ex=articulo) ped_ex.save() return HttpResponseRedirect('/solicitar/pedidos-extra/') return render(request, 'form2.html', {'form':form, 'especialidad':especialidad, 'articulo':articulo}) class Pedido_Extra(models.Model): articulo_ex = models.ForeignKey('Articulo') especialidad_ex = models.ForeignKey('Especialidad') fecha_pedido_ex = models.DateTimeField(auto_now_add=True,null=True, blank=True) fecha_entrega_ex = models.DateTimeField(auto_now_add=False) cantidad_ex = models.IntegerField(blank=True, default=0) estado_ex = models.CharField(max_length=20, blank=True, default='pendiente') def __str__(self): return '{}'.format(self.articulo_ex, self.especialidad_ex, self.estado_ex, self.cantidad_ex) -
Pagination in Django while rendering data with AJAX call
I am working on a Django project I which I get data from AJAX call now I have to apply pagination on that data. for It I am trying to get a paginated data with AJAX call same in which I am getting data . But there is some error due to which I am unable to render data. Problem is not with error. Just Guide me how I can apply pagination on this data . //accepting all data with Ajax call function loadMaps(id) { var field = { id : id }; jQuery.ajax('{% url "mapport.maps.product" %}', { data : field, success: function(response, status, xhr) { showMaps(response.data) } }); } function showMaps(data) { //foreach var tbody = $('#tbl-maps tbody'), tr; tbody.html(''); $.each( data, function( key, value ) { tr= $('<tr></tr>'); tr.append('<% 9.times do %><td><input type="checkbox" name="ids" value="'+data[key].id+'"></td><% end %>'); tr.append('<td>'+data[key].name+'<td>'); tr.append('<td><a href="/'+data[key].slug+'">Main Interface</a><td>'); tr.append('<td><a href="/maps/'+data[key].id+'/">Dashboard</a><td>'); tbody.append(tr); }); } //template <table id="tbl-maps" class="table" > <thead> <tr> <th></th> <th>Name</th> <th></th> <th></th> </tr> </thead> <tbody> </tbody> </table> {% if id.has_other_pages %} <ul class="pagination"> {% if id.has_previous %} <li><a href="?page={{ id.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in .paginator.page_range %} {% if id.number == i %} <li class="active"><span>{{ … -
How to config django restful api for an external SQLServer database
I was using Django restful framework with the default MySQL database, however, lately I need to pull up data from an external SQLServer database with the same API. I was able to retrieve the data by installing pymssql, but not quite how to write the serializer & ViewSet with a raw sql query set. Is it possible to have some sample code on this? Thanks -
Django. Adding objects that have two foreign keys to the same class
my problem is that when you want to add objects to a class that contains two foreign keys to other (equal) classes. First add an object of the class to which the foreign key refers. And when you want to select the same object but in another field, it does not appear. models.py class Team(models.Model): name = models.CharField(max_length=255) class Match(models.Model): home = models.ForeignKey(Team) away = models.ForeignKey(Team) So .. How do I do if I want local and away to be the same teams without having to update the admin page when I create the local team? Thanks! Agu -
Cannot send JSON Array - Django Oauth Toolkit & Django Rest Framework
My DRF API's are secured by Django OAuth Toolkit, but when I send a POST with JSON Array data as the body, it doesn't work, the problem I found was in the oauth2_backends module. It extracts the body, expecting a dict, (dict.items()), then sends this data onwards to something in OAuthlib. I've tried finding a workaround, and have prevented the error at dict.items(), the error is eventually in OAuthlib, and I don't really want to change that, as I ave no clue whats happening. What I want to know, is if there's a decent workaround, and if it comes to it I'll just change how I send the request. -
How to upload a folder in django
As a newbie to django, I'm having an insanely difficult time figuring out how to upload a folder to the site directory with django. Let me give some context. I'm making a sort of blog. In this blog, I store details on an article in the database, such as headline, author, etc... Then, I write the article in word, save it as an html document, and upload the file to django. All of this can be done through the builtin admin page. But the reason I need to upload an entire folder is because if I use images in my article, Word places them inside a folder with the same name as the article and appends '.fld' to the folder name. Let's say I save an article as 'test.html'. It saves that file and any other files it needs in a folder named 'test.fld' right next to the html file. If I could upload the article and folder along with it, it would make life a lot easier. That being said, the django documentation for uploading multiple files sucks. I was wondering if anyone could give me clearer explanation on how to do this. And if possible, how to upload … -
Django Form csrf_token
whenever we want to perform a POST request in django we need to add a csrf_token. For example if you want to create a form: <form action="#" method="POST"> {% csrf_token %} This is pretty simple if you do it in HTML. However, I want to create forms dynamically using jQuery. I have the following code: $div = $('<form/>') // First I am creating the `form` div .attr("method","POST") //POST method .attr("action","#"); ($div).appendTo('#team_notification_'+index); //Appending it var $button = $('<button/>') //Creating the buttons .attr("type","submit") .attr("name","Accept") .attr("value", invite[0].pk); //Setting some value $($button).appendTo($div); But how can I append the csrf_token using jQuery? Thanks -
TemplateSyntaxError trying to use cut filter in template tag in Django
I am trying to set a link href as part of the current URL path in my Django view template. But I am currently getting the error Could not parse some characters: request.get_full_path|()||cut:'?thumbnail=true' This is my code {% if 'thumbnail' in 'request.get_full_path()' %} <a href="{{ request.get_full_path()|cut:'?thumbnail=true' }}">Link</a> {% endif %} Why am I getting this error? Can I use the cut filter this way? Thanks -
I can load static files locally with 'runserver' but not in production
I can load static files locally with 'runserver' but not in production. I successfully manage to load templates in production, but not static files. in the .html page I included the lines: <!DOCTYPE html> {% load staticfiles %} ... ... <img src="{% static "images/mypic.jpg" %}" alt="this pic" /> my settings in settings.py include these lines BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [STATIC_DIR, ] STATIC_URL = '/static/' and in urls.py I have: from django.conf.urls.static import static and urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^pages/', include('pages.urls')), url(r'^admin/', admin.site.urls), url(r'about^$', views.about, name='about'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I've been trying for hours, any idea why I can't access them? -
Django + Crispy Forms To Download a Filtered Table to CSV
I am new to Django and have created some class-based views to display a database table. I also implemented filtering on the table. The customer requested that they can download the filtered table to a CSV. I think I am having trouble figuring this out because the only other time I created a web app was in Flask and I didn't use class-based views. I thought the answer to this question might help but I had a lot of trouble following his example. Also tried to follow a few other stack overflow answers but couldn't quite get it. Any help GREATLY appreciated. Here is my code: views.py from models import Submission from tables import SubmissionTable from filter import SubTableFilter from forms import SubFormHelper from utils import PagedFilteredTableView class Submissions(PagedFilteredTableView): template_name = 'submissions.html' model = Submission table_class = SubmissionTable filter_class = SubTableFilter formhelper_class = SubFormHelper paginate_by = 200 forms.py from models import Submission from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Reset, Button class SubFormHelper(FormHelper): model = Submission form_tag = False form_method = 'GET' layout = Layout('spuid', 'g_number', 'accession', 'bioproject', 'biosample', 'ncbi_submission_id', 'submission_status', Submit('submit', 'Filter'), Reset('reset', 'Reset'), Button('download', 'Download') ) filter.py (note there are more fields here than form basically … -
youtube api graphs charts on dashboard
I am trying to create dashboard which will show youtube analytics data similar to what we see on youtube analytics page. I am writing in python and I can get json data via api calls. Now I want to display this data graphs, charts on dashboard. What are the best tools, approach for this. I am thinking of using django for backend, are there any tools compatible with django to easily display api data, json on dashboard similar to youtube analytics? -
Is it better to parse an uploaded file for data, or create a model to store inbound data?
I have a django application that uses the DRF to handle data input and output. Right now, the project owners are suggesting that the application read data from a CSV that they will upload to a data folder. I'm thinking that it would be cleaner to create a model and POST that data so I can then build out the resulting report using django's templating language. Is there a third way that I'm not aware of? What is the most efficient way to handle incoming data in a django app? -
How to filter Django GeopositionField based on longitude or latitude
I have a geoposition field that contains lat,long value of a point. >> object.location >>11.23,21.23 >>object.location.latitude >> 11.23 I have tried queryset.filter(location__latitude__lte=20.00) but its not working. -
Django: How to limit_choices_to when using custom intermediate table
Let me start by saying that I am working with a legacy database so avoiding the custom intermediate table is not an option. I'm looking for an alternative way to get the limit_choices_to functionality as I need to only present the options flagged by the sample_option boolean in the Sampletype Model in my ModelForm: class PlanetForm(ModelForm): class Meta: model = Planet fields = ['name', 'samples'] Here is a simplified view of my models class Planet(models.Model): name= models.CharField(unique=True, max_length=256) samples = models.ManyToManyField('Sampletype', through='Sample') class Sample(models.Model): planet = models.ForeignKey(Planet, models.DO_NOTHING) sampletype = models.ForeignKey('Sampletype', models.DO_NOTHING) class Sampletype(models.Model): name = models.CharField(unique=True, max_length=256) sample_option = models.BooleanField(default=True) Sample is the intermediate table. Normally, if the project had been started with Django in the first place, I could just define the ManyToManyField declaration as: samples = models.ManyToManyField('Sampletype', limit_choices_to={'sample_option'=True}) But this is not an option.. So how do I get this functionality ? Django clearly states in their documentation that: limit_choices_to has no effect when used on a ManyToManyField with a custom intermediate table specified using the through parameter. But they offer no information on how to get that limit in place when you DO have a custom intermediate table. I tried setting the limit_choices_to option on the … -
How website like leetcode implemented online python, c/c++ interpreter?
by sending your code to run by server every time you click 'run'? or have some sort of javascript implementation of python, c/c++? I don't have much experience with django, or flaks, is it achievable by using those? -
Manage an email address with django / python / pythonanywhere
I'm looking to host my django app and am currently hosting free on pythonanywhere.com. The django app uses all-auth which requires SMTP emailing. I'm porting hosting to my own domain name, and with that want to start using an email @mywebsite.com. How can I A) create and B) manage my @mywebsite.com inbox? A) Am I able to do this through python anywhere? B) Is there a neat django extension for this (e.g. a webmail client). All I know is to use the following settings for gmail: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = DEFAULT_FROM_EMAIL = 'gmail account' EMAIL_HOST_PASSWORD = 'gmail password' My domain-register is asking a ridiculous amount per mailbox (£35) so I'm not sure what my options are. -
Unable to login Angular2 / Django rest framework
I am using seesion authentication with the folowing Angular 2 service method. login(username : string, password : string) { var data = { username: username, password: password } return this.http.post(environment.apiEndpoint + 'login', data) .catch((error) => { return Observable.throw(error.json()); }); } Result : Response contains csrftoken and seesionid in the header setcookie value but it's ignored by angular. Adding withCredentials causes CSRF invalid token error. How to login using Angular 2 and Django rest framework with seesion authentication scheme ? -
Can I prevent pip from downgrading packages implicitly?
I have Django 1.10.5 installed in my python virtual environment. When I install djblets into my virtualenv with pip install djblets, unfortunately, Django is being implicitly downgraded to version 1.8.17 along the way. This breaks my environment. Is there something I could have done to prevent this? I certainly wasn't asked whether I'm okay with the downgrade. But I really should have. djblets version 0.9.6 doesn't even install because it depends on Pillow, which refuses to build. It's all just broken and kills my environment along the way because uninstalling comes first. All I can think about is trying the installation in a separate, but identical, virtual environment and seeing what happens. Like a dry-run. Now I have to install my environment from scratch. Am I missing something, or is this just the way it is?