Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
APIListView returns ids instead of values
class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book") class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('died', null=True, blank=True) class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('title', 'author', 'summary') class BookAPIListView(ListAPIView): serializer_class = BookSerializer queryset = Book.objects.all() urlpatterns += [ path('api/books/', views.BookAPIListView.as_view(), name='api_books') ] I am trying to write an API to return the title, author and the summary of the book. However, since the author of the book is the foreign key, it returns an id instead of the name of the author. What is the simple way to fix it? Thanks in advance. -
Is there any good tutorial or book to learn Django faster?
I am learniing python. Is there any good book or tutorial about Django that will be helpful for me to do better project and help me learning? -
Math on Django queryset field
I have the following Django model: class Accounts(models.Model): account_code = models.CharField(max_length=12) account_name = models.CharField(max_length=50) value = models.IntegerField(null=True, default=0) When a query the database I want the returned queryset to have its field value divided by 1000. How can I do this kind of math on a model field as I query the database? -
Initial data not being fully displayed in django modelformset_factory
I am trying to display different initial data for each form in my formset. I don't get an error, however the data is not being totally displayed. Only the first object shows up. How do I fix this? all_names = defaultdict(list) for object in MyModel.objects.all(): # obj1 = John, obj2 = Bob all_names['name'].append(object) MyFormSet = modelformset_factory(MyModel, fields=('name'), extra=2) formset = MyFormSet(initial=[{'name': n for n in names} for names in all_names.values()] When I run: [print(form.initial) for form in formset] I get: {'names': <Name: John>} {} # Where is my second object? -
django/javascript alert the user before leaving the page if wrote something and didn't click submit
I have the following django form: <form class="form-inline" method = "post" > {% csrf_token %} {{ form.media }} {{ form.as_p }} <button type="submit" onclick="change_status()">Submit</button> </form> and the following javascript var user_can_leave = true; #challenge #1 (not sure how to switch the status to true) function change_status() { this.user_can_leave = true; } #challenge #2 #validate the form.media # if form.media.size>0 # then user_can_leave=false window.onbeforeunload = function (e) { if(user_can_leave == false) return "Are you sure to exit?"; } The objective is this: user can leave with no alert unless something was written in the text area (form.media) and the submit was not clicked (as in the user typed something and moved to a different page). My struggle is in the 'javascript change of status' and how to check that something was written in form.media. (need to that in javascript). -
django 2 deploy to heroku fail - at=error code=H10 desc="App crashed"
My build succeeded but my heroku website returns me with error. I use heroku logs --tail to see the error messages. Here is what it says: Build succeeded 2019-01-23T17:34:37.203663+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=multilingualnotetaking.herokuapp.com request_id=f964ab62-fac9-40f8-84a5-26bea61f183d fwd="39.10.71.43" dyno=web.1 connect=5001ms service= status=503 bytes= protocol=https 2019-01-23T17:34:38.222491+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=multilingualnotetaking.herokuapp.com request_id=069cc8d6-41d9-4d13-b8e2-be0a982b1279 fwd="39.10.71.43" dyno= connect= service= status=503 bytes= protocol=https Procfile: web: gunicorn --pythonpath notetaking notetaking.wsgi -b 0.0.0.0:$PORT gunicorn project.wsgi:application --preload --workers 1 runtime.txt python-3.7.1 requirements.txt dj-database-url==0.5.0 dj-static==0.0.6 Django==2.1.5 djangorestfra mework==3.9.1 gunicorn==19.9.0 mysqlclient==1.4.1 numpy==1.16.0 pandas==0.23.4 Pillow==5.4.1 psycopg2==2.7.7 python-dateutil==2.7.5 pytz==2018.9 six==1.12.0 static3==0.7.0 xlrd==1.2.0 -
How can i set image path while saving it
when i upload the image from the form it is just saving name of in database not saving the image and uploading to the path, but when i upload the image from database it stores perfectly urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',include('students.urls')), path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models # Create your models here. class student_registration(models.Model): registration_number = models.CharField(primary_key=True,max_length=100) student_name = models.CharField(max_length=100) student_father_name = models.CharField(max_length=100) student_image=models.FileField(default='default.jpg', upload_to='media', blank=True) views.py from django.shortcuts import render from .models import student_registration from django.contrib import messages from django.conf import settings # Create your views here. def student_registeration(request): if ("registration_no" in request.POST and "student_name" in request.POST and "student_fname" in request.POST and "student_image" in request.POST): registration_no = request.POST["registration_no"] student_name = request.POST["student_name"] student_fname = request.POST["student_fname"] student_image = (settings.MEDIA_URL + request.POST["student_image"], 'JPEG') s = student_registration(registration_no,student_name, student_fname, student_image) s.save() messages.success(request, f'Your account has been created! You are now able to log in') return render(request,'students/student_registration.html') else: return render(request, 'students/student_registration.html') -
Problem in adding user to Django based backend
I am working on an app in which user can login using his/her Facebook account. For logging in I am using Facebook SDK. And after logging in I am sending that token to backend (Django application) to add user details to my database. However I am facing weird issue. When I make post request using postman I am able to create user but when same thing is done from client using alamofire I am getting error. "error_description" = "Backend responded with HTTP400: {\"error\":{\"message\":\"Invalid OAuth access token.\",\"type\":\"OAuthException\",\"code\":190,\"fbtrace_id\":\"Cq\/R7AvLpJ1\"}}."; let path = "api/social/convert-token/" let url = baseURL?.appendingPathComponent(path) print(url) let params:[String: Any] = ["grant_type":"convert_token","client_id":FB_CLIENT_ID,"client_secret":FB_CLIENT_SECRET,"backend":"facebook","token":FBSDKAccessToken.current()?.tokenString!,"user_type":"customer"] Alamofire.request(url!, method: .post, parameters: params, headers: nil).responseJSON { (response) in switch response.result { case .success(let value): let jsonData = JSON(value) self.accessToken = jsonData["access_token"].string! self.refreshToken = jsonData["refresh_token"].string! self.expired = Date().addingTimeInterval(TimeInterval(jsonData["expires_in"].int!)) completionHandler(nil) case .failure(let error): completionHandler(error as NSError?) Facebook Login is working fine. I am passing client id and client secret same as application installed in backend. I am using alamofire. Not sure if it's because my header is nil. Any pointers will be appreciated. -
How to set a navbar link "active" for multiple url with Django tags
I have the following code navbar.html: {% url 'news:list' as news_url %} {% url 'news:list-detail' as news_url_detail %} [..] <ul class="navbar-nav"> [..] <li class="nav-item "> <a class="nav-link {% if request.path == news_url %}active{% endif %}" href="{{ news_url }}">News<span class="sr-only">(current)</span> </a> </li> </ul> My goal is to set as active the navbar link "News" even if the current url is not the "News" one (news_url) <a class="nav-link {% if request.path == news_url or request.path == news_url_detail %}active{% endif %}" href="{{ news_url }}">News<span class="sr-only">(current)</span> How can I do that? Thank you for any help you can provide. -
Django collectstatic only admin assets
I tried to use --ignore with a negative look-around like so: python manage.py collectstatic --settings=project.dev --ignore "^((?!admin).)*$" Alas, no dice. Seems like they only allow for explicit excludes vs. includes? How can I achieve this? -
How to sum values of a queryset in the view.py
This is my view.py: class PaymentControlList(ListView): template_name = "any.html" model = Payment def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = PaymentFilter(self.request.GET, queryset=self.get_queryset()) return context In that model (Payment) I have a field called value, how can I create an variable called total and used it in my template? That is my template.py {% for item in filter.qs %} {% if item.entrada %} <tr> <th scope="row">{{ item.data }}</th> <td>{{ item.payment }}</td> <td>{{ item.type }}</td> <td class="item-value">{{ item.value }}</td> </tr> {% endif %} {% endfor %} <h3> {{ total }} </h3> <!--Sum of item.value Just to let you know I have written the filter using django-filter -
LIstSerializer AssertionError
I am trying to use a ListSerializer so that I can create/de-serialize multiple objects in a list on a POST. I followed the guide at https://www.django-rest-framework.org/api-guide/serializers/#listserializer but seem to be running into this error when i visit the endpoint. assert self.child is not None, '``child`` is a required argument.' python3.7/site-packages/rest_framework/serializers.py in __init__, line 592 My serializers are as follows: class PredictionListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): pass def create(self, validated_data): predictions = [Prediction(**item) for item in validated_data] return Prediction.objects.bulk_create(predictions) class NestedPredictionSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) # Nested Serializer data = DataSerializer() class Meta: model = Prediction list_serializer_class = PredictionListSerializer fields = ('id', 'specimen_id', 'data' 'date_added',) extra_kwargs = { 'slug': {'validators': []}, } datatables_always_serialize = ('id',) The assertion error is being thrown in the initialization of the ListSerializer, however, the serializer is being initialized in a ViewSet like so. class BulkPredictionViewSet(viewsets.ModelViewSet): queryset = Prediction.objects.all() serializer_class = PredictionListSerializer Anyone familiar with this issue? I am wondering if my lack o control around initialization of the serializer (because I am using a ViewSet) is affecting this. If I try to pass the NestedPredictionSerializer into the ViewSet I get "Invalid data. Expected a dictionary, but got list." -
Can you please tell me how to use "(?P<pk>\d+)" in <a href=" here">{{ obj.title }}</a>
I want to know how to use "(?P\d+)" in our html file -
django.apps: an error appears during the template rendering when I loop on get_models()
I want to display the list of applications and the models of these applications in an HTML page. In view.py I update my view context with this : from django.apps import apps context.update({applications: apps.get_app_configs()}) in my template, when I loop on application, it works: {% for application in applications %} {{ application }} {% endfor %} But when I loop on the models, it doesn't work anymore: {% for application in applications %} {{ application }} {% for model in application.get_models %} {{ model }} {% endfor %} {% endfor %} I get: RelatedObjectDoesNotExist at /dumpy/ Permission has no content_type. The strange thing is that in a shell, this works fine: from django.apps import apps for application in apps.get_app_configs(): print (application) for model in application.get_models(): print(model) -
Django rest framework + axios: Invalid preflight http method on first request
We have a rather strange situation with a react based frontend using axios to talk to our Django rest framework based backend. When logging in a preflight OPTIONS request is sent by axios (as expected) but the first time the backend receives it, it seems to be malformed and thus results in a 401. However if I the retry, or even replay the exact same request using the browsers dev tool, the backend accepts the OPTIONS request and everything works as expected. We can consistently reproduce this. The Django development server log looks like this: First request [23/Jan/2019 15:43:42] "{}OPTIONS /backend/api/auth/login/ HTTP/1.1" 401 Subsequent Retry [23/Jan/2019 15:43:52] "OPTIONS /backend/api/auth/login/ HTTP/1.1" 200 0 [23/Jan/2019 15:43:52] "POST /backend/api/auth/login/ HTTP/1.1" 200 76 So as you can see, curly braces are added in the request method, which means that the request is not considered to be an OPTIONS request, and therefore a 401 is returned. The django view class LoginView(KnoxLoginView): authentication_classes = [BasicAuthentication] # urls.py (extract) path('auth/login/', LoginView.as_view(), name='knox_login'), The Axios request axios.post('/backend/api/auth/login/', {}, { headers: { 'Authorization': 'Basic ' + window.btoa(creds.username + ":" + creds.password) } }).then((response) => { dispatch({type: 'SIGNIN_SUCCESS', response}) }).catch((err) => { dispatch({type: 'SIGNIN_ERROR', err}) }) Some package version info … -
Django display specific text if date is older than 10 days
I'm working on a project for a customer who wants to display 'Alert' in a table if a users join date is older than ten days. I don't want to use a filter to only return the objects that satisfy the query because I want to display all of the members in the table. I'm using Django 2.x and python 3.6. Any help would be greatly appreciated. models.py: class Member(models.Model): name = models.CharField('Name', max_length=50,) join_date = models.DateField('Join Date', auto_now=False, auto_now_add=False,) views.py: def memberList(request, template_name='members/memberList.html'): member = Member.objects.all() data = {} data['object_list'] = member return render(request, template_name, data) and my template, memberList.html: {% extends "base.html" %} {% load static %} {% block content %} <table> <thead> <tr> <th>Name</th> <th>Join Date</th> <th>Alert</th> </tr> </thead> <tbody> {% for member in object_list %} <tr> <td>{{ member.name }}</td> <td>{{ member.join_date }}</td> <td> **??**</td> </tr> {% endfor %} </tbody> </table> {% endblock %} -
How to fire an 'if condition' after making an ajax call to a view?
I'm building a search bar that searches for objects in my database and if the search finds some matching objects, it then displays the objects in the html page without reloading it. But after I fire the Ajax call and get the tuples from the database, they are not being rendered on the template So, the flow is like this: I search for 'apple' in the search bar, hit search button and fire the ajax call to my view. After that, I set a boolean value 'search_successful' to 'True' if I find any 'apple' in my database. I then pass it to my template from where I fired the ajax in the first place. Now I am successfully getting the data and the boolean sets to 'True' correctly. Until this point everything works perfect. But after passing the context to my template, It does not fire the if condition that will display the data if search_successful = True. All this is carried out by an ajax call without reloading the page. Here is the if condition which I expect to work after the ajax call has been made to print the data: <form id="search_object"> {% csrf_token %} <input type="text" id="search_my_object" … -
Django manage.py command having SyntaxError on ElasticBenstalk
I'm using AWS for first time, and after uploading my Django project I wanted to know how to backup the information of the DB into a file to be able to modify the data in case I have to modify the models of my project (still on development) and keep having some population data. I thought about the django dumpdata command, so to be able to execute it on EB through the CLI I did the following (and here is where maybe I'm doing something wrong): - eb ssh - sudo -s - cd /opt/python/current/app/ - python manage.py dumpdata --natural-foreign --natural-primary -e contenttypes -e auth.Permission --indent 4 > project_dump.json For what I understand, the first command is just to access to the SSH on Elastic Beanstalk. The second one is to have root permissions inside the linux server to evade problems creating and opening files, etc. The third one is just to access where the current working aplication is. And the last is the command I have to use to dump all the data "human friendly" without restrictions to be able to use it in any other new database. I have to say that I tried this last command on … -
Why is data persisted when using postgres Docker image and docker-compose?
I'm new to Docker and I'm trying to get a Django app working in a Docker container. This app needs a PostgreSQL database (and redis). In order to try that, I created an image (Dockerfile) for my app, and used the basic postgres image for the database server. My docker-compose file looks like: version: '3.7' services: db: image: postgres redis: image: redis api: build: . command: python3 manage.py runserver 0.0.0.0:8000 environment: - DJANGO_SETTINGS_MODULE=api.settings.docker_settings volumes: - ./api:/code/api ports: - "8000:8000" depends_on: - db - redis As my docker-compose file does not define any volume for the database, I expected the database data to be lost when the container is stopped, but it's not! That is, if I run docker-compose up, add data to the db, stop docker-compose and start it again, the data is still there! Is a volume automatically created by Docker? (I noticed a VOLUME command in the Dockerfile of the postgres image, see here). Now I would like to add a volume to docker-compose to store the database somewhere I can control. How can I do that? I thought I should change the docker-compose file to ... db: image: postgres volumes: - ./postgres_data:/var/lib/postgresql/data ... but how can I … -
ElasticSearch field boost
I have the following ElasticSearch DSL query query = Q("bool", should=[ Q("match_phrase", title=term), Q("match_phrase", description=term), Q("match_phrase", name=term), Q("match_phrase", some_other_field=term), ]) I would like to boost the score when term is matching name field and also would like to lower the score when the match is on the description field. I've tried many things, like: Q("match_phrase", description={'query': term, boost: '0.1'}), or Q("match_phrase", name={'query': term, boost: 10}), But couldn't make it work. I also tried combining should with must, etc, but didn't get too far - not even worth sharing. Is there a simple way to do it without reindexing/re-scoring all my documents? An answer with a ES query (rather than ES-DSL) would be helpful as well. -
Django error on custom session middleware when calling request.session.save on process_response
Traceback (most recent call last): File "/home/user/.virtualenvs/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/user/.virtualenvs/env/lib/python3.6/site-packages/django/utils/deprecation.py", line 93, in __call__ response = self.process_response(request, response) File "/home/user/Desktop/project/my_project/app1/middleware.py", line 98, in process_response request.session.save() File "/home/user/.virtualenvs/env/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 83, in save obj = self.create_model_instance(data) File "/home/user/.virtualenvs/env/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 70, in create_model_instance session_data=self.encode(data), File "/home/user/.virtualenvs/env/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 96, in encode serialized = self.serializer().dumps(session_dict) File "/home/user/.virtualenvs/env/lib/python3.6/site-packages/django/core/signing.py", line 87, in dumps return json.dumps(obj, separators=(',', ':')).encode('latin-1') File "/usr/local/lib/python3.6/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/usr/local/lib/python3.6/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/local/lib/python3.6/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/usr/local/lib/python3.6/json/encoder.py", line 180, in default o.__class__.__name__) TypeError: Object of type '__proxy__' is not JSON serializable I've already checked the values in request.session.keys by logging each value and their types. None is a proxy object. Also, it's unlikely that a str is actually a django functional.proxy object or some translation object because it would show. Is it possible to be a django error? Django==2.1.4 The middleware I'm using class CustomMiddleware(SessionMiddleware): ... This only happens to one of my view that handles post method and returns a JSON response so it's unlikely that the variable causing this error comes from the view as it would show when calling render_json_response(context) -
Creating Forms dynamically from a model
I'm learning Django as I go right now, but I'm trying to do something more dynamically. Basically I've got multiple models defined as so: class Group(models.Model): name = models.CharField(max_length=255) type = models.CharField(max_length=255) # Ignore this, is used somewhere else class User(models.Model): name = models.CharField(max_length=255) group = models.ForeignKey(Group, verbose_name='group', on_delete=models.CASCADE) (there are more models than these two) I feel like writing a different view for each of these models isn't really a Django way to do it, but I'm struggling to find a different way. Basically I want to automatically create forms depending on what fields the model has. So on /department/ there should be an text input for name and type. But on /user/ there should be an text input for name and an selection for group. All that rather in the same template. If possible ofcourse. If it isn't possible, what's the best way to do this? Since creating a different template for each model doesn't seem right. -
API request to already opened django channels consumer
I've got a django channels consumer communicating with a client. I've got an external API that wants something from the client. I want then to tell that consumer to ask a request to the client through his socket. I'm currently exploring django rest framework but I can't find a way for now to directly ask anything to that socket. Well I've got an idea but it involves creating another socket and communicate through channels' channel. But I wish I could get rid of this overload. -
No Value being returned in Django Post Request in the QueryDict
I am trying to learn Django and can't find a solution anywhere. I run a submit button to gather a fullname, but when I hit submit, it shows None as the value. I don't understand what I am doing wrong. It was missing the csrf token, but I added that and it still comes back with none. view.html <div class='containter'> <div class='row'> <div class='col'> <p>{{ content }}</p> <div class='col-sm-6 col-12'> <form method="POST"> {% csrf_token %} <input type='text' class='form-control' placeholder="Name" value='fullname'> <button type='submit' class='btn btn-default'>Submit</button> </form> </div> </div> </div> </div> </div> views.py from django.shortcuts import render from django.http import HttpResponse def home_page(request): context = { "title": "Homepage", "content": "Welcome to the Homepage" } return render(request, "home_page.html", context) def about_page(request): context = { "title": "About Page", "content": "Welcome to the About Page" } return render(request, "home_page.html", context) def contact_page(request): context = { "title": "Contact Us", "content": "Welcome to the Contact Page" } if request.method == "POST": print(request.POST) print(request.POST.get('fullname')) return render(request, "contact/view.html", context) urls.py from django.conf.urls import url from django.contrib import admin from .views import home_page, about_page, contact_page urlpatterns = [ url(r'^$', home_page), url(r'^about/$', about_page), url(r'^contact/$', contact_page), url(r'^admin/', admin.site.urls), -
How to hide other data from current user
In django rest framework, When any user logged in and create a order then he can see his order history, i have created a view to do that task but the current user sees all of the information on the coffee_order table. How can i authenticate from other's data from current user ? class coffeeorderAPIView(generics.ListAPIView): queryset = coffee_order.objects.all() serializer_class = coffeeorderSerializer I have tried object level authentication in djangorestframework but i am a newbei, i can not do it. please give the solution.