Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exception when swapping a ForeignKey with ManyToMany Field in Admin
I am getting the following error after I changed a ForeignKey relation to a ManyToMany relationship. Cannot update model field (only non-relations and foreign keys permitted). Now this happens in the admin section where I did some minor customization which I will also post. But first this is the model whose field I changed to ManytoMany Exhibit A: class modelPatient(models.Model): #student = models.ForeignKey(modelStudent ,null=True, blank=True ) #Mutlipe Patients for single student student = models.ManyToManyField(modelStudent,null=True,default=None,blank=True) patient_name = models.CharField(max_length=128, unique=False) Now this is what I have in my admin section (admin.py). Basically the purpose of this form was to allow the user to assign multiple students to a modelPatient in the admin interface.I would still like that feature Exhibit B: class adminStudentForm(forms.ModelForm): class Meta: model = modelStudent fields = '__all__' patients = forms.ModelMultipleChoiceField(queryset=modelPatient.objects.all()) def __init__(self, *args, **kwargs): super(adminStudentForm, self).__init__(*args, **kwargs) if self.instance: self.fields['patients'].initial = self.instance.modelpatient_set.all() def save(self, *args, **kwargs): try: instance = super(adminStudentForm, self).save(commit=False) self.fields['patients'].initial.update(student=student=None) <-------EXCEPTION HERE self.cleaned_data['patients'].update(student=instance) except Exception as e: print(e) return instance and then this is the registered interface Exhibit C: class modelStudentAdmin(admin.ModelAdmin): form = adminStudentForm search_fields = ('first_name','user__username') #What records to show when the model is clicked in the admin #The super user should get everything and staff … -
Update model in poll based on django tutorial
I follow the django tutorial(https://docs.djangoproject.com/en/1.10/intro/tutorial02/). After I finish tutorial. I want to make some change by myself. I come up this requirement. Can we specify color like this way: Specify any valid web color in hex triplet format (en.wikipedia.org/wiki/Web_colors#Hex_triplet). When a voter views a Choice, its font-color should be the color that I choose. I am able to specify a different color for each Choice. Here is my update code for Choice model: class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) color = models.CharField(default=0, max_length=200) -
How to give permissions to users without the admin web app
I am currently trying to make a django form in order to give permissions to users. I have 4 different permissions for my Models: view, update, add and delete. I would like to have kind of a checkbox system where for each Model, the administrators can select the permissions for a particular user Let's say, I am using this kind of url: myapp/update/permissions/user/15 And I arrive on a page to select the permissions of user whose id is 15. To make it simple, let's assume I have one model called 'Comment'. On this page I can choose whether the user can view, update, add or delete a comment. Of course, the administrators can select multiple checkboxes at once and the permissions the user has are already pre-checked. Does anyone know how I could handle that? Thanks a lot in advance! :) PS: I know it is possible to give permissions to users via the admin app, but I want to have my own app to deal with that. -
Create intermediate table manually in django
I have an excel that contains three tables, table_a, table_a_b and table_b. table_a id | name table_b id | product table_a_b id | a_id | b_id I've created those tables manually and gathered the data to the DB through csv. My models file looks like this class A(models.Model): name = models.TextField(null=True) class Meta: db_table = 'As' class B(models.Model): name = models.TextField(null=True) class Meta: db_table = 'Bs' class AB(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B) class Meta: db_table = 'AsBs' I have a huge problem here, I cannot access to all objects B from a particular object A. I tried putting ManyToManyField in A and B like here class A(models.Model): ... Bs = models.ManyToManyField(B) and it doesn't work Two Questions: 1) Is my approach (creating the intermediate table manually?) good? 2) Is there a way to get all objects of B of A following my approach? -
Testing POST with authentication in Django Rest Framework
I'm trying to test POSTing data to a view in django-rest-framework that requires authentication. But I can't. I've read many threads of supposed solutions, but can't find any that solves to me. Serializer: class ResearcherSerializer(serializers.ModelSerializer): studies = serializers.PrimaryKeyRelatedField( many=True, queryset=Study.objects.all() ) class Meta: model = Researcher fields = ('id', 'first_name', 'surname', 'email', 'studies') View: class ResearcherSerializer(serializers.ModelSerializer): studies = serializers.PrimaryKeyRelatedField( many=True, queryset=Study.objects.all() ) class Meta: model = Researcher fields = ('id', 'first_name', 'surname', 'email', 'studies') Test: class ResearcherAPITest(APITestCase): base_url = reverse('api_researchers') # ... def test_POSTing_a_new_researcher(self): user = User.objects.create(username='lab1', password='nep-lab1') self.client.login(username=user.username, password=user.password) response = self.client.post( self.base_url, { 'first_name': 'João', 'surname': 'das Rosas', } ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) new_researcher = Researcher.objects.first() self.assertEqual(new_researcher.first_name, 'João') self.client.logout() I receive this error: FAIL: test_POSTing_a_new_researcher (experiments.tests.test_api.ResearcherAPITest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/caco/Workspace/nep-system/nep/experiments/tests/test_api.py", line 130, in test_POSTing_a_new_researcher self.assertEqual(response.status_code, status.HTTP_201_CREATED) AssertionError: 403 != 201 ---------------------------------------------------------------------- Had read drf Testing documentation but can't see what I'm doing wrong. -
Securely storing Django REST API token in Chrome extension
I'm making a Chrome extension which should allow users to enter their username and password into a pop-up interface, post those to the server via AJAX, and receive a Django REST API token which the Chrome extension can use to interact with the Django app (get user info, create new records, etc. - so it should be secure). Right now I've got the Chrome extension making the request and receiving the API token, but I'm struggling with how to store the API token securely. I know that chrome.storage is out because the docs say that it's not secure. Would it be possible to use cookies here? The extension needs to run on multiple domains, so I'm not sure if I can use cookies securely. I'd like to not require the user to log in every time they use Chrome, but I'm not sure how to go about storing the API data. -
Python Web-Framework independent route plugin
I have two routes, /x/something and /x/somethingelse, that are required to perform some general tasks which are useful across multiple python web apps in-house. Is the a way to build a web-app component which has these two relative routes, and have it be easy to apply to a variety of the popular python web-frameworks (Flask, Django, Bottle, Pylons, etc.)? The component in flask-like module would look like: @route('/x/something') def ping(): return {} @route('/x/somethingelse') def behaviour(): # some non-trivial functionality return body, status_code Then the use of it could be like import my_thing from my_thing import something_module # Flask my_thing.graft('flask', app, something_module) # Bottle my_thing.graft('bottle', app, something_module) # Pylons my_thing.graft('pylons', app, something_module) Flask has the Blueprint, which is used to create a modular web-application. This seems like exactly the kind of behaviour I want, but it is Flask specific. -
Using openshift Rest Api in Django framework Python application
i want to strarted to build an application using framework Django in python to consume Openshift rest api that the user will be able to authentication and use their resources. i try to read the officiel documentation through URL :https://access.redhat.com/documentation/en-US/OpenShift_Online/2.0/pdf/REST_API_Guide/OpenShift_Online-2.0-REST_API_Guide-en-US.pdf but i can't find a way to start building the application and consuming this rest api. have any one an idea to start -
for loop not working on django
I'm sure I'm doing something very stupid wrong, but I can't really figure out what. This same identical code on my django idle works perfectly, but in django it just doesn't. I have a property_id which is for example 72227686, I want to loop through a dictionary to find which site is that: site_dic = {'Eight': ['84872224','http://eight.org'], 'Malta': ['72822237', 'http://Malta.com'], 'Rome Tour': ['72227686', 'http://rometour.org']} print (site_dic) # This return the dictionary above print (type(site_dic)) # This returns <class 'dict'> (Just to check) for site,val in site_dic.items(): print ('trying: ' +val[0]+' and '+property_id) if val[0] == property_id: # I know this will happen, so an "else" is almost unnecessary property_name = site property_url = val[1] property_id = val[0] print('Matched: '+property_name) current_user = str(request.user) # Otherwise some LazyLoad bug comes up! 0.o gp_object, created = GoogleProperty.objects.get_or_create(google_email=current_user) gp_object.property_name = property_name gp_object.property_url = property_url gp_object.property_id = property_id gp_object.save() print('Now the property should be saved!') else: print('x') # This is impossible If I run this code on my notebook I get the expected result: trying: 84872224 and 72227686 trying: 72822237 and 72227686 trying: 72227686 and 72227686 Match found: Rome Tour However django runs only the first: trying: 84872224 and 72227686 and then prints x and … -
Django python csv. How to open and read a file
I'm wondering how can I use python's library csv to open and read a file saved in a django FileField. I tried opening the file outside of django with a script like this: import csv with open('the_csv_file.csv', 'rb') as f: reader = csv.reader(f) for row in reader: print row It prints the csv content correctly: ['EAN', 'NOMBRE', 'CANTIDAD', 'UNIDAD', 'SKU', 'PRECIO'] ['7861024608794', 'Fioravanti', '1.35', 'L', '6546546', '666'] So, when I try to open the same file in django, it doesn't work: stocklist.csv_file.open(mode="rb") csv_file = stocklist.csv_file.read() csv_reader = csv.reader(csv_file) for row in csv_reader: print(row) It prints this: ['EAN'] ['', ''] ['NOMBRE'] ['', ''] ['CANTIDAD'] ['', ''] ['UNIDAD'] ['', ''] ['SKU'] ['', ''] ['PRECIO'] ... etc So, how do I use the csv library with a django csv file in a FileField ? -
Graphene-Django and Model Properties
Presume a Django model similar to this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) name = models.CharField(max_length=255) other_alias = models.CharField(blank=True,null=True,max_length=255) @property def profile_name(self): if self.other_alias: return self.other_alias else: return self.name I'm using Graphene-Django with this project, and I successfully created a schema to describe the Profile type, and can access it properly through a GraphQL query. However, I can't see any way that I can make that property available too. Is the presumption that I should remove all property-style logic from my Django models, and instead only use GraphQL with the raw information in the model, and then do that logic instead in the place that I use the GraphQL data (eg. in the React app that uses it)? -
What is an array type in XML?
I am trying to make a SOAP API call to a web service. In the documentation, there is a parameter called aCustomParameters which is of type Array. In addition, in the documentation it says the following: All custom parameters to use in a transaction are stored in a Byte Array field. The naming convention for each entry in the array is CustomParamName=CustomParamValue. In other words, each entry in the array should consist of the field name to update, followed by an equals ‘=’ character, and then followed by the value of the specified field. I'm not exactly sure what a type array is in XML format. I tried the following but nothing seemed to work. <urn: aCustomParameters> [FIELD_1=21] </urn: aCustomParameters> <urn: aCustomParameters> <array> FIELD_1=21 </array> </urn: aCustomParameters> -
How to explain inheritance tree for django_mongoengine.fields
I'm newish to python. I'm doing some performance and tuning work and am trying to get to the bottom of how django_mongoengine.fields.djangoflavor.DecimalField inherits from mongoengine.fields.DecimalField. Here's what I see: In [29]: inspect.getmro(fields.DecimalField) Out[29]: (django_mongoengine.fields.DecimalField, django_mongoengine.fields.djangoflavor.DecimalField, django_mongoengine.fields.djangoflavor.MinMaxMixin, django_mongoengine.fields.djangoflavor.DjangoField, mongoengine.fields.DecimalField, mongoengine.base.fields.BaseField, object) Looking at the code I see multiple inheritance of MinMaxMixin and DjangoField but can't grok how this ultimately inherits from mongoengine.fields.DecimalField. What am I missing? Code on Github here: https://github.com/MongoEngine/django-mongoengine/blob/master/django_mongoengine/fields/djangoflavor.py -
How to set the path for css for django apps
I understand that when in the settings.py under Templates 'APP_DIRS' is set to True, django will look for templates in the apps. However, in my case I would like to use a single style.css file for all apps. Specifically I would like to use it for django-registration. When I look in the code <link rel="stylesheet" href="style.css" /> and as result it cannot find it, even though in my base.html I set it to: <link rel="stylesheet" href="{{ STATIC_URL }}style.css" /> so I would expect it to correcty find the stylesheet, which I put into the main folder of the project (not the app) /static. What am I doing wrong? Any help is appreciated so I can have all apps and external apps such as django-registration access the same style sheet. -
Django REST Framework update foreing key
I am trying to update an instance of the Indicator Component model that has a foreign key of the Indicator model. If I pass the primary key of the Indicator it return the following error: Cannot assign "4": "IndicatorComponent.indicator_id" must be a "Indicator" instance. But if I pass the Indicator instance I get the following error: "Incorrect type. Expected pk value, received Indicator." Model class IndicatorComponent(models.Model): indicator_component_id = models.AutoField( primary_key=True ) date = models.DateField( verbose_name='Fecha', auto_now=False, null=True ) indicator_id = models.ForeignKey( 'Indicator', null=True ) def __str__(self): return self.name class Meta: verbose_name_plural = 'Componente Indicador' Serializer class IndicatorComponentSerializer(serializers.ModelSerializer): class Meta: model = models.IndicatorComponent fields = ( 'indicator_component_id', 'name', 'description', 'date', 'position_x', 'position_y', 'size_width', 'size_height', 'indicator_id', 'template_report_id', 'component_styles_id' ) read_only_fields = ('creation_date', 'last_modified_date',) What can i do to avoid this contradiction? Thanks for your help! -
How to extend django user default models database
I am currently creating an online e-commerce website in Django, however, I am using the following library that already has a readily available user table. from django.contrib.auth.models import User class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) phone = forms.CharField(max_length=30) address = forms.CharField(max_length=100) class Meta: model = User fields = ['username','first_name','last_name', 'email', 'password','phone','address'] my products and basket are made in models.py and they work fine, however, the problem I am having is for the user field I need to have at least: name, email, phone and address. but when i view the table created it only has, username, first_name, last_name and password, it doesn't implement phone and address into the table created! image of tables through admin does anyone know how i am able to do this? -
Django page not loading form
I am developing a website in Django. On a home page, it has a navbar on which there are different sections of my website listed as a list items: As shown in screen shot there is a login button on right top. when I click on login a Modal drops from top which has a login form. This arrangement is working fine only for home page. If I go to some other tab in Navbar I only get empty modal. This is my base.html where I am including header and footer and body section gets added as I extend base.html in respective pages. {% include "header.html" %} {% block body %} {% endblock %} {% include "footer.html" %} I assume, How page loads form correctly because in the its view I pass form variable through context. Now, Since none other page knows what login form means it just renders empty modal. adding login form in every pages view would be too redundant. Is there any approach to go about it? -
Django translation from database
I have got strings in my data base that I need to translate so that the user can see it in the language of their choice. I am unsure on how to go about doing this. In my template I have: {% for author, titleList in authorTitle.items %} <h2>"{{author}}"</h2> {% for title in titleList %} <p>"{{title}}"</p> {% endfor %} {% endfor %} And in my views.py I have: authorList = list(TblBooks.objects.values_list("authorid__authorname", flat = True).distinct()) authorBook = {} for author in authorList: authorBook[author] = TblBooks.objects.filter(authorid__authorname = author).order_by("title") return render(request, 'index.html', { 'authorTitle': authorBook } ) Is there any way to translate the title either from the views or the template. If not, how do I go about translating the titles? -
django: display UpdateView in language defined by the object
I have a django project where I would like to display an UpdateView of a ModelForm in the language which is defined by the model itself. I would like to avoid using i18n patterns in the URL. The object to be displayed is identified via an UUID provided in the URL of the form http://name.tld/submit/55dbf53c-9364-4938-873f-6abad2e4ed45 I have: Model: class MyModel(models.Model): unique_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) language = models.CharField( default = "en", max_length=7, choices=settings.LANGUAGES ) ModelForm: class MyModelForm(forms.ModelForm): class Meta: model = MyModel localized_fields = '__all__' fields = '__all__' UpdateView: class MyModelUpdate(UpdateView): model = MyModel form_class = MyModelForm template_name_suffix = '_form' def get_object(self, **kwargs): # get the uuid and find the corresponding object obj = MyModel.objects.filter(unique_id=self.kwargs.get('uuid')).first() if not obj or obj.is_answered: raise Http404("Page not found") else: translation.activate(obj.language) return obj def get_success_url(self): return reverse('submit-success') Template: {% load i18n %} {% trans alert %} <h2>{% trans "My great translated UpdateView" %}</h2> <form action="" method="post"> {% csrf_token %} {% form %} </form> However, despite providing the translated strings in the PO files (created using django-admin makemessages and django-admin compilemessages the page always shows up in English (my browser language, that is). What am I missing? -
Mocking TemporaryUploadedFile in Django
I'm using Django (1.10.5) together with DRF (3.5.4) to create API. I've defined a view to handle file upload and call the foo method with the data passed in the post request and the path to temporary file where the uploaded file is being stored. class FooView(APIView): parser_classes = (FormParser, MultiPartParser) def post(self, request, format=None): serializer = NewFooSerializer(data=request.data) if serializer.is_valid(): file_obj = serializer.validated_data["my_file"] name = serializer.validated_data["name"] foo_id = my_module.foo(name=name, my_file=file_obj.temporary_file_path()) result_url = reverse('api:foo', kwargs={"foo_id": foo_id}) return Response({"result_url": result_url}, status=status.HTTP_202_ACCEPTED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My serializer to validate incoming data looks like this class NewFooSerializer(serializers.Serializer): name = serializers.CharField() my_file = serializers.FileField() Basically I'd like to test this view without the filesystem interaction using mock library. My current test method is defined below @mock.patch('my_module.foo') def test_post_should_invoke_foo_method(self, mocked_foo): mocked_foo.return_value = "123456" self.client.post(self.VIEW_URL, {'my_file': self.file_mock, 'name': 'Test file' }, format='multipart') mocked_new.assert_called_with(name="Test file", my_file="/some/dummy/path" This one of course raises AssertionError AssertionError: Expected call: foo(my_file='/some/dummy/path', name='Test file') Actual call: foo(my_file='/tmp/tmp0VrYgR.upload', name=u'Test file') I couldn't find any solution how to mock TemporaryUploadedFile so I tried to mock tempfile.NamedTemporaryFile which is being used by this class. So I've added these lines before TestCase named_temporary_file_mock = mock.MagicMock(spec=tempfile.NamedTemporaryFile) named_temporary_file_mock.name = mock.MagicMock() named_temporary_file_mock.name.return_value = "/some/dummy/path" and then decorate my test method with … -
Django with Bootstrap-file-upload
I'm using a Django form to load an image and I'm using Bootstap-fileinput. When the form has already been initialised with an image I want the image displayed immediately but it simple shows no image currently. How do I get the template to automatically show the file-input-exists version of the Bootstap HTML rather than the file-input-new version? Forms.py : class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['image',] widget = { 'image' : forms.FileInput(attrs={'class': 'form-control', 'id' : 'input-file'}), } My template has: {{form.image}} {{form.image.errors}} This generates the following HTML whether the form contains an image or not <div class="file-input file-input-new"><div class="file-preview "> <div class="close fileinput-remove">×</div> <div class=""> <div class="file-preview-thumbnails"></div> <div class="clearfix"></div> <div class="file-preview-status text-center text-success"></div> <div class="kv-fileinput-error file-error-message" style="display: none;"></div> </div> </div> <div class="kv-upload-progress hide"></div> <div class="input-group "> <div tabindex="500" class="form-control file-caption kv-fileinput-caption"> <div class="file-caption-name"></div> </div> <div class="input-group-btn"> <button type="button" tabindex="500" title="Clear selected files" class="btn btn-default fileinput-remove fileinput-remove-button"><i class="glyphicon glyphicon-trash"></i> Remove</button> <button type="button" tabindex="500" title="Abort ongoing upload" class="btn btn-default hide fileinput-cancel fileinput-cancel-button"><i class="glyphicon glyphicon-ban-circle"></i> Cancel</button> <div tabindex="500" class="btn btn-primary btn-file"><i class="glyphicon glyphicon-folder-open"></i> &nbsp;Browse …<input class="form-control" id="input-file" name="image" type="file" required=""></div> </div> </div> -
How to run gunicorn from a folder that is not the django project folder
I git cloned a project in my home folder, let's call it /home/telessaude. So the project root is located at /home/telessaude/telessaude_branch_master If I am inside the Django project home folder ( /home/telessaude/telessaude_branch_master ) and issue a gunicorn comman such as gunicorn -w 2 -b 0.0.0.0:8000 telessaude.wsgi_dev:application --reload --timeout 900 gunicorn starts and works just fine. However ... if I try to run the same command on one directory above ( /home/telessaude ), I get the following error: telessaude@ubuntu:~$ gunicorn -w 2 -b 0.0.0.0:8000 telessaude.wsgi_dev:application --reload --timeout 900 [2017-03-22 16:39:28 +0000] [10405] [INFO] Starting gunicorn 19.6.0 [2017-03-22 16:39:28 +0000] [10405] [INFO] Listening at: http://0.0.0.0:8000 (10405) [2017-03-22 16:39:28 +0000] [10405] [INFO] Using worker: sync [2017-03-22 16:39:28 +0000] [10410] [INFO] Booting worker with pid: 10410 [2017-03-22 16:39:28 +0000] [10410] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 557, in spawn_worker worker.init_process() File "/usr/local/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/usr/local/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 136, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python2.7/dist-packages/gunicorn/util.py", line 357, in import_app __import__(module) ImportError: No module named telessaude.wsgi_dev I also tried running … -
django distributed application communication security
I am developing a distributed Django application that consists of several worker instances communicating via HTTP API back to a set of load balanced master instances. What is the best method for authenticating communication between the worker instances and master instances? I'm using OAuth for user authentication, but it seems that OAuth tokens are designed to expire, which rules that out. I have considered just setting an identical 'secret' in the settings of each instance, and including that in requests, but I'm curious if there are better ways of doing this. I haven't had any luck finding anything about this scenario by searching. Thanks in advance for your opinions and expertise! -
Django query using Greatest with NULL values (MySQL)
I need to order a query by the most recent date of two fields. Django >1.9 has the Greatest function, but with a MySQL engine, if any of the compared field values is NULL, Greatest() returns NULL (Postgres will overlook the NULL value). The docs say: The PostgreSQL behavior can be emulated using Coalesce if you know a sensible minimum value to provide as a default. but I've been unable to figure out the necessary syntax. Basically I want: results = MyModel.objects.filter(publish_status=1).order_by('-override_date', '-publish_date') such that the most recent of the three fields is used for the ordering (there's a FK between MyModel and ParentModel). The 'override_date' is the "last chance" entry, but that's typically NULL. publish_date is set on save() but that might've been ages ago. This is for a site that has lots of non-technical content managers. Basically, they're requesting a way to force some items to float to the top of the list, but without having to re-save dozens of items to accomplish that, or having to manually set 'override_date' for everything. I suppose I could create a default for override_date that's way in the past, but creating "fake data" doesn't seem to be the best way to … -
'tuple' object has no attribute - Django
I'm trying to save some data to my database, but I keep getting the error: 'tuple' object has no attribute 'view_id I think that somehow I'm getting the object wrongly from my db. Models.py class GoogleProperty(models.Model): # Settings for each single site, a user can have many! user = models.CharField(max_length=200) # Owner of site google_email = models.EmailField(max_length=200) profile_id = models.CharField(max_length=200) # Needed to delete users, but should be removed! property_name = models.CharField(max_length=200, blank=True, null=True) property_id = models.CharField(max_length=200, blank=True, null=True) property_url = models.CharField(max_length=200, blank=True, null=True) view_id = models.CharField(max_length=200) def __str__(self): return str(self.property_url) Views.py def some_function(requests): if len(list_of_views)==1: # Save to DB and call it a day view_name = list_of_views[0]['name'] view_id = list_of_views[0]['id'] print(view_id) # 123823290 dic_views[view_name]=view_id # Save View to DB ''' obj, created = GoogleProperty.objects.get_or_create(google_email=current_user, defaults={'view_id': view_id}) if not created: obj.view_id = view_id obj.save() ''' objx = GoogleProperty.objects.get_or_create(google_email=current_user) print(objx) # (<GoogleProperty: None>, False) objx.view_id = view_id objx.save return HttpResponse(request, '/ga_app/report.html', {'view_id':view_id}) else: # Many Views, ask which one they want to track Do something edit added traceback: File "/my-path/views.py", line 212, in select_view objx.view_id = view_id AttributeError: 'tuple' object has no attribute 'view_id' I've put as side note the results of the print() function. Also, in some parts of my …