Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve the problem of Application labels aren't unique, duplicates: users?
I am trying to makemigrations but it is giving me problem but where are duplicates? settings.py AUTH_USER_MODEL = 'users.User' INSTALLED_APPS = [ 'django.contrib.admin', 'users.apps.UsersConfig', 'firstapp.apps.FirstappConfig', 'crispy_forms', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users' ] admin.py admin.site.register(User) models.py from django.contrib.auth.models import AbstractUser from django import forms class User(AbstractUser): Id_card_number = forms.CharField(max_length=15, required=True) -
Django- Dependent Dropdown Form results in "invalid choice" on POST
I'm using this tutorial: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html to add a dependent dropdown to my form, but when I post the data it comes back form invalid with an invalid choice error. In my form's init override, if I eliminate the dropdown queryset then it works, but that defeats the purpose. My view: def add_have(request, id=None): if request.method == "POST": print("User: {}".format(request.user)) for key, value in request.POST.items(): print('{}: {}'.format(key, value) ) form = HaveForm(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.profile = request.user model_instance.save() else: print(form.errors) print("FORM IS INVALID") return redirect('display_have_list') else: form = HaveForm() return render(request, 'add_have.html', {'form': form}) My form: class HaveForm(forms.ModelForm): class Meta: model = Have fields = ['category', 'item'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category'].queryset=Category.objects.all() self.fields['item'].queryset = Items.objects.none() The error message I'm getting implies that it's not loading the item: web_1 | User: <my_username> web_1 | csrfmiddlewaretoken: <my_token> web_1 | category: 1 web_1 | item: 4496 web_1 | <ul class="errorlist"><li>item<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul> web_1 | FORM IS INVALID web_1 | [31/Jul/2019 09:01:24] "POST /trade/add_have/ HTTP/1.1" 302 0 web_1 | [31/Jul/2019 09:01:24] "GET /trade/display_have_list/ HTTP/1.1" 200 2638 web_1 | [31/Jul/2019 09:01:24] "GET /static/css/styles.css HTTP/1.1" 404 1767 If I elimitante the … -
Is it possible to set up a web app that runs a Python script on a schedule?
I have no experience in web app development, but I want to make a project like the following: My school dorm requires you to make a leave request online on Monday in order to leave the dorm on the weekends. My friends and I always forget to do this. I want to make a web app that basically if the user inputs their information, it would automatically make a leave request every Monday for that user. I have a leave request script written, and I'm sure I can figure out how to make a website and store user data in the database. My question is, is it possible in a Django web app to schedule a script to run once every week? I'm planning on deploying to Heroku, would I have to schedule it in Heroku or Django? If this isn't possible in Django, what would I use in order to go about implementing it? I'm sorry for such a vague question, I'm just not sure where to start and I'm very new to web app development. Any help is appreciated! -
How to create modal signup form in Django?
Home Page Screen Shot Modal Screen Shot I'm fairly new to Django so not sure how to solve my problem. I've created a simple UserCreationForm in a view function to sign up new users. However, I can't seem to display the form in a boostrap modal or in my index.html template. I'm thinking by creating a separate view for the sign up form I need to have a separate template and url path to register new users. I'd like to have the sign up modal on the home page and not direct the user to a separate signup page. {% extends "myapp/base.html" %} {% block navbar %} <li class="nav-item active"> <a class="nav-link" href="#"> Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">Log In</a> </li> <li class="nav-item"> <a class="btn btn-primary nav-item" href="#" role="button" data-toggle="modal" data-target="#myModal"> Sign Up </a> </li> <!-- The Modal --> <div class="modal fade" id="myModal"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Sign Up</h4> <button type="button" class="close" data-dismiss="modal"> &times; </button> </div> <!-- Modal body --> <div class="modal-body"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join today</legend> {{ form.as_p }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </form> <div class="border-top pt-3"> <small … -
How to: Run Django Project in Subpath
Okay, so I'd like to start by saying that I am not running NGINX like many of the other questions I've seen.I'm running Gunicorn alongside Whitenoise. My task is to implement scientific plots in a separate directory of an existing website. My problem is getting the django project to not run in the root directory of the website. I need it to run in a directory like 'example.com/app',so that I can call the plotting application from there as opposed to the main webpage. I tried changing the application urls.py to say 'example.com/app/pretty_plots' and navigating to the page that way, but it fails to load all of the resources. Everything works as expected if I change the web access path of the app to '/' (eliminating the original homepage), and navigating to example.com/pretty_plots, but I'd like to leave the home page intact. FORCE_SCRIPT_NAME = '/app' did not do the trick for me either. URLConf mysite/urls.py from django.contrib import admin from django.urls import path, include import plots.plotly_apps urlpatterns = [ path('admin/', admin.site.urls), path('plots/', include('plots.urls')), path('django_plotly_dash/', include('django_plotly_dash.urls')), ] The above code works from the root, but not anywhere else. I see no options of configuring Whitenoise to run Django from a subpath. The … -
MultichoiceField in ModelForm for Django with DB relations
This is my first post ever on Stackoverflow so please ignore mistakes. Before posting I had tried a dozen solutions bun none worked. I have table relations in models for users. I need to create a ModelForm to let customer select multiple users for any project from the frontend. I am having hard time implementing it in code. Also for another field I need to limit the choice to one user. Following is the code. Models: class Project(models.Model): project_name = models.CharField(max_length=100) project_users = models.ManyToManyField(User) project_team_lead = models.OneToOneField(User, on_delete=models.CASCADE, related_name='lead') def init(self): return str(self.project_name) Form. class ProjectForm(forms.ModelForm) class Meta: fields = ['project_name', 'project_users', 'project_lead'] View: def projects(request): template = 'projects/projects.html' if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): form.save() else: form = ProjectForm() return render(request, template, {'form': form}) HTML: <form action='' method='post'> {% csrf_token %} {{ form }} <button type='submit' class='btn btn-primary'>Submit</button> </form> Some help is highly appreciated. -
Django/Python how to define different required fields for different actions?
I can't figure out the "best" way (or the way with least cons) to do this. For example I have a Realestate model and FlatProfile which has a ForeignKey to the Realestate. There are some actions in the system which can or cannot be done according to filled (not null) fields. For example, to be visible on presentation page, the fields name,seller,flatprofile.rooms_count must be filled. On the other hand, to be in a list of Realestates on brochure, different set of fields has to be filled and this set can contain even related fields like flatprofile.rooms_count. My solution: I define two methods on Realestate model. def can_be_on_presentation(self): lst = ["name","seller","flatprofile__rooms"] for fieldname in lst: # check if the field is not null # if null raise Exception Is there a built in way or some pattern to do such thing? This has many cons like the fields are in string format so static analysis won't show error if there is no such field etc... -
How i can register on Django admin a field for upload of files
I'm trying use a lib boto3 for upload files in django admin, but i dont think i doing this correctly. I'm trying to create a form class, and use it inside admin to upload This my forms.py from django import forms from django.conf import settings from .models import Invoice import boto3 from botocore.exceptions import ClientError class InvoiceForm(forms.ModelForm): file = forms.FileField(label='Arquivo', required=False) class Meta: fields = '__all__' model = Invoice def upload(): s3 = boto3.client('s3') try: s3.upload_fileobj(file, settings.UPLOAD_BUCKET) except ClientError as e: logging.error(e) return False return True And this my admin from .forms import InvoiceForm class InvoicesAdmin(admin.ModelAdmin): search_fields = ['name', 'user'] list_display = ['name', 'user','value', 'installment', 'due_date', 'status', 'file'] exclude = ['updated_by', 'created_by', 'attributes'] autocomplete_fields = ['user'] form = InvoiceForm admin.site.register(models.Invoice, InvoicesAdmin) I don't get an error, but the file is not saved to aws-s3 -
What is the format for strptime() to get datetime objects serialized in DjangoJSONEncoder()?
I didn t manage to get datetime objects from strings generated from dates serialized through DjangoJSONEncoder() The problematic part is the timezone with +HH:MM (as defined in ECMA-262). I don't see the strptime equivalent in http://strftime.org/ I only see %z for "+HHMM" and %Z for time zone name. Code : d = DjangoJSONEncoder().encode(localtime(now())) print(d) # "2019-07-31T16:48:19.665+02:00" import datetime d_no_timezone="2019-07-31T17:04:00.282" datetime.datetime.strptime(d_no_timezone, '%Y-%m-%dT%H:%M:%S.%f') d # "2019-07-31T17:04:00.282+02:00" datetime.datetime.strptime(d, '%Y-%m-%dT%H:%M:%S.%f%z') #ValueError, does not match format datetime.datetime.strptime(d, '%Y-%m-%dT%H:%M:%S.%f%Z') #ValueError, does not match format datetime.datetime.strptime(d, '%Y-%m-%dT%H:%M:%S.%fz') #ValueError, does not match format datetime.datetime.strptime(d, '%Y-%m-%dT%H:%M:%S.%fZ') #ValueError, does not match format PS : using Python 3.6.8 and Django 2.2.3. -
How to point Django app to new DB without dropping the previous DB?
I am working on Django app on branch A with appdb database in settings file. Now I need to work on another branch(B) which has some new DB changes(eg. new columns, etc). The easiest for me is to point branch B to a different DB by changing the settings.py and then apply the migrations. I did the migrations but I am getting error like 1146, Table 'appdb_b.django_site' doesn't exist. So how can I use a different DB for my branchB code without dropping database appdb? -
create a form and model to rate countries
I am new to django and I work on data science project, that require to rate some countries by users , how I can do it ? some thing like that -
My comment system in Django is not working as expected
I'm creating an application where a user can create their own posts, and other users can comment on the posts. I have already tried retrieving comments from the database, and displaying them for that certain post, however this has been unsuccessful Here is my code to tackle this problem: views.py def comment(request, pk): form = CommentForm() comments = Comment.objects.filter(post=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment() comment.body = form.cleaned_data['body'] comment.user = request.user comment.post = Post.objects.get(pk=pk) comment.save() return redirect('home') return render(request, 'posts/comments.html') else: return render(request, 'posts/comments.html', {'error': 'Please submit valid data'}) else: return render(request, 'posts/comments.html', {'form': form}, {'comments': comments}) comments.html {% block content %} <div class="container"> {% for com in comments.all %} <p>{{ com.body }}</p> <br> {% endfor %} {% if error %} {{ error }} <br> <br> {% endif %} <br> <br> <br> <br> <br> <form method="post"> <h2> Comment</h2> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary"> Comment</button> </form> </div> {% endblock %} models.py class Comment(models.Model): body = models.CharField(max_length=130) user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.body This is expected to display a posts comments when a button is pressed to view the post, however the comments do not … -
What the best way to pass in a user-facing attribute and print it in html?
When my errors get caught by is_valid() in django, I print them in html. I'd like to add a friendly user-facing html title that prints along with the error so they know which form is invalid. I thought I could just add a custom attribute and print it, but the only attribute html can print is "name" for some reason. Django abstracts it away, but in this case the "name" attribute in the html object = end_date. I'd just like to print the "friendly" attribute but html prints nothing instead. Here is the form declaration: end_date = forms.DateField(widget=forms.TextInput(attrs={'id':"datepicker", 'autocomplete':"off", 'friendly':"End Date"}), required=True) Here is the un-abstracted html for this object that gets printed on the page error reload, you can see "End Date" right there, but it is still null on the page: <tr><th><label for="datepicker">End date:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input autocomplete="off" friendly="End Date" id="datepicker" name="end_date" type="text" /></td></tr> The error printing. {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ field.name }}: {{ error|escape }} </strong></strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }} </strong> </div> {% endfor %} … -
DRF: Making external requests and building serializers
I'm using Django rest framework and on a POST request need to make an external request to a SOAP server which outputs weather reports. I receive something like this to my API { 'city': 'Manchester', 'country': 'GB', 'locality': 'EU' } Now this is the data I get. Serializing this data is fine and I get that. However since the SOAP address requires me to make a request within the following format I get confused. I haven't really tried anything but looking for a best solution in this. { 'geopgrahpy': { 'country': 'GB', 'city': 'Manchester', }, 'locality': 'EU', 'userID': '123', 'password': 'xxxxx' } My question is what would be the best solution? Manually building a util function which will return the userID, password (from the request) or build another serializer matching to the soap server needs. Also bear in mind I know SOAP is XML but the Zeep library converts it to and from XML. -
twilio multi factor authentication - Django Python
I am trying to implement a multi factor authentication on my Django web app , I went over some guides and answers but i am still confused , I want that after a user is login with his user name and password to have another step where he will get an SMS with one time token he will put it in the login and then he will be able to continue to the web app. I opened an account on Twillo , but here i got confused , in some example you need Authy and in some you dont ,i installed the Django OTP and Django two factor Auth , and i wasnt be able to bind them all together . Will relay appreciate an explanation on the different terms and how to bind them together. Thanks, Nir -
How to deserialize dates saved into Django s
I came across the “datetime.datetime not JSON serializable” error and wanted a clean Django solution for it So I tried to use DjangoJSONEncoder, but I didn t manage to deserialize the data after serializing it (I want to store it in a JSONField). I get a DeserializationError. What am I doing wrong ? This is what I came up so far : from django.utils.timezone import localtime, now from django.core.serializers.json import DjangoJSONEncoder from django.core.serializers import deserialize a = DjangoJSONEncoder().encode(localtime(now())) print(a) # "2019-07-31T16:48:19.665+02:00" b = deserialize("json",a) print(b) # <generator object Deserializer at 0x0000006CD0F35A40> for c in b : print(c) # django.core.serializers.base.DeserializationError PS : using Python 3.6.8 and Django 2.2.3. -
How to use TinyMCE 5 with Django?
There are no packages to support TinyMCE 5 for Django. The only available packages are version 3 or 4. I tried this guide https://www.tiny.cloud/docs/quick-start/ TinyMCE forms use native HTML and you have initialized it with javascript but Django forms work a different way. You have to make them in Views and I'm not that advanced to modify it. How should I go about that? -
Django query ValueError: hour must be in 0..23
I'm making a query through Django querysets and it's returning "ValueError: hour must be in 0..23" filtering the dates: In models.py: class handoff_model(models.Model): batch = models.ForeignKey(batch_def_model, on_delete=models.CASCADE) date = models.DateField(blank=True, null=True) class batch_def_model(models.Model): name = models.CharField(max_length=200) start_time = models.TimeField(blank=True, null=True) In views.py: def ho_open(request): date = '2019-07-29' all_b = batch_def_model.objects.all() for b in all_b: if not handoff_model.objects.filter(date=date, batch=b.name).exists(): batch = handoff_model(batch=b, date=date) batch.save() handoff_list = handoff_model.objects.filter(date=date,batch__start_time__lt='08:00') return handoff_list I already have a few "batch_def_model" objects in my database. Every time you run "ho_open" (changing the hardcoded date) it should create the handoff_models same as "batch_def_model" but for the hardcoded date. When I set the date as "2019-07-29" it works correctly. Whith date as "2019-07-30" or "2019-07-31" I get the following error: File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 151, in typecast_time return datetime.time(int(hour), int(minutes), int(seconds), int((microseconds + '000000')[:6])) ValueError: hour must be in 0..23 I'm not sure why it's not working with those dates because the entire month is working correctly. I've tested by filtering with date__contains=date without success. Do you have any hint? -
Why do the fields of the selected form return the value "none" and "null" in the database?
I am trying to save a value in the field 2 fields, but when saving them I change the value to "none" and in the db also in the field it shows me "null" I have tried to change the parentheses by the square brackets, seeing if the 2 values of the form are taken to the database, but I don't quite understand the difference between "form.cleaned_data () and form.cleaned_data []", but by doing so with the square brackets, it sends me an error my views.py def solit(request): if request.method == 'POST' and request.is_ajax(): form = addiForm(request.POST) if form.is_valid(): peticion = form.save(commit=False) peticion.usuario = request.user peticion.save() peticion.usuario.d_pendientes = form.cleaned_data.get('d_pendientes') peticion.usuario.h_pendientes = form.cleaned_data.get('h_pendientes') peticion.usuario.save() print (peticion.usuario.d_pendientes) print (peticion.usuario.h_pendientes) return JsonResponse({'status': 'true', 'msg': 'Procesado Correctamente'}) else: return JsonResponse({'status': 'false', 'msg': 'Los datos no son validos'}) form = addiForm() return render(request, 'plantillas/adicionar.html', {'form':form}) my models.py class Usuarios(AbstractUser): numero_empleado = models.IntegerField(null= True, blank= True) area = models.CharField(max_length = 200, null= True, blank= True) d_pendientes = models.IntegerField(null= True, blank= False) h_pendientes = models.IntegerField(null= True, blank= False) f_init = models.DateField(max_length = 200,null= True, blank= True) init_vac = models.DateField(max_length = 200, null= True, blank= True) fin_vac = models.DateField(max_length = 200, null= True, blank= True) ul_vac_tomadas = models.IntegerField(null= … -
Django: M2M database annotation query
Given the following models: User -------- Thread -------- Post -------- thread: ForeignKey(Thread) read_by: ManyToManyField(User) Now, I would like to retrieve all posts for a specific thread annotated if they are read by the currently logged in user. So, I start with fetching the posts: Post.objects.filter(thread=self.thread) Now, I am not sure how I can annotate with the read/unread flag set to True/False. The currently logged in user is available using the variable self.request.user. -
How to Improve the Efficiency of RESTful API Requests
I have a RESTful API request which returns upwards of 1,000 records in the form of JSON data. From this data I pull an ID to reference in a second API request to a different domain. The current logic results in slow page load times due to the large number of records being iterated through during the second request. How can I transition to 1+1 requests instead of 1+n in order to increase availability? views.py cw_presales_engineers = [] for opportunity in opportunities: try: opportunity_id = str(opportunity['id']) presales_ticket = cwObj.get_tickets_by_opportunity(opportunity_id) if presales_ticket: try: cw_engineer = presales_ticket[0]['owner']['name'] cw_presales_engineers.append(cw_engineer) except: pass else: cw_engineer = '' cw_presales_engineers.append(cw_engineer) except AttributeError: cw_engineer = '' first.request def get_opportunities(self): try: r = requests.get( self.URL + 'sales/opportunities?conditions=status/id=1 OR status/id=13 AND company/name!="XYZ Test Company" &pageSize=50& &oage=1& &orderBy=company/name asc&', headers=self.Header) r.raise_for_status() except: raise return r.json() second.request def get_tickets_by_opportunity(self, request): try: r = requests.get( self.URL + 'service/tickets?conditions=opportunity/id=' + request, headers=self.Header) r.raise_for_status() except: raise return r.json() -
how to replace value in dataset django
i've a dataset from a model with 40 fields, is there a smart way to replace a certain value(like NULL)? i've tried with nested for loops without success -
run postgres container when using docker
I have used cookiecutter-django for my django projects. I am using docker to run the project locally. The project is running well. However, i could not explore postgres while using docker. Here are the steps i followed to run the project docker-compose -f local.yml build docker-compose -f local.yml up -d docker-compose run django python manage.py makemigrations docker-compose run django python manage.py migrate local.yml looks like following version: '3' volumes: local_postgres_data: {} local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: travel_local_django depends_on: - postgres - mailhog volumes: - .:/app env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: travel_production_postgres volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres compose/production/postgres/Dockerfile FROM postgres:11.3 COPY ./compose/production/postgres/maintenance /usr/local/bin/maintenance RUN chmod +x /usr/local/bin/maintenance/* RUN mv /usr/local/bin/maintenance/* /usr/local/bin \ && rmdir /usr/local/bin/maintenance .envs/.local/.postgres # PostgreSQL POSTGRES_HOST=postgres POSTGRES_PORT=5432 POSTGRES_DB=simplifytour POSTGRES_USER=debug POSTGRES_PASSWORD=debug when i did docker-compose -f local.yml ps, i get the container related to this project. I then executed the postgres container with command docker exec -it travel_postgres_1 sh. There i tried running the command like psql, psql -U postgres but nothing worked for me. I wanted to explore the postgres like listing the tables, connecting to the … -
django.db.utils.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
I'm using. Django 2.1.10 Python 3.6.8 pyodbc 4.0.26 I have installed Microsoft ODBC Driver 17 for SQL Server. I want to connect to a SQL SERVER 2012 database, but when running "runserver" it shows the following error: Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f895628b9d8> Traceback (most recent call last): File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/sql_server/pyodbc/base.py", line 307, in get_new_connection timeout=timeout) pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/core/management/base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 61, in applied_migrations if self.has_table(): File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 44, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/backends/base/base.py", line 255, in cursor return self._cursor() File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/backends/base/base.py", line 232, in _cursor self.ensure_connection() File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, … -
How to filter queryset value in one of the form fields using CreateView?
My task is to change the value of one field in the form (drop-down list with Foreignkey connection). I use CreateView and ModelForm. forms.py class SkillCreateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(SkillCreateForm, self).__init__(*args, **kwargs) employee_current_technology = Technology.objects.filter(??? --- How can I get editing user pk ????-----) self.fields['technology'].queryset = Technology.objects.exclude(name__in=employee_current_technology) I know that somehow I can get pk from url using kwarg and get_form_kwarg values, but I can't figure out how to do that. urls.py path('profile/<int:pk>/skill/create/', SkillCreateView.as_view(), name='skill_create'), views.py class SkillCreateView(AuthorizedMixin, CreateView): """ Create new course instances """ model = Skill form_class = SkillCreateForm template_name = 'employee_info_create.html' def get_form_kwargs(self): kwargs = super(SkillCreateView, self).get_form_kwargs() Employee.objects.get(pk=self.kwargs['pk']) -->get me pk ???? return kwargs .....