Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django OVERRIDE default templatetags
I want to make {% url %} fail silently if no reverse match is found and just output a simple '#' or default homepage link. How can I accomplish this without adding {% load tags %} to my 100s of HTMLs? Kind of like monkey-patching but something production-ready. -
Exclude Specific model field with foreignkey relation from Django model Serializer
I have three table. Student, School, Result class Student(models.Model): name = models.CharField(max_length=225) address = models.CharField(max_length=255) school = models.Foreignkey(School) class School(models.Model): name = models.CharField(max_length=225) class Result(models.Model): student = models.Foreignkey(Student) marks = models.FloatField() corresponding serializers for those models are like class SchoolSerializer(serializers.ModelSerializer): class Meta: model = School fields = '__all__' class StudentSerializer(serializers.ModelSerializer): school = SchoolSerializer(read_only=True) class Meta: model = student fields = '__all__' class ResultSerializer(serializers.ModelSerializer): student = StudentSerializer(read_only=True) class Meta: model = student fields = '__all__' Whenever resultserializer call, i want studentSerializer should hide student address information. I have already tried to include exclude field as exclude = ('student__address',) from this documentation but this doesn't work as student__address is not a model field of result model. How to exclude that address field or hide it from serializer response. -
How to prevent usernames from containing @/./+/-/_.?
I'm using django-allauth, and for some reason the username default allows: "letters, digits and @/./+/-/_." How can I ensure usernames are strictly alphanumeric (without @/./+/-/_.? -
Django deleting where SET_NULL
I have an issue with a ForeignKey and on_delete=SET_NULL. When deleting the last_data referenced in my Stuff model, it also deletes the stuff object just as if this was a cascade, which is obviously not what I expected, rather setting the last_data field null. Here is how my models are defined in two different django apps. # App 1 class Device(models.Model): last_data = models.ForeignKey('Data', null=True, blank=True, related_name="last_data_device", on_delete=models.SET_NULL, help_text="Latest data") class Data(models.Model): content = models.CharField(max_length=255) date_created = models.DateTimeField(blank=True, null=False, db_index=True) device = models.ForeignKey(Device, related_name="data", db_index=True, on_delete=models.CASCADE) # App 2 class Stuff(models.Model): device = models.OneToOneField(Device, null=True, blank=True, related_name="stuff", db_index=True, on_delete=models.CASCADE) last_data = models.ForeignKey(Data, null=True, blank=True, help_text="Latest data", db_index=True, on_delete=models.SET_NULL) I must have misunderstood how this is linked, what I want is that a stuff object is never deleted when data is removed, but that the last_data reference it has may be nulled when this happens. How should I write this or what did I do wrong here? Thanks PS: Migrations are up to date and db is synced. -
django-countries not using aws static folder
I'm setting up a django project with the static files on AWS. I am using django-countries to show country flags. It works fine locally, but when I put it on a server I am using an AWS S3 bucket for the static files. When I try and show the flag within a template, using <img class="flag-img" src="{{ object.country.flag }}"/> it doesn't show a flag and if I inspect the object it is showing /static/flags/za.gif as the url for the flag. All other static files are showing https://s3-bucket-name.s3.amazonaws.com/static/app_name/css/style.css What do I need to amend? -
How can I serialize a list via Django REST Framwork
I have a function which base on different Pandas processes it result a list ([6, 6, 6]). My question is how can I serialize it with Django REST Framwork. I tried to implement the documentation bit I just get different errors. Unfortunately I am newby in rest, and this is the fist time when I build Django with API endpoint. Here is my attempt: [serializers.py] class TestSerializer(serializers.ListField): child = serializers.IntegerField() [views.py] class TestListCreate(generics.ListCreateAPIView): queryset = Test().test_list[0] # This results the list --> [6, 6, 6] serializer_class = TestSerializer -
Get the data at a time in Django and make it use through out the application
How to create a Project/ application scope variable in django will be loaded when I start the server and that variable will be accessible to all views in a app i,e. Application level -
Updating a database row using form in Django
I'm trying to update an existing row from my database with Django's forms. I have no problem creating a new row but when I try to update an existing one, I get a ValueError ( traceback at the end of the post ). I understand that my 'product' attribute is mistaken as the primary key but just can't figure why. Here is my code : models.py class Rates(models.Model): my_id = models.AutoField(primary_key=True) product = models.CharField(unique=True, max_length=255) taux_comm_1 = models.FloatField(blank=True, null=True) taux_comm_2 = models.FloatField(blank=True, null=True) taux_euros = models.FloatField(blank=True, null=True) taux_uc = models.FloatField(blank=True, null=True) taux_prud = models.FloatField(blank=True, null=True) forms.py class RatesForm(forms.ModelForm): class Meta: model = Rates fields = ['product', 'taux_comm_1', 'taux_comm_2', 'taux_euros', 'taux_uc', 'taux_prud'] labels = { 'product': "Nom du produit", 'taux_comm_1': "Taux de commission de production", 'taux_comm_2': "Taux de commission de portefeuille", 'taux_euros': "Taux de commission sur l'encours euros", 'taux_uc': "Taux de commission sur l'encours UC", 'taux_prud': "Taux de commission sur l'encours UC Prudentes", } def __init__(self, *args, **kwargs): super(RatesForm, self).__init__(*args, **kwargs) self.fields['product'].widget.attrs.update({'class': 'form-control', 'readonly':'readonly'}) self.fields['taux_comm_1'].widget.attrs.update({'class': 'form-control'}) self.fields['taux_comm_2'].widget.attrs.update({'class': 'form-control'}) self.fields['taux_euros'].widget.attrs.update({'class': 'form-control'}) self.fields['taux_uc'].widget.attrs.update({'class': 'form-control'}) self.fields['taux_prud'].widget.attrs.update({'class': 'form-control'}) views.py product = request.session['product'] if request.method == 'POST': rates_form = RatesForm(request.POST) if rates_form.is_valid(): rate = Rates.objects.get(pk=2) rates_form = RatesForm(instance=rate) rates_form.cleaned_data.get('product') rates_form.cleaned_data.get('taux_comm_1') rates_form.cleaned_data.get('taux_comm_2') rates_form.cleaned_data.get('taux_euros') rates_form.cleaned_data.get('taux_uc') rates_form.cleaned_data.get('taux_prud') rates_form.save() return … -
Creating a payload with optional keys
I need to create a data payload for a restful web api. The template for the dict contains some optional keys. The usual way is to create a dict with all the required keys and then check and add optional keys one by one: def create_payload(key1, key2, ..., key10=None,key11=None): data = { 'key1' : key1, 'key2' : key2, ... } if key10: data[ 'key10' ] = key10 if key11: data[ 'key11' ] = key11 return data Is there an alternative way to start with the data template and then automatically delete optional keys that are None? def create_payload(key1, key2, ..., key10=None,key11=None): data = { 'key1' : key1, 'key2' : key2, ... 'key10' : key10, 'key11' : key11 } # delete keys that are None return data -
Uploading and retrieving files from django frontend to postgresql backend
This is my table in postgres: How would I bring this into the frontend so that users can upload their documents without having to access the DB. Right now I can only upload docs into the filesystem instead of the DB: views.py: def upload(request): if request.user.is_authenticated: username = request.user.username if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'app/upload.html', { "uploaded_file_url": uploaded_file_url, "username": username, }) return render(request, 'app/upload.html', { "username": username, }) upload.html: {% if form.errors %} <p>You did not select a file to upload!</p> {% endif %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p> {% endif %} Also how would I retrieve the uploaded documents. -
Back button doesn't return search result list on my django project
When I search, I look for something on the page, and when I click on one of the results, the detail page opens. The results listed are lost when I press the back button. This error does not occur in FireFox. The error is happening on chrome. Steps; Chrome opens, The call is made, Click one of the incoming results to go to the detail page, Press the Back button to go back to the search page, The listed results are displayed again. There is an error in step 5. -
how to run external django project different computer?
I developed a project on django, after that uploaded it on Github. I want to see this project any other computer, on django's development server but, when I downloaded the project and tried to run by python manage.py runserver command, localhost:8000 works but, I have TemplateDoesNotExist at/ errors. How can I fix this? -
Django related_name default syntax
According the documentation, related names must be unique. Again according to the documentation the default value, (if not set explicitly by the developer) is FOO_set, where FOO is the source model name. So if I have two foreign keys (pointed to two different models, of course), wouldn't the (default)related names be similar ? -
Can not run unit test from PyCharm in Django project
Whenever I try to test some existing (and working) unit tests in my Django project with PyCharm pro, I get the following error: File "/home/user/pycharm-2018.2/helpers/pycharm/django_test_runner.py", line 156, in run_tests return super(DjangoTeamcityTestRunner, self).run_tests(test_labels, extra_tests, **kwargs) TypeError: run_tests() takes exactly 2 arguments (12 given) The way unit tests are executed seems to be hardcoded in PyCharm helpers. The project is based on Django 1.9. Could that explain the incompatibility of the test runner? Or did I miss something in setup? -
How can I order by nested annotated field?
Given the following models: from django.db import models class FooQuerySet(models.QuerySet): def with_baz(self): return self.annotate(baz=models.F('pk')) class Foo(models.Model): objects = FooQuerySet.as_manager() class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) And the following setup: In[2]: from main.models import * In[3]: f = Foo.objects.create() In[4]: b = Bar.objects.create(foo=f) How can I build query which orders Bar objects by Foo.baz field? Tried the following: In[5]: from django.db.models import Prefetch In[6]: Bar.objects.prefetch_related(Prefetch('foo', queryset=Foo.objects.with_baz())).order_by('foo__baz') Error: Traceback (most recent call last): File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/IPython/core/formatters.py", line 224, in catch_format_error r = method(self, *args, **kwargs) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/IPython/core/formatters.py", line 702, in __call__ printer.pretty(obj) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/IPython/lib/pretty.py", line 400, in pretty return _repr_pprint(obj, self, cycle) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/IPython/lib/pretty.py", line 695, in _repr_pprint output = repr(obj) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/django/db/models/query.py", line 248, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/django/db/models/query.py", line 272, in __iter__ self._fetch_all() File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/django/db/models/query.py", line 1179, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1053, in execute_sql sql, params = self.as_sql() File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 446, in as_sql extra_select, order_by, group_by = self.pre_sql_setup() File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 51, in pre_sql_setup order_by = self.get_order_by() File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 316, in get_order_by field, self.query.get_meta(), default_order=asc)) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 663, in find_ordering_name field, targets, alias, joins, path, opts = self._setup_joins(pieces, opts, alias) … -
Django - annotate with multiple Count
I have a model called Post which has two fields upvotes and downvotes. Now, upvotes, downvotes are ManyToManyField to a User. This is the model: class Post(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) title = models.CharField(max_length=300) content = models.CharField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE) upvotes = models.ManyToManyField(Profile, blank=True, related_name='upvoted_posts') downvotes = models.ManyToManyField(Profile, blank=True, related_name='downvoted_posts') So, I want to fetch all the posts such that they are in the order of total(upvotes) - total(downvotes) So I have used this query: Post.objects.annotate( total_votes=Count('upvotes')-Count('downvotes') ).order_by('total_votes') The problem with this query is the total_votes is always turning out to be zero. The below queries will explain the situation: In [5]: Post.objects.annotate(up=Count('upvotes')).values('up') Out[5]: <QuerySet [{'up': 1}, {'up': 3}, {'up': 2}]> In [6]: Post.objects.annotate(down=Count('downvotes')).values('down') Out[6]: <QuerySet [{'down': 1}, {'down': 1}, {'down': 1}]> In [10]: Post.objects.annotate(up=Count('upvotes'), down=Count('downvotes'), total=Count('upvotes')-Count('downvotes')).values('up', 'down', 'total') Out[10]: <QuerySet [{'up': 1, 'down': 1, 'total': 0}, {'up': 3, 'down': 3, 'total': 0}, {'up': 2, 'down': 2, 'total': 0}]> Seems like both up and down are having the same value(which is actually the value of up). How can I solve this? I have tried this: In [9]: Post.objects.annotate(up=Count('upvotes')).annotate(down=Count('downvotes')).values('up', 'down') Out[9]: <QuerySet [{'up': 1, 'down': 1}, {'up': 3, 'down': 3}, {'up': 2, 'down': 2}]> … -
Django csrf token for Ajax
I have given {% csrf_token %} inside the form. Do I have to give another {% csrf_token %} inside the AJAX $.ajax({ .......... )} ? <form method="post" data-validate-username-url="{% url 'validate_username' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script> $("#id_username").change(function () { console.log($(this).val()); var form = $(this).closest("form"); $.ajax({ url: form.attr("data-validate-username-url"), data: form.serialize(), dataType: 'json', success: function (data) { if (data.is_taken) { alert(data.error_message); } } }); }); </script> -
Django testing - TypeError: int() argument must be a string, a bytes-like object or a number, not 'User'
I'm writing test cases for my first Django application and using mixer to generate random values for some modules. Test case written for testing on the models is like test_model.py from datetime import datetime, timedelta from django.core.exceptions import ValidationError from tzlocal import get_localzone import pytest from django.test import TestCase from mixer.backend.django import mixer from transactions.models import ModeOfPayment, AmountGiven pytestmark = pytest.mark.django_db @pytest.mark.django_db class TestAmountReturned(TestCase): def test_model_amount_return_add(self): amount_returned = mixer.blend( 'transactions.AmountReturned', amount_given=mixer.blend( 'transactions.AmountGiven', given_date=datetime.now(get_localzone()) - timedelta(days=300) ), amount=100.00, return_date=datetime.now(get_localzone()) - timedelta(days=50) ) assert str(amount_returned) == str(amount_returned.amount), '__str__ should return amount string' def test_model_amount_due(self): amount = 10000.00 interest_rate = 9.5 duration = 365 given_date = datetime.now(get_localzone()) - timedelta(days=200) returned_amount = 150.00 amount_given = mixer.blend( 'transactions.AmountGiven', contact=mixer.blend('contacts.Contact'), amount=amount, interest_rate=interest_rate, duration=duration, given_date=given_date, mode_of_payment=mixer.blend('transactions.ModeOfPayment', title='Cash') ) mixer.blend( 'transactions.AmountReturned', amount_given=amount_given, amount=returned_amount, return_date=datetime.now(get_localzone()) - timedelta(days=50) ) assert amount_given.amount_due == amount_given.total_payable - returned_amount, 'Should return dues amount' But on running the testing pipenv run py.test It is giving the following error ______________________________ TestAmountReturned.test_model_amount_due _______________________ self = <django.db.models.fields.AutoField: id>, value = <User: khess> def to_python(self, value): if value is None: return value try: > return int(value) E TypeError: int() argument must be a string, a bytes-like object or a number, not 'User' ../../../.local/share/virtualenvs/koober-py-McGChbzt/lib/python3.6/site-packages/django/db/models/fields/__init__.py:940: TypeError During handling of the above … -
I don't understand How Createview and updateview works??
Class HelloModelForm(CreateView) Statement Class HelloUpdateForm(UpdateView) statement -
Why relay in graphene-django?
I would like to know why Relay spec in graphene-django? I understand that using relay in graphene-django we get pagination and filters by default. My requirement is to call graphql apis from React(for Web) and use Apollo client for Andriod and iOS. Will there be a problem for clients to consume graphql apis written using graphene-django with Relay complaint especially pagination(and cursors) feature? How to support subscriptions using graphene-django? Any help would be highly appreciated. -
Django - Python :: How to pass a variable to another page on Render/Redirect
I have a login page A, in which I take User/Pwd info, and post to another 3rd party website and get a sessionid variable in JSON format. When I redirect/render ingestion page B I need this sessionid variable to be displayed/available there. This is what I've tried, but I can't seem to get it to work. Can someone help please? urls.py from django.urls import path from loginp.views import LoginView from loginp.views import IngestionView urlpatterns = [ path('login/', LoginView.as_view(),name='LoginView'), path('ingestion/', IngestionView.as_view(template_name='registration/ingestion.html'),name='IngestionView'),] views.py from django.views.generic import TemplateView from django import forms from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from .forms import LoginForm from .forms import IngestionForm import json import requests class LoginView(TemplateView): template_name = 'registration/login.html' def get(self, request): form = LoginForm() return render(request, self.template_name, {'form':form}) def post(self, request): form = LoginForm(request.POST) if form.is_valid(): #print form.cleaned_data() text = form.cleaned_data['email'] pwd = form.cleaned_data['password'] data = { "@type": "login", "username": text, "password": pwd } data_json = json.dumps(data) headers = {'Content-type': 'application/json'} url='https://cloud.com/ma/api/v2/user/login' response = requests.post(url, data=data_json, headers=headers) sessionid=response.json()['icSessionId'] form1 = IngestionForm() #return render(request,'registration/ingestion.html',{'sessionid':sessionid}) #{'info':args}) #return HttpResponseRedirect(reverse('IngestionView', kwargs={'sessionid':sessionid})) return redirect(request,'registration/ingestion.html',sessionid=sessionid) class IngestionView(TemplateView): template_name = 'registration/ingestion.html' def post(self, request): form1 = IngestionForm(request.POST) args1 = {"form": form1} return render(request, self.template_name, args1) login.html <html> <head> <title>Login … -
Django PasswordChangeForm in view.py not working
I'm trying to implement the change-password functionality using Django, but it's not working. Seems like it always render a new form without going into the form_valid statement, without giving any error informations also. Here is my code in my views.py def password_reset_by_user(request): if request.method == 'POST': form = PasswordChangeForm(user=request.user, data=request.POST) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return render(request, 'check_success.html') form = PasswordChangeForm(user=request.user) context = {'form': form, } return render(request, 'user/reset_by_user.html', context) I'm wondering what I did wrong, please help me. Thank you -
Django: Delete InMemoryUploadedFile
I'd like to delete InMemoryUploadedFile. I made a file uploader by django. And uploaded files are saved to 'static/files/' directory if those files don't violate validations. So, I' like to delete InMemoryUploadedFile which violates validations after checking validations. But, in the document, there isn't any descriptions about that. How can I delete InMemoryUplodedFile ? -
Is polymorphic query of base Model in case of Multi-table inheritance in Django possible?
I.e. we have class Place(models.Model):... class Restaurant(Place):... class Cafe(Place):... I'd like to query Place somehow: q = Place.objects.all() # how? but for q[x] i'd like to have not Place class instance, but Restaurant or Cafe instead (what are really stored), so I'll be able to call some polymorphic methods of the models classes. Possible? -
exposing only /token/ endpoint to public: Django oauth toolkit
I'm using this plugin which does not require applications creation by any user and any OAuth application can be only added by superuser. I have this included in the urlpatterns path('auth/', include('oauth2_provider.urls', namespace='oauth2_provider')), This is exposing all urls including enpoints for managing applications to the public auth/ ^authorize/$ [name='authorize'] auth/ ^token/$ [name='token'] auth/ ^revoke_token/$ [name='revoke-token'] auth/ ^introspect/$ [name='introspect'] auth/ ^applications/$ [name='list'] auth/ ^applications/register/$ [name='register'] auth/ ^applications/(?P<pk>[\w-]+)/$ [name='detail'] auth/ ^applications/(?P<pk>[\w-]+)/delete/$ [name='delete'] auth/ ^applications/(?P<pk>[\w-]+)/update/$ [name='update'] auth/ ^authorized_tokens/$ [name='authorized-token-list'] auth/ ^authorized_tokens/(?P<pk>[\w-]+)/delete/$ [name='authorized-token-delete'] I want only /token/ endpoint for the public to generate an access token and refresh token. How can I prevent other endpoints from public and allow only from admin panel?