Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best Hosting platform [closed]
I am building a website and I am using tailwind css templates and django in backend. Which will be the easiest and most suitable platform for hosting website in cheap rates? I want SSL certificate too... What are the best options for hosting as well as for buying a good domain? -
FlatList in combination with Axios
I already saw many questions regarding Axios and Flatlist, but none of them helped me to be honest. What I am trying to do: I am fetching a url using axios, which is working fine. I can see the response from the server side as well as when logging the response from the React Native client. Then I was trying to use Flatlist in order to list the favorites (from the response) into the app. I am fetching a url of a server using axios: useEffect(() => { axios.get(`app/appGetFavorites`) .then(res => { //setting favorites as the stringified response of "res" setFavorites(JSON.stringify(res.data)) //string to JSON (works fine) setJson(JSON.parse([favorites])) }) .catch(error => { console.warn('Parse (e): ' + error) }) }, []) the variable favorites is the following when logged (typeof String): [{"id":"2182","name":"Smithfield Foods Inc 2","address":{"street":"Friedhofstraße","street_number":"100","postal":"41472","city":"Neuss","latlng":{"latitude":"51.1609417","longitude":"6.6619322"}},"logo":"192.168.2.109:8000/static/logos/2101.jpg"},{"id":"2344","name":"Weatherford International Inc 2","address":{"street":"Heisterbacher Str.","street_number":"","postal":"47139","city":"DU","latlng":{"latitude":"51.4747044","longitude":"6.6986361"}},"logo":"192.168.2.109:8000/static/logos/2263.jpg"},{"id":"3539","name":"Webwork Innovations GmbH","address":{"street":"Witzelstraße","street_number":"18","postal":"40225","city":"Düsseldorf","latlng":{"latitude":"51.2030737","longitude":"6.7836779"}},"logo":"192.168.2.109:8000/static/companyFiles/2329/logo/logo_1611569379.png"}] This is the view, which is including the FlatList component: return ( <View> <FlatList ListHeaderComponent={renderHeader} data={json} renderItem={renderItem} keyExtractor={item => item.id} /> </View> ) This is the renderItem component, which is used to render an individual favorite item. The properties are sent to an individual component, which is located in another class: const renderItem = ({ item }) => ( <SingleFavorite item={item} … -
Django url path converter not working in production
I'm using path converter in my django app like so: # urls.py from . import views from django.urls import path urlpatterns = [ path('articles/<str:collection>', views.ArticleView), ] # views.py @login_required def ArticleView(request, collection): print(collection) if collection == "None": articles_query = ArticleModel.objects.all() ... This works fine in development for a url suck as : http://localhost:8000/articles/My Collection which gets encoded to http://localhost:8000/articles/My%20Collection, and is decoded properly in the ArticleView. However, in development, I have to edit the view like so to get it to work: # views.py import urllib.parse @login_required def ArticleView(request, collection): collection = urllib.parse.unquote(collection) print(collection) if collection == "None": articles_query = ArticleModel.objects.all() ... Otherwise, the print(collection) shows My%20Collection and the whole logic in the rest of the view fails. This happens in the admin interface as well. requirements.txt asgiref==3.2.10 Django==3.1.1 django-crispy-forms==1.9.2 django-floppyforms==1.9.0 django-widget-tweaks==1.4.8 lxml==4.5.2 Pillow==7.2.0 python-pptx==0.6.18 pytz==2020.1 sqlparse==0.3.1 XlsxWriter==1.3.3 pymysql What am I doing wrong here? Thanks in advance! -
I am trying to run cookiecutter on https://github.com/chopdgd/cookiecutter-django-reactjs and I cannot figure out how to use it
I am new to this and trying to learn, If possible someone please explain to me how to run react with Django using this cookiecutter. I am always getting this error - FileNotFoundError: [Errno 2] No such file or directory: '/app/frontend/build/static'. Thank you for your attention. -
Connecting React JS Front End with Django REST API using axios/fetch
So I have my REST api in Django REST Framework with the following endpoints: app/shipments/create/ app/shipments/list/ app/shipments/retrieve/<str:id> app/shipments/update/<str:id>/ app/shipments/delete/ I installed and configured Django CORS I am using React JS for my frontend and axios for fetching the API URLs. For the frontend: Here is my React Code, which is a form that the user fills and then clicks on submit button: class ShippingRequest extends React.Component{ constructor(){ super(); this.state = { shipments:[], }; //we want to get the shipments everytime the app loads, have them displayed when the application first starts this.getShipments(); } getShipments = async () =>{ try{ let data = await axios.get('http://127.0.0.1:8000/app/shipments/list/') .then(({data}) => data) this.setState({shipments: data}); }catch(error){ console.log(`Shipment Retrieval Error:\n ${error}`); } } createShipments = async () =>{ try{ let response = await axios.post('http://127.0.0.1:8000/app/shipments/create/'); console.log(response); this.getShipments(); }catch(error){ console.log(`Shipment(s) Creation Error:\n ${error}`); } } componentDidMount(){ this.getShipments(); } retrieveShipment = async () =>{ try{ let response = await axios.get("http://localhost:8000/app/shipments/retrieve/"); console.log(response); this.getShipments(); }catch(error){ console.log(error); } } deleteShipments = async () =>{ try{ let data =await axios.delete(`http://localhost:8000/app/shipments/delete/`); this.getShipments(); }catch(error){ console.log(`Shipment(s) Deletion Error: ${error}`); } } updateShipments = async (id, val) =>{ try{ let data = await axios.put(`http://localhost:8000/app/shipments/update/`); this.getShipments(); //to see shipments after updating }catch(error){ console.log(`Shipment(s) Update Error: ${error}`); } } submitHandler … -
Remplir automatiquement un champ avec des données d'autres champs Django
Bonjour ! C'est la première fois que je poste quelque chose, désolé si c'est mal fait ou maladroit. Je travaille sous django en python sur l'une des dernières versions. J'aimerais qu'un de mes champs de mon formulaire (KEY) soit rempli automatiquement avec la concaténation de mes autres champs tel que : KEY = avec 'SENT_' + search_categories + '_' + '001' et que le '001' s'autoincrement. Je ne peux pas vous montrer le model car c'est le code mon entreprise, je ne suis donc pas sûr de la légalité de la chose si je vous fournis le code mais la KEY est définie comme ça dans mon model : key = models.CharField(max_length=30, blank=False, null=False, unique=True) J'espère que vous allez pouvoir m'aider. Merci beaucoup ! -
How to redirect an UpdateView upon success?
I created a small Django application to manage data that fits a simple a model. For now I only need two views: one to list all records and another to edit a record with a generic form. Everything functions as expected, except the redirection from the edit view upon a successful update. In urls.py are the following contents: from django.urls import path from . import views app_name = 'reqs' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.ReqUpdateView.as_view(), name='update'), ] In forms.py: from django.forms import ModelForm from .models import Requirement class RequirementForm(ModelForm): class Meta: model = Requirement fields = ['name', 'priority', 'source' , 'rationale'] And the templeate requirement_form.html: <h1>{{ requirement.id }} - {{ requirement.name }}</h1> <form method="post" novalidate> {% csrf_token %} <table> {{ form.as_table }} <tr><td></td><td><button type="submit">Save</button></td></tr> </table> </form> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <br><br> <a href="{% url 'reqs:index' %}">Back to list</a> Finally views.py, on a first attempt to redirect the update to the list: from django.views.generic import ListView, UpdateView from django.urls import reverse_lazy from .models import Requirement from .forms import RequirementForm class IndexView(ListView): template_name = 'reqs/index.html' context_object_name = 'requirements_list' def get_queryset(self): return Requirement.objects.order_by('subject') class ReqUpdateView(UpdateView): model = Requirement form_class = RequirementForm success_url = reverse_lazy('/') With this formulation … -
Assign a simple HTML site with django
I want to assign/add a simple static HTML site to my django site. I know that's not what django is for but at the beginning I just want to create a simple site with a href to the other directories on the project. For e.g. index.html <html> <head></head> <body> <a href="/speiseplan">anzeige</a><br /> <a href="/speiseplanEdit">Speiseplan </a><br /> <a href="/speiseplan">Menu1</a><br /> <a href="/speiseplan">Menu2</a><br /> <a href="/speiseplan">Menu3</a><br /> </body> </html> Now I want to add this site to urls.py. I read that it shoud be possible with TemplateView. I already tried this: urlpatterns = [ path('', TemplateView.as_view(template_name="/templates/speiseleitsystem/index.html")), path('speiseplan/', views.speiseplan_Anzeige, name='speiseplan_Anzeige'), path('speiseplanEdit/', views.speiseplan_Eintragen, name='speiseplan_Eintragen'), path('menu1/', views.speiseplan_menu1, name='speiseplan_menu1'), path('menu2/', views.speiseplan_Anzeige, name='speiseplan_menu2'), path('menu3/', views.speiseplan_Anzeige, name='speiseplan_menu3'), ] Did I missed something? -
Is it possible to add/remove HTML Attributes for every formfield in Django
My goal is to remove the required tag from every formfield in my django app. The problem is that I've installed some 3rd party libraries and I want to remove it from their forms either. I thought about creating a custom Formrenderer, but I'm not shure how or maybe you have another idea. -
button on list_display django admin
I want to create a button called check Issues for each instance of my Scenario class. But the button it doesn't work. I am going to show you the code: class Scenario(TemporalObject): ... def def issues_button(self): return format_html( '''<form action="issue/" method="POST"> <button type="submit">Check Issues</button> </form>''') class ScenarioAdmin(admin.ModelAdmin): list_display = ("name", "user", "start", "end", "nb_hours","issues_button") ... def get_urls(self): urls = super().get_urls() my_urls = [ django.urls.path('issue/', self.gen_issues), django.urls.path('duplicate/', self.gen_duplicate), ] return my_urls + urls def gen_issues(self, request): if len(request.user.username) > 0: queryset=self.get_queryset(request) if len(queryset) > 0: for i in range(len(queryset)): sv = ScenarioVerifier(queryset[i]) sv.verify() return HttpResponseRedirect("../") else: self.message_user(request,"The queryset is empty" ,level=messages.ERROR) return HttpResponseRedirect("../") What I have to change?? -
Create a CRUD API for django auth permission ang groups tables
I'm new to Django and i am working on an application, and i want to create a CRUD API for the Authentication permission and groups tables I do not want to add permissions in models because i don't know all the permissions and groups needed, that's why i want to give access to the user to create the permission and group he want and manage every thing by CRUD API i did not find an example to do that with Django Thanks i am using latest django version and the django rest framework -
django.db.utils.ProgrammingError: relation "web_workspace" does not exist on running tests
I am writing tests in one of my django(Django==3.1.6) projects. After writing and testing around 10 tests, today when i ran them i got an error relation "web_workspace" does not exist resulting in aborting the tests. However, on running the project i.e python manage.py runserver my project runs flawlessly. Here is a screenshot with complete traceback i am getting on running tests I have stripped all the test cases and kept only one just to keep things minimal for this question, and i am still getting this error. Here is the test code for API i am using. from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase def confirm_success_response(self, response, expected_response, match_values=False): self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIsInstance(response.data, dict) self.assertEqual(set(response.data.keys()), set(expected_response.keys())) if match_values: self.assertEqual(response.data, expected_response) class APItests(APITestCase): # pre and post test methods def setUp(self): pass def tearDown(self): pass # methods for tests internal use # Actual API test methods def test_dummy_api(self): url = reverse('test') response = self.client.get(url, None, format='json') expected_response = {'success':True, 'message': "Api passed test"} confirm_success_response(self, response, expected_response, True) Things i have already tried but didn't work: Delete migrations directory and recreating migrations and migrating them. Running app specific migrations as python manage.py makemigrations <app_name> and then migrating … -
Django social auth collect githb data and save into a database
Currently i am using social-auth-app-django to create an interface for users to login and I wish to collect their data in the back end. I've already managed to do the authorization but i cannot access their data. I wish to: Disable the default of saving user info into the auth_user table, as i only wish to store their github information, I don't need any other functionality. Fetch the user's github access token and request their github information via github's API inside the home views function, and save it into another database i created (not auth_user). settings.py AUTHENTICATION_BACKENDS = ( 'social_core.backends.github.GithubOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GITHUB_KEY = 'XXXXXXXXXXXXXXXX' SOCIAL_AUTH_GITHUB_SECRET = 'XXXXXXXXXXXXX' SOCIAL_AUTH_GITHUB_SCOPE = [ "read:user" ] LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = 'home' core's urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("", include('mystats.urls')), path('oauth/', include('social_django.urls', namespace='social')) ] app's urls.py from django.urls import path from . import views urlpatterns = [ path("myoauth/", views.myoauth, name="myoauth"), path("", views.home, name="home") ] app's views.py from django.shortcuts import render def myoauth(request): return render(request, 'app/myoauth.html') def home(request): ################################################ # I want to do something here # access the github access token of a user and use the Github API to … -
Make it so url can only be accessed through redirect
I am redirecting my users from a paypal payment to the register.html so that you can only register once you have paid the subscription. How do I make it so that this redirect is the only way to access the page and not simply by putting mysite.com/register in the browser? I have pages where login is required but obviously this will be before a user has registered so cannot do that. -
Add option to change columns and data dynamically in Django Admin changelist_view
Is it possible to change the columns displayed in a models's admin changelist_view page dynamically? For example: Include a toggle button that depending on its state will change the order of the columns displayed or even display new columns (with new headers) that are already part of the model. Or even maybe add a new column that has operations performed with the model object? More practical example: I have a Region model and within the region I have a Sale related model of all the sales performed in that region. So in the Region changelist_view, if I toggle the button I will display the total sum of the sales per region or, if I untoggle the button, I will display the percentage in relation to the total. -
Wagtail - Expand Orderable / InlinePanel functionality
What I am trying to do is attempted before in different forms: Add Taxonomy to Wagtail, a feature present in most other popular CMSs (Drupal as "Taxonomy", Craft as "Categories, ...). I know Wagtail has some type of implementation called "Collections" but it is not as fully fledged as other implementations and its interface does not cater to large trees. My approach: Build upon Orderable models, as they already give us a nice way to order child items related to an other model (think Menu -> MenuItems). Together with InlinePanel, Orderables give you a nice interface to manage your main Taxonomy name and all of its "nodes". Yet, an Orderable is one-dimensional, it only goes up or down via a sort_order column on the Orderable model. My idea is to provide a second dimension, to go left or right, with a parent column. A super simple data model: class NestedOrderable(Orderable): parent = models.IntegerField(null=True, blank=True, editable=False) class Meta: abstract = True ordering = ['parent', 'sort_order'] Now in the InlinePanel, the sort order gets inserted as a hidden field on each child item. I am trying to now find a way to get this parent attribute to be included into the HTML … -
IntegrityError at /images/create/ NOT NULL constraint failed: images_image.users_like_id
I'm working on a project from the book 'Django3 by example'. I want to add an image from the URL which the user provided. But when I try to save the page it gives me this error: IntegrityError at /images/create/ NOT NULL constraint failed: images_image.users_like_id. I have tried the solutions other posted but it didn't help. Here is my code: models.py from django.db import models from django.conf import settings from django.utils.text import slugify class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='images_created') users_like = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='images_liked') title = models.CharField(max_length=100) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to='images/%Y/%m/%d/') description = models.TextField() created = models.DateField(auto_now_add=True, db_index=True) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super().save(*args, **kwargs) views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import ImageCreateForm @login_required def image_create(request): if request.method == "POST": form = ImageCreateForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data new_item = form.save(commit=False) new_item.user = request.user new_item.save() messages.success(request, 'Image added successfully') return redirect(new_item.get_absolute_url()) else: form = ImageCreateForm(data=request.GET) context = {'section':'images', 'form':form} return render(request, 'images/image/create.html', context) forms.py from django import forms from urllib import request from django.core.files.base import ContentFile from django.utils.text import slugify from .models import Image … -
Two django forms result in empty boto3 upload
When using two forms in one template / view, I am getting an empty file uploaded to S3. Removing one of the forms, results in an upload with more than 0 bytes. Example for working view: def test(request): file_form = UploadFilesForm() if request.method == 'POST': file_form = UploadFilesForm(request.POST, request.FILES) file = request.FILES['file'] s3_client = boto3.client('s3', region_name=settings.AWS_ZONE, aws_access_key_id=settings.AWS_KEY, aws_secret_access_key=settings.AWS_SECRET) response = s3_client.upload_fileobj(file, '', bucket'test2.pdf') return HttpResponse('uploaded') return render(request, 'upload.html', {'fileform': file_form}) Not working view: def index(request, company, key): context = { 'company': 'Sample Co.', } if request.method == 'POST': form = CaseForm(request.POST) file_form = UploadFilesForm(request.POST, request.FILES) if form.is_valid(): case = form.save() if file_form.is_valid(): file_form = file_form.save(commit=False) if 'file' in request.FILES: file = request.FILES['file'] if file: file_type = file.content_type extension = file.name.split(".")[-1] s3_client = boto3.client('s3', region_name=settings.AWS_ZONE, aws_access_key_id=settings.AWS_KEY, aws_secret_access_key=settings.AWS_SECRET) response = s3_client.upload_fileobj(file, 'bucket', 'test2.pdf') file_form.filename = filename file_form.case = case file_form.save() return redirect('confirmation') else: form = CaseForm() file_form = UploadFilesForm() return render(request, 'upload.html', {'form': form, 'fileform': file_form, 'context': context}) The file object is definitely there, as I can print(file.file), print(file.read())... Even size is shown correctly. It is just not uploading the bytes to S3. -
Remove add button in Django admin Many-to-many field
How can I remove add button in Many-to-many field selection from Django admin? See this screen Thank you. -
Only show the posts which are published before now ( Scheduling BlogPosts to post in future)
I am building a BlogApp and I am building a Feature that Users can schedule posts to post at the time user is selected. I do it with the help of Timezone. What am i doing I filtering posts which are published before now AND i am Not showing the posts that's time is settled up to post in future. It means when the user is selected time for the Future in DateTimeField in Create BlogPost section then the post is posted but not showing in BlogPosts list. It will be seen or post at the time which is set up by User. The Problem When i filter BlogPosts to show the all BlogPosts which are published now and before, then they are not showing in Page. models.py class BlogPost(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') date_added = models.DateTimeField(auto_now_add=True,null=True) views.py def posts(request,user_id): now = timezone.now() posts = BlogPost.objects.filter(date_added=now) context = {'posts':posts} return render(request, 'posts.html', context} posts.html {% for post in posts %} {{ post.post_title }} {{ post.post_owner }} {% endfor %} I don't know what am i doing wrong. Any help would be appreciated. Thank You in Advance. -
python Django reportlab can't find msyh.ttf file
When I use from reportlab.pdfbase import pdfmetrics pdfmetrics.registerFont(TTFont('msyh', 'msyh.ttf')) I meet a bug that is reportlab.pdfbase.ttfonts.TTFError: Can't open file "msyh.ttf" However, if I download the msyh.ttf file and use an absolute path like pdfmetrics.registerFont(TTFont('msyh', r'C:\Users\xxx\xxx\xxx\xxx\msyh.ttf')) It works. How could I fix this bug ? -
datetime filed shwo me charfield only django
i'm trying to show a date time Field like in the admin page or any other representation for the datetime Field but it did not work i try few thnigs, but nothing work this is my model.py file class Listing(models.Model): creator = models.ForeignKey(User, on_delete=models.PROTECT, related_name="all_creators_listings") title = models.CharField(max_length=60) description = models.CharField(null=True, max_length=500) startingBid = models.FloatField() min_adding_bid = models.FloatField() # adding the min adding bid and add this to the condution flActive = models.BooleanField(default=True) currentBid = models.FloatField(blank=True,null=True) created_date = models.DateTimeField(default=timezone.now) close_date = models.DateTimeField(null=True) # adding the end of the listing blank=True, null=True category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE ,related_name="similar_listings") watchers = models.ManyToManyField(User, blank=True, related_name="watched_listings") buyer = models.ForeignKey(User, null=True, on_delete=models.PROTECT) def __str__(self): return f"{self.title} - {self.startingBid} - {self.currentBid}" def save(self, *args, **kwargs): if not self.close_date: raise ValidationError("close date missing!! Please add the the closing dateand time") if not self.close_date > self.created_date: raise ValidationError("the closing date must be grater than the current date") and this is my forms file class newListingForm(forms.ModelForm, forms.DateTimeField): """Form definition fos New_listing_.""" class Meta: """Meta definition fos New_listing_form.""" # close_date = forms.DateTimeField(initial=timezone.now) ----> not working # close_date = forms.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) ----> not working # def __init__(self, *args, **kwargs): # super(newListingForm, self).__init__(*args, **kwargs) # self.fields['close_date'] = forms.DateTimeField(input_formats=['%Y-%m-%d %H:%M'],widget=XDSoftDateTimePickerInput(attrs={'minDate':time.date(),'allowTimes':'12:00','class':'cal'}),label='Окончание аренды') # … -
How can I show all users I follow?
I have models: Profile mode class Profile(AbstractUser): following = models.ManyToManyField("self", through=UserFollowing, related_name="followers", verbose_name=_("following"), symmetrical=False) And UserFollowing model class UserFollowing(models.Model): following_from = models.ForeignKey("Profile", related_name="following_from", on_delete=models.CASCADE, verbose_name=_("Following from")) follow_to = models.ForeignKey("Profile", related_name="follow_to", on_delete=models.CASCADE, verbose_name=_("Following to")) created = models.DateTimeField(auto_now_add=True, db_index=True) How can I show all profiles I follow? How Can I setup query set to show al followers and followed Profiles? Profile.objects.filter... ? -
how can i order items based on a method
i wanna know how can i order a listView using a method , like here i wanna order my posts based on numbers of likes , i am using class based views ... here is my code models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) # content = models.TextField() content = RichTextField(blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) post_image = models.ImageField(upload_to='post/cover') category = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() likes = models.ManyToManyField(User, related_name='blogpost_like') def __str__(self): return self.title def get_absolute_url(self): return reverse("core:detail", kwargs={ 'slug': self.slug }) def delete(self, *args, **kwargs): self.post_image.delete() super().delete(*args, **kwargs) @property def comment_numbers(self): return Comment.objects.filter(post=self).count() def number_of_likes(self): return self.likes.count() views.py class PostListView(ListView): model = Post template_name = 'home.html' context_object_name = 'posts' paginate_by = 6 ordering = ['-date_created'] -
Getting items related to selected foreign key in django
I'm building a django app that has customers model and projects model and tasks model. in tasks model I can select the customer name and project but the problem is that in admin panel it shows all the projects, is there any way to show projects only for the selected customer from django.db import models from django.contrib.auth.models import User from suppliers.models import Currency from users.models import Profile class Customer(models.Model): customer_id = models.AutoField(primary_key=True) customer_first_name = models.CharField(max_length=200) customer_last_name = models.CharField(max_length=200) company = models.CharField(max_length=200) customer_phone = models.CharField(max_length=200) customer_address = models.CharField(max_length=200) email = models.EmailField(null=True, blank=True) website = models.CharField(max_length=200, null=True, blank=True) creation_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) notes = models.TextField() def __str__(self): return str(self.customer_first_name) + ' ' + str(self.customer_last_name) class Account(models.Model): max_discount = models.DecimalField(max_digits=2, decimal_places=2) credit_limit = models.DecimalField(max_digits=20, decimal_places=2) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) currency = models.ForeignKey(Currency, on_delete=models.CASCADE) sales_man = models.OneToOneField(User, on_delete=models.CASCADE) Agent = models.OneToOneField(Profile, on_delete=models.CASCADE) status = models.BooleanField(default=True) reason = models.TextField() class TaskPriority(models.Model): priority_id = models.AutoField(primary_key=True) task_priority_name = models.CharField(max_length=200) def __str__(self): return str(self.task_priority_name) class Project(models.Model): project_id = models.AutoField(primary_key=True) project_name = models.CharField(max_length=200) project_balance = models.DecimalField(max_digits=20, decimal_places=2) customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) notes = models.TextField() def __str__(self): return str(self.project_name) class Task(models.Model): task_id = models.AutoField(primary_key=True) task_name = models.CharField(max_length=200) customer_name = models.ForeignKey(Customer, …