Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(Re)Checking Dependencies with PIP
Is it possible to re-check the dependencies of packages installed with pip? That is, suppose we have a working environment. Then, one of the packages changes (gets upgraded, etc). Is there a command one can run to make to make sure that the dependency tree is still sound and does not have conflicts? -
Excluding URLs from Django redirects
Im redirecting all my files on the root of my site to the English subdirectory url(r'^(?P<zero>([a-z-]*)).(htm|php|html)$', redirect, {'to': '/en/{0}.html', 'permanent': True}), I want to exclude a specific page. If I were using apache I could easily do this with an alias or a mod rewrite before it hits the Django application. However Im using Nginx and the redirect gets process regardless of the alias. Is there a rule I can use above so a specific page on my root won't get redirected? -
How to get the next n records in a django queryset?
Is there a way to get the next n records in django queryset? For example, how would I get the next 5 records after getting the first five records? My use case is that I have a see more button on my page and I want to load the next 5 records whenever the see more button is clicked (via ajax) I would like to do something like this #function that handles ajax def load_next_five(initial_five) next_five = initial_five.??? return JsonResponse({'next_five': list(next_five)}) def main_view(request): initial_five = Car.objects.filter(year__gte=2000) ... How would I go about the load_next_five function? -
Cassandra: occasional permission errors
I use cqlengine with django. In some occasions Cassnadra throws an error indicating that user has no permissions do to something. Sometimes this is select, sometimes this is update or sometimes it is something else. I have no code to share, because there is no specific line that does this. I am very sure that user has all the permissions, and sometimes it works. So if user did not have the permissions it should always throw no permission error. So what might be the reasons behind this and how to find the problem? -
One drop down the botton correctly but not the other
What is the difference between {% load i18n %} <a class="material-icons" href="#" data-activates="dropdown1">create<i class="material-icons">arrow_drop_down</i></a> <ul id="dropdown1" class="dropdown-content"> <li> <a href="{# url "requests:accept" pk=object.pk #}" class="green-text" data-turbolinks="false"> <i class="material-icons left">check_circle</i>{% trans "Accept" %} </a> </li> <li> <a href="{# url "requests:reject" pk=object.pk #}" class="red-text text-darken-2" data-turbolinks="false"> <i class="material-icons left">remove_circle</i>{% trans "Reject" %} </a> </li> </ul> and {% load i18n %} <a class="dropdown-button btn" href="#" data-activates="dropdown1" style="padding:0 1rem;"><i class="material-icons">arrow_drop_down</i></a> <ul id="dropdown1" class="dropdown-content"> <li> <a href="{# url "requests:accept" pk=object.pk #}" class="green-text" data-turbolinks="false"> <i class="material-icons left">check_circle</i>{% trans "Accept" %} </a> </li> <li> <a href="{# url "requests:reject" pk=object.pk #}" class="red-text text-darken-2" data-turbolinks="false"> <i class="material-icons left">remove_circle</i>{% trans "Reject" %} </a> </li> </ul> The second block allows me to drop down the button with 'Accept' in green and 'Reject' in red, but not the first block. How could I fix it? Thanks in advance! P.S. Please tell me if the question is unclear. -
django how to delete query object from template
how can I perform an object delete from queryset when I click some button in template for django view here is my code ... HTML views.py def CamerasList(request): model = Cameras # This function can hadle both the retrieval of the view, as well as the submission of the form on the view. if request.method == 'POST': form = CamerasForm(request.POST, request.FILES) if form.is_valid(): form.delete_cam_id = request.POST.get('delete_cam_id') deletelement = Cameras.objects.get(pk=form.delete_cam_id) deletelement.delete() var = {} var = user_group_validation(request) theuser = request.user theuserid = Users.objects.get(user_id=theuser.id).pk theorgid = Users.objects.get(pk=theuserid).organization_id.pk if var['grupo'] == 'superuser': object_list = Cameras.objects.all() organization = Organizations.objects.all() url = request.session['url'] if var['grupo'] == 'admin' or var['grupo'] == 'user': object_list = Cameras.objects.filter(organization_id=request.session['userInc']) organization = Organizations.objects.filter(id=request.session['userInc']) url = request.session['url'] template = get_template(app+u'/cameras_list.html') return HttpResponse(template.render(locals())) -
Google Maps not showing all the markers on the Map
I am trying to plot some coordinates which are transferred from Django backend to front end using Templates. However whenever I see results,all coordinates are not placed,like if I have set of 8 coordinates , I see 6 markers only. Can anybody tell me where is the problem? Code: <script> {{ coordinatelist }}; var sentiment={{ sentimentlst|safe}}; var results= parseInt("{{ Hits }}"); var map; function initMap() { // Constructor creates a new map - only center and zoom are required. map = new google.maps.Map(document.getElementById('map'), { center: {lat: 33, lng:-26}, zoom:2 }); var i=parseInt("0"); {% for item in coordinatelist %} var he = new google.maps.LatLng({{ item.1}},{{ item.0}}); console.log(sentiment[i]) if(sentiment[i]==="positive") { var marker = new google.maps.Marker({ position: he, icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png', title: "Mymarker" }); } else if (sentiment[i]==="neutral") { var marker=new google.maps.Marker({ position: he, icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png', title:"Mymarker"}); } else { var marker=new google.maps.Marker({ position: he, icon:'http://maps.google.com/mapfiles/ms/icons/red-dot.png', title:"Mymarker"}); } marker.setMap(map); i=i+1; {% endfor %} } </script> -
Django project restructure: Can't import app
I'm trying to restructure my project to match the recommendation in the latest Two Scoops of Django book (for Django 1.11). After completing the restructure, my app can't be imported. secureDash_project ├── README.rst ├── config │ ├── __init__.py │ ├── __pycache__ │ ├── db.sqlite3 │ ├── settings │ │ ├── __init__.py │ │ ├── __pycache__ │ │ └── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── requirements.txt └── secureDash ├── __init__.py ├── __pycache__ ├── dash │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py └── templates └── dash settings.py excerpt: ... import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))) ENV_PATH = os.path.abspath(os.path.dirname(__file__)) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'secureDash.dash.apps.DashConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'django_static_jquery', # 'bootstrap3', ] ... When running python3 manage.py runserver --settings=config.settings.settings I get: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1076b0d08> Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in … -
Django: WSGI, slow when running apps.populate, only runs occasionally
I have a django app running on Apache2 and WSGI. I have the wsgi python module below, and added a print statement after application = get_wsgi_application(). When watching the logs this process takes about 1 second. What is confusing, is when this gets triggered. I have a page that sends a simple text output. I hit refresh a bunch of times, and this print gets written to the log once. If I wait a few seconds, it gets written on the next page request. If I refresh successively, it does not until I wait for a period again. My call and response is about 10 milliseconds, but when this is executed (as verified by the print in the log) it takes about a second. This is adding a tremendous amount of unnecessary load to my server and slowing things down. I have it narrowed down to the apps.populate(settings.INSTALLED_APPS) that is called in the django.setup() method. Is there a way I can prevent this from running so often or make it run faster? Thanks for any guidance, or advice you can offer to figure this out or prevent it. wsgi.py: import datetime import os import sys from django.core.wsgi import get_wsgi_application root_path … -
Handle 2 django forms in separate modals but same template
I have a "landing page" in a django template which contains 2 modals with 2 different django forms inside (contact form & signup form) and i'm not sure of how to handle them independently via ajax, i mean the user can fill either form or the 2 of them without rendering the template again(refreshing). I only got to manage 1 of them at first, because after a successfull submission of any of the forms, both forms stop working. For example: if i fill out the contact form and is valid or invalid how do i return both forms in the view? (The success or error message for the contact form and the signup form empty in case the user wants to fill that one too and viceversa) Here's my code. Forms.py class SignUpForm(forms.ModelForm): class Meta: model = Subscriber fields = ['client_name', 'email_address'] widgets = { 'client_name': forms.TextInput(attrs={'class': 'form-control', 'type': 'text'}), 'email_address': forms.EmailInput(attrs={'class': 'form-control', 'type': 'email'}), } class ContactForm(forms.Form): client_name = forms.CharField(required=True,max_length=40,widget=forms.TextInput(attrs={'class': 'form-control', 'type': 'text'})) email_address = forms.EmailField(required=True,widget=forms.TextInput(attrs={'class': 'form-control', 'type': 'email', 'required': 'required'})) message = forms.CharField(required=True,widget=forms.Textarea(attrs={'class': 'form-control', 'type': 'text'})) def sendEmail(self, datas): message = "Hello, " + datas['username']+" "+ datas['email_from'] + " contacted you. here's the message: " + datas['message'] msg … -
Stick the pencil on the right
I'd like to center 'Status' with the pencil on the picture : Here is the html code : {{ headers }} {% load i18n admin_static material_admin %} {% if results %} <div class="results"> <table id="result_list" class="table bordered highlight"> <thead> <tr> {% for header in result_headers %} {% if 'action_checkbox' in cl.list_display and forloop.counter == 1 %} <th class="action-checkbox"> {{ header.text }}<label for="action-toggle">&nbsp;</label> </th> {% else %} <th scope="col" {{ header.class_attrib }}> {% if header.sortable %} {% if header.sort_priority == 0 %} <a href="{{ header.url_primary }}" data-turbolinks="false">{{ header.text|capfirst }}</a> {% elif header.ascending %} <a href="{{ header.url_primary }}" title="{% trans "Toggle sorting" %}" data-turbolinks="false"><i class="material-icons">arrow_upward</i>{{ header.text|capfirst }}</a> {% else %} <a href="{{ header.url_remove }}" title="{% trans "Remove from sorting" %}" data-turbolinks="false"><i class="material-icons">arrow_downward</i>{{ header.text|capfirst }}</a> {% endif %} {% else %} <span>{{ header.text|capfirst }}</span> {% endif %} </th>{% endif %}{% endfor %} <th style="text-align:right;" style='postion: relative; right: 500px'>{% trans "Status" %}</th> {% if row_actions_template %} <th style="text-align:right;">{% trans "Actions" %}</th> {% endif %} </tr> </thead> <tbody> {% for row in results %} <tr class="{% cycle 'row1' 'row2' %}"> {% for item in row.cols %} {{ item }} {% endfor %} <td class="material-icons">create</td> {% if row_actions_template %} <td class="row-actions">{% include row_actions_template with object=row.object %}</td> … -
Django edit UserAdmin removes change password form from Admin Site
I have a model that looks like this: class Device(models.Model): user = models.ForeignKey(User, related_name='device', db_index=True, null=True, blank=True) If I do this in the admin, it removes the "change password" form from the admin site: class UserAdmin(admin.ModelAdmin): inlines = [DeviceInline] admin.site.unregister(User) admin.site.register(User, UserAdmin) Why? The DeviceInline is just a regular inline. -
Django range input instead of text
I am using django forms as you can see in the view.py file and the result is to have a text box.I can submit values numbers and then use this numbers to run script.py etc. I want to do the same with a range input instead of text so that every time the value on the slider change. My views.py def get_name(request): form = NameForm() if request.method == 'POST': a = request.POST['your_name'] # do somethink with the value entered in the form print(a) a = int(a) while a>0: print(a) a = a -1 return render(request, 'personal/code2.html', {'form': form}) My code2.html {% extends "personal/header.html" %} {% block content %} <form action="" method="POST"> {% csrf_token %} {{form}} </form> {% endblock %} And my forms.py from django import forms class NameForm(forms.Form): your_name = forms.DurationField(label='% Brightness ') -
Fields added to Django's AbstractUser aren't showing up in the migration
I'm creating a custom User model based on AbstractUser: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): certs_only: models.BooleanField() When I run manage.py makemigrations, the migrations are created, but the certs_only field isn't there. All other fields from AbstractUser are there, eg password, last_login, etc. I see this migration in 0001_initial.py. This field also doesn't show up in the admin site, since it doesn't actually exist. I've tried ./manage.py makemigrations common, as some suggested ('common' is my app name), but this made no difference. I've also tried adding fields of different types, but this seems to happen regardless. What could be causing this? -
Python syntax error
I can not quite seem to find what is wrong with this code. from django.db import models from django.utils import timezone from django.contrib.auth.models import user # Create your models here. class post(models.Model): STATUS_CHOICES = ( ('draft','Draft'), ('published','Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250,unique_for_date='publish') author = models.ForeignKey(User,related_name='blog_posts') body= models.TextField() publish = models.DateTimeField(default=timezone.now) created= models.DatetimeField(auto_now_add=True) updated= models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def__str__(self): return self.title upon running I get the error message line 34 "def__str__(self):" invalid syntax. The colon seems to be the issue but im not sure why. -
Filtering objects in django admin
I want to manage objects in django admin, though I would like to be able only to edit objects with a specific value of some attribute. Precisely I have now in admin.py: class UnitAdmin(admin.ModelAdmin): list_display = ('type', 'name', 'result_file') list_filter = ['type'] admin.site.register(Unit, UnitAdmin) And I would like to manage only units with type='SomeSpecificType'. I saw something with overriding SimpleListFilter class, though I can't see how this applies here. -
using string variable with REGEXP select pymysql query in python3
i have a chat bot django web application that take the user input and tries to find the matching input in the DB then retrieve the corresponding output. This is a part of chatbot.py code: # -*- coding: utf-8 -*- import re,string,sys import codecs import types import nltk import csv import pymysql from nltk import pos_tag from nltk.tokenize import regexp_tokenize from nltk.tokenize import word_tokenize from nltk.stem.isri import ISRIStemmer from chatbotx1.arabic_const import * from chatbotx1.normalize import * from chatbotx1.stemming import * from nltk.tag.stanford import StanfordPOSTagger from chatbotx1.ar_ghalat import * from chat.models import chat, user_info # initialize the connection to the female_database conn = pymysql.connect("***","***","***","***") cursor = conn.cursor() conn.text_factory = str def run_conversation_male(): last_B =' '.join(chat.objects.values_list('chatbot_response', flat=True).latest('id')) H = ' '.join(chat.objects.values_list('user_iput', flat=True).latest('id')) New_H= ' '.join(PreProcess_text(H)) cursor.execute('SELECT respoce FROM Male_Conversation_Engine WHERE request REGEXP?',[New_H]) reply = cursor.fetchone() if reply: B8=reply[0] new_data(H,B8) ID = chat.objects.values_list('id', flat=True).latest('id') chat.objects.filter(id=ID).update(chatbot_response=B8) Before i was using sqlite3, but now after using Mysql i got this error message: TypeError: not all arguments converted during string formatting I have tried this solution: openconnect = pymysql.connect(host='xxxx',port=3306,user='xxx',passwd='xxx',db='xxxx',charset='utf8') and i got this error message: pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax;) (PS: I am using Python3.5,Mysql, pymysql,Django10, and the text is in … -
auth_views.password_reset keeps rendering the root url template, not the password reset one
urls.py url(r'^password-reset/$', auth_views.password_reset, {'template_name': 'password_reset/password_reset.html', 'email_template_name': 'password_reset/password_reset_email.html', 'subject_template_name': 'password_reset/password_reset_subject.txt'}, name="password_reset"), When I visit localhost:8000/my_app/password-reset/ I get my landingpage.html template instead. The dev server output definitely shows a single GET to /my_app/password-reset/, and I've checked all the project's apps' urls.py; the password-reset url isn't duplicated anywhere else. I've even commented out that app's TEMPLATES directory in my settings file to try to force a TemplateDoesNotExist, and it does nothing - the password-reset view seems to be ignoring the template_name parameter that I pass in the url config file. I'm stumped. What could cause this? -
django formset posts an extra (and blank) row
I have a problem with a django formset that I can't really explain to myself. Here is the involved code. forms.py: class ScoreForm(forms.ModelForm): class Meta: model = models.Score fields = ( 'period', 'home_team_score', 'away_team_score', ) ScoreFormSet = forms.inlineformset_factory( models.Fixture, models.Score, form=ScoreForm, extra=5 ) models.py: class Score(models.Model): fixture = models.ForeignKey(Fixture, related_name="score") user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="score") inserted_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) period = models.IntegerField(blank=True, null=True) home_team_score = models.IntegerField(blank=True, null=True) away_team_score = models.IntegerField(blank=True, null=True) class Meta: db_table = 'score' views.py: class InsertScoreView(CreateView): form_class = forms.ScoreForm model = Score template_name = 'gamestream/insert_score.html' success_url = "/gamestream/score_list/" def get_context_data(self, **kwargs): fixture = Fixture.objects.get(id=self.kwargs['fixture_id']) data = super(InsertScoreView, self).get_context_data(**kwargs) if self.request.POST: data['scores'] = forms.ScoreFormSet(self.request.POST) data['fixture'] = fixture else: data['scores'] = forms.ScoreFormSet() data['fixture'] = fixture return data def form_valid(self, form, **kwargs): user = self.request.user fixture = Fixture.objects.get(id=self.kwargs['fixture_id']) context = self.get_context_data() formset = forms.ScoreFormSet(self.request.POST) if formset.is_valid(): scores = formset.save(commit=False) for score in scores: score.fixture = fixture score.user = user score.save() return super(InsertScoreView, self).form_valid(form) and the template: <div class="container"> <h3>Please insert scores for the following match:</h3> <h4>{{ fixture.starting_time }} -- {{ fixture.league.league_name }} -- {{ fixture.home_team }} vs {{ fixture.away_team }}</h4> <form action="." method="POST"> {% csrf_token %} {{ scores.management_form }} {% for form in scores %} <p>{{ form }}</p> {% endfor … -
Getting a total number of objects inside each object using django markup
Using Django, I am trying to output the total number of lots in each community. A community has several lots, and there are several communities. Here is an example of what I am getting... Total lots: 99. This community only has 2 lots. There are 4 communities with a total of 9 lots between them. The models and views seem correct. Is there a filter I am missing or a different way of writing this to get the correct result? {% if community.is_active %} <a class="panel-link" href="{% url 'community-detail' pk=community.id %}" %}> <div class="col-md-6 community_col"> <div class="community_box"> <div class="row"> <br> <div class="col-md-4 community_img"> <img src="/media/{{ community.logo }}" alt=""> </div> <div class="col-md-7 col-md-offset-1"> <h1 style="margin-bottom: -10px; margin-top: -15px;"><small>{{ community.name }}</small></h1> <h4>{{ community.city }}, {{ community.state }}</h4> <h6>Total lots: {% for lot in community.lot_set.all %}{{ lots|length }}{% endfor %}</h6> <h6>Total Active lots: </h6> <h6>Total Sold lots: </h6> <h6>Total Inactive lots: </h6> </div> </div> </div> </div> </a> {% endif %} {% endfor %} -
Images not showing up when viewing HTML code
I have an index page for a django project I am working on but the images I attach to the buttons aren't showing up when I view it. <html> <head> <title>Support Tools</title> <style type="text/css"> .button { float: left; margin-left: 30px; margin-bottom: 30px; width: 350px; height: 150px; background: url('/media/img/blank.png'); background-repeat: no-repeat; cursor: hand; } .button img { position: relative; left: 20px; top: 10px; } .button div { font-family: Trebuchet MS, Calibri; color: white; font-weight: bold; font-size: 22pt; text-align: center; position: relative; top: -100px; left: 120px; width: 220px; } .title { font-family: Calibri, Helvetica, Arial, Verdana; font-size: 18pt; font-weight: bold; } a, a:link, a:visited, a:active, a:hover { text-decoration: none; } </style> <!--[if lte IE 6]> <script type="text/javascript" src="/media/js/supersleight-min.js"></script> <![endif]--> </head> <body id="b"> <p class="title">GAI Support Tools</p> <a href="/eam/"> <div class="button"> <img src="/media/img/tools.png" /> <div>EAM<br />Support Tool</div> </div> </a> <a href="/admin/minisar/"> <div class="button"> <img src="/media/img/database.png" /> <div>miniSAR<br />Administration</div> </div> </a> <a href="/ai_stats/"> <div class="button"> <img src="/media/img/chart.png" /> <div>Web Service<br />Dashboard</div> </div> </a> <a href="/health/production/"> <div class="button"> <img src="/media/img/monitor.png" /> <div>&nbsp;Web Service<br />Health</div> </div> </a> <a href="/toys/user/"> <div class="button"> <img src="/media/img/users.png" /> <div>User<br />Search</div> </div> </a> <a href="/toys/ud_data_extract/"> <div class="button"> <img src="/media/img/database.png" /> <div>UD Data<br />Extract</div> </div> </a> <a href="/solutions/"> <div class="button"> <img src="/media/img/solutions.png" … -
Get all model objects of a table and get corresponding related row from other table only for particular user/field value
Here are my models class Request(models.Model): song = models.ForeignKey(Song) requestee = models.ForeignKey(User) upvotes = models.IntegerField() downvotes = models.IntegerField() youtubeId = models.CharField(max_length=120) added = models.DateTimeField(auto_now_add=True) played = models.BooleanField(default=False) def __str__(self): return self.song.name class VoteRecord(models.Model): user = models.ForeignKey(User) request = models.ForeignKey(Request) upvoted = models.BooleanField(default=False) downvoted = models.BooleanField(default=False) up_difference = models.IntegerField(default=0) down_difference = models.IntegerField(default=0) class Meta: unique_together = ('user', 'request',) # db_table = 'voterecord' def __str__(self): return (self.user.username + '-' + self.request.song.name) Now I want all request objects (distinct) but for every request objects the corresponding voterecord should be for the current user. If the voterecord not exists the row should have voterecord fields as null. -
Django MySQL schema selection
In the same MySQL server we have a database for each client. This databases share the same table structure. We were able to create a Model for table Foo that looks like this: class Foo(models.Model): id = models.AutoField(primary_key=True) bar = models.CharField(max_length=50) class Meta: managed = False db_table = 'foobar' Our Django project needs to manage all of our clients. As all of them have the same structure we would also like to share the Foo model. At the begging we were able to handle this issue by defining in the project settings each client's database and using routers. At the moment we have too many clients to have them all defined in setting.py. Is there any reasonable way to tell the model which schema has to be used every time we use it? -
How do I write this query in Django
How would I write the following SQL query in Django. SELECT COUNT(*) FROM orion.accounts_transactions LEFT JOIN orion.accounts_notes ON orion.accounts_notes.accounts_core_id = orion.accounts_transactions.accounts_core_id WHERE email_status='clicked' AND email_template_id IS NOT NULL AND orion.accounts_transactions.creation_date >= orion.accounts_notes.creation_date AND orion.accounts_transactions.creation_date <= orion.accounts_notes.creation_date + INTERVAL 7 DAY; -
Django rest framework not creating object with FK to a model with unique=True field
I have two models like this: class Sector(models.Model): name = models.CharField(max_length=100, db_index=True, unique=True) class Address(models.Model): ... sector = models.ForeignKey(Sector, null=True, blank=True) And a serializer for the Address model: In the view, I have this: address_serialized = AddressSerializer(data=request.data) if address_serialized.is_valid(): address_serialized.save(client=client) It never gets to the create function. I have a serialized with a create function that looks like this: class AddressSerializer(serializers.ModelSerializer): city_gps = CitySerializer(required=False) sector = SectorSerializer(required=False) class Meta: model = Address fields = (..., "sector") def create(self, validated_data): ... sector_dict = validated_data.get("sector", None) sector = None if sector_dict and "name" in sector_dict and city_gps: if Sector.objects.filter(name=sector_dict["name"], city=city_gps).exists(): sector = Sector.objects.get(name=sector_dict["name"], city=city_gps) # pdb.set_trace() if "sector" in validated_data: validated_data.pop("sector") if "city_gps" in validated_data: validated_data.pop("city_gps") address = Address.objects.create(sector=sector, city_gps=city_gps, **validated_data) return address The code never touches this function, is_valid() returns False. And the message is {"sector":{"name":["sector with this name already exists."]}} I need to be able to create a new address with FK to the already existing sector. How can I achieve that? Any advice will help.