Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Add extra data to response in middleware
I've a middleware. I want to update the response object inside the middleware. Here is how I'm doing it. class ErrorMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if 'errors' in response.data: response.data.update({'success': False}) print(response.data) return response It prints the correct response, but what the client receives, is without success field. What am I missing? Here is my settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'modules.utils.middleware.ErrorMiddleware' ] -
Django keeps inserting instead of updating
I'm learning Django right now and I ran into this problem where all my updates are actually inserting instead of...well, updating. Can anyone tell me what's wrong with my code? @login_required def edit(request, project_id): data = get_object_or_404(Project, pk=project_id) form = ProjectForm(initial=data.__dict__) if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): data.project = form.cleaned_data['project'], data.appname = form.cleaned_data['appname'], data.description = form.cleaned_data['description'], data.is_visible = form.cleaned_data['is_visible'], data.update() return redirect(reverse('index')) return render(request, 'add-project.html', {'form': form}) Besides that, I'm also very interested in finding out how any of you would write this considering it's a simple edit form submission. Not related but I'm including my addproject form in case you see anything worth changing/optimizing. @login_required def addproject(request): # Init form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): formdata = { 'project': form.cleaned_data['project'], 'appname': form.cleaned_data['appname'], 'description': form.cleaned_data['description'], 'is_visible': form.cleaned_data['is_visible'], } Project.objects.create(**formdata) return redirect(reverse('index')) return render(request, 'add-project.html', {'form': form}) -
How to generate formset in django
Lecturer can add multiple marking criteria for one assignment. each criteria and marks for it, stored in marking model with assignment id as foreign key. I'd like to retrieve all criteria belong to one assignment in a single page and each criteria should have one form next to eat it where lecturer can enter marks. once submitted. mark and criteria id should be stored in StudentMarking model. anyone have any idea? i came up with one view. but it does not work My models class AssignAssignment(models.Model): title=models.CharField(max_length=30) duedate=models.DateField() intakedetails=models.OneToOneField(IntakeDetails, on_delete=models.CASCADE,related_name='details') class Marking(models.Model): criteria = models.CharField(max_length=60) marks = models.PositiveIntegerField() assignment = models.ForeignKey(AssignAssignment, on_delete=models.CASCADE) def __str__(self): return 'criteria: {},marks: {}'.format(self.criteria, self.marks) class StudentMarking(models.Model): criteria=models.ForeignKey(Marking, on_delete=models.CASCADE) student= models.ForeignKey(Student, on_delete=models.CASCADE) mark= models.PositiveIntegerField() My view function @login_required @lecturer_required def marking_upload(request,pk): assignment = get_object_or_404(UploadAssignment, pk=pk) criteria = MarkingModel.objects.filter(assignment_id=assignment.assignment_id) criteria1 = MarkingModel.objects.filter(assignment_id=assignment.assignment_id).count() MarkingFormset = formset_factory(StudentMarking,extra=criteria1) if request.method == 'POST': formset = MarkingFormset(request.POST) list2=zip(formset,criteria) if formset.is_valid(): list2=zip(formset,criteria) for form,cri in list2: if form.has_changed(): mi=form.save(commit=False) mi.assignment_id=assignment.id mi.criteria_id=cri.id mi.save() messages.success(request, 'Marking is successfully added') return redirect('lecturer:ModelIndexView') else: formset = MarkingFormset() lists=zip(formset,criteria) return render(request,'accounts/lecturer/mark.html', {'lists':lists}) -
Problems with underscore in the domain name
Let me first describe my original problem, and solution: I have several docker-compose files which describe different parts of my application. The parts are developed and deployed independently, so they can not be integrated into a single compose file. But those components need to communicate with each other, and the solution I am using at the moment is to have an external network (bridge) which all services are connecting to. So far so good, and I can indeed connect to my service started with any docker compose file as long as I am connected to the custom bridge network: $ docker run --network=mynet --rm --name ping_test -it xenial-networking bash root@0319469f7951:/# ping -c 1 proj_web_1 PING proj_web_1 (172.30.0.3) 56(84) bytes of data. 64 bytes from 172.30.0.3: icmp_seq=1 ttl=64 time=0.071 ms --- proj_web_1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.071/0.071/0.071/0.000 ms Why am using proj_web_1? Because that is the DNS entry that docker compose is creating. This works fine, and nobody cares that underscores are not that great in domain names. Nobody ... except django it seems: ERROR Invalid HTTP_HOST header: 'proj_web_1:8000'. The domain name provided is not valid according to RFC … -
RetrieveAPIView must be called with a URL keyword argument
So I am trying to specify a lookup and I am getting the error Expected view GetEmployersEmailUnique_RetrieveAPIView to be called with a URL keyword argument named "user__email". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. This is what my url looks like http://127.0.0.1:8000/api/employer/email_available/?user__email=someEmaol@gmail.com and this is what my url path looks like url(r"^email_available/",GetEmployersEmailUnique_RetrieveAPIView.as_view()), and this is what my view looks like class GetEmployersEmailUnique_RetrieveAPIView(RetrieveAPIView): queryset = modelEmployer.objects.all() lookup_field = 'user__email' serializer_class = Serializer_ListEmployer permission_classes = (permissions.AllowAny,) The modelEmployer has a one to one relation with the user model Any idea what I might be doing wrong here ? -
Resetting Password By Sending Email
I'm trying to reset password by sending an email to the user. Here's what I did, urls.py, url(r'^user/password_reset/$', password_reset, {'template_name': 'password_reset_form.html'}, name='password_reset'), url(r'^user/password_reset/done/$', password_reset_done, {'template_name': 'password_reset_done.html'}, name='password_reset_done'), url(r'^user/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', password_reset_confirm, {'template_name': 'password_reset_confirm.html'}, name='password_reset_confirm'), url(r'^user/reset/done/$', password_reset_complete, {'template_name': 'password_reset_complete.html'}, name='password_reset_complete'), settings.py, EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True This code is working perfectly fine in the development, I can send email & also change the password. But on the live server it's not sending email, instead it's rising an error 502 Bad Gateway. I have two server blocks in the nginx file, server { listen 80; . . . } server { listen 443 ssl; . . . } Also, I have a firewall -> Firewall Rules Image How can we solve this problem? Thank You! -
Skipping Initial Login Page with Django Allauth
I am using django-allauth for a website. I have integrated Google login through it. Currently, when I access the login, I get the standard sign-in page, on which is a link to sign in through Google. What is the best way to skip the standard sign-in page and go straight to the Google one (as in the one on accounts.google.com...)? All login is done through Google, so I don't need to see the initial page, just the Google one. Should I override the provided template to just redirect? Or is there a better way to configure it? -
Django: Setup model with images
I've created blog post model where I'm going to add variable number of pictures. How to setup relations with picture model? In the admin panel in blog form should displaying only pictures attached to this post. Each picture might be used in many posts. class Post(models.Model): name = models.CharField(max_length=200, null=False) article = models.TextField(null=False) img = models.ManyToManyField('Picture') class Picture(models.Model): def get_image_path(instance, filename): return os.path.join('images', str(instance.id), filename) picture = models.ImageField(upload_to=get_image_path, default = 'images/no-img.jpg') -
Django bootstrapform render field and lable separate in template
I am using Django 2.0.4 with bootstrapform https://github.com/tzangms/django-bootstrap-form . I would like to render my field and label separately in my template. Currently I can render the field using: {% load bootstrap %} {{ form.fieldname|bootstrap }} I would to find a way to separate the render of the label from the field so that I can insert text next to the label for selecting tool-tip. Is anyone able to point me in the right direction to achieve this? Any help will be much appreciated! -
Push results of one to another job django-rq
I'm building an application in which users' information are frequently updated from external APIs. For that, I'm using django-rq. The first job is scheduled once a day to get users who need to update their profiles. With each result returned by the first job, schedule another job to get new user information from remote API and update the user in my database. # tasks.py import requests from django_rq import job @job('default') def get_users_to_update(): """Get a list of users to who need update""" users = User.objects.filter(some_condition_here...) return users @job('default') def remote_update_user(user): """Calls external API to get new user information""" url = 'http://somwhere.io/api/users/{}'.format(user.id) headers= {'Authorization': "Bearer {}".format(user.access_token)} # Send the request, probably takes long time r = requests.get(url, headers=headers) data = r.json() # new user data for key, value in data.items(): setattr(user, key, value) user.save() return user I can schedule those two jobs like following: # update_info.py import django_rq scheduler = django_rq.get_scheduler('default') scheduler.schedule( scheduled_time=datetime.utcnow(), func=tasks.get_users_to_update, interval=24 * 60 * 60 ) scheduler.schedule( scheduled_time=datetime.utcnow(), func=tasks.remote_update_user, interval=24 * 60 * 60 ) However, this is certainly not what I want. I'm wondering if there is any way in django-rq to notify when get_users_to_update is finished, get its results and schedule the remote_update_user. rq allows … -
How do I convert this complex SQL into a Django model query?
I'm writing a Python/Django application to do some stock analysis. I have two very simple models that look like this: class Stock(models.Model): symbol = models.CharField(db_index=True, max_length=5, null=False, editable=False, unique=True) class StockHistory(models.Model): stock = models.ForeignKey(Stock, related_name='StockHistory_stock', editable=False) trading_date = models.DateField(db_index=True, null=False, editable=False) close = models.DecimalField(max_digits=12, db_index=True, decimal_places=5, null=False, editable=False) class Meta: unique_together = ('stock', 'trading_date') I want to find all the stocks that made a yearly low within the past week. But to make this question simpler, just assume that I want to find all the stocks whose lowest point since '2017-05-04' occurred on or after '2018-04-30'. Below is the SQL I wrote to find it. It works. But I need help figuring out what Django Query to write to get the same results as this SQL. How can I do it? select s.symbol, sh.trading_date, low_table.low from ( select stock_id, min(close) as low from stocks_stockhistory where trading_date >= '2017-05-04' group by stock_id ) as low_table, stocks_stockhistory as sh, stocks_stock as s where sh.stock_id = low_table.stock_id and sh.stock_id = s.id and sh.close = low_table.low and sh.trading_date >= '2018-04-30' -
In the early morning my django application shows page is not working
But after restart apache in my google cloud then my application works.How to solve this issue. I did not get any error message from apache log file.But when open google cloud cli i found message as 141 packages can be updated. 0 updates are security updates. * System restart required * Can you please help me how to solve the issue in my server. -
Customize queryset in django-filter select and multi-select menus based on request
I'm using django-filter in 2 places: My Django Rest Framework API, and in my FilterViews (Django Filter's Generic ListViews.) In the case of my FilterViews I'm showing both select boxes (drop-downs) and multi-select boxes to be filtered on. I need to be able to limit what's in those select and multi-select inputs based on a field inside the request. Right now it's possible to customize the queryset as a kwarg inside the FilterView, but you don't get access to the request object if you do it that way. Is there any way to customize the queryset in those inputs on a per-request basis? Preferably both on FilterViews and in the HTML API browser, but just in FilterViews would be fine if it's too complicated for the HTML API browser. -
Saving two or multiple records at the same time with a foreign key relation in Django Admin
I am creating an application manages an interview process. In one interview, a candidate can be interviewed by one or more interviewer and an interviewer can interview one or more candidates. This is similar to a "round table" interview. The simplified version of the models are: class Interviewer(models.Model): interviewer_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=200, blank=False, null=False) last_name = models.CharField(max_length=200, blank=False, null=False) candidates = models.ManyToManyField('Candidate', through='Interview') class Candidate(models.Model): candidate_id = models.PositiveIntegerField( primary_key=True, blank=False, null=False) first_name = models.CharField(max_length=200, blank=False, null=False) last_name = models.CharField(max_length=200, blank=False, null=False class Interview(models.Model): interview_name = models.CharField(max_length=200, blank=True, null=True) candidates = models.ForeignKey( Candidate, on_delete=models.CASCADE, blank=True, null=True, related_name='candidates') interviewers = models.ForeignKey( Interviewer, on_delete=models.CASCADE, blank=True, null=True, related_name='interviewers') In Django admin, for the Interview model, adding an entry for an interview would mean that I have to create the entry for each candidate and interviewer. This process is cumbersome if there are a lot of candidates and/or interviewers. What I would like to do is to add all candidates and the interviewers for a particular interview. I changed my model to use ModelMultipleChoiceField form instead of the default SelectField for Django uses for Foreign Keys. class InterviewAdminForm(forms.ModelForm): interviewers = forms.ModelMultipleChoiceField( queryset=Interviewer.objects.all(), widget=FilteredSelectMultiple( verbose_name='interviewers', is_stacked=False ) ) candidates = forms.ModelMultipleChoiceField( queryset=Candidate.objects.all(), widget=FilteredSelectMultiple( verbose_name='candidates', … -
Render page under new URL in Django?
I am trying to render a new HTML page under the index url. For example render wb.html with ('/') url. Is there a way to do this? OR an alternative would be to add html to an .html file when user = logged in and they came from the login page. Here is what I have (doesn't work) def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): #login user = form.get_user() login(request, user) return HttpResponseRedirect('/') return render(request, 'posts/wb.html', 'form':form) #Of course this doesn't render else: form = AuthenticationForm() context = { 'form' : form } return render(request, 'posts/login.html', context) -
How can I get the url of a Django ImageField?
I am using a modelformset_factory method with forms containing only an ImageField. The Model the forms are based on contains a user field that has a many-to-one relationship with a User Model that extends AbstractUser(See Extending User Model with Abstract User). Currently, each instance of a user has a correlating User Profile, but I would also like to allow the user to upload a gallery of images to their profile. models.py class Gallery(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to='user_gallery', blank=True, null=True) def create_gallery(sender, **kwargs): if kwargs['created']: user_gallery = Gallery.objects.create(user=kwargs['instance']) user_gallery.save(); post_save.connect(create_gallery, sender=User) forms.py class GalleryForm(forms.ModelForm): image = forms.ImageField(label='FormImage') class Meta: model = Gallery fields = ['image'] views.py def EditProfile(request): GalleryFormSet = modelformset_factory(Gallery, form=GalleryForm, extra=3, max_num=3) if request.method == "POST": formset = GalleryFormSet(request.POST, request.FILES) if formset.is_valid(): for form in formset.cleaned_data: my_image = form['image'] photo = Gallery(user=request.user, image=my_image) photo.save() return render(request, 'user_handler/editprofile.html', {'formset': formset}) else: formset = GalleryFormSet() return render(request, 'user_handler/editprofile.html', {'formset': formset}) Template <form id="post_form" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{form.image}} <img src="{{form.image.url}}"/> {% endfor %} <input type="submit" name="submit" value="Submit" /> </form> The problem I'm have is that using {{ form.image }} produces this result: ... and using {{ … -
Changing Wagtail Admin Page Title
Can I remove "Wagtail" from Wagtail's Admin Page? Wagtail Admin Title Is it possible? -
ImportError: No module named 'config.settings'; 'config' is not a package
I'm trying to get my cookiecutter-django app running under Apache with mod_wsgi installed via pip. python3 manager.py runserver works. But after running it in Apache, I got an error saying Module config not found. So I pip install config. (It is not installed on my development system.) That put a config.py file in my /usr/local/pulseenv/lib/python3.5/site-packages. That file had various syntax errors which I fixed. The errors were due to changes between python 2.7 and 3.5 as far as I can tell. But now I get this error and I'm stuck where to go from here: ImportError: No module named 'config.settings'; 'config' is not a package Here's the entire error.log file: [Mon May 07 01:19:49.030541 2018] [mpm_event:notice] [pid 25666:tid 140667404081024] AH00489: Apache/2.4.18 (Ubuntu) OpenSSL/1.0.2g mod_wsgi/4.6.4 Python/3.5 configured -- resuming normal operations [Mon May 07 01:19:49.030613 2018] [core:notice] [pid 25666:tid 140667404081024] AH00094: Command line: '/usr/sbin/apache2' [Mon May 07 01:19:49.085624 2018] [wsgi:info] [pid 25669:tid 140667404081024] mod_wsgi (pid=25669): Attach interpreter ''. [Mon May 07 01:19:49.115868 2018] [wsgi:info] [pid 25669:tid 140667404081024] mod_wsgi (pid=25669): Imported 'mod_wsgi'. [Mon May 07 01:19:58.803919 2018] [wsgi:info] [pid 25669:tid 140667262568192] [remote 172.31.93.15:62927] mod_wsgi (pid=25669, process='pulsemanager', application=''): Loading Python script file '/var/www/pulsemanager/config/wsgi.py'. [Mon May 07 01:19:59.041630 2018] [wsgi:error] [pid 25669:tid 140667262568192] [remote … -
Django Markdown Editor
I would really like a clear straightforward example for implementing a text editor in Django that is like the proposed pagedown or markdownx. I cannot get either of these solutions working in Django 2.0, and all the references I find including the documentation are around older versions of Django. I just want one field in my models to be a text editor like this, that includes uploading images and the use of LaTeX/markdown. -
how can I run django-uwsgi-nginx with https-portal by docker-comporse
I build my image from dockerfiles/django-uwsgi-nginx. Now it's run by this code docker run -d -p 80:80 teranori/mailzon *this is private docker repository. Next I want to run my image with https-portal So I wrote docker-compose.yml like this. https-portal: image: steveltn/https-portal:1 ports: - '80:80' - '443:443' links: - django restart: always environment: DOMAINS: 'mailzon.net' STAGE: local # STAGE: 'production' # FORCE_RENEW: 'true' volumes: # - /path/to/http_config:/var/lib/nginx-conf/my.example.com.conf.erb:ro - ./nginx-app.conf:/var/lib/nginx-conf/mailzon.net.ssl.conf.erb:ro - ./uwsgi_params:/home/docker/code/uwsgi_params django: image: teranori/mailzon ports: - '80' and put "nginx-app.conf" and "uwsgi_params" on same directory with docker-compose.yml. It's comes from django-uwsgi-nginx. "nginx-app.conf" is combined with django-uwsgi-nginx and https-portal nginx-app.conf in django-uwsgi-nginx *it works in new image. # nginx-app.conf # the upstream component nginx needs to connect to upstream django { server unix:/home/docker/code/app.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on, default_server indicates that this server block # is the block to use if no blocks match the server_name listen 80 default_server; # the domain name it will serve for server_name mailzon.net; # substitute your machine's IP address or FQDN charset utf-8; # max upload … -
django-filter conjoined not working as expected
I'm using django-filter in my application in order to imlement some basic filtering. By default, django-filter does an OR query but I want to do an AND query. I've trued using conjoined=True as described in the docs, but it's still returning results using OR My code looks like this class ReservationFilter(django_filters.FilterSet): tags = django_filters.ModelMultipleChoiceFilter(queryset=Tag.objects.all(), conjoined=True) where tags is a m2m key in Reservation model tags = models.ManyToManyField(Tag, related_name='tags') How can I build an AND query? -
Python script to delete rows on Heroku Posgres not working
I am using Heroku to develop a Python/Django web application, and I am using a Heroku Postgres database. I want schedule the following SQL script that deletes duplicate rows from the database: DELETE FROM table_name WHERE id IN ( SELECT id FROM ( SELECT id, ROW_NUMBER() OVER ( PARTITION BY column_name ORDER BY id) AS row_num FROM table_name) t WHERE t.row_num > 1 ) ; When I connect to the database with pgAdmin4 and run the script, it works as expected. When I wrap the query in the following Python script, however, it runs without error but does not delete any rows. def run(): # Environment variables DB_NAME = os.environ.get('DB_NAME') DB_USER = os.environ.get('DB_USER') DB_PASSWORD = os.environ.get('DB_PASSWORD') # Establish connection 1 conn = psycopg2.connect( host='host', dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD, sslmode='require' ) cursor = conn.cursor() # Delete duplicate articles in database cursor.execute(""" DELETE FROM table_name WHERE id IN ( SELECT id FROM ( SELECT id, ROW_NUMBER() OVER ( PARTITION BY column_name ORDER BY id) AS row_num FROM table_name) t WHERE t.row_num > 1 ) ; """) conn.close() I have similar Python scripts with SELECT statements that work as expected. Is there a reason that DELETE statements would not work in the same way? … -
Django view and templates
how I can command a call from the view to them forms that I put directly in an html file(buttons, checkbox, input-text) to be able to work with them from the view. -
ImportError: No module named 'environ' with gunicorn on django
I'm using Ubuntu 14.04 with Django 2.0.5 with Django Cookiecutter. I am trying to start a Django server on DigitalOcean and i'm validating whether out not gunicorn works. python manage.py runserver works fine, but the issue is when i run the command below. Any tips are greatly appreciated, Thanks. I've ran pip install-r base.txt pip install-r local.txt pip install-r production.txt and reinstalled django-environ 0.4.4 This is the error that I receive when I run the following gunicorn command: gunicorn --bind 0.0.0.0:8000 manaland.wsgi:application (venv) root@django-manaland:/home/django/mana/manaland# sudo gunicorn -b 0.0.0.0:8000 config.wsgi:application [2018-05-07 00:12:32 +0000] [20500] [INFO] Starting gunicorn 19.8.1 [2018-05-07 00:12:32 +0000] [20500] [INFO] Listening at: http://0.0.0.0:8000 (20500) [2018-05-07 00:12:32 +0000] [20500] [INFO] Using worker: sync [2018-05-07 00:12:32 +0000] [20503] [INFO] Booting worker with pid: 20503 [2018-05-07 00:12:32 +0000] [20503] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.5/dist-packages/gunicorn/util.py", line 350, in import_app __import__(module) File "/home/django/mana/manaland/config/wsgi.py", line 38, in <module> application … -
Applying foreign key object
I am having an issue with the following line: user_brand = UserBrand(user=user, brand=serializers), I keep getting the following error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rest_framework/views.py", line 466, in dispatch response = self.handle_exception(exc) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rest_framework/views.py", line 463, in dispatch response = handler(request, *args, **kwargs) File "/Users/jeansymolanza/projects/adsoma-api/api/views.py", line 137, in post return self.create(request, *args, **kwargs) File "/Users/jeansymolanza/projects/adsoma-api/api/views.py", line 154, in create user_brand = UserBrand(user=user, brand=serializers) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/base.py", line 439, in __init__ setattr(self, field.name, rel_obj) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 207, in __set__ self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "<module 'rest_framework.serializers' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rest_framework/serializers.py'>": "UserBrand.brand" must be a "Brand" instance. All I want to do is apply the foreign key (Brand) into the User Brand object. views.py class BrandSignup(generics.CreateAPIView): """ Brand signup HTTP POST """ queryset = Brand.objects.all() serializer_class = BrandSignupSerializer def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def create(self, request, *args, **kwargs): if User.objects.filter(email=request.data['email']).exists(): response_details = { 'data': "", 'message': "This email account is already in use. Please try using another one.", 'code': "400", …