Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add User model to Profile model in Django right way?
I am new to Django and trying to create a Profile(Patient) model. Here are my models. class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.PositiveSmallIntegerField() gender = models.CharField(max_length=1) def __str__(self): return str(self.user.username) class Doctor(models.Model): name = models.CharField(max_length=50) max_slots = models.PositiveIntegerField(default=10) available = models.PositiveIntegerField(default=0) def __str__(self): return str(self.name) class Assistant(models.Model): name = models.CharField(max_length=50) docid = models.OneToOneField('Doctor', on_delete=models.CASCADE) def __str__(self): return str(self.name) class Appointment(models.Model): confirmed = models.BooleanField(default=False) patid = models.OneToOneField('Patient', on_delete=models.CASCADE) docid = models.ForeignKey('Doctor', on_delete=models.CASCADE) assid = models.ForeignKey('Assistant', on_delete=models.CASCADE) def __str__(self): return str(self.patid) Last migration file class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('doctor', '0014_auto_20200318_0219'), ] operations = [ migrations.AlterField( model_name='patient', name='user', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ] and error I am getting when I run migrations Operations to perform: Apply all migrations: admin, auth, contenttypes, doctor, sessions Running migrations: Applying doctor.0011_auto_20200318_0211...Traceback (most recent call last): File "C:\Users\syd's\.virtualenvs\django-hospital-0gp1XnhJ\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "doctor_patient" does not exist I tried dropping all my tables and running migrations again but no use. P.S. The name of my Django app is "doctor" and I am using PostgreSQL. -
Python 3.8 + Apache 2.4 + mod_wsgi to run django site
so I am running out of things I can possibly check for, I've made sure my python as well as apache are both 64 bit, python is a system wide install, I've uninstalled the 32 bit version before and reinstalled mod_wsgi to get the 64 bit module file, just in case I had the wrong build tools I even tried a pre-compiled mod_wsgi-4.7.1+ap24vc15-cp38-cp38-win_amd64.whl, but I did have the right build tools, I keep getting an error that says 'c:/users/eryk/pycharmprojects/django blog/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win_amd64.pyd into server: The specified module could not be found. .' The file is there, these are my parameters for the config that mod_wsgi-express module-config produces: LoadModule wsgi_module "c:/users/eryk/pycharmprojects/django blog/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win_amd64.pyd" WSGIPythonHome "c:/users/eryk/pycharmprojects/django blog/venv" And here is my httpd.conf, in case anyone's wondering i disabled ssl cause I was getting an error saying 443 is taken, will troubleshoot that once I can actually get the apache service to start as this is getting silly, anyone got an idea what the issue might be? Would be greatly appreciated. CTRL + F "python" will find the python edits in the apache config ''' # Apache Hause .conf file for TLS/1.3 supported versions # # This is the main Apache HTTP server configuration file. It … -
ValueError: Cannot assign foreign key, value must be instance
Models.py class SalesOrder(BaseOrder): customer = models.ForeignKey(.... In serializers.py sales_order, sales_order_created = models.SalesOrder.objects.get_or_create( status_there = True, is_internal=False, ).first() billing_address = models.Address.objects.filter(sap_id__icontains='123').first() and sales_order.billing_address=billing_address sales_order.save() ValueError: Cannot assign "(Customer-Cyberdyne Systems-a5233,)": "SalesOrder.customer" must be a "Customer" instance. I'm having the same error everywhere. this wherein files serializer, I am updating the sales order model. even with booleans ** When I print the billing address its just Customer-Cyberdyne Systems-a5233, But when I'm assigning to the sales order it is looking like this "(Customer-Cyberdyne Systems-a5233,)": "SalesOrder.customer" ** Please let me know where I'm missing something, and is it okay to update a model from another serializer -
How to get python python-decouple to work on a live server?
I can't seem to get python-decouple to work on a live server. I have a Django project in which python-decouple is used to separate my important variables such as secret key, debug, database vars, and so on in a .env file. When the project is run locally, python-decouple works well and I have no problems. After confirming that it works well locally, I then added the .env file to my .gitignore file, pushed the code to my GitHub repository, then pulled the code to the AWS live server. However, when trying to make migrations while configuring the project on an AWS EC2 Ubuntu server, I get the error below. It seems as though the variables in the .env file are not being applied on the AWS Ubuntu server which would make sense because of the .gitignore file. But I thought the whole point of python-decouple was to not have the important variables on the live server. Does anyone know why this error is occurring? and how I can fix it? or do not fully understand the use cases of python-decouple? $ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/theo/aggtrends/aggenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, … -
Make a custom of periodic tasks in django celery
i read about celery about periodic tasks use : # Import for custom tasks from __future__ import absolute_import, unicode_literals from celery import shared_task from celery import Celery from celery.schedules import crontab @periodic_task(run_every=crontab(minute="*/2")) def print_mail(): print("Send Mail to A Specific Time") i want to know if i can change the time in minute not set already but from an input of the form and the task will run periodic by the time of form input , can celery do that and how ??? , tks you ! -
Can we edit the user profile without using forms.py in django?
How to create view for the registered user to edit there profile in the user dashboard using django ? Please provide the view . I have created the register profile without using the forms.py , Now I want to create the userprofile edit only without using forms.py. And Is it possible to submit the data again to the database. (Dont use forms.py) Accounts/views.py def register(request): if request.method == 'POST': #get form values first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] #Check if passwords match if password == password2: #check username if User.objects.filter(username = username).exists(): messages.error(request,'That username is taken') return redirect('register') else: if User.objects.filter(email=email).exists(): messages.error(request,'That email is being used') return redirect('register') else: #looks good user = User.objects.create_user(username = username, password = password, email = email, first_name = first_name, last_name = last_name) #login after register # auth.login(request, user) # messages.success(request, 'You are now logged in') # return redirect('index') user.save() messages.success(request, 'You are now registered and can log in') return redirect('login') else: messages.error(request,'passwords do not match') return redirect('register') else: return render(request, 'accounts/register.html') -
OperationalError at /admin/weather/city/
i am following this tutorial and it created migrations folder without any error but when i logon to localhost:8000/admin and click cities i get OperationalError at /admin/weather/city/ models.py from django.db import models # Create your models here. class City(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Meta: verbose_name_plural = 'cities' views.py import requests from django.shortcuts import render # Create your views here. def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=###' city = 'Las Vegas' r = requests.get(url.format(city)).json() city_weather={ 'city':city, 'temperature':r['main']['temp'], 'description':r['weather'][0]['description'], 'icon' : r['weather'][0]['icon'], } context = {'city_weather': city_weather} return render(request,'weather/weather.html',context) after performing python manage.py makemigrations python manage.py migrate 0001_initial # Generated by Django 3.0.3 on 2020-03-18 02:30 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='City', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25)), ], options={ 'verbose_name_plural': 'cities', }, ), ] then added below code in admin admin.py from django.contrib import admin from .models import City # Register your models here. admin.site.register(City) After several similar questions and answers i had deleted migration folder and again performed python manage.py makemigrations python manage.py migrate tried python manage.py migrate --run-syncdb too but all in vain getting the same error , please help stuck for … -
Django annotate string value
I'm trying to use the following SQL query in my the django query UNION query: 'transfer' AS transaction_type, And as using annotate i would use: annotate(transaction_type=Value('transfer', CharField())) But i keep getting this following error in my view : invalid literal for int() with base 10: 'transfer' I even tried annotate(transaction_type=Value('transfer', output_field =CharField())) but still got the same error How do i use string in annotate ? -
Django Method Not Allowed (POST) 405
Can anyone help me with this. I'm trying to get the value of my input in html by using javascript but when i ran my project it shows this. Method Not Allowed (POST) May you help me find what is the problem and how am i gonna solve this? url: from django.conf.urls import url,include from . import views from django.contrib.auth.decorators import login_required from django.views import View urlpatterns = [ url(r'^change-nameserver/$', login_required(views.bulkNSChange.as_view()), name='change_NS'), ] views: class bulkNSChange(GENERIC_PERMISSION_MIXIN,View): permissions_required = 'can_use_DNS_API' def post(self, request): context = { 'result': { 'bulkChange': False, } } body = json.loads(request.body) print body,'loaded' if body: assert type(body == dict) print 'eto po' log.info('PROCESSING CHANGE NS- {1} to {2}'.format(body['domain'], body['nameServer'])) context['result']['bulk'] = { 'bulkChange': True, 'bulkNS': 'YEAH' } return HttpResponse(json.dumps(context), content_type='application/json') js: function bulkUpdateNS(){ var prompt = confirm('Execute Bulk NS Changes? (This event is logged)') if (prompt){ var domain = document.getElementById('domain') var nameServer = document.getElementById('nameServer') var nsbody = { 'domain': domain.value, 'nameServer': nameServer.value } console.log(nsbody) $.ajax({ type: "POST", dataType: "json", url: "/domains/change-nameserver/", data: JSON.stringify(nsbody), success: function(result) { alert('Bulk Changing Domain NS started') }, error: function(err) { console.log(err) }, complete: function(){ domain.value ='' nameServer.value ='' $('#bulkChangeNSModal').modal('hide'); } }); } } -
How to use the Django DRF serializer for ManyToManyField
I'm trying to write a serializer for my models which has a ManyToManyField. My problem seems to be very similar to this example, but at this time I'm not interested in using a SlugField and nevertheless it's not clear to me what my problem is. models.py class Objective(models.Model): objective_name = models.CharField(max_length=10) objective_description = models.CharField(max_length=30) def __str__(self): return self.objective_name class Assessment(models.Model): objective = models.ManyToManyField(Objective) date_completed = models.DateField(auto_now_add=True) serializers.py class AssessmentSerializer(serializers.ModelSerializer): objective = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Assessment fields = ['name', 'date_completed', 'objective'] class ObjectiveSerializer(serializers.ModelSerializer): class Meta: model = Objective fields = '__all__' From the DRF docs, I thought that the following POST would create an Assessment object where I already have two Objective objects with id's of 3 and 4 respectively. { "name": "Quiz 3", "objective": [ 3, 4 ] } However, this creates the Assessment object but there is no link between it and the Objectives. { "name": "Quiz 3", "date_completed": "2020-03-17", "objective": [] } Is my serializer incorrect, or am I using wrong syntax for the POST, or is there a different issue? -
Convert virtualenv project to pipenv Without a requirements.txt File
I've set up a DigitalOcean droplet with Ubuntu, python 3.6, and django 3.0. The instructions I used installed virtualenv. I'd like to change to pipenv, which is what I use in development. The answers I've seen say to set it up in the same directory as the requirements.txt file. I've never seen any such file. I'm new to django so I'm guessing it was used in older versions. I do have a projectXdir that contains projectX and projectXenv. ProjectX contains the actual project. ProjectXenv contains bin, include, lib, lib64, pyvenv.cfg, and share. The bin has the packages I've installed. Where do I run pipenv to set it up for the project? What do I get rid of afterwards? -
Unknown Command: 'manage.py' in runserver in Pycharm
I have an app I want to run in Django and when I run it or just try to test in in runserver in Pycharm, it gives me the "Unknown command: 'manage.py' manage.py@ATWM_Django > manage.py "C:\Program Files\JetBrains\PyCharm 2019.1.3\bin\runnerw64.exe" C:\Users\dbkar\Desktop\ATWM_Django\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 2019.1.3\helpers\pycharm\django_manage.py" manage.py C:/Users/dbkar/Desktop/ATWM_Django Tracking file by folder pattern: migrations Unknown command: 'manage.py' Type 'manage.py help' for usage. Process finished with exit code 1 -
Mounted a local direcotry in my Docker image, but it can't read a file from that directory
I'm trying to build a docker container with MySql, Django, and Apache images. I have set up this docker-compose.yml ... version: '3' services: mysql: restart: always image: mysql:5.7 environment: MYSQL_DATABASE: 'maps_data' # So you don't have to use root, but you can if you like MYSQL_USER: 'chicommons' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: - "3406:3306" volumes: - my-db:/var/lib/mysql command: ['mysqld', '--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci'] web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn maps.wsgi:application --reload -w 2 -b :8000 volumes: - ./web/:/app depends_on: - mysql apache: restart: always build: ./apache/ ports: - "9090:80" links: - web:web volumes: my-db: I would like to mount my docker Django image to a directory on my local machine so that local edits can be reflected in the docker container, which is why I have this volumes: - ./web/:/app in my "web" portion. This is the web/Dockerfile I'm using ... FROM python:3.7-slim RUN apt-get update && apt-get install RUN apt-get install -y libmariadb-dev-compat libmariadb-dev RUN apt-get update \ && apt-get install -y --no-install-recommends gcc \ && rm -rf /var/lib/apt/lists/* RUN python -m … -
How do I correctly retrieve objects from a database using Django REST api?
I'm teaching my self how to use the Django REST api but I'm running into a JSONDecodeError. I'm trying to display posts depending on the user that is stored in the session. I'm storing the user username, password, and id in the session for later use. The JSONDecodeError is targeting the line with instruction posts = posts_response.json() when I look at the HTML error page Here's my views.py: posts_path = "http://127.0.0.1:8000/posts/" def index(request): if request.method=='GET': post_form = PostForm() posts_response = requests.get(posts_path) posts = posts_response.json() context = { 'post_form': post_form, 'post_list': posts, } return render(request, 'UserLanding/index.html', context) else: return render(request, "UserLanding/index.html") This is my viewsets: class PostView(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer def get_queryset(self): query_set = self.queryset.filter(user=self.request.session['id']) return query_set class SubscriberView(viewsets.ModelViewSet): queryset = Subscriber.objects.all() serializer_class = SubscriberSerializer My registered urls: router = routers.DefaultRouter() router.register('posts', viewsets.PostView) router.register('users', viewsets.SubscriberView) And serializers: class SubscriberSerializer(serializers.ModelSerializer): class Meta: model = Subscriber fields = ('id', 'username', 'password') class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'post_text', 'pub_date', 'user') Please help me spot the problem. Thanks in advance -
Django Rest Framework - create object with field value from URL
Is it possible to use a ModelViewSet to create an instance from a POST request where one of the field values is specified in the URL? EG: POST /teams/3/members with data name = Bob should create Member(team_id=3, name="Bob") Conceptually similar to filtering against the url -
pip install mysql-python fails with missing config-win.h
The python command is pip install mysql-python The full error is _mysql.c(42): fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory Can someone please tell me how to fix this error? What exactly is mysql-python and how is it different from regular mysql? Another stack overflow post suggested installing it with a setup executable, where can I find this? I installed something called mysql python connector from here: https://downloads.mysql.com/archives/c-c/ It installed into C:\Program Files\MySQL\MySQL Connector C 6.1 However, I cannotfind mysqld executable anywhere in this folder -
Django 3.0.5 connection trouble to sql server 2012
I am trying to connect Django 3.0.5 to SQL server 2012 and I went through lots of posts on various websites. they mostly said that use "django-pyodbc-azure" but when I go to download that i found out it supports only django 2.1 so is there any other tool or something i am missing or i need to actually do my work only in django 2.1? -
Cannot navigate in django url smoothly
I am making a web app in django ,i have set the url path in "urls" file of the app and also set views but the problem is that when i click the menu items once it works , now when i am on that page when i click it some other button or even reclick the same menu option it gives an error , it seems like its not routing properly . i have to go back to home and then go to some other url... when first time i click menu item ( http://localhost:3000/chest/ ) route sets like this. when i click menu item in the new page it appends to the route like this ( http://localhost:3000/chest/bicep ) instead of this ( http://localhost:3000/bicep/ ). Code: urls.py from django.contrib import admin from django.urls import path from . import views # from django.conf.urls import url urlpatterns = [ path("", views.home, name = "HOME"), path("blog_detail/<int:id>", views.blog_detail, name = "blog"), # path("about/", views.about, name="about"), # path("contact/", views.contact, name="contact"), path("back/", views.back1, name="back"), # re_path(r'^back/$', views.back1, name="back"), path("chest/", views.chest, name="chest"), path("shoulder/",views.shoulder, name="shoulder"), path("abs/", views.abs, name="abs"), path("bicep/", views.bicep, name="bicep"), path("tricep/", views.tricep, name= "tricep"), path("forearm/", views.forearm, name="forearm"), path("legs/", views.legs, name="legs"), path("fullbody/", views.fullbody, name="fullbody"), path("search/", views.search, name="search"), … -
Matplotlib shift plot graph to left
I'm wondering if it is possible to shift the graph only to the left for the following plot graph. import matplotlib import matplotlib.pyplot as plt import numpy as np # Data for plotting t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks') ax.grid() fig.savefig("test.png") plt.show() I want to leave the x ticks the same but want to shift the graph so that the starting point of the graph is on y-axis. Any suggestions? Thank you in advance. -
Too many values to unpack in MultipleChoicefield choices, though the choices element is an iterable list
I have this form, with a multiplechoicefield. The choices, I need to first split the values I get from the queryset, and then have them seperated before I can use them. class SsReportOndemandForm(forms.Form): recipient_email = forms.MultipleChoiceField(required=False,choices=email_choices) I tried this, and I got a simple list. email_choices = [] for emails in SsReportType.objects.all().values_list('email', flat=True): email_choices.append(str(emails).split(",")) print(email_choices) I printed out the list email_choices and got smth like this [[u'sumassing@sa.com ', u'shidwvargh@ss.com ', u'seweatigund@ff.com'], [u'sumaswqeing@gg.com', u'sumasing@hh.com ', u'shivdargh@aa.com ', u'satqweigweund@gg.com']] Which is fine, but when I render the form, it shows me error : ValueError at /ssreport/on_demand_ssreport too many values to unpack Request Method: GET Request URL: http://127.0.0.1:8000/ssreport/on_demand_ssreport Django Version: 1.7.6 Exception Type: ValueError Exception Value: too many values to unpack Exception Location: /home/rohit/Documents/matrix_cloud/env/local/lib/python2.7/site-packages/django/forms/widgets.py in render_options, line 530 I cannot use tuple here , as I need to split the values. Any idea what I can do?? -
Django auth api
I am following this short tutorial to make an api to authenticate users with Django. The tutorial mentions that this should not be used in production and I wanted to know why as I plan to use it in production. Is it just the '*' in the allowed hosts part which shouldn't be used? https://afdezl.github.io/post/authentication-react-native-django-1/ thanks -
Contact Form with Django 3, G Suite - email sending error
Goal Deploying a landing page on Digital Ocean built with Django 3. Adding my G suite account to the contact form so people can type in their email, subject, message and send it to me. What I have done I have built my contact from with the following guide. I have tested it and it prints out all the parameters in the terminal as it should Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: helllo From: customeremail@gmail.com To: admin@example.com Date: Tue, 17 Mar 2020 14:29:40 -0000 Message-ID: <12121212121212.1222212121212.1212121212121212@mymachinename.local> This is the message. After I have finished the tutorial I have added/switched the following things to the settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_HOST_USER = 'mayname@mycompanydomain.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True I have purchased a G Suite subscription that contains G Suite SMTP relay service that can send 10'000 email/day. ERRORS 1.After the 1st run I have received the following e-mail: Sign-in attempt was blocked myname@businessemaildomainname.com Someone just used your password to try to sign in to your account from a non-Google app. Google blocked them, but you should check what happened. Review your account activity to make sure no one else has access. Check … -
Importing csv file into django and getting list index out of range error
I'm trying to upload a csv file into my django projects and save data into my model. The problem is i'm getting list index out of range but the data is uploaded correctly and saved into model. Can anyone please help me to solve this issue? this is my method in views.py : def admin_upload(request): template = "admin_upload.html" prompt = { 'order': 'CSV fichier cef, cin, nom, prenom, group, module, note_1, note_2, note_EFM' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'Please upload a CSV file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar='|'): _, created = Note.objects.update_or_create( cef=column[0], cin=column[1], nom=column[2], prenom=column[3], group=column[4], module=column[5], note_1=column[6], note_2=column[7], note_EFM=column[8] ) context = {} return render(request, template, context) my model : class Note(models.Model): cef = models.CharField(max_length=30, unique=True) cin = models.CharField(max_length=30) nom = models.CharField(max_length=50) prenom = models.CharField(max_length=50) group = models.CharField(max_length=10) module = models.CharField(max_length=30) note_1 = models.CharField(max_length=5) note_2 = models.CharField(max_length=5) note_EFM = models.CharField(max_length=5) When i upload a csv file the data get uploaded but i get list index out of range error: IndexError at /import/ list index out of range Request Method: POST Request URL: http://127.0.0.1:8000/import/ Django Version: 3.0.2 Exception Type: IndexError … -
formset doesn't save data
I've got a problem and i don't know how to solve it. I created formset where you can write your question in poll. I used formset because in future i want to make dynamic form from it. For now i just wanted one form to see if it works and ... it doesn't. When i click button everything is working as expected but when i click on detail view i can't see my choices. Also there is no data from form in database. Here is my code: model.py class Question(models.Model): question_text = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE, null=False) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) forms.py class CreateChoiceForm(forms.ModelForm): class Meta: model = Choice fields = ('choice_text',) def __init__(self, *args, **kwargs): self.question = kwargs.pop('question') super(CreateChoiceForm, self).__init__(*args, **kwargs) ChoiceFormSet = modelformset_factory(Choice, form=CreateChoiceForm, extra=1) class ChoiceFormSet(ChoiceFormSet): def __init__(self, *args ,**kwargs): self.question = kwargs.pop('question') super(ChoiceFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False def _construct_form(self, *args, **kwargs): kwargs['question'] = self.question return super(ChoiceFormSet,self)._construct_form(*args, **kwargs) views.py def createChoice(request, pk): question = get_object_or_404(Question, pk=pk) formset = forms.ChoiceFormSet(question=question) if request.method == 'POST': if formset.is_valid(): formset = forms.ChoiceFormSet(question=question, … -
Cannot assign "'type1'": "users.user_type" must be a "types" instance
I have a 'users' model that have a OneToOneField to UserModel and a ForeignKey Field to 'types' model. How can I save the ForeignKeyField in database? models.py: class types(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default='') name = models.CharField(max_length=100) def __str__(self): return self.name class users(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default='') user_type = models.ForeignKey(types, on_delete=models.SET_NULL, blank=True, null=True) mobile = models.CharField(max_length=20) def __str__(self): return self.mobile + "(" + self.user.first_name + " " + self.user.last_name + ")" @property def full_name(self): return '%s %s' % (self.user.first_name, self.user.last_name) @receiver(post_save, sender=User) def update_user_users(sender, instance, created, **kwargs): if created: users.objects.create(user=instance) instance.users.save() views.py: def signup(request): if request.method == 'POST': form = forms.SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.users.mobile = form.cleaned_data.get('mobile') user.users.user_type = form.cleaned_data.get('user_type') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('index') else: form = forms.SignUpForm() return render(request, 'user/signup.html', {'form': form}) forms.py: lass SignUpForm(UserCreationForm): mobile = forms.CharField(max_length=20) user_type = forms.CharField(max_length=100) class Meta: model = User fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'mobile', 'user_type', ) But, I have this error: Cannot assign "'type1'": "users.user_type" must be a "types" instance.