Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django authentication view SetPasswordForm
I'm trying to modify password reset confirmation default template by adding styling to forms. My scripts: forms.py from django.contrib.auth.forms import SetPasswordForm class PasswordResetConfirmForm(SetPasswordForm): new_password1 = forms.CharField( label="New password", strip=False, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'New password', }), ) new_password2 = forms.CharField( label="New password confirmation", strip=False, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Confirm New Password', }), ) views.py from django.contrib.auth import views as auth_views class ConfirmPasswordResetView(auth_views.PasswordResetConfirmView): form_class = PasswordResetConfirmForm template_name = 'registration/password_reset_confirm.html' password_reset_confirm.html {% extends 'base.html' %} {% block content %} {% if validlink %} <div class="mx-auto" style="width: 400px;"> <form method="post" style="background-color: #f0ebbe; padding: 20px;">{% csrf_token %} <h1>Change password</h1> <div class="form-group"> {{ form.new_password1 }} </div> <div class="form-group"> {{ form.new_password2 }} </div> <button type="submit" class="btn btn-primary">Change password</button> </form> </div> {% else %} <p> The password reset link was invalid, possibly because it has already been used. Please request a new password reset. </p> {% endif %} {% endblock %} Problem is that, class and placeholder attributes are not passed to inputs in the template. What can be the problem? -
Why does Python Request's JSON decoder return the concatenation of top-level keys
I am using the Requests library to decode a JSON response as follows: Payload Being Decoded: { "objectOne": { "desc": "one" }, "objectTwo": { "desc": "two" } } Code: from django.http import HttpResponse import requests class ApiService: @staticmethod def say_something(self): resp = requests.get('http://127.0.0.1:9501/polls/test/') return HttpResponse(resp.json()) Output: objectOneobjectTwo I followed the simple example from the official documentation: JSON Response Content In addition I wrapped the response in [] brackets to see if the response must be in a JSON array but it just returns an array with 'objectOneobjectTwo' as the 1st and only element. -
how to use integer variable as subscript in Django template
I have a for loop in a Django template: {% for i in no_of_lift_series_range %} {{ workout.lifts.series.i.activity_name }} {% endfor %} where this fails to output anything. The problem lies in the use of i. I know this, because this: {% for i in no_of_lift_series_range %} {{ workout.lifts.series.0.activity_name }} {% endfor %} outputs what it is supposed to output. Why can't I use i in the way I want and how do I make this work? -
django-filter access foreign keyed entries
The problem I'm using the django-filter package to filter through my results. Suppose my models look like the following: class Material(models.Model): id name class Test1(models.Model): id materialTested = models.ForeignKey(...) TestResult class Test2(models.Model): id materialTested = models.ForeignKey(...) TestResult I am trying to filter using the package using results from both Test1 and Test2. The reason the tests are their own models is because multiples of the same test (or none) can be run for the same materials Current Progress I currently have it set up to filter using a single test by defining the following filter: class Filter1(django_filters.FilterSet): class Meta: model = Test1 fields = {'TestResult':['gte','lte']} -
django create N number of forms in template
I was wondering if it was possible to write a more generic form to use as a template so that during the render it will create as many forms as necessary? If not how would one write code to create N number of forms, where the number is Dependant on the result of some query set? I know the code below doesn't work I am leaving it in as more sudo code forms.py: class OptionalSFRForm(forms.Form): selected_optional_sfr = forms.ModelMultipleChoiceField(queryset=sfrs_models.ProtectionProfile.objects.all()) def Custom(QueryPP): selected_optional_sfr = forms.ModelMultipleChoiceField(queryset=QueryPP.Optional_SFR.objects.all()) models.py class ST_Title(models.Model): Selected_SFR = models.ManyToManyField(sfrs_models.SFR, related_name='Selected_SFR') AttachedPPs = models.ManyToManyField(sfrs_models.ProtectionProfile, related_name='ST_PPs') sfrs.models.py class ProtectionProfile(models.Model): Optional_SFR = models.ManyToManyField(SFR, related_name='Optional') template: {% for AttachedPPs in ST_Title.AttachedPPs.all %} <form action="{% url 'SecurityTarget:stview' ST_Title.id %}" method="post" id="conformanceform"> {% csrf_token %} {{OPTSFRS.Custom(AttachedPPs)}} </form> -
What is the purpose of manage.py in Django startproject?
I come from a JS background, and decided to start a Python project to learn the basics of creating/deploying an app in Python, and I do not see any concise explanations of what the purpose of manage.py is, so I decided to give it an ask. -
Django form for hidden input fields
I have two models, Post and Attachment. Attachment has a foreign key to Post. I have a PostCreateView with PostForm. While writing a post, you may upload images using jquery-fileupload (AJAX). If files are uploaded the following lines are appended to <form>. <input type="hidden" name="attachments" value="1" /> <input type="hidden" name="attachments" value="2" /> <input type="hidden" name="attachments" value="3" /> The values(1, 2 and 3) are PK for Attachment model in order to make a relationship between Post and Attachment when I save a post. I was able to get a list in view: def form_valid(self, form): attachments = self.request.POST.getlist('attachments') However, I'd like to declare the form field in PostForm for the following validations: PKs must be integers. Attachment's foreign key must be null with those PKs. A post may have NO attachment, so the attachment hidden input tag does not exist at first. That's why it could be hard to have a form field. These are appended by AJAX/jQuery. If it is diffcult, I'd like to know the best practice which method shoud be overridden in CreateView. Thank you. -
Django Rest Framework admin extend model
I am trying to extend Django Rest Framework admin model. This is the code that I have: from django.contrib import admin from .models import * from markdownx.admin import MarkdownxModelAdmin def process_topics(_, __, queryset): from person.tasks import calculate_factors for object in queryset: calculate_factors(object) process_topics.short_description = "Process topics manually" class ObjectAdmin(admin.ModelAdmin): list_display = ('pk', 'sender', 'note',) actions = [process_topics, ] # admin.site.register(Object, ObjectAdmin) admin.site.register(Object, MarkdownxModelAdmin) I would like to use ObjectAdmin to extend MarkdownxModelAdmin class. -
GeoDjango GDAL error in terminal
I have an application which I wrote some months ago which included geodjango but I now visited the project today and ran the project in my terminal and got this error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", "gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. . I since dont know how to figure it out. any help will be appritiated and further codes would be supplied on request -
django many to many modelform view
I'm newbie with django. I want to show all models in view. For example if this code is launched, it doesn't show the Author model. from django.db import models from django import forms #Models class Author(models.Model): name = models.CharField(max_length=100) birth_date = models.DateField(blank=True, null=True) def __str__(self): return self.name class Book(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author) class Peoples(models.Model): name = models.CharField(max_length=30) book = models.ManyToManyField(Book, blank=True) def __str__(self): return self.name #ModelForm class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ['name', 'birth_date'] class BookForm(forms.ModelForm): class Meta: model = Book fields = ['name', 'authors'] class PeoplesForm(forms.ModelForm): class Meta: model = Peoples fields = '__all__' #View def test(request): if request.method == 'POST': form = PeoplesForm(request.POST) else: form = PeoplesForm() return render(request, 'test/form.html', {'form': form} ) How diplay all models wich have servals manytomany relations ? Thanks a lot. -
Which technologies can I authorize users of my Django app to call an API Gateway endpoint?
so I'm developing a Django-based webapp and hosting it on AWS Elastic Beanstalk. Right now, users log in and are authenticated by Django's default Session based auth system. I also have a Chrome Extension, and an AWS Lambda function as part of the same system. The Chrome Extension, when installed, will periodically send requests to the AWS Lambda function via AWS API Gateway. When a request reaches API Gateway, I want to only allow Django-authenticated (authorized?) requests to pass. In the Lambda function, I would like to find out which user sent the request and process the data as required. My understanding is that I'll need to move away from session-based authentication to a public/private key encryption of some sort. I have seen AWS Cognito mentioned, OAuth2, OpenID, and JWT. I am struggling to compare these technologies as they seem to serve slightly different purposes in some cases. I see words like "authentication" and "authorization" being used and I don't fully understand the different meanings. Can anybody help me understand which technologies I can use and in what ways in order to achieve my use-case? -
django form raising keyerror when values are left to default
I have a form which is not connected to any kind of model. class NumberForm(forms.Form): quantity = forms.IntegerField(widget=forms.NumberInput(), initial=0, required=True) I create a formset out of this and then simply add up all the numbers entered by the user. This works so long as a value is entered in every input. When I leave one of the inputs on the initial value I get a keyerror trying to access cleaned_data, no matter what I set the initial value to. For example, if I manualy change all inputs to 1 I do not get a keyerror, but if I set initial=1, all values are set to 1 in my template, but when I try to submit my form once again a key error is raised. What is going on here? -
'AsgiRequest' object has no attribute 'user'
Automat-0.6.0 Django-2.0.1 asgi-redis-1.4.3 asgiref-1.1.2 attrs-17.4.0 autobahn-17.10.1 channels-1.1.8 constantly-15.1.0 daphne-1.4.2 hyperlink-17.3.1 incremental-17.5.0 msgpack-python-0.5.1 pytz-2017.3 redis-2.10.6 six-1.11.0 twisted-17.9.0 txaio-2.8.2 zope.interface-4.4.3 Environment: Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 2.0.1 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'chat'] Installed 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', ] Traceback: File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/channels/handler.py" in process_exception_by_middleware 243. return super(AsgiHandler, self).process_exception_by_middleware(exception, request) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/contrib/admin/sites.py" in wrapper 241. return self.admin_view(view, cacheable)(*args, **kwargs) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner 212. if not self.has_permission(request): File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/contrib/admin/sites.py" in has_permission 186. return request.user.is_active and request.user.is_staff Exception Type: AttributeError at /admin/ Exception Value: 'AsgiRequest' object has no attribute 'user' -
The latest version of Python 3 is python-3.6.4 (you are using Python-3.6.4, which is unsupported) [on hold]
-----> Python app detected ! The latest version of Python 3 is python-3.6.4 (you are using Python-3.6.4, which is unsupported). ! We recommend upgrading by specifying the latest version (python-3.6.4). Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing Python-3.6.4 ! Requested runtime (Python-3.6.4) is not available for this stack (heroku-16). ! Aborting. More info: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed -
Django validation in model clean() with M2M fields can not work on creation
How do you handle model validation that implies M2M fields? For example, class Object1 objects_2 = models.ManyToManyField(Object2) def clean(): # any operation implying objects_2 field. # for example: if self.objects_2.exists() ... This will work for un update, but at object creation, I will encounter this error: "<Object1>" needs to have a value for field "id" before this many-to-many relationship can be used.. I understand this error, but how would you do to make a proper validation in that case? My current workaround is to remove the objects_2 field from the form if the user is creating an Object1 instance, and force the user to edit the Object1 instance to change that field. Awful right? Thanks for your help. -
Django rest Docker with MySQl
I am trying to dockerize my Django rest project. I am using MySQL database instead of default SqlLite. My Dockerfile looks like following: FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt and Docker-compose: version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" I did not run docker-compose run web python manage.py migrate docker-compose build is successful However docker-compose up fails eventually saying Can't connect to local MySQL server. I am guessing that I need to install MySQl in my container as well, but do not know how. What am I missing in my Dockerfile? -
How to make for models with ForeignKey (autocomplete_fields) multi-step choices in standard Django Admin?
Question for Django 2.0 with Select2 on the box. How to make for models with ForeignKey (autocomplete_fields) multi-step choices in standard Django Admin? My tours app is: tours/models.py: class Tours(models.Model): country = models.ForeignKey(Countries, on_delete=None, default=None) resort = models.ForeignKey(Resorts, on_delete=None, null=True, default=None) tours/admin.py: @admin.register(Tours) class ToursAdmin(admin.ModelAdmin): list_display = ('country', 'resort',) autocomplete_fields = ('country', 'resort',) And this is my countries app: countries/models.py: class Countries(models.Model): name = models.CharField(max_length=255) class Resorts(models.Model): name = models.CharField(max_length=255) country = models.ForeignKey(Countries, on_delete=models.CASCADE, default=None) countries/admin.py: class ResortsInlineAdmin(admin.StackedInline): model = Resorts @admin.register(Countries) class CountriesAdmin(admin.ModelAdmin): list_display = ('name',) search_fields = ('name',) inlines = [ResortsInlineAdmin,] @admin.register(Resorts) class ResortsAdmin(admin.ModelAdmin): list_display = ('name', 'country',) search_fields = ('name',) Would be nice after choose value in Country field — leave in Resort field only values that relate to this Country (inlines option in countries/admin.py). Similar demo with PHP + jQuery. -
Test input message text and answer in Django custom admin command
I want to test user input confirmation answer in a custom management command. The test is for message displayed to user and answer that she enters. The commands' code is: class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('id', type=int) def handle(self, *args, **options): try: experiment = Experiment.objects.get(pk=options['id']) except Experiment.DoesNotExist: raise CommandError( 'Experiment with id "%d" does not exist' % (options['id']) ) answer = input('Are you sure? (Y/n)') if answer == 'Y': experiment.delete() This accepted answer suggests to use mocking, but it's in a lonely context. I want to test the user input as well other things that I could add to the custom command. What would be an efficient approach? -
Comparing dataframe object with string value in django
I'm implementing machine learning model and using training dataset from MySQL table and all this is built upon Django. So basically all the calculations are done by converting entire data from MySQL table to dataframe. df = pd.read_sql("select * from naivebayes_player",connection) However, I'm facing problem in comparing dataframe column value with a string. So I have a column named classification in MySQL table which has 2 fixed values 'RS' or 'NRS' stored in varchar(10) format. Since I've converted an entire table into dataframe whenever I calculate the count of 'RS' values in classification column in dataframe it always returns 0. But actually, there are 63 entries of 'RS'. total_RS = df['classification'][df['classification']=='RS'].count() In above line of code I'm trying to find out all records where classification is 'RS' which should be 63 but I'm getting 0. What am I doing wrong? I have tried above code when reading data from CSV instead of MySQL table and everything worked fine. -
Django admin action delete_selected to be the last option in the drop-down list
I would like to display the delete_selected action in the drop-down list in the admin screen as the last option just for one model. -
Pass argument to Django form
There are several questions on stackoverflow related to this topic but none of them explains whats happening neither provides working solution. I need to pass user's first name as an argument to Django ModelForm when rendering template with this form. I have some basic form: class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.first_name = ??? super(MyForm, self).__init__(*args, **kwargs) class Meta: model = MyModel fields = [***other fields***, 'first_name'] Here's my sample class-based view: class SomeClassBasedView(View): def get(self, request): some_value = 'foo' user_first_name = request.user.first_name form = MyForm(???) return render(request, 'my_template.html', {'form': form}) What do I pass to MyForm when initialising it and how do I access this value inside the __init__ method? I want to use 'first_name' value as a placeholder for one of the fields in template by updating self.fields[***].widget.attrs.update({'placeholder': self.first_name}). -
The size of checkbox django is very huge
I am creating a checkbox for subscribing using forms.py in Django. The size of the checkbox is very huge I don't why. Models.py: receive_notification = models.BooleanField('Receivenotification',default=True) Forms.py: receive_notification = forms.BooleanField(required=False) The CSS file: h8 { width: 320px; padding-left: 20px; margin-top: 710px; position: absolute; } The HTML file: <h8> {{ field.label }} {{ field }} </h8> -
custom field value forgets values
Apologies for a long complicated question. I've done my best to make it concise and easy to understand, but still, I think it will require some deep Django knowledge to answer. I'm trying to create a custom field type which stores my Lifts class. Here is the class that I want stored: class Series(object): """Series is a list of AbstractSerie objects""" def __init__(self, series, serie_class): self.series = [] for serie in series: if type(serie) != serie_class: raise TypeError("List passed to constructor should only contain "+serie_class.__name__+" objects.") self.series.append(serie) class Lifts(Series): def __init__(self, series): """ Series is a list of LiftSeries """ super().__init__(series, LiftSerie) And here is the LiftSerie class and its parent AbstractSerie that are stored in a Lifts object: class AbstractSerie(object): def __init__(self, activity): """activity is an Activity""" self.activity_name = activity.name def pre_json(self): """ A function that returns a dict version of the serie. Should be implemented in subclasses. """ raise NotImplementedError class LiftSerie(AbstractSerie): """Represents a lift and the number of reps and weight for each set of it.""" def __init__(self, lift_activity, setlist): """ lift should be an instance of LiftActivity. setlist is a list containing (weight, reps) for each set that has been performed. """ if not (isinstance(setlist, collections.Sequence) … -
NoReverseMatch at /judge/judge-timeslot.html Reverse for 'sub' with arguments '('',)' not found
Running Django 2.0.1. Getting the following error: NoReverseMatch at /judge/judge-timeslot.html Reverse for 'sub' with arguments '('',)' not found. 1 pattern(s) tried: ['judge\/(?P[0-9]+)$'] Request Method: GET Django Version: 2.0.1 Exception Type: NoReverseMatch urls.py: from django.urls import path from django.conf.urls import url from . import views app_name = 'judge' urlpatterns = [ path('judge-home.html', views.index, name='index'), path('judge-score.html', views.score, name='score'), path('judge-timeslot.html', views.timeslots, name='timeslots'), path('results.html', views.results, name='results'), path('<int:choice_id>', views.sub, name='sub'), ] sub view in views.py: def sub(request, choice_id): template = loader.get_template("judge/judge-timeslot.html") c = get_object_or_404(Choice, pk=choice_id) try: selected_choice = c.choice_set.getlist(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, template, { 'choice': c, 'error_message': "You didn't select a choice.", }) else: # selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('judge/judge-timeslot.html', args=(c.id,))) Here is the judge-timeslot.html: <form action="{% url 'judge:sub' choice.id %}" method="post"> {% csrf_token %} <table class="table table--bordered table--highlight"> <tbody> {% for slot in slots %} <tr> <td> <label class="checkbox"> <input type="checkbox", name="choice" id="choice {{forloop.counter}}" value="{{choice.id}}"/> <span class="checkbox__input"></span> </label> </td> <td>{{slot}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> <button class="btn btn--primary">Select</button> </form> It is referring to this line: … -
Non-overlapping constraint on Django postgres IntegerRangeField
I found that Django has support for Postgres' range fields and also found that in Postgres, we can have non-overlapping constraint (exclusion constraint) as described here at section 8.17.10. Can anyone tell me how can I apply this constraint in Django in Field iteself not in migration file. I am using django 1.8 and postgres 9.4 Your help will be highly appreciated.