Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Facing issue with custom user authentication and oauth2 in django
I am making an application which has protected API and only an authenticated users should have access to it. To make use of the django's powerful authentication, I decided to extend its User model with some extra fields and customised. I am using the custom user model by extending AbstractUser Model. But Facing below issue while requesting the oauth2 token. Below is my code: class MyUser(AbstractUser): """Extended version of Django User Model""" is_email_verified = models.BooleanField( verbose_name="Email Verified?", default=False, choices=T_N_F_CHOICES, auto_created=True, help_text="This flag indicates if the email address is authentic and validated" ) mobile = PhoneNumberField( verbose_name="Phone Number", blank=True, null=True, unique=True ) is_mobile_verified = models.BooleanField( verbose_name="Mobile Verified?", default=False, choices=T_N_F_CHOICES, auto_created=True, help_text="This flag indicates if the mobile number is authentic and validated" ) profile_pic = models.ImageField( verbose_name="Profile Picture", upload_to=settings.UPLOAD_DIR, height_field=None, width_field=None, max_length=None, blank=True, null=True ) USERNAME_FIELD = "email" REQUIRED_FIELDS = ['mobile'] objects = CustomUserManager() def __str__(self): return self.email class Meta: managed = True db_table = "MyUser" verbose_name = "MyUser" verbose_name_plural = "MyUsers" settings.py ... AUTH_USER_MODEL = 'users.AlphaslateUser' CORS_ORIGIN_ALLOW_ALL = True ... INSTALLED_APPS = [ ... 'oauth2_provider', 'corsheaders', 'countries_plus', 'rest_framework', 'users', ] ... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ] } ... AUTHENTICATION_BACKENDS = ( 'oauth2_provider.backends.OAuth2Backend', 'django.contrib.auth.backends.ModelBackend' ) ... MIDDLEWARE = [ ... … -
django makemigrations doesn't recognize new model
I created a new model with manage.py startapp supplier edited some stuff in the views, url and models. Now I execute python manage.py makemigrations but django doesn't recognize my new model "No changes detected" it says -
Django: how to create a ChoiceField/html Select element without a name?
I currently have a Django form that creates an html <Select> element for me:- class RegionSelectionForm(forms.Form): lstAll = [('', '(ALL)')] lstChoices = lstAll + list(region.objects.values_list('code', 'name').order_by('name')) RegionSelection=forms.ChoiceField(choices=lstChoices, widget=forms.Select(attrs={'class': 'form-control searchfields'}), required=False, label="") This gets passed via a view to a template that allows the user to select a constituency from another <select> element. The sole purpose of the RegionSelectionForm is to apply a region filter to the other <Select> using JavaScript and enable the user to more easily find what they want. It never gets used in a submit to specify GET request parameters. Yet it appears in the URL:- https://mydummysite.co.uk/test_map/?!!!!RegionSelection!!!!=&displayfind=Random&find=0&findtype=&maptype=normal I like using Python in the forms file to play with the data, tweak the options etc. It's a lot easier (for me) than using Django template tags in the actual template and iterate through it using a {% for ... %} loop and feels like a better place to put it. And it works fine. But I'm going to end up with quite a busy template with users being able to request various things and I want to generate GET requests that aren't cluttered with unused parameters. I want to lose the name="RegionSelection" attribute of the <select> element … -
Many items in requirements file for Heroku
I finished the Django tutorial yesterday and I wanted to put it on Heroku for fun. My requirements file has many files listed: alembic==0.9.3.dev0 apturl==0.5.2 asgiref==3.2.5 asn1crypto==0.24.0 Babel==2.4.0 blinker==1.4 Brlapi==0.6.6 certifi==2018.1.18 chardet==3.0.4 click==6.7 colorama==0.3.7 command-not-found==0.3 cryptography==2.1.4 cupshelpers==1.0 defer==1.0.6 distro-info===0.18ubuntu0.18.04.1 dj-database-url==0.5.0 Django==3.0.4 Flask==0.12.2 Flask-BabelEx==0.9.3 Flask-Compress==1.4.0 Flask-Gravatar==0.4.2 Flask-Login==0.4.0 Flask-Mail==0.9.1 Flask-Migrate==2.1.1 Flask-Paranoid==0.2.0 Flask-Principal==0.4.0 Flask-Security==1.7.5 Flask-SQLAlchemy==2.1 Flask-WTF==0.14.2 gunicorn==20.0.4 httplib2==0.9.2 idna==2.6 itsdangerous==0.24 Jinja2==2.10 keyring==10.6.0 keyrings.alt==3.0 language-selector==0.1 launchpadlib==1.10.6 lazr.restfulclient==0.13.5 lazr.uri==1.0.3 louis==3.5.0 macaroonbakery==1.1.3 Mako==1.0.7 MarkupSafe==1.0 netifaces==0.10.4 oauth==1.0.1 olefile==0.45.1 paramiko==2.0.0 passlib==1.7.1 pexpect==4.2.1 Pillow==5.1.0 protobuf==3.0.0 psutil==5.4.2 psycopg2==2.8.4 pyasn1==0.4.2 pycairo==1.16.2 pycrypto==2.6.1 pycups==1.9.73 pygobject==3.26.1 pyinotify==0.9.6 pymacaroons==0.13.0 PyNaCl==1.1.2 pyOpenSSL==17.5.0 pyRFC3339==1.0 python-apt==1.6.5+ubuntu0.2 python-dateutil==2.6.1 python-debian==0.1.32 pytz==2019.3 pyxdg==0.25 PyYAML==3.12 reportlab==3.4.0 requests==2.18.4 requests-unixsocket==0.1.5 SecretStorage==2.3.1 simplejson==3.13.2 six==1.11.0 SQLAlchemy==1.1.11 sqlparse==0.3.1 sshtunnel==0.1.4 system-service==0.3 systemd-python==234 ubuntu-drivers-common==0.0.0 ufw==0.36 unattended-upgrades==0.1 urllib3==1.22 usb-creator==0.3.3 wadllib==1.3.2 Werkzeug==0.16.0 WTForms==2.1 xkit==0.0.0 zope.interface==4.3.2 I don't know where these files came from. I didn't install them directly. I installed Django, postgressql, pgAdmin 4, etc. I didn't specifically install all these packages by name and I don't even know if they are required. It even shows Flask as a requirement but I have never used it. Also, when I try to put the code on heroku with git, alembic doesn't install on heroku because it says it can't find the proper version. -
Django - Image not being displayed in the webpage
In my project, I have a DetailView, so a user can view their profile. On here, I want to display their profile picture. However when I open the browser and go to the detail page, no profile picture is displayed. My code is displayed below. models.py: class User(AbstractUser): profilePic = models.ImageField(upload_to='profile_pics/', default='static/default-profile.png') views.py: class DetailProfile(generic.DetailView): model = User # Template that a users profile picture should be displayed in template_name = 'detail_profile.html' detail_profile.html: <img width="200px" src="{{ user.profilePic.url }}" alt=""> Error returned by the browser: GET http://localhost:8000/media/static/default-profile.png 404 (Not Found) urls.py (for the users apps): urlpatterns = [ path('signup/', views.signup, name='signup'), path('login/', views.login, name='login'), path('resetone/', views.resetone, name='resetone'), path('resetwo/', views.resetwo, name='resetwo'), path('viewprofile/<int:pk>', views.DetailProfile.as_view(), name='detail_profile'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) SETTINGS.PY: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'proj2/static/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Currently, all the users have the file default-profile.png assigned to their profile pic, however later I am going to implement the ability for users to change their profile pic. default-profile.png is stored in the static folder(Check my settings.py code above), and is also assigned to a user when they first signup. Does anybody know why this file isn't being … -
Django Signals.py. How to combine receiver's and initiate function in a new thread
which is the best way to combine Django receiver's from signals.py and initiate a function in a new thread. Example with post_delete and post_save : from django.db.models.signals import post_delete, post_save from django.dispatch import receiver @receiver(post_delete, sender=Application) def test_delete_function(sender, instance, **kwargs): if isinstance(instance, Application): deletefunc() @receiver(post_save, sender=Application) def test_save_function(sender, instance, **kwargs): if isinstance(instance, Application): savefunc() So, Q1: Is this a good way to express different receiver types - @receiver and then functions after that? Q2: When saving Application from the fronend with POST, test_save_function is initiated in the same thread. How to run test_save_function on a different thread? - I expected this to be handled by Django Framework, but it seems I need additional configuration? Thanks! -
How can i find my root user on Hostgator server?
i am a newbie. im learning python and i recently bought a server from hostgator in order to publish a site i deveoped in django and viewed it on localhost until now. when i bought the server from them i recived an email with username and password. i ssh'd through Putty to connect to the server but i found out i can't use sudo command. when i tried to use it... "sudo: effective uid is not 0, is sudo installed setuid root?" is all i get. i looked everywhere for an answer but i couldn't find Thank's for anyone who can help! -
Output print statement from external python script to Django website
I have a django site which accepts a user input (ip address) and have that user input to run in an external python script which scans the open ports. I already have it output like this from my external python script: ip: 10.10.10.10 portsOpen: [21, 80] I want it to have the output to the django site. My views.py: from django.shortcuts import render, render_to_response from subprocess import run,PIPE import requests import sys from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse # Create your views here. def index(request): return render_to_response('index.html') @csrf_exempt def external(request): inp=request.POST.get('param') out=run([sys.executable, 'D://Desktop//quanta//Quanta//testerfordjango.py',inp], shell=False) print(out) return render(request, 'index.html',{'data1':out.stdout}) The only output i get from the django site after the script has finished running is None I have tried using this but it seems not to work: return HttpResponse(out) -
get_user_model doesn't return a value
as my first project in Django I am creating a todo app, that lets people log in and see their own tasks that they created. For that, I need to save author info in single task data. From what I learned reading the documentation and doing lots of google-searching, the current approach is to use the get_user_model function from django.contrib.auth. The problem is, that whenever I try to use it in my model, it seems to not get the username from the currently logged in user. While printing the form.errors to my console, the output is: <ul class="errorlist"><li>added_by<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Seems like the get_user_model is not returning any value. Can anyone recommend a better approach for me to do that? Or is there something obvious that I missed? Here are the code snippets: models.py from django.db import models from django.contrib.auth import get_user_model class Task(models.Model): title = models.CharField(max_length=35) completed = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.title forms.py from django import forms from .models import * class TaskForm(forms.ModelForm): class Meta: model = Task fields = '__all__' widgets = { 'title': forms.TextInput(attrs={'class': 'new_task_text', 'placeholder': 'Add new task'}), } views.py @login_required def list_homepage(request): tasks = Task.objects.all() … -
How to set path of multiple custom apps in django?
Can anyone please help me with this. MyProject is the name of my project in django with two different apps HappyHomes and HappyHomesAdmin. I want to switch from HappyHomesto HappyHomesAdmin. How to set path in urls file? How many files in total I will need? And also how to set path of moving to different app in views.py file in django. I am here C:/Users/MaitRi/Desktop/PROJECT/MyProject/HappyHomes/templates/reg.html and want to move at C:/Users/MaitRi/Desktop/PROJECT/MyProject/HappyHomesAdmin/templates/home.html -
Django CreateView Object could not be created because the data didn't validate
Good day. I'm trying to create a object based on form input, i tesed out the data, everything is provided but, for some reason the form is not validated. I've also tried overriding form_valid(self,form) but the problem with that method was django never went to it as if it didn't exist. forms.py class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' views.py class CreatePost(CreateView): form_class = CreatePostForm template_name = 'dashboard/add-product.html' # success_url = redirect('user_posts:post_detail') def post(self, request, *args, **kwargs): form = CreatePostForm(request.POST) if self.form_valid(form): post = form.save(commit=False) post.user = request.user post.save() return redirect('user_posts:post_detail', args=post.slug) print('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA') code in the template is basic form, not gona import it. data that has been passed via request.POST user 'b8a3b0b3-0eef-48ed-b257-a6f9bfdd5cda' title 'theetitle' main_description 'agdgdfg' slug '' main_image 'Bucee_Lee_smile.jpg' subtitle1 '' sub_description1 '' sub_image1 '' subtitle2 '' sub_description2 '' sub_image2 '' subtitle3 '' sub_description3 '' sub_image3 '' total_likes '' traceback points to this line if self.form_valid(form): -
Django how to forward URL named paramters
I'm new to django so i could be asking a dumb question, but how am i supposed to forward URL A's named parameter to URL B? For example: URL A = https://stackoverflow.com/questions?parameter=1 URL B = https://stackoverflow.com/ask What i actually want is: URL B = https://stackoverflow.com/ask?parameter=1 I need to do this because i need to pass those parameters to the view that is being called at the second url, could someone help me? -
How to get post form data using AJAX?
I'm trying to get the data from a post form using AJAX. I'm failing in some point because I can't access to the form's data. template.html <form method="POST" autocomplete="off" action="/index" id="mail_form_id"> {% csrf_token %} <input type="email" name="mail_input" id="mail_input"> <button type="submit" onclick="send_mailform()" ></button> ... views.py ... if request.is_ajax: print(request.POST['mail_input']) #This is not working script.js // I'm avoiding to refresh using this function var form = document.getElementById("mail_form_id"); function handleForm(event) { event.preventDefault(); } form.addEventListener('submit', handleForm); function send_mailform(){ var http = new XMLHttpRequest(); http.open("POST", "/index", true); http.setRequestHeader('X-CSRFToken', getCookie('csrftoken')); var mail_input = document.getElementById('mail_input').value; http.send(mail_input); } ... I've been searching and there are several solutions for django 1.X or using Jquery. I didnt put the getCookie function in scripts.js but it's working properly. I'm triying to avoid Jquery. Thank you in advance! -
Why will a CSRF POST request to 'localhost:8000' be successful, but '127.0.0.1:8000' will fail?
My frontend (React) and backend (Django) are decoupled, runnning on localhost:3000 and 127.0.0.1:8000 respectively. Consider the following frontend request: async function test() { let token = await getCsrfToken() // fetched from other endpoint let url = 'http://localhost:8000/test' let response = await fetch(url, { method: 'POST', headers: { 'X-CSRFToken': token, }, credentials: 'include', }) let response_text = await response.text() return response_text } test() to the following endpoint: def test(request): return HttpResponse('OK') It works fine. But if I change: let url = 'http://localhost:8000/test' to: let url = 'http://127.0.0.1:8000/test' it will fail with: Forbidden (CSRF cookie not set.): /test Per my understanding, localhost and 127.0.0.1 are supposed to be synonymous. Why isn't it so in this context? What confuses me even more is that the Django's development server explicitly runs on 127.0.0.1:8000. Note: I am using django-cors-headers middleware and the following CORS/CSRF settings: CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ['http://localhost:3000'] CSRF_TRUSTED_ORIGINS = ['localhost:3000'] -
Django multiple repeating dropdowns
I am repeating a Django Form dropdown as follow: html <form class="form-group" method="post"> {% csrf_token %} {{ form.X1}} {{ form.X1}} </form> where, model.py class MyModel(models.Model): X1 = models.ForeignKey(otherModel, on_delete=models.CASCADE) form.py class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' When I submit the form, I only see one instance of X1 being returned to my view. I don't see the second X1 value... How can I pass the second X1 as well? -
Django - Data from Views to HTML
Hello I am learning Django and I cannot pass data from model to view. I am trying to make a simple blog for learning purpose, but always when i render view, variable is present if i do an if condition but when i am trying to access that variable - it writes Did you forget to register or load this tag error.. html: {% if posts %} {% posts %} {% else %} without posts {% endif %} models.py: STATUS = ( (0,"Draft"), (1,"Publish") ) class Category(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) active = models.BooleanField(default=False) img = models.ImageField() description = models.TextField() class Meta: ordering = ['-name'] def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') wide_img = models.ImageField() hide_img = models.ImageField() updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) category = models.ForeignKey(Category, on_delete= models.CASCADE) class Meta: ordering = ['-created_on'] def __str__(self): return self.title views.py from blog.models import Post def index(request): posts = Post.objects.filter(status=1).order_by('?')[:3] context = { "posts": "jaj", } template_name="index.html" return render(request, template_name, context) -
Django /Python Program Flow and Structure
I am a new developer and have been learning Python and Django. I'm trying to understand the structure and flow behind the scenes and I'm confused by a line of code that I encountered. Well, I'm actually confused by a number of things but this is one specific example. Can someone help me understand the flow of the following code: from django.contrib import admin from .models import Post admin.site.register(Post) When I search the library files in my virtual environment I find a folder called django and inside that folder I find contrib and inside that folder I find admin. I see that that the init.py file in the admin package has import statements that import in * which I understand to be everything in the various modules that are available. When I go digging through the various modules, I find sites.py and inside sites.py I find a "site" variable that is an object that has been instantiated. Here is the snippet of code from the sites.py module: site = DefaultAdminSite() Ok, here is where I'm confused. Looking back at the original code, where does the "register" function get pulled in. I'm accessing a variable that contains an instantiated object from … -
How to separate the servers for heavy task
I have django web application which has heavy commandline task. like python manage.py my_heavy_task Now I have three servers. One is for webserver ,the second is for command python manage.py my_heavy_task and the last one is for relational database. What is the best practice to separate for two servers??(for Relational database is easy to understand). I have idea to upload whole django framework on each server and one is for web and the other is for command. Is this a silly idea??? or is there any tricks?? I am newbee for django, any helps are welcomed. -
I'm not able create virtual environment using virtualenv
C:\Users\NAVEEN\Desktop\Demo>virtualenv venv Traceback (most recent call last): File "c:\users\naveen\appdata\local\programs\python\python38\lib\runpy.py", line 192, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\naveen\appdata\local\programs\python\python38\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\NAVEEN\AppData\Local\Programs\Python\Python38\Scripts\virtualenv.exe__main__.py", line 4, in File "c:\users\naveen\appdata\local\programs\python\python38\lib\site-packages\virtualenv__init__.py", line 3, in from .run import cli_run File "c:\users\naveen\appdata\local\programs\python\python38\lib\site-packages\virtualenv\run__init__.py", line 12, in from .plugin.activators import ActivationSelector File "c:\users\naveen\appdata\local\programs\python\python38\lib\site-packages\virtualenv\run\plugin\activators.py", line 6, in from .base import ComponentBuilder File "c:\users\naveen\appdata\local\programs\python\python38\lib\site-packages\virtualenv\run\plugin\base.py", line 7, in from importlib.metadata import entry_points ModuleNotFoundError: No module named 'importlib.metadata' -
Django unable to set IntegerField on Serializer
I am not a professional Django user, I will try to described this problem as concise as I can. I have a Django Serializer definition: class PrioritisedMarketActionSerializer(serializers.Serializer): marketaction = MarketActionSerializer(required=True) priority = serializers.IntegerField() My objective is to create a list of these serializers objects, after I received through a POST method a list of MarketAction objects. I declare an empty list where to store these objects: output = [] Then, iterating over the received objects: prioritised_ma["marketaction"] = MarketActionSerializer(ma).data prioritised_ma["priority"] = 1 output.append(PrioritisedMarketActionsSerializer(prioritised_ma_clearing).data) The ["priority"] field was set to 1, {int}, for testing purposes. However, when I call: PrioritisedMarketActionsSerializer(prioritised_ma).data I get this strange error: 'int' object has no attribute 'pk' I assume the error is related to the "priority" field, which is the {int} value, but I can not figure it out. Could someone help me please, or give me a hint towards what am I doing wrong here? I would deeply appreciate it. Thank you very much, I wish you a wonderful day! -
Django: how to make the User registration form create another object too
For a school project, we have to make a food delivery platform using django. In the registration form, I have a checkbox to register yourself as a restaurant owner. If this checkbox is checked, I need it to create not only the User but a Restaurant object as well with the restaurant_name the User entered. How can I accomplish this? Below is the HTML code for my reg form: {% extends 'food_cloud/base.html' %} {% load staticfiles %} {% block title_block %} Register {% endblock %} {% block body_block %} <script type="text/javascript"> function dynInput(cbox) { if (cbox.checked) { var restaurant_name = document.createElement("input"); restaurant_name.type = "text"; restaurant_name.name = "restaurant_name"; var div = document.createElement("div"); div.id = cbox.name; div.innerHTML = "Restaurant name: "; div.appendChild(restaurant_name); document.getElementById("insertinputs").appendChild(div); } else { document.getElementById(cbox.name).remove(); } } </script> <div class="jumbotron p-4"> <div class="container"> <h1 class="jumbotron-heading">Register</h1> </div> </div> <div class="container"> <div class="row"> <div class="form-group" > <form role="form" method="post" action="."> {% csrf_token %} <div class="form-group"> <p class="required"><label class="required" for="id_username"> Username:</label> <input class="form-control" id="id_username" maxlength="30" name="username" type="text" /> <span class="helptext"> Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only. </span> </p> <p class="required"><label class="required" for="id_email"> E-mail:</label> <input class="form-control" id="id_email" name="email_address" type="email" /> </p> <p class="required"><label class="required" for="id_password1"> Password:</label> <input class="form-control" id="id_password1" name="password1" … -
Displaying additional attributes of the standard User on the admin page
To the standard User (Django 2.1.5) imported from django.contrib.auth.models I added an additional attribute: from django.contrib.auth.models import User User.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) class Contact(models.Model): user_from = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rel_from_set') user_to = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rel_to_set') created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return '{} follows {}'.format(self.user_from, self.user_to) Does anyone know how to register this attribute ("following" and "followers") on the admin page so that it is displayed there in the subpage "'http://127.0.0.1:8000/admin/auth/user/< int:id >/" -
Django: test TemplateView based views triggered by url pattern?
Say I have the following url path('clients/by_<str:order>', BrowseClients.as_view(), name='browse_clients') and its corresponding view @method_decorator(login_required, name='dispatch') class BrowseClients(TemplateView): template_name = "console/browse_clients.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['clients'] = Client.objects.filter( owner=self.request.user.id).order_by(self.kwargs["order"]) context['form'] = AddClientForm() return context How can I test what is in the context? class TestBrowseClientsView(TestCase, GeneralViewTest): fixtures = ['users.yaml', 'clients.yaml'] def setUp(self): self.request = RequestFactory().get('/console/clients/by_inscription') self.request.user = User.objects.get(pk=1) def test_return_client_ordered_by_inscription_date(self): view = BrowseClients() view.setup(self.request) context = view.get_context_data() Naively, I thought that view.setup(self.request) would "feed" .get_context_data() with the relevant kwargs based on the pattern found in self.request. But it does not seem to be the case. ====================================================================== ERROR: test_return_client_ordered_by_inscription_date (console.tests.TestBrowseClientsView) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/src/jengu/console/tests.py", line 164, in test_return_client_ordered_by_inscription_date context = view.get_context_data() File "/usr/src/jengu/console/views.py", line 34, in get_context_data owner=self.request.user.id).order_by(self.kwargs["order"]) KeyError: 'order' ---------------------------------------------------------------------- Why is that the case? I managed to fix my problem by passing status and order explicitly but it looks a bit ad hoc: def get_context_data(self, status, order, **kwargs): def test_return_clients_ordered_by_parameter(self): view = BrowseClients() view.setup(self.request) context = view.get_context_data("all", "inscription") Among the different options mentioned here, which one is the more canonical? Am I taking a wrong path, explicitly using variables when defining get_context_data()? -
Django/ i have modal where i can change password users
I have problem when i change password user. How can i add hash password or just password edit? thanks for answers -
Django Formtools Add Formset Dynamically
I am using Django Formtools to create a multistep form for a Job posting process. In one of the forms, I have Job Questions which I want the user to add dynamically, say a checkbox that generates the question form if they are interested in adding questions. They should have a button to create as many questions as possible. Now my challenge is that when I use normal model forms, I am able to complete the job posting process but if i replace the question form with a model formset and include it in the form_list I get key errors. Secondly, if I try the various Javascript responses on adding fields dynamically such as this stack overflow response, I get form validation errors. Just to mention, the question Form uses the same model as the other forms (Job Model) thus my expectation is that regardless of how many questions are added they will be save to the Job Model. Does anyone know how to go about this? Adding fields in Django formtools dynamically and saving to the model? My Form tools wizard looks as below: class JobWizard(SessionWizardView): form_list=[JobForm7,JobForm1,JobForm2,JobForm3, JobForm4,JobForm5,JobForm6 ] file_storage= FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'jobs')) template_name="jobs/jobforms.html" def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, …