Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django check box from models WITHOUT using the form.py?
How to render a checkbox with multiple selection allowed in Django by just using the model.py file and without using the form.py file? This is my code (which works however only for dropdown single selection and not checkbox multiple selection): from django.db import models class PropertyAmenities(models.Model): # here below is the list of multiple choices that I would like the user to be able to select PROPERTY_AMENITIES_CHOICES = ( ('maid_room', 'MAID_ROOM'), ('study','STUDY'), ('balcony_or_terrace', 'BALCONY_OR_TERRACE')) # the below only work as "dropdown single choice". How can I have it as a "multiple choice check box"? property_amenities = models.CharField(max_length=20, choices=PROPERTY_AMENITIES_CHOICES) Question: How to modify the model class without having to touch or use the form.py file? -
Dynamically get field name which relates two Django models
Let's say I have the following Django model: class Parent(models.Model): name = models.CharField(max_length=50) children = models.ManyToManyField("Child") class Child(models.Model): name = models.CharField(max_length=50) I have the Parent and Child models stored in variables in a script. Given these two models, how can I dynamically get the field name children as a string: def get_field_name(model, related_model): # what do I need here get_field_name(Parent, Child) # "children" -
How can only certain users see the page?
I created a system with Django. I have several users and these users can have different ranks. I have a page but I want to just one rank (lead) can see these page. How can I do that? models.py class UserProfile(AbstractUser): ranks = ( ('analyst', 'Analyst'), ('seniorAnalyst', 'Senior Analyst'), ('lead', 'Lead'), ('manager', 'Manager'), ('seniorManager', 'Senior Manager'), ('director', 'Director'), ('regionalDirector', 'Regional Director'), ('cfo', 'Chief Financial Officer'), ) comp_name = models.CharField(max_length=200, default='', blank=True, null=True) user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500, unique=True) ... views.py @login_required def lead_page(request): return render(request, 'lead.html') -
Subtract Time from Datetime Field in Django/Python
This question seems obvious and easy but I am getting my head stretched out here. Problem is I have datetime field in model and I want to subtract time from another attribute. here is my code I have tried so far. @property def boarding_time(self): print('---------------------------') time = self.schedule.travel_date_time.time() print() time_added = self.schedule.bus_company_route.routeboardingpoint_set.get( point=self.boarding_point ).time_added time1 = timedelta(hours=time.hour, minutes=time.minute, seconds=time.second) time2 = timedelta(hours=time_added.hour, minutes=time_added.minute, seconds=time_added.second) return (time1-time2) Scenario is I have suppose time=date and time of 2021/1/13 8:15 am and time_added is 8:45am now I want to return 30 minutes added to your location like that but I am getting error as 'datetime.timedelta' object has no attribute 'isoformat' -
What is the pypi link for django_saml package?
As discussed in this link, can any one guide me to the pypi link for the answer provided by Nessi? -
Django static files are saved recursively creating bloat via collectstatic
When running collectstatic on my production system, it seems like a bunch of files is stored recursively e.g. (real example): 'production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/css/lib/nestable/nestable.css' This causes bloat every time I update my static files (which is necessary when I update any javascript for the front-end). My settings.py file has the following: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/production/') STATICFILES_DIRS = ([ os.path.join(BASE_DIR, "static"), ]) I also have + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my main urls.py In my Nginx available-sites config file I have the following lines: location /static/ { alias /home/ubuntu/myapp/static/production/; expires modified +1w; } To circumvent this issue, I now have to run collectstatic -c and delete all my static files with every update which isn't ideal. Where am I going wrong? -
Django-channels file/image handling
I'm trying to upload files/images to server via django-channels I have no idea how to send it to my consumers.py while I'm sending the file as var file = attachment.prop("files")[0]; var fileName = file.name; var fileSize = file.size; var fileType = file.type; finalData = { "attachment": file, "attachment-name": fileName, "attachment-size": fileSize, "attachment-type": fileType, } socket.send(JSON.stringify(finalData)); in server side just i can asscess the file name,size,type but not the actual file to save it, instate i get an empty dictionary. in server i'm using data = json.load(mydata) to get the the data and data.get("attachment") is always {} while I can assess type name.. i think it sends the file object to my server as string right? how to send the file as it is( actual savable file), so that i can use FileSystemStorage(url).save(filename,file) to my server. -
Django - Aggregating scores based on nested objects
my model is structured as follows: Model A -> Bundle Model B -> Products Model C -> Products Feedback Example: Bundle X Product A Feedback #A.1: score = 4 Feedback #A.2: score = 5 Product B Feedback #B.1: score = 2 Feedback #B.2: score = 4 ... In the "Bundle" detail view, I'd like to show this: Bundle X Product A (avg score = 4.5) Product B (avg score = 3.0) While in the "Product" details view I'm able to display the average scores, in the "Bundle" details view I'm able to display the list of products related to it, but I can't figure out how to show the scores. Any idea? Here some relevant code: class BundleDetail(generic.DetailView): model = Bundle template_name = 'bundle_detail.html' def get_context_data(self, **kwargs): context = super(BundleDetail, self).get_context_data(**kwargs) bundle = self.object context["hyp"] = Product.objects.filter(bundle=bundle).order_by('bundle') return context class ProductDetail(generic.DetailView): model = Product template_name = 'product_detail.html' def get_context_data(self, **kwargs): context = super(ProductDetail, self).get_context_data(**kwargs) test_conducted = self.object context["test_conducted"] = ProductFeedback.objects.filter(product_tested=test_conducted).order_by('test_conducted') a_s = ProductFeedback.objects.filter(product_tested=test_conducted).all().aggregate(Avg('score')) h_t = ProductFeedback.objects.filter(product_tested=test_conducted).all().aggregate(Count('score')) context["avg_score"] = round(a_s['score__avg'],1) context["nr_tests"] = h_t['score__count'] return context bundle_details: ... <div class="container"> <div class="row"> <div class="col mb-4 mt-3 left top"> {% for a in hyp %} <div class="card mb-2 mt-2 left top"> <div class="card-body"> … -
Write if else logic before creating api in serializer DRF
I need to write if else logic to show text alongside my values.before using get method. models.py class AnalysisResult(models.Model): user_id=models.IntegerField(primary_key=True) E=models.IntegerField() A=models.IntegerField() C=models.IntegerField() N=models.IntegerField() O=models.IntegerField() total=models.IntegerField() class Meta: db_table='analysis_result' def __str__(self): return self.response using DRF and serializer I have created api for this model.my created api looks like this when i hit url . [ { "user_id": 1, "E": 25, "A": 14, "C": 14, "N": 38, "O": 8, "total": 99 } ] but now i want to show some text based on the value of individual E,A,C,N,O. my api should look something like this [ { "user_id": 1, "E": 25 :"some text", "A": 14 :"some text", "C": 14 :"some text", "N": 38 :"some text", "O": 8 :"some text", "total": 99 } ] this texts vary with different values of E,A,C,N,O how can i achieve this task i am not understanding.Please give me a lead. serailizer.py class AnalysisResultSerializer(serializers.ModelSerializer): class Meta: model=AnalysisResult fields='__all__' views.py @api_view(['GET']) def AnalysisResultInfo(request,user_id): if request.method == 'GET': Results=AnalysisResult.objects.filter(pk=user_id) serializer=AnalysisResultSerializer(Results, many=True) return Response(serializer.data) urls.py path('Results/<int:user_id>/',views.AnalysisResultInfo) -
Django inserting data into loop but insert as object [duplicate]
I am adding data into table using foreign key of another table in for loop. It is inserting only id and another is in as Object. Here is my code for , model.py class companySaleStages(models.Model): userId = models.ForeignKey(userInfo , on_delete=models.CASCADE) saleStage_id = models.ForeignKey(saleStages , on_delete=models.CASCADE) saleStatus = models.CharField(max_length=250) salePercentage = models.CharField(max_length=250) created_date = models.DateTimeField(default=timezone.now) class Meta: db_table="companySaleStages" views.py def sectorData(request): saleStage = saleStages.objects.all() if request.method == 'POST': if request.POST.get('sectorId'): for sale in saleStage: companySale = companySaleStages() companySale.userId = userInfo.objects.latest('id') companySale.saleStage_id = saleStages.objects.get(id=sale.id) companySale.saleStatus = saleStages.objects.get(saleStatus=str(sale.saleStatus)) companySale.salePercentage = saleStages.objects.get(saleStatus=str(sale.saleStatus)) companySale.save() return redirect('capabilities') else: return redirect('sector') else: return render (request , 'sector.html' , {'saleStage' : saleStage}) Into database, value for 'saleStatus' and 'salePercentage' insert as "saleStages object (1)" instad of string value from data. -
Django image is not defined
In my html Django file every single image is runing, but one is not <img src="{% static 'img/logoR.png' %}" class="company-logo" alt="Logo"> the path of image is perfect everything is good with media, because other images are displaying I have copied that little code and pasted in the end of html tag, but is still not working. -
Django query to dict with corresponding values
I'm working on a shop project and want to be able to see what most sold products on my shop are. Here is my models.py class Product(models.Model): #some values like name, price, etc... class Purchase(models.Model): purchase_completed = models.BooleanField(default=False) # This is the only important field for this model regarding the problem that I Have # Other fields include stuff like buyers info, end price, etc... class PurchaseContains(models.Model): #Every product has its amount, purchase its related to and the product of course, with some other values as well, but not related to the problem I'm having product = models.ForeignKey(Product...) purchase = models.ForeignKey(Purchase...) amount = models.PositiveIntegerField(blank=False, null=False) Now what I want is to do a query thats going to give me what Products from PurchaseContains are bought the most (by amount from the table) and also the Purchase itself must be completed (purchase_completed==True in Purchase for the given product in PurchaseContains) Now this is what I have done: sold_the_most= PurchaseContains.objects.filter(purchase__purchase_completed=True).values("product", 'amount') sold_the_most_dict= {} for i in sold_the_most: sold_the_most_dict[i["product"]] = sold_the_most_dict.get(i['product'], 0)+i["amount"] As you can see I get the products and amount for purchases that are completed and then do the loop for it to get them in the dictionary. Now this does … -
how do I add to a JSON field in Django
AIM --- I am using Django to make a mock trading website for a project. I am running into problems trying to keep track of stocks a person owns. The problem is if someone buys 4 TSLA stocks and then 4 again it should be treated as 8 stocks of TSLA out of which they can sell 7 if they want. (BTW, I am using postgresql) Problem --- Turns out this is very difficult to do, I couldn't find anything that would help me keep track of the stocks a person owns. so, I read and read and finally turned to JSON fields. but, I am running into an issue there are well when I do u.stocks_owned = {f"{ticker}" : f"{stocks_bought_here}"} u.save() it works, it adds a key-value pair with the ticker and a number, but I don't know how to create a new row using this, or if someone already owns some stock of a company then how do I add to that?? Conclusion --- I don't need to to write code for me, just point me in the right direction I will figure it out myself! -
Django_filters multi-select dropdown with checkboxes
I am trying to create a multi-select dropdown with checkboxes for each dropdown item. I have tried Select2, but it simply returns what I already had in the first place with django_filters and formset. I have tried iterating through the choices using standard html and bootstrap, but that didn't work. To be clear, I have a properly working multi-select scroll-down box but it looks horrible; it is not a dropdown button. I want a standard drop-down with checkboxes for each item so that it is obvious to the user that multiple options can be selected. I have searched for answers on here to help, but everything seems to point to Select2 (which did not seem to get me any further in solving my problem as it yielded the same results I had originally). I have to think that this can't be difficult (though it is proving to be for me), and must be something people do pretty regularly. I am new to Django so any help is welcome. filters.py class AdvancedSearchFilter(AnimalFilter): #Inherits from Class AnimalFilter(FilterSet) filter_overides = { models.BooleanField: { 'filter_class': BooleanFilter, 'extra' : lambda f: { 'widget': forms.CheckboxInput, }, }, } class Meta: model = Animal fields = ['type', … -
I am trying to disply the search value and already filled the details but i can't see the input value of last 3 column ? Help Appricated
I have entered the data then click on the search button and I could see the other column and row display the data but I cannot see the last 3 column and row data when I clicked to search button. attached screenshot for reference. screenshot Here is my moodle.py from django.db import models from django.utils.encoding import smart_text from multiselectfield import MultiSelectField # Create your models here. class ResultQuery(models.Model): os_choice = ( ('Select an Institution', 'Select an Institution'), ('School of Management', 'School of Management'), ) operating_system = models.CharField(max_length=30, blank=True, null=True, choices=os_choice) os_choice2 = ( ('Select a level', 'Select a level'), ('Bachelor', 'Bachelor'), ('Master', 'Master'), ) level = models.CharField(max_length=30, blank=True, null=True, choices=os_choice2) os_choice3 = ( ('Select a Program', 'Select a Program'), ('MBA', 'MBA'), ('BBA', 'BBA'), ('BHM', 'BHM'), ) program = models.CharField(max_length=30, blank=True, null=True, choices=os_choice3) os_choice4 = ( ('Select a Semester', 'Select a Semester'), ('1st', '1st'), ('2nd', '2nd'), ('3rd', '3rd'), ('4th', '4th'), ('5th', '5th'), ('6th', '6th'), ('7th', '7th'), ('8th', '8th'), ) semester = models.CharField(max_length=20, blank=True, null=True, choices=os_choice4) exam_year = models.IntegerField() institute = models.CharField(max_length=4) reg_no = models.CharField(max_length=50) symbol_num = models.IntegerField() student_name = models.CharField(max_length=50) dob = models.DateField() sgpa = models.TextField() result = models.CharField(max_length=40) name = models.CharField(max_length=30) sn = models.IntegerField(max_length=222, blank=True, null=True) subject1_code=models.CharField(max_length=40) subject1_title=models.CharField(max_length=40) subject1_credit_hour=models.TextField() subject1_grade_point=models.IntegerField(max_length=212, … -
I want to update the todo list but when I try to update it add new todo task
The screenshot of my cide def updateTask(request, pk): task = Task.objects.get(id=pk) form = TaskForm(instance=task) if request.method == "POST": form = TaskForm(request.POST, instsnce=task) if form.is_valid(): form.save() return redirect('/') context = { 'form': form } return render(request, 'update_task.html', context) -
How to return queryset instead of list from Django model manager with custom SQL
I'm dealing with a legacy data source and a driver not supported by Django orm. I can only submit queries using their proprietary odbc driver via pyodbc. My workaround is to submit custom sql via pyodbc from the model manager. This techniqe (inspired by Django documentation) returns a list and not a queryset. This works great until I use packages that expect querysets. How do I convert the result list to a queryset? Is there a way to inject the results into a queryset? class MyManager(models.Manager): def getdata(self): con_string = 'DSN=myOdbcDsn;UID=id;PWD=pass' conn=pyodbc.connect(con_string) cursor=conn.cursor() result_list = [] try: sql = "select distinct coalesce(WORKCENTER_GROUP, 'na') workcenterGroup, WORKCENTER_CODE workcenterCode FROM Workcenter" cursor.execute(sql) for row in cursor.fetchall(): p = self.model(workcenterGroup=row[0], workcenterCode=row[1]) result_list.append(p) except pyodbc.Error as ex: print("----------------ERROR %s: %s" % (ex.args[0], ex.args[1])) conn.close() return result_list -
How to pass foreign key id to form? or link form to a foriegn key value DJango
I am trying to auto populate my form Student field with the name Carl Park. In short I want my form to use to automatically use the Object ID instead of having to manually select the name Carl Park from the student field drop down menu. How do I automatically link my Model Form to a foriegn key ID and have the form auto populate based on that value. Here is my current form, my models.py forms.py views.py and HTML #models class Teacher(models.Model): name = models.CharField(max_length=75) room = models.CharField(max_length=10) bio = models.TextField() class Student(models.Model): teacher = models.ForeignKey('Teacher', on_delete=models.CASCADE) name = models.CharField(max_length=75) class Student_Performance(models.Model): student = models.ForeignKey('Student', on_delete=models.CASCADE) behavior_grade = models.CharField(max_length=1) #form class StudentPerfromanceForm(ModelForm): class Meta: model = Student_Performance fields = ( "name", "behavior_grade") #view def student_details(request, id): obj = get_object_or_404(Student,pk=id) form = StudentPerfromanceForm() if request.method == 'POST': form = StudentPerfromanceForm(request.POST) if form.is_valid(): form.save(commit=True) return all_students_list(request) #pass success message return render(request, 'class_roster/student_details.html', {'obj':obj, 'reviewForm':form}) #HTML <form method="POST"> {% csrf_token %} {{reviewForm.as_p}} <input type="submit" value="Submit Review"> </form> -
DateTimeField with field specific timezone in Django admin
I'm working on a basic django application and just can't figure out a way to implement a requested feature. I have a Campaign model linked to an Alert model through a 1-n relationship. The Alert has a DateTimeField (to represent the configured alert time). However, each Alert should be able to be set for a specific timezone. I tried to override the save function to apply a the model specific timezone instance, but I can't get it to work in a satisfying manner. When displayed after save it will use the global timezone. Simplified code: import pytz from django.db import models from django.conf import settings from timezone_field import TimeZoneField class Campaign(models.Model): name = models.CharField(max_length=80, unique=True) class Alert(models.Model): campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, related_name='alerts') timezone = TimeZoneField(default=settings.TIME_ZONE) run_at = models.DateTimeField() def save(self, *args, **kwargs): tz = pytz.timezone(str(self.timezone)) print("Converting", self.run_at) self.run_at = self.run_at.replace(tzinfo=None) self.run_at = tz.localize(self.run_at) print("to", self.run_at) super().save(*args, **kwargs) I would appreciate if anyone had any suggestions on how to make it work properly. Or direct me to a plugin I could install to solve it (I couldn't find any). -
Django - ProgrammingError at / column <new_column> does not exist
I want to add a new field to my model. After adding and migrating I had: django.db.utils.ProgrammingError: relation already exists I've found this comment https://stackoverflow.com/a/39805907/10226040, but now I am having: ProgrammingError at / column <new_column> does not exist And migration folder isn't creating. I've deleted fields, rerunned without migration and it has worked. And I do this in Docker, BTW. Thank you. -
Many to many field all instances created are being added as relations to the models where the relation is being declared
I'm using Django-polymorphic and I think this might be the reason behind my woes. I want to have some instances of a model connected to three others through a foreign key to be added and others not, I'm not sure how to do it is there a need for an intermediate step what should I do? Here's my models: from django.db import models from polymorphic.models import PolymorphicModel from django.contrib.contenttypes.fields import GenericRelation from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class UserModel(models.Model): MEMBERSHIP_TYPE = [ ('NM', 'NORMAL'), ('PT', 'PLATA'), ('OR', 'ORO'), ('PL', 'PLATINO'), ] id = models.AutoField(primary_key=True) username = models.CharField(max_length=100, unique=True) photo = models.ImageField(upload_to='images/', blank=True) address = models.TextField() client_type = models.CharField(max_length=2, choices=MEMBERSHIP_TYPE, default= 'NM') def __unicode__(self): return self.name class ArticleModel(models.Model): id = models.AutoField(primary_key=True) code = models.IntegerField(unique=True) description = models.TextField() def __str__(self): return str(self.code) class OrderModel(models.Model): id = models.AutoField(primary_key=True) client = models.ForeignKey('UserModel', on_delete=models.CASCADE) gen_time = models.DateTimeField(auto_now_add=True) gen_supplied = models.DateTimeField(null=True, blank=True) urgent = models.BooleanField() order_to = models.ForeignKey('OrderToModel', on_delete=models.CASCADE) article = models.ForeignKey('ArticleModel', on_delete=models.CASCADE) quantity= models.IntegerField() class OrderToModel(PolymorphicModel): id = models.AutoField(primary_key=True) class WarehouseModel(OrderToModel): warehouse_num = models.IntegerField(unique=True) name = models.CharField(max_length=100) address = models.TextField() articles = models.ManyToManyField(ArticleModel, blank=True) def __str__(self): return "Warehouse"+ str(self.warehouse_num) class StoreOrderModel(OrderToModel): reference = models.IntegerField(unique=True) store_num = models.ForeignKey('StoreModel', on_delete=models.CASCADE) def __str__(self): return str(self.reference) class … -
Django: How to add select-option dropdown to a CreateView form?
This feels like an easy question, but I am not finding it in the docs or other answers online. I have a template that displays a form for a user to create a new review. I want the "Library" field on that form to be a dropdown that limits the values for that field (that is, choose from 'TV', 'Music', 'Movies' and nothing else). Here's my models.py class Review(models.Model): library = models.CharField(max_length=200) title = models.CharField(max_length=200) review_body = models.TextField(null=True) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) def __str__(self): return self.title def get_absolute_url(self): return reverse('review_detail', args=[str(self.id)]) Here's views.py class ReviewCreateView(CreateView): model = Review template_name = 'review_new.html' library_choices = ['TV', 'Movies', 'Music'] library = forms.ChoiceField(choices=library_choices) fields = ('library', 'title', 'review_body', 'author',) And here's the template: {% extends 'base.html' %} {% block content %} <h1>New Review</h1> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <button class="btn btn-success ml-2" type="submit">Save</button> </form> {% endblock content %} I got the idea to use forms.ChoiceField from this answer, but it did not work- there is just a text field in Library. Maybe it doesn't belong in the views.py? Or maybe I can't do this while subclassing CreateView and need a forms.py. -
Safely process user content in Django template language [duplicate]
I'm making a blog app in Django, where the users can write their own blog post. I have the worry that the User could introduce malicious code in the database while writing a blog post. For example, by writing javascript code in the blog post body: alert("malicious code here, ahh!) So there is any way to process the content of the user by parsing the value of the content, or something like that? -
NoReverseMatch at /add_stock Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<id>[^/]+)$']
Listed below are the files, I tried looking at the other answers on here but didn't seem to help. When I tried to output just the primary key by doing items.id on the add_stock.html page nothing came out so I'm wondering if there is an issue accessing the primary key for the database. urls.py file from django.urls import path from . import views urlpatterns = [ path('',views.home,name="home"), path('about',views.about,name="about"), path('add_stock',views.add_stock,name="add_stock"), path('delete/<stock_id>',views.delete,name="delete") ] views.py file def add_stock(request): if request.method=='POST': form = StockForm(request.POST or None) if form.is_valid(): form.save() messages.success(request,("Stock Has Been Added")) return redirect('add_stock') else: stockInfo = Stock.objects.all() ticker = [] for ticker_item in stockInfo: url = "https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/get-quotes" querystring = {"region":"US","lang":"en","symbols":str(ticker_item)} headers = { 'x-rapidapi-host': "apidojo-yahoo-finance-v1.p.rapidapi.com", 'x-rapidapi-key': "1ab2c68079msh721b8caa3532a08p125aafjsn601191304fe3" } api_request = requests.request("GET", url, headers=headers, params=querystring) try: api=json.loads(api_request.content) dpi=StockInfo(api['quoteResponse']['result'][0]['symbol'],api['quoteResponse']['result'][0]['regularMarketPrice'], api['quoteResponse']['result'][0]['fullExchangeName'],api['quoteResponse']['result'][0]['regularMarketChange'], api['quoteResponse']['result'][0]['regularMarketChangePercent']) ticker.append(dpi) except Exception as e: dpi="Error" return render(request,'add_stock.html',{'stockInfo':stockInfo,'ticker':ticker}) # in the add_stock html page we pass the stock_id as signature request is not passed used for completing communication def delete(request, stock_id): item = Stock.objects.get(pk=stock_id) item.delete() return redirect(add_stock)#redirect back to the page forms.py from django import forms from .models import Stock class StockForm(forms.ModelForm): class Meta: model = Stock fields = ["ticker"] -
Django test cases - data not getting loaded into default database
I am writing test cases to one of my learning project. I have added sample data via admin site, I can see that data successfully. While writing test cases for the same model, seems data not loading into test database. I am not sure what I am missing here. Any suggestions greatly appreciated. todos/models.py from django.db import models # Create your models here. class Todo(models.Model): title = models.CharField(max_length=200) body = models.TextField() def __str__(self): return self.title todos/tests.py from django.test import TestCase from .models import Todo # Create your tests here class TodoModelTest(TestCase): @classmethod def setupTestData(cls): Todo.objects.create(title='first todo', body='a body here') def test_todo_count(self): todo_count = Todo.objects.all() self.assertEqual(len(todo_count), 1) def test_title_content(self): todo = Todo.objects.get(id=1) expected_object_name = f'{todo.title}' self.assertEquals(expected_object_name, 'first todo') def test_body_content(self): todo = Todo.objects.get(id=1) expected_object_body = f'{todo.body}' self.assertEquals(expected_object_name, 'a body here') test result Creating test database for alias 'default'... System check identified no issues (0 silenced). EEF ====================================================================== ERROR: test_body_content (todos.tests.TodoModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tests.py", line 23, in test_body_content todo = Todo.objects.get(id=1) File "/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/python3.9/site-packages/django/db/models/query.py", line 429, in get raise self.model.DoesNotExist( todos.models.Todo.DoesNotExist: Todo matching query does not exist. ====================================================================== ERROR: test_title_content (todos.tests.TodoModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File …