Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My database already have 20 row but when i save new row they start with id from 1
Curently, I import data to my database table with 20 rows already When I use save() method to that table they start saved data with pk=1 lead to Error And they come true when pk=21 Can anyone help me with this although id column in my model is default I dont overwrite it -
django create client user
I try to call create a client user so i have toc call create_client method from the client model to create a client user, I can create superuser but I don't know how to create client user I really don't understand how it works if someone can explain to me and I will be thankful view.py : def signup(request): form = RegisterForm(request.POST or None) if form.is_valid(): form.save() return render(request, 'accounts/signup.html', {'form': form}) form.py class UserAdminCreationForm(forms.ModelForm): """ A form for creating new users. Includes all the required fields, plus a repeated password. """ password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email','full_name') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserAdminCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ password = ReadOnlyPasswordHashField() class Meta: model = User fields = ('email','full_name','password', 'active', 'admin') def … -
Sum aggregated value django ORM
I have a very simple database with two classes: class Contact(models.Model): nombre = models.CharField(max_length=50) class Address(models.Model): contact = models.ForeignKey(Contact, on_delete=models.PROTECT, related_name='addresses') quantity = models.FloatField() What I am trying to achieve is to get the sum of quantity grouping by the number of addresses for each contact, so I get the sum of quantity for all contacts that have 0 addresses, the sum of quantity for all contacts that have 1 address and so on. This is what I have tried so far: Contacto.objects.all() \ .annotate(num_contact=Count('nombre')) \ .values('num_contact','addresses__quantity') \ .annotate(sum_quantity=Sum('addresses__quantity')) but no luck, I'm not even sure I can do it with ORM -
Django OnToOne key to parent class given invalid name
My Django 2.2 model (trimmed to include only what I believe are the relevant sections) is as follows: class DataSet(models.Model): name = models.CharField(..) ::: class Meta: abstract = False class SurveyRunDataSet(DataSet): status = models.CharField(..) ::: class Meta: app_label = 'dataset' class RestrictedDataSet(SurveyRunDataSet): date_start = models.DateField(null=True) date_end = models.DateField(null=True) ::: # Spoonfeed DJango with parent link # parent_link = models.OneToOneField('SurveyRunDataSet', parent_link=True, db_column='dataset_ptr'), class Meta: app_label = 'dataset' After clearing all migration files and running "django-admin makemigrations", the relevant classes in the 0001_initial.py file are as follows: operations = [ migrations.CreateModel( name='DataSet', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(..)), ::: ], options={ 'abstract': False, }, ), migrations.CreateModel( name='SurveyRunDataSet', fields=[ ('dataset_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='dataset.DataSet')), ('status', models.CharField(..)), ::: ], bases=('dataset.dataset',), ), migrations.CreateModel( name='RestrictedDataSet', fields=[ ('surveyrundataset_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='dataset.SurveyRunDataSet')), ('date_start', models.DateField(null=True)), ('date_end', models.DateField(null=True)), ::: ], bases=('dataset.surveyrundataset',), ), But when I then run "django-admin migrate", it fails with the error : FieldError: Cannot resolve keyword 'surveyrundataset_ptr' into field. Choices are: dataset_ptr, dataset_ptr_id, datasets, flush_date, id, name, primary_dataset, report, report_id, source_data_set where these field names list all those included in the classes DataSet and SurveyRunDataSet (some omitted above for brevity). I understand Django creates a OneToOneField automatically, and for this … -
JWT access tokens: How to continually regenerate?
As I understand it, a new access token should be generated every time the user makes an API call. My question is about how exactly that access token should be generated. I have an endpoint to do that: api/token/refresh/. Does this mean: a) After every regular API call I make, I make a second call to that endpoint? (Doubling the number of API calls from what it would be without authentication) b) Use one API call (the regular one) and have Python make the second call from Django. Then send back the new access token within the response? c) Other? I am using: Vue.js, Django Rest Framework, and djangorestframework_simplejwt. -
Table doesn't exist after deleting database in Django
I wanted Django database to be rebuilt from scratch and did the following : delete migrations from my apps delete db.sqlite3 from my project folder dropped database create database Now when I try to run makemigrations, I got an error : MySQLdb._exceptions.ProgrammingError: (1146, "Table 'my_db.my_table' doesn't exist") How do I let django know i want to make a brand new database ? -
Django - Ajax call outputting nothing
In my project, I use AJAX to return a message to the user if a form is invalid without them having to refresh their page. I make the AJAX call however the outcome is not what is expected: HTML FORM: <div id="testDiv"> </div> AJAX: $('#signupForm input[type=text]').keyup(function() { var usernameField = $('#usernameField').val(); // Retrieved from SignUpForm in forms.py, and has id of usernameField var emailField = $('#emailField').val(); // Retrieved from SignUpForm in forms.py, and has id of emailField var passwordField = $('#passwordField').val(); // Retrieved from SignUpForm in forms.py, and has id of passwordField var confirmPasswordField = $('confirmPasswordField').val(); // Retrieved from SignUpForm in forms.py, and has id of confirmPasswordField $.ajax({ url: '/users/signupval/', data: { 'usernameField': usernameField, 'emailField': emailField, 'passwordField': passwordField, 'confirmPasswordField': confirmPasswordField, }, dataType: 'json', success: function(data) { $('#testDiv').text(data['message']); console.log("Worked!") }, error: function(err) { console.log(err) } }) }) views.py: def signupval(request): form = SignUpForm(request.GET) if form.is_valid(): usernameField = form.cleaned_data.get('usernameField') emailField = form.cleaned_data.get('emailField') passwordField = form.cleaned_data.get('passwordField') confirmPasswordField = form.cleaned_data.get('confirmPasswordField') if len(usernameField) > 7: return JsonResponse({'message': 'Username field > 7'}) elif len(emailField) > 5: return JsonResponse({'message': 'Email field > 7'}) elif len(passwordField) > 6: return JsonResponse({'message': 'Password field > 7'}) elif len(confirmPasswordField) > 6: return JsonResponse({'message': 'Password field > 7'}) else: return JsonResponse({'error': 'Something … -
Accessing dictionary keyed by object in django template
I am trying to access dict values in my django template. The dict keys are objects. Here is a snippet of my codebase: models.py class ProductCategory(models.Mode): name = models.CharField(max_length=64, blank=False, null=False, unique=True) slug = models.SlugField(blank=False, null=False, unique=True) class Product(models.Model): category = models.ForeignKey(ProductCategory, on_delete = models.CASCADE) # other fields pass def __str__(self): return self.title views.py def index(request): products = Product.objects.all() categorized_products = {} for p in products: prod_category = p.category temp = categorized_products.get(prod_category,[]) temp.append(p) categorized_products[prod_category] = temp context = {'products_dict': categorized_products, 'categories': categorized_products.keys() } return render(request,'product/index.html', context=context) mytemplate.html (relevant snippet) <div class="tab-content"> {% for category in categories %} {% if not forloop.counter0 %} <div class="tab-pane fade in active" id="{{ category.slug }}"> {% else %} <div class="tab-pane fade in" id="{{ category.slug }}"> {% endif %} <div > <h4>{{ category.description }}</h4> <div class="container-fluid"> <div class="row"> <div class="col-md-3" style="border:1px solid red;"> {% for product in products_dict.category %} {{ product }} {% endfor %} When I step through the code with a debugger, I can see that the variable products_dict is a dict and correctly populated by the view. However, when I run the code, the for loop code is not executed. Similarly, when I run the same code I have in views.py in the … -
Pipfile.lock (d67565) out of date, updating to (4f9dd2)
Can somoene explain why i get this error Pipfile.lock (d67565) out of date, updating to (4f9dd2)…when i try to install packages using pipenv .Altoough i have used pipenv install enter image description here -
Can't insert data to the model from a CSV file upload in Django
After I click submit nothing happens, I think because it can't import Mobile from .models so that the from .models import Mobile from forms.py is unused. How to import it so that I can upload a CSV file successfully and insert the data to Mobile model. forms.py looks like this import io import csv from django import forms from .models import Mobile class DataForm(forms.Form): data_file = forms.FileField() def clean_data_file(self): f = self.cleaned_data['data_file'] if f: ext = f.name.split('.')[-1] if ext != 'csv': raise forms.ValidationError('File Type not supported') return f def process_data(self): f = io.TextIOWrapper(self.cleaned_data['data_file'].file) Mobile = csv.DictReader(f) for i in Mobile: Mobile.objects.create_data(i['mobile_owner'], i['mobile_number']) views.py looks like this: from .models import Mobile from django.views.generic import TemplateView from .forms import DataForm from django.views.generic import FormView class DataView(FormView): template_name = 'sms/mobile.html' form_class = DataForm success_url = '/upload/' def form_valid(self, form): form.process.data() return super().form_valid(form) mobile.html looks like this {% extends 'base/base.html' %} {% block title %}Add SMS Data{% endblock title %} {% block scripts %} {% endblock scripts %} {% block content %} <form action="{% url 'mobile' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label>Upload mobile numbers</label> <input type="file" name="data_file"> <input type="submit" value="submit"> </form> {% endblock content %} urls.py looks like this: from django.urls import path, … -
Key value map between django microservices
I am working on microservice architecture and I need to create a common key value map where I can add key value pairs from 1 service and consume it in another. How can I do this? Is there any package that can already do this? -
Why can't I use @staticmethod here?
I'm using django-fsm to implement a state machine. The code looks like def user_ok_to_check_me( instance, user): ... class Job( models.Model): # ... many screenfulls of code @transition( field=state, target=BOOKING, source=CHECKING, permission=user_ok_to_check_me) def fail_checking(self, **kwargs): ... and it's working. Code readability is impaired by having that little utility function outside the class it belongs with, so I tried class Job( models.Model): # ... many screenfulls of code @staticmethod def user_ok_to_check_me( instance, user): ... @transition( field=state, target=BOOKING, source=CHECKING, permission=user_ok_to_check_me) def fail_checking(self, **kwargs): which does not work. Not sure what user_ok_to_check_me does now do, it behaves like a no-op function always returning True even when all it does is return False Why? And is there any way to declare this little function inside the class? (It's just a little bit too long to use lambda instance, user: ) -
Django - libssl.1.1.dylib library not loading error - Why is this occuring?
I am trying to migrate my changes in my existing Django project to mysql database using command python3 manage.py migrate. I transferred to a new MacBook with Catalina OS and installed everything from scatch. When I try to run the command I keep on getting this error trace stack: Traceback (most recent call last): File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: libssl.1.1.dylib Referenced from: /Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, … -
MultiValueDictKeyError at / 'username' - login at mainpage
I'm making a simple homepage with a login system, which redirects user to another page if he's authenticated. I found a tutorial with custom possibility to make a login view but it shows me the above mentioned error. from django.shortcuts import render, redirect, reverse from django.contrib.auth import logout, login, authenticate def main(request): if request.user.is_authenticated: return redirect(reverse('game')) logout(request) username = password = '' if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) redirect(reverse('game')) return render(request, 'game/main.html') -
Unable to create a custom admin template url, getting errors Template errors & creating custom admin site errors
I am using this blog: https://medium.com/@adriennedomingus/adding-custom-views-or-templates-to-django-admin-740640cc6d42 Unable to make a custom template view in the Django Admin. I am getting django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet If I comment out the app in the settings.py, I get error admin.site.register(Template, TemplateAdmin) NameError: name 'Template' is not defined. Unable to do: 1) custom_admin_site.register & 2) models.Template is not found. Says there is no Template in models. I have this on admin.py: from django.contrib import admin from django.db import models class TemplateAdmin(admin.ModelAdmin): change_form_template = ‘admin/test_attempt.html’ admin.site.register(Template, TemplateAdmin) # Even the following doesnot work custom_site_admin.register(Template, TemplateAdmin) I have this on views.py: from django.shortcuts import render from django.http import HttpResponse from django.template import loader def preview(self, request, object_id): context = {} load_template = request.path.split('/')[-1] context = { **self.each_context(request), 'title': self.index_title, # Unable to get this app_list as well # 'app_list': app_list, } request.current_app = self.name template = loader.get_template('admin/' + load_template) return HttpResponse(template.render(context, request)) I have this on urls.py: from .views import preview class CustomAdminSite(admin.AdminSite): def get_urls(self): urls = super(CustomAdminSite, self).get_urls() custom_urls = [ path(r’^admin/test/(?P<object_id>\d+)$’, self.admin_view(preview), name=”preview”), ] return urls + custom_urls I have this on my apps.py: class CustomAdminSiteConfig(AdminConfig): default_site = 'batchexits.admin.CustomAdminSite' I have added this in my settings.py registered apps: 'batchexits.admin.CustomAdminSiteConfig', I have read this: … -
Django distinct method
I have this query in my views.py me = StudentsCoreValuesDescription.objects.filter(grading_Period = coreperiod)\ .values('id','Marking','Students_Enrollment_Records').distinct('Students_Enrollment_Records') .order_by('Students_Enrollment_Records') this is the result I just want that for every selection box, the display must be different ID's, To understand more, Please take a look to my admin site, and check the ID, the ID must be unique in the selection Box and the same as the admin site, to function properly when I update the data its looks like it only loop the result of distinct Student name this is my html {% for students in me %} <tr> <td colspan="4" class="names"><input type="hidden" value="{{students.id}}" name="student">{{students.Students_Enrollment_Records}}</td> <td colspan="2"> <select name="marking" > <option value="{{students.Marking.id}}" >{{students.id}}</option> {% for m in marking %} <option value="{{m.Marking}}" >{{m.Marking}}</option> {% endfor %} </select> </td> <td colspan="2"> <select name="marking"> <option value="{{students.Marking.id}}" >{{students.id}}</option> {% for m in marking %} <option value="{{m.Marking}}">{{m.Marking}}</option> {% endfor %} </select> </td> <td colspan="2"> <select name="marking"> <option value="{{students.Marking.id}}" >{{students.id}}</option> {% for m in marking %} <option value="{{m.Marking}}">{{m.Marking}}</option> {% endfor %} </select> </td> <td colspan="2"> <select name="marking"> <option value="{{students.Marking.id}}" >{{students.id}}</option> {% for m in marking %} <option value="{{m.Marking}}">{{m.Marking}}</option> {% endfor %} </select> </td> <td colspan="2"> <select name="marking"> <option value="{{students.Marking.id}}" >{{students.id}}</option> {% for m in marking %} <option value="{{m.Marking}}">{{m.Marking}}</option> {% endfor %} … -
"detail": "Method \"POST\" not allowed."
here i tried with custom user login in djangorestfulapi but i am getting error that "detail": "Method \"POST\" not allowed." . can anybody please explain where i am getting wrong? class LoginAPIView(APIView): def user_login(self,request,format=None): # context = RequestContext(request) if request.method == 'POST': user = ''' SELECT * FROM users ''' # Gather the username and password provided by the user. username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) print("auth",str(authenticate(username=username, password=password))) if user: # Is the account active? It could have been disabled. if user.is_active: login(request, user) return HttpResponseRedirect('/') else: return HttpResponse("xxx") else: # Bad login details were provided. So we can't log the user in. print ("Invalid login details: {0}, {1}".format(username, password)) return HttpResponse("Invalid login details supplied.") -
Django Makemigrations returns ModuleNotFoundError: with module name suffixed by 'django'
I've been following the Python Crash Course 2e tutorial. I encountered a problem with makemigrations function from Django chapter(18). I created first app using startapp, and then tried to call makemigrations. It returns ModuleNotFoundError but it gives an app name suffixed by 'django'. What I did was: python -m venv ll_env ll_env\Scripts\activate pip install django (installed asgiref-3.2.3 django-3.0.3 pytz-2019.3 sqlparse-0.3.1) django-admin startproject learning_log . python manage.py migrate python manage.py runserver This part runs smoothly, webserver works, everything is great. Then I opened another terminal(on project level), and typed: ll_env\Scripts\activate python manage.py startapp learning_logs <edited settings.py to include 'learning_logs'> python manage.py makemigrations learning_logs As a result makemigrations returns this traceback: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Admin\PycharmProjects\djangoproj\ll_env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Admin\PycharmProjects\djangoproj\ll_env\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\Admin\PycharmProjects\djangoproj\ll_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Admin\PycharmProjects\djangoproj\ll_env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Admin\PycharmProjects\djangoproj\ll_env\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen … -
Migration from version 1.8 to 2.2 css is ruined
""" Django settings for Train project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import django.conf.global_settings as DEFAULT_SETTINGS import os from .config import * from django.contrib.messages import constants as message_constants import smtplib BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) admins = [('TRAIN', 'Train@gmail.com')] email_use_tls = True email_host = 'smtp.gmail.com' email_port = 587 email_host_user = 'Train@gmail.com' email_host_password = '*****' default_from_email = email_host_user database_name = '******' database_user = '<DATABASE_USER>' database_pass = '<DATABASE_PASS>' database_host = 'localhost' database_port = '' static_root = '<STATIC_PATH>' media_root = 'mediafiles' # the path where all the uploaded files are stored allowed_hosts = ['localhost', '127.0.0.1', 'train.com', '10.103.10.217'] debug = True search_engine = 'solr' email_cronjob = False db_index_cronjob = True db_workers = 4 MEDIA_ROOT = 'mediafiles' MEDIA_URL = '/mediafiles/' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '******************************' PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__)) SITE_ROOT = os.path.dirname(PROJECT_ROOT) FILE_UPLOAD_TEMP_DIR = os.path.join(MEDIA_ROOT, 'temp') # directory for holding temporary files (database files for upload) # print('FILE_UPLOAD_TEMP_DIR: ' + FILE_UPLOAD_TEMP_DIR) SITE_ID = 1 # SECURITY WARNING: don't run with debug turned on in … -
What's the best database model for product with different sizes and quantity
I have got a table with products that are supposed to have different sizes (S,M,L,XL) and I wanted to have a quantity for every size. Lets say that a have a bike with different frame sizes, and there's a quantity for each size. What would be the best model to get this to work? I am planning to lower the quantity(-1), when the bike is added to the basket. Here's what I currently got in my Models: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) category = models.ManyToManyField(Category, blank=True) image = models.ImageField(upload_to='bikes') brand = models.ManyToManyField(Brand) -
Django Social auth add new oauth2 user to a group
I have successfully setup oauth2 for Google using the social auth from the website below. https://python-social-auth.readthedocs.io/en/latest/configuration/django.html The system creates a user in the User database visible from admin console. What i am unable to do is add the newly authenticated user to a group called "Guardians". I know this code will do the job but not sure which module to add it in. from django.contrib.auth.models import Group, User user.groups.add(Group.objects.get(name='Guardians')) Please help -
How do you pre-populate a Django form from a model
I have a Django form that is is generated from a model model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) telephone = models.CharField(max_length=15, blank=True) email_address = models.CharField(max_length=30, blank=True) date_of_birth = models.DateField(null=True, blank=True) How can I pre-populate the form when I select user? -
Dynamically filter queryset ModelMultipleChoiceField
I have a ModelMultipleChoiceField named questions which needs a dynamically created queryset. For doing this I would expect to first pass queryset=None then update it in the __init__ method but this returns: AttributeError: 'NoneType' object has no attribute 'count' Forms.py: class BaseQuizCreateForm(forms.ModelForm): title = forms.CharField() receiver = forms.ModelMultipleChoiceField( queryset=None, required=True, widget=forms.CheckboxSelectMultiple,) questions = forms.ModelMultipleChoiceField( queryset=None, # AttributeError 'NoneType' object has no attribute 'count' required=False, widget=forms.CheckboxSelectMultiple,) def __init__(self, *args, **kwargs): self.company = (kwargs.pop('company', None)) super(BaseQuizCreateForm, self).__init__(*args, **kwargs) self.fields['receiver'].queryset = EmployeeType.objects.filter(company=self.company) if self.instance.pk: self.fields['questions'].initial = self.instance.question_set.filter(category=2).select_subclasses() # I need this dynamically created Forms.py which does not filter: class BaseQuizCreateForm(forms.ModelForm): title = forms.CharField() receiver = forms.ModelMultipleChoiceField( queryset=None, required=True, widget=forms.CheckboxSelectMultiple,) questions = forms.ModelMultipleChoiceField( queryset=Question.objects.all().select_subclasses(), required=False, widget=forms.CheckboxSelectMultiple,) def __init__(self, *args, **kwargs): self.company = (kwargs.pop('company', None)) super(BaseQuizCreateForm, self).__init__(*args, **kwargs) self.fields['receiver'].queryset = EmployeeType.objects.filter(company=self.company) if self.instance.pk: self.fields['questions'].initial = self.instance.question_set.filter(category=2).select_subclasses() # I need this dynamically created -
Django sort form fields from two models
I have extended the Django user model with some extra fields models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) telephone = models.CharField(max_length=15, blank=True) email_address = models.CharField(max_length=30, blank=True) date_of_birth = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('telephone', 'email_address', 'date_of_birth') widgets = { 'date_of_birth': forms.DateInput(attrs={'type': 'date'}), } views.py def response_form(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): profile, created = Profile.objects.get_or_create(user=request.user) user_form.save() profile_form.save() messages.success(request, ('Your profile was successfully updated!')) date_of_birth = profile_form.cleaned_data['date_of_birth'] user = profile_form.cleaned_data['user'] context = { 'user': user, 'date_of_birth': date_of_birth } template = loader.get_template('thank_you.html') return HttpResponse(template.render(context, request)) else: messages.error(request, ('Please correct the error below.')) else: user_form = UserForm() profile_form = ProfileForm() return render(request, 'response_form.html', {'user_form': user_form, 'profile_form': profile_form}) When the template is loaded it places the user fields above the profile fields. How can I place the User dropbox above the First name field? -
Django, models form Not saving data in database
I am new to django, I created a form to save Data into my database but it not working corectly, I got no error but data is not sent in database. Thanks for helping! views.py @login_required() def data(request): if request.POST == "POST": form = CreatePost(request.POST) if form.is_valid(): form.instance.author = request.user form.save() return redirect(data) else: form = CreatePost() context = { "form": form } return render(request, "sms/data.html", context) forms.py class CreatePost(forms.ModelForm): class Meta: model = Post fields = ["title", "content"] models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title