Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Inter dependent filter api in django rest framework
I want to expose the sample dataset through a single generic HTTP API endpoint, which is capable of filtering, grouping and sorting. In this I want API to be interdependent. For eg. If I have to show the number of impressions and clicks that occurred before the 1st of June 2017, broken down by channel and country, sorted by clicks in descending order. I know how to perform singular operation in django filter by using django ORM and django rest_framework_filters but I'm completely unaware of this problem statement. Any sort of help will be appreciated. -
Django celery referencing obsolete tables
So I have this interesting issue with celery and will appreciate another set of eyes. So I have model Ark. class Ark(models.Model): name = models.CharField(max_length) title = models.CharField(max_length) So I ran migrations and ran a couple of periodic tasks using the model After sometime I made a change to the model class Ark(models.Model): name = models.CharField(max_length) # title field was removed ran migrations again, restarted celery + beat. The issue is my current tasks are failing because they I get this error that says something like column ark.title does not exist now, I didn't have any migration issues when I removed title and have also been able to create new ark objects. It is also important to note that I have DELETED all previous instances of ark objects just to be sure no old data persists. What am I missing here? -
Django allauth redirect_url_mistmatch
Hello i have A problem with django allauth. I have A site and i wanna connect Google and github login via django allauth. If i want login via google/github have error: redirect_url_mistmatch. Sorry for my bad English. -
Double users created
I have an issue with my code in the sense that when a student registers, a double instance of the student is created. I don't know what's the problem with these block of code. Please help out,also I don't know how to make a link between a teacher and a student so as to allow the teacher to add results for students. views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm,UserUpdateForm ,InformationUpdateForm,InformationForm def home(request): return render(request, 'student/home.html') def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) a_form=InformationForm(request.POST) # ####and a_form.is_valid() if form.is_valid() and a_form.is_valid(): user = form.save() # form.save() #finally this get links the models, forms and views for user input and all information is registered information = a_form.save() # a_form.save() user.information.majors=a_form.cleaned_data.get('majors') user.information.department=a_form.cleaned_data.get('department') user.information.nationality=a_form.cleaned_data.get('nationality') user.information.date_of_birth=a_form.cleaned_data.get('date_of_birth') user.information.passport_number=a_form.cleaned_data.get('passport_number') user.information.phone_number=a_form.cleaned_data.get('phone_number') user.information.sex=a_form.cleaned_data.get('sex') user.save() information.save() # for this type user input is for for username,last,first and email is registered # form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() a_form = InformationForm() context={'form':form,'a_form':a_form }#,'a_form':a_form return render(request, 'student/register.html', context) @login_required def profile(request): return render(request, 'student/profile.html')#,context @login_required def profile_update(request): if request.method == 'POST': u_form=UserUpdateForm(request.POST,instance=request.user) … -
Django model showing up multiple times in queryset
I have the following Django 3.0 models: class Profile(models.Model): id = ShortUUIDField(primary_key=True, unique=True) user = models.OneToOneField(User, on_delete=models.CASCADE) class Bounty(models.Model): id = ShortUUIDField(primary_key=True, unique=True) creator = models.ForeignKey('Profile', related_name="created_bounties", on_delete=models.SET_NULL, null=True, blank=True) original_completion = models.OneToOneField('ProfileTrophy', related_name="original_bounty",on_delete=models.SET_NULL, null=True, blank=True) name = models.CharField(max_length=50) class ProfileTrophy(models.Model): id = ShortUUIDField(primary_key=True, unique=True) profile = models.ForeignKey('Profile', related_name="bounty_completions", on_delete=models.CASCADE) bounty = models.ForeignKey('Bounty', related_name="bounty_completions", on_delete=models.CASCADE) name = models.CharField(max_length=50, null=True, blank=True) So the premise is that there are profiles, and bountys. Profiles can create bountys (stored as creators on the bounty). Profiles can complete a bounty, which is stored as a ProfileTrophy (trophy for completing the bounty) and they can complete bountys they created or bountys created by others (bounties can have many completions, but the original by the creator is stored in original_completion). The problem I'm running into is that if I have two Profiles, Bob and Jim, and Bob creates a bounty called "Bounty 1" and completes it everything is fine. If Jim then completes "Bounty 1" everything works fine, except when I call Bob.created_bounties.all() I get <QuerySet [<Bounty: Bounty 1>, <Bounty: Bounty 1>]> and queryset[0]==queryset[1]. The database shows only one bounty, and everything looks as it should. If I look at the queryset SQL of Bob.created_bounties.all() I see … -
How to call urls.py fetching a value from a loop in Django
On my index page, I have an image gallery. When someone clicks on an image, it should show more information with more photos in another page. All are loading from MySQL database using a for loop. I'm unable to get the detail of clicked image from my data base. It loads all the data This page's process is like a news website -- all the news loading from a loop. if someone clicks on a news item it should only show details about the clicked item. Below is my index.html page, my urls.py and views.py source code also. I'm using Python, Django with MySQL; all latest versions. Home page, source code of my images gallery {% for x in destination %} <!-- Destination --> <a href="destination" id="{{x.id}}"><div class="destination item" > <div class="destination_image"> <img src="{{x.img.url}}" alt=""> {% if x.offer %} <div class="spec_offer text-center"><a >Special Offer</a></div> {% endif %} </div> <div class="destination_content"> <div class="destination_title"><a href="">{{x.name}}</a></div> <div class="destination_subtitle"><p>{{x.short_description}}</p></div> <div class="destination_price">From ${{x.price}}</div> </div> </div></a> {% endfor %} from . import views from django.urls import path urlpatterns = [ path('destination', views.destination, name='destination'), path('', views.index, name='index') ] from django.shortcuts import render from .models import Destination def destination(request): dest = Destination return render(request, 'destination.html', {'sub_destination': dest}) -
Does Django have any built in mechanisms to prevent Web Parameter Tampering in Model Formsets?
When using the model formsets provided by Django, the forms are rendered with a required ID field which is hidden. However, if you use the dev tools in any web browser, you can easily change the ID and cause that commit to affect a completely different object in the database. Looking into the form validation logic, it doesn’t look like there is a built in way to confirm ownership over these objects, and the request does not even get passed to the validation function. How can you prevent tampering of these objects? -
While resetting the password in django using built-in support it is rendering password different page
Actually i new to django framework. In my practicing, while resetting the password using built-in support, i just created the template with name of "password_reset_form.html" in templates subfolder registration folder. When i run the server it is rendering the "password_reset/done" page, but showing with different content. but my "password-reset_done.html" content is different so please reffer the below snippet of password-reset_done.html. Here is the snippet of password-reset_done.html. {% extends 'base.html' %} {% block content %} <div class="row justify-content-center"> <div class="col-8"> <h2>Reset your password</h2> <p>We've emailed you instructions for setting your password, if an account exists with the email you entered. You should receive them shortly.</p> <p>If you don't receive an email, please make sure you've entered the address you registered with, and check your spam folder.</p> </div> </div> {% endblock %} Here is the pic of rendering with different content. Here is the template of login {% extends 'base.html' %} {% load static %} {% block head %} <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no" name="viewport"> <title>password change</title> <!-- General CSS Files --> <link rel="stylesheet" href="{% static '\css\app.min.css'%}"> <!-- Template CSS --> <link rel="stylesheet" href="{% static '\css\style.css'%}"> <link rel="stylesheet" href="{% static '\css\components.css'%}"> <!-- Custom style CSS --> <link rel="stylesheet" href="{% static … -
Cookie not sent when with request
I am pretty new to web development with API. So I have a function that send a request to the server with the code below. It get sent along with a token that I store in cookie. var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); myHeaders.append("Content-Type", "text/plain"); var raw = "{\n \"latitude\": \"69.23489236336972000\",\n \"longitude\": \"-69.08944702148439000\",\n \"log_start\": \"2020-05-03T09:37:41Z\",\n \"log_end\": \"2020-05-03T10:00:00Z\"\n}"; var requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: 'follow', credentials: 'include', }; fetch("http://127.0.0.1:8000/logs/log/", requestOptions) .then(response => response.json()) .then(result => console.log(result)) .catch(error => console.log('error', error)); However, I keep getting this error when I try to send it. https://i.stack.imgur.com/StU0q.png After a bit digging, I notice that my cookie is not being sent with the request (as shown by the picture below). This is pretty odd to me because I set "credentials" to "include" in the requestOptions. https://i.stack.imgur.com/Hp1mi.png However, when I comment out lines that append "Content-Type" to header so that the header becomes empty. The cookie is included in the header again, along with other headers that were not included in the first place. var myHeaders = new Headers(); // myHeaders.append("Content-Type", "application/json"); // myHeaders.append("Content-Type", "text/plain"); var raw = "{\n \"latitude\": \"69.23489236336972000\",\n \"longitude\": \"-69.08944702148439000\",\n \"log_start\": \"2020-05-03T09:37:41Z\",\n \"log_end\": \"2020-05-03T10:00:00Z\"\n}"; var requestOptions = { … -
How to get the private key of an object (from views.py) whose DetailView we are in?
I have 2 models: Patient and Location. Locations are connected to Patients 1-to-1. When a user goes into a PatientDetailView for a specific patient, he can query for the locations with same names between patients. The user is choosing the query location from a dropdown menu. Currently, the dropdown menu shows all the Location objects but I want to show only the locations connected to this specific patient whose DetailView we are in. Basically, I want this line to query locations which are connected to the patient whose DetailView we are in. queryset=Location.objects.all().order_by('location_name') View def profile_search(request,pk): if request.method == 'POST': query_form = QueryForm(request.POST) if query_form.is_valid(): model=Location location = query_form.cleaned_data['location'] location_str = str(location).split(',')[0] period = query_form.cleaned_data['period'] entry_list = list(Location.objects.all()) return_dict = {} for i in range(len(entry_list)): if location_str == entry_list[i].location_name and \ location.patient.idn != entry_list[i].patient.idn: print('match') return render(request, 'covidapp/query_page.html',{'return_dict':return_dict, 'query_form':query_form}) else: query_form = QueryForm() return render(request, 'covidapp/query_page.html',{'query_form':query_form}) Form: class QueryForm(forms.Form): period = forms.IntegerField() location = forms.ModelChoiceField(queryset=Location.objects.all().order_by('location_name')) Models: class Patient(models.Model): name = models.CharField(max_length=200) idn = models.CharField(max_length=200, unique=True) date_of_birth = models.DateField() date_of_confirm = models.DateField() case_number = models.IntegerField() def get_absolute_url(self): return reverse("patient_detail", kwargs={'pk':self.pk}) def __str__(self): return self.name class Location(models.Model): patient = models.ForeignKey(Patient, related_name='locations', on_delete=models.CASCADE, null=True, blank=True) location_name = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=300, … -
Join queryes of ManyToMany Models on Django
I have to merge the all bands that all persons are in. here is the Models: class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50, blank=True, null=True) aka = models.CharField(max_length=50, blank=True, null=True) bio = models.TextField(blank=True, null=True) birthday = models.DateField(blank=True, null=True) birth_place = models.CharField(max_length=80, blank=True, null=True) photo = models.ImageField(blank=True, null=True) location = models.CharField(max_length=80, blank=True, null=True) gender_choices = [ ('m', 'Male'), ('f', 'Female'), ('u', 'Unknown'), ] gender = models.CharField(max_length=1 ,choices=gender_choices, default='u') class Band(models.Model): name = models.CharField(max_length=100) past_names = models.CharField(max_length=180 , blank=True, null=True) bio = models.TextField(blank=True, null=True) origin_country = models.CharField(max_length=30 , blank=True, null=True) location = models.CharField(max_length=80 , blank=True, null=True) formed_in = models.IntegerField(blank=True, null=True) genre = models.CharField(max_length=80, blank=True, null=True) themes = models.CharField(max_length=80, blank=True, null=True) members = models.ManyToManyField(Person) Since one person can have multiple bands, and a band can have multiple members, I assume it's rigth to create a ManyToMany relation with Person model on Band model Of course a relation table is created, but how I use this table on View assuming I whant make a query similar to this: select person.*, band.* from person inner join band_members on band_members.person_id = person.id inner join band_band on band.id = band_members.band_id order by band_person.id Rith now, my view have a query listing all perons, and a simpler … -
Python 3 venv interpreter not available
I am following this Django App Documentation and I ran into this error from models.py Error: Unable to import 'django.db' models.py code below from django.db import models I am new to python and django so I followed the following steps in creating the app for python 3. STEPS: Followed this video to change the PATH of Python 3. In the cmd I ran the following: >python --version [ RESULT: Python 3.8.2 ] >python -m venv polling-website >Scripts/activate [Successfully activated] >py -m pip install Django [Django version 3.0.6] >django-admin startproject mysite >python manage.py migrate >python manage.py startapp polls >py manage.py runserver I was able to activate the virtual environment and the django server ran successfully. I noticed that the virtual environment I made for the project cannot be identified by the Command Palette when I use Python: Select Interpreter command. Image of command palette with no venv option How will I be able to make the venv interpreter appear? What mistake was made in installing the Django App? Thanks in advance. -
Django Rest Framework Custom Register View (RegisterView) failing to return token + user data
I'm using allauth and rest_auth in my django rest framework app. When registering an user a token (key) is returned, what I'm trying to achieve is to return the token + user data after registration. To do so I've the following serializer: from rest_framework import serializers from rest_framework.response import Response from allauth.account import app_settings as allauth_settings from allauth.utils import email_address_exists from allauth.account.adapter import get_adapter from allauth.account.utils import setup_user_email from kofiapi.api.users.models import User, UserProfile from rest_framework.authtoken.models import Token from rest_auth.models import TokenModel class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('dob', 'phone', 'receive_newsletter') class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) class Meta: model = User fields = ('url', 'email', 'first_name', 'last_name', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create_token(self, user): token, created = Token.objects.get_or_create(user=user) return token def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() token = self.create_token(user) UserProfile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = validated_data.get('email', instance.name) instance.save() profile.dob = profile_data.get('dob', profile.dob) profile.phone = profile_data.get('phone', profile.phone) profile.receive_newsletter = profile_data.get('receive_newsletter', profile.receive_newsletter) profile.save() return instance class TokenSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() class Meta: model = TokenModel fields = ('key', 'user') def get_user(self, instance): request = self.context.get('request') serializer_context = { 'request': … -
How to link each title to an Image in Django
Hi I've been thinking about how to ask the right question to get the right answer. I am making a project where users upload images as posts in one phase . Next I want to change these posts to items in another models what is the steps I need to follow In App No. 1 called score. Users/designers can upload several images and that's the role of this model only. In another app called Core, I have a class in a model called item which from it I can post these images from the admin. I want to be able to select the name of the user Select the required title which is shortlisted to the selected user only The image related to the title which was previously uploaded (from the 1st app called CORE) to be selected (instead of uploading it one more time ). I am trying to simplify it as much as possible so if you have any questions please ask Here is the 1st model for Score where designers can upload images: class Post(models.Model): designer_name = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to='new designs') title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def … -
Any better way to queryset objects from one app to another in wagtail/django?
I have a home app with HomePage model which gets object from BlogPage model in blog app. I use this code below the obtain the object from BlogPage to HomePage. blog app class HomePage(Page): primary_header = models.CharField(max_length=100, blank=True,) secondary_header = models.CharField(max_length=100, blank=True,) hero_banner_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=False, on_delete=models.SET_NULL, related_name='+') def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) # Get object from Blog Page blogpages = self.get_children().get(title='Blog Page').get_children().live().public().order_by('-first_published_at') context['blogpages'] = blogpages return context I used get() to obtain the object by title, but I feel that it may not be the best way to do it. If I were to rename the BlogPage title field to for example, "The Blog Page", it will break the code since 'Blog Page' is no more used. Is there a better way to queryset from BlogPage to HomePage model? home app class BlogPage(Page): subpage_types = ['PostPage'] def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) category_slug = request.GET.get('category', None) context['categories'] = BlogCategory.objects.all() return context -
django-storages media file could not be retrieved by url
I'm using Django and django-storage with dropbox to store media files. my model is class MyModel(models.Model): pdf_file = models.FileField(upload_to='file/%Y/%m/%d', blank=False) But when I access the url like obj = MyModel.objects.get(...) obj.pdf_file.url `` It gives error like dropbox.exceptions.ApiError: ApiError('ff7d53ab72d6faead1b54b58d0f11343', GetTemporaryLinkError('path', LookupError('not_found', None))) Accessing the file from admin panel is working fine. -
Add star display from database in Django
I would like to have a star rating display generated from the user in my Django project. My form collects the data in a charField drop down ("1star", "2stars", "3stars", "4stars", "5stars") so when I go to display it in my template, it is presented as text. Is there a way to convert the text to a star rating display or do I change the field type? Any help would be great. Unfortunately my code may me out of context let me know if you need more. forms.py: class ReviewsForm(forms.Form): apartment_rating = forms.CharField(label="Apartment Rating", widget=forms.Select(choices=Stars)) landlord_rating = forms.CharField(label="Landlord Rating", widget=forms.Select(choices=Stars)) neighborhood_rating = forms.CharField(label="Neighborhood Rating",widget=forms.Select(choices=Stars)) -
Django vs Flask - Which framework is more powerful considering I want to design an end to end IOT solution
Planning to build an end to end IOT application. I know that we can do it using Django and Flask. Which one is a better choice and how it is better? -
django dependent dropdown is not working though implemented according to a blog
I have a dependent dropdown list in my template. forms.py class Bill_CreateForm(forms.ModelForm): def __init__(self, context, *args, **kwargs): super(Bill_CreateForm, self).__init__(*args, **kwargs) self.fields['added_by'] = forms.ChoiceField(choices=tuple([(name, name.members) for name in context['users']])) self.fields['added_to'] = forms.ChoiceField(choices=tuple([(name.id, name.group_name) for name in context['groups']])) self.fields['share_with'].queryset = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=tuple([])) if 'group' in self.data: try: group_id = int(self.data.get('group')) u_l = GroupMembers.objects.filter(group_name=group_id).order_by('members') self.fields['share_with'].queryset = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=tuple([(name, name.members) for name in u_l])) except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['share_with'].queryset = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=tuple(self.instance.group.groupmembers_set.order_by('name'))) class Meta: model = Transactions fields = ( 'bill_type', 'amount', 'added_by', 'added_to', 'share_with', ) template {% extends 'base.html' %} {% load crispy_forms_tags %} {% block body %} <div class='container'> <div class='row justify-content-center'> <div class='card' style='width: 28rem;;margin: 0 auto;float: none; margin-bottom: 10px; /* Added */'> <div class="card-body"> <form method='post' id='billform' user-data-url="{% url 'ajax_load_users' %}" novalidate> {% csrf_token %} {{ form|crispy }} <button class='btn btn-primary'> Add bill </button> </form> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> $("#id_added_to").change(function () { var url = $("#billform").attr("user-data-url"); // get the url of the `load_cities` view var group_id = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/) … -
PyCharm Cannot resolve file "url" in Django project
I am using PyCharm Professional 2019.3 and Django 3.0. PyCharm highlights <a href="/login/">Log In</a> with the following inspection Cannot resolve file: login (Inspection info: This inspection checks unresolved file references in HTML.) How do I configure PyCharm to pick up urls and inspect correctly? -
'Image' object has no attribute '_committed' while generating Qr code from model
from django.db import models import qrcode model # Create your models here. class Customer(models.Model): name=models.CharField(max_length=255) address=models.CharField(max_length=255) gender=models.CharField(max_length=255) registerd_date=models.DateTimeField(auto_now_add=True, blank=True) Image = models.ImageField(upload_to="media/static/images/",blank=True,null=True) def __str__(self): return self.name function take data and convert to qr code and save to model field data def save(self, *args, **kwargs): self.Image=qrcode.make(self.name) super(Customer,self).save(*args, **kwargs) -
How to make Django models refer to each other bidirectionally?
I am trying to create a relationship where a blog post can be assigned any number of tags, and a tag can be associated with any number of blog posts. But I'm having difficulty setting up this bidirectional relationship. Right now, to create a blog post and assign any number of tags, here is my model for the posts: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=100, unique=True, null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now=True) tags = models.ManyToManyField("Tags", blank=True) content = RichTextUploadingField() created_on = models.DateTimeField(auto_now_add=True) And the model defining the tags: class Tag(models.Model): name = models.CharField(max_length=20, unique=True) This works. I can log into the admin interface and create a bunch of tag objects, then create a post object and assign it any number of those tags. But let's say I also want to do the opposite. I want to be able to log into the admin interface, select a tag object, and then associate it with any number of post objects. I tried to do this by defining a ManyToManyField in the Tag model like so: class Tag(models.Model): name = models.CharField(max_length=20, unique=True) posts = models.ManyToManyField("Post", blank=True, related_name="posts") This does show a list of posts on the change … -
Django Admin custom record view
I want to create a custom view which, unlike the changelist_view, shows you the record instead of showing you a form. It will have the URL /app/model/<int:pk/test/view. Is this the best way to do it: @admin.register(Property) class ModelAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() custom_urls = [ path('<int:pk>/view/', self.admin_site.admin_view(self.test_view)) ] return custom_urls + urls def test_view(self, request): record = Model.objects.get(pk=pk) # ... return django.http.HttpResponse('test') # P.S: I will rendering a template -
django I get a TemplateDoesNotExist when loading a page
My directories are structured in this picture I don't know why i'm getting the error. Please assist. Let me know if you need more info. Screenshot of the ERROR -
String mismatch on test in django model test
Been banging my head against a wall for two days trying to figure out why my test is not passing. I've wrapped them in str(). Multiline string. Just can't get this to pass. What am I missing here. Please help. This is my first post. So if I left anything out in my post that I could do better please let me know. Here is my model class MemberAddress(models.Model): address_type = models.CharField(max_length=100, default='Home') address_line_one = models.CharField(max_length=100) address_line_two = models.CharField(max_length=100, default=None) city = models.CharField(max_length=50) state = models.CharField(max_length=50) zipcode = models.CharField(max_length=50) UserProfile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) REQUIRED_FIELDS = ['address_type', 'address_line_one', 'city', 'state', 'zipcode' ] def __str__(self): address = self.address_line_one + '\n' if (self.address_line_two is not None): address += self.address_line_two + '\n' address += self.city + ' ' + self.state + ' ' + self.zipcode return address Here is my test: def test_member_address_is_created(self): faker = Faker('en_US') test_address = MemberAddress( address_type='Home', address_line_one=faker.street_address(), address_line_two=faker.secondary_address(), city=faker.city(), state=faker.state(), zipcode=faker.zipcode(), UserProfile=self.user ) test_address.save() queried_address = MemberAddress.objects.get(id=1) object_string_test = '{}{}{}{}{} {} {}'.format( test_address.address_line_one, '\n', test_address.address_line_two, '\n', test_address.city, test_address.state, test_address.zipcode) self.assertEqual(test_address.address_type, queried_address.address_type) self.assertEqual(test_address.address_line_one, queried_address.address_line_one) self.assertEqual(test_address.address_line_two, queried_address.address_line_two) self.assertEqual(test_address.city, queried_address.city) self.assertEqual(test_address.state, queried_address.state) self.assertEqual(test_address.state, queried_address.state) self.assertEqual(test_address.zipcode, queried_address.zipcode) self.assertEqual(test_address.UserProfile, queried_address.UserProfile) self.assertEqual(object_string_test, test_address) # <---- Failing Test ----<<< Here is my error: python manage.py test Creating …