Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid HTTP_HOST header: The domain name provided is not valid according to RFC 1034/1035
Our Django server is often having this error: Invalid HTTP_HOST header: u'/home/appname/run/gunicorn.sock:'. The domain name provided is not valid according to RFC 1034/1035. I think this happens when the host is a real IP rather than a domain name. If you're thinking why such a host is making it to the Django app, it's because we're actually actually any host: ALLOWED_HOSTS = ['.appname.org', '*'] And we want to keep it this way because we're allowing clients to point their own domains to our proxy. We have a DomainNameMiddleware which checks the host name against our database and if not found, the request is rejected. However, it seems the "Invalid HTTP_HOST header" error happens before our domain name middleware runs, so the error is raised when our middleware would've handled it silently. How can I have this error fail silently? -
How to convert ajax code into vue.js axiox method in django
If user click on like button web page not refresh and count of the likes also updated without refreshing so, In first I have written in ajax then I want to convert it into vue.js after converting into vue.js its not working. Can any one please help me to achieve this. Here I have written vue.js axios method. That I have accessed in html template html template <div id = "deals-vikreya"> <a class="likebutton" style=" {% if request.session.email %}pointer-events: auto; {% else %}pointer-events: none;{% endif %}" id="like-{{i.id}}" href="#" data-catid="{{ i.id }}"> <i class="fa fa-thumbs-o-up" id="like-icon-{{i.id}}" aria-hidden="true" style="color: gray"></i> </a> <span id="cm_count{{i.id}}"> ({{ c_count }}) </span> </div> vue.js axiox <script> new Vue({ el: '#deals-vikreya', data() { return {}; methods: { $('.likebutton').click(function(){ var catid; catid = $(this).attr("data-catid"); console.log(catid); axios( { method : "POST", url: "{% url 'post_comment_like' + catid %}", //django path name data:{ post_id: catid }, success: function( data ) { console.log("like saved"); console.log(data.comment_count); document.getElementById("cm_count"+catid).innerHTML ="(" + data.comment_count + ")"; $( '#like-'+ catid ).attr("href", "/post_comment_like_remove/" + catid); $( '#like-icon-'+ catid ).css("color", "#DB0038"); } }) }); }, }) </script> -
ValueError: Missing staticfiles manifest entry for 'css/homepage.css' heroku
i am trying to deploy my django app on heroku and i am unable to collect static files. i tried many things including whitenoise but it still shows error ValueError: Missing staticfiles manifest entry for 'css/homepage.css' and there is internal server error due to this my settings: please help THANK you -
Django filter check if small range is in a bigger range
I want to check a simple logic, for example if 15 - 25 is inside 1 - 100. I tried gte, lte and range but no luck. It does not match what I need. Here is my sample code: if obj.max_number == 0: objRange.append(Q(number_min__gte=obj.min_number) and Q(number_max__gte=obj.min_number)) elif obj.min_number == 0: objRange.append(Q(number_min__lte=obj.max_number) and Q(number_max__lte=obj.max_number)) else: objRange.append(Q(number_min__range=(obj.min_number, obj.max_number))) objRange.append(Q(number_max__range=(obj.min_number, obj.max_number))) Note, I only need the else part since if and elif is a working condition -
I have to display 'location' with respective to the 'latitude' and 'longitude'. Got the desired location printed in the console but not getting saved
I tried many approaches including SerializerMethodField and didn't work. I want to print the location in the result with respect to the latitude and longitude from the models. Models.py class CustomerProfile(models.Model): location = models.PointField(default=Point(0,0),geography=True) latitude = models.DecimalField(blank=True,max_digits=9,decimal_places=6,default=None,null=True) longitude = models.DecimalField(blank=True,max_digits=9,decimal_places=6,default=None,null=True) Serializer.py class CustomerSerializer(serializers.ModelSerializer): class Meta: model = CustomerProfile fields = "__all__" Views.py from django.contrib.gis.geos import GEOSGeometry class CustomerView(APIView): def get(self, request, format=None): query = CustomerProfile.objects.all() serializer = CustomerSerializer(query, many=True) return Response(serializer.data) def post(self, request,data,format=None): serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): lat=getattr(data,"latitude") lon= getattr(data,"longitude") lat_1 = float(str(lat)) lon_1 = float(str(lon)) print(lon_1) if lat_1 and lon_1: location = Point((lat_1, lon_1), srid=4326) print(location) if location: loc=getattr(data,"location") print(loc) loc=location Serializer.save() return Response({"message":"Customer Profile Updated Successfully","data":serializer.data}, status=200) return Response({"message":"Customer registration failed!!","data":serializer.data}, status=400) -
Excel file cannot be auto download by browser
My server is based on Django, below is the response for my download request. ... stream_file = BytesIO() pivot_df.reset_index() pivot_df.to_excel(stream_file) stream_file.seek(0) response = StreamingHttpResponse(stream_file) response['Content-Type'] = 'application/octet-stream;' response['Content-Disposition'] = 'attachment; filename="{}.xlsx"'.format('account_data') return response The size of response is about 33.13MB, after a period of time my browser doesn't response anything. It showed Failed to load reponse data. Request URL: https: xxxxxx Request Method: POST Status Code: 200 OK Remote Address: xxxxxx Referrer Policy: strict-origin-when-cross-origin But if I try this request with Postman, I can get right file data. Why cannot I get excel file download from browser. Thanks. I'm using Chrome 90.0.4430.93 -
Changes are not being reflected in template even after cache expiry( TIMEOUT-180 ) in django?
Using filebased cahche in django, and set 3-minutes of timeout , But even after cache expiry, Page is being loading wiht the same content in template and not with the new data middleware in settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] using filebasedbackend for cache CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': 'cahcefiles', } } -
Using User module of the Django where it is saving the data
I am using User module to save the data for the registration from django.contrib.auth.models import User ## forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required = True) class Meta: model = User fields = ('username', 'email', 'password1', 'password2') ## views.py def register_request(request): if request.method == 'POST': form = forms.NewUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') and this is working but I want to in which table Django is saving the data... -
Showing user_1 that user_2 is typing
I am building a ChatApp and I am trying to implement a Feature that shows another user that User is typing in chat. User is typing is showing correctly to user who is typing BUT it is not showing in another side of user which is seeing that user_1 is typing. template.html <input type="textbox" id="typer" placeholder="Start typing here..." /> <div id="status"></div> <script> let timer, timeoutVal = 1000; // time it takes to wait for user to stop typing in ms const status = document.getElementById('status'); const typer = document.getElementById('typer'); typer.addEventListener('keypress', handleKeyPress); typer.addEventListener('keyup', handleKeyUp); // when user is pressing down on keys, clear the timeout function handleKeyPress(e) { window.clearTimeout(timer); status.innerHTML = 'Typing...'; } // when the user has stopped pressing on keys, set the timeout // if the user presses on keys before the timeout is reached, then this timeout is canceled function handleKeyUp(e) { window.clearTimeout(timer); // prevent errant multiple timeouts from being generated timer = window.setTimeout(() => { status.innerHTML = 'All done typing! Do stuff like save content to DB, send WebSocket message to server, etc.'; }, timeoutVal); } </script> <style> #typer { padding: 8px; font-size: 1.2em; } #status { padding: 10px; font-size: 1.1em; } </style> I tried by making a … -
Django PhoneNumberField library giving problem when using bootstrap class
I am using PhoneNumberField library. But when I access the field and give bootstrap class, the layout changes. It displays PhoneNumberPrefixWidget in one line and PhoneNumberField in another line. I want them to display next to each other. I tried using for loop but I still couldn't get what I want. forms.py phone_no = PhoneNumberField( widget=PhoneNumberPrefixWidget(attrs={'class': 'form-control'}) ) In settings.py PHONENUMBER_DB_FORMAT = 'NATIONAL' PHONENUMBER_DEFAULT_REGION = 'BT' In my html template {{ form.phone_no }} Is there a way to access this fields separately? By default when I access {{form.phone_no}}, both the fields appear together Thanks in advance -
Chartjs splitting double digit numbers
I have seen this question asked a few times but I couldn't find a solution that worked for me. I am passing a Django variable into Chartjs to plot, all of the single-digit numbers are correct but it turns double-digits into single. Like 11 is 1,1...23 is 2,3. I have tried a bunch of different ways but cant figure it out, I appreciate any help you can offer. var home_runs = '{% for game in all_games.home_ten %}{{ game.runs }}{% endfor %}' var ctx = document.getElementById('runChart').getContext('2d'); var runChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [ { label: home_team, data: home_runs }, { label: away_team, data: away_runs, ], } ] }, options: { responsive: true, }, }); -
Form.cleaned_data form not found in django
I am trying to auto create an agent from user. once a user signed up, it creates and agent successfully but it doesn't inherit it's name, and email from the signup form. I tried using Cleaned data but it says form not found. what should I do? here is my models.py: from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser from django import forms class User(AbstractUser): is_techtanium = models.BooleanField(default=False) is_organizer = models.BooleanField(default=False) is_agent = models.BooleanField(default=True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class Client(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=20) mobile_number = models.CharField(max_length=12) email = models.EmailField() organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) agent = models.ForeignKey("Agent", related_name="clients", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="clients", null=True, blank=True, default=4, on_delete=models.SET_NULL) company_name = models.CharField(max_length=50 , default=None) street_address = models.CharField(max_length=50 , default=None) baranggay = models.CharField(max_length=50 , default=None) city = models.CharField(max_length=50 , default=None) region = models.CharField(max_length=50 , default=None) date_added = models.DateTimeField(auto_now_add=True) phoned = models.BooleanField(default=False) special_files = models.FileField(blank=True , null=True) def __str__(self): return f"{self.first_name} {self.last_name}" class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True, blank=True) middle_name = models.CharField(max_length=20, null=True, blank=True) last_name = models.CharField(max_length=20, null=True, blank=True) agent_type = models.CharField(max_length=20, null=True, blank=True) email = models.EmailField(null=True, blank=True) … -
got image from one model to second models via views and make a copy in pillow and save to new path,how to get new path img and old path img in html
model ''' class generated_certificates(models.Model): certifyuser = models.ForeignKey(User, related_name = "generated_certificates", on_delete=models.SET_NULL,null=True) cerficpic = models.ImageField(upload_to = 'pictures/generatedslips', null = True, blank = True) cerficpic2 = models.ImageField(upload_to = 'pictures/generatedslips', null = True, blank = True) cerficpic3 = models.ImageField(upload_to = 'pictures/generatedslips', null = True, blank = True) description = models.TextField(null = True) timestamp = models.DateTimeField(auto_now_add = True) def save(self, *args, **kwargs): userdata = self.certifyuser userprofile = profileforsurvay.objects.get(user = userdata) userrating = str(userprofile.total_rating) usertotalviews = str(userprofile.viewcounts) usergrade = str(gradcounter(userdata)) stamp = stampgenerator(usergrade, userrating, usertotalviews) if self.cerficpic: initial_path = self.cerficpic.path imag = self.cerficpic ext = initial_path.split('.')[-1] filename = "%s.%s" % (userdata, ext) new_path=os.path.join(os.path.dirname(initial_path),"generatedslips/",filename) print(new_path) newimg = paststamp(imag, stamp) newimg.name=imag.name newimg.path=new_path newimg.save(newimg.path) super().save(*args, **kwargs) #image saved to newpath but how to get newpath img in html template # if you see template code it show oldpath img my views where i copy images from other model named profileforsurvay# def generate_slip(request): profile = profileforsurvay.objects.get(user = request.user) img = profile.userpics.pic img2 = profile.userpics.pic2 img3 = profile.userpics.pic3 description = profile.description latests = generated_certificates(certifyuser = request.user, cerficpic = img, cerficpic2 = img2, cerficpic3 = img3, description = description) latests.save() return render(request, 'generate_slip.html') my template to show image: {% if i.cerficpic %} <div class="col-6 col-md-4" style="widh:500;height:500"><img src="{{i.cerficpic.url}}" > </div> {% endif … -
How to send the current form tab in a request.POST via JavaScript
I have a form, in the form I have a series of objects, for each object there is a tab. For example: object 1: tab1 object 2: tab2 object 3: tab3 Code example: <ul class="nav nav-pills" id="evidence-formset-tab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="evidence-form-1-tab" data-toggle="pill" href="#evidence-form-1" role="tab" aria-controls="evidence-form-1" aria-selected="true">1</a> </li> <li class="nav-item"> <a class="nav-link" id="evidence-form-2-tab" data-toggle="pill" href="#evidence-form-2" role="tab" aria-controls="evidence-form-2" aria-selected="false">2</a> </li> </ul> I would like to know the value of the selected tab at the time of submitting the form. function validateRegister() { event.preventDefault(); $('#evidence-formset').attr('action', "{% url 'interpretation' %}").submit(); } Is there a way to inject the value of the current tab and then process it in the (request.POST) in the backend? -
Django Tutorial Error in Tutorial 4 (OperationalError at /polls/1/)
I m new to coding and web development, but I am keen to learn and progress. I have encountered this error during template rendering. Checked issues but cant find any answer can anyone help on this. Not able to understand what is the operational error. Error displayed on screen is as follows OperationalError at /polls/1/ no such column: polls_choice.id Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/ Django Version: 3.2.1 Exception Type: OperationalError Exception Value: no such column: polls_choice.id Exception Location: /Users/rishipalsingh/Projects/notes/mysite_dj1/venv/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /Users/rishipalsingh/Projects/notes/mysite_dj1/venv/bin/python3 Python Version: 3.9.0 Python Path: ['/Users/rishipalsingh/Projects/notes/mysite_dj1/mysite', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/rishipalsingh/Projects/notes/mysite_dj1/venv/lib/python3.9/site-packages'] Server time: Fri, 07 May 2021 10:20:59 +0530 Error during template rendering In template /Users/rishipalsingh/Projects/notes/mysite_dj1/mysite/polls/templates/polls/detail.html, error at line 10 no such column: polls_choice.id 1 2 <!--Option 3--> 3 4 <h1>{{ question.question_text }}</h1> 5 6 {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} 7 8 <form action="{% url 'polls:vote' question_id=question.id %}" method="post"> 9 {% csrf_token %} 10 {% for choice in question.choice_set.all %} 11 <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> 12 <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> 13 {% endfor %} 14 <input type="submit" value="Vote"> 15 </form> 16 17 <!-- 18 {{ question }} 19 20 --> polls/views.py def vote(request, question_id): … -
does image extension matters in django projects (like jpg and png)
am trying to load static and adding image in my project and I get this error "GET http://localhost:8000/static/kpn.jpg 404 (Not Found)" please I need your help -
Only one word is reading from .txt file
I am building a BlogApp and I am implementing a Feature, What i am trying to do :- I am trying to read and work on .txt file BUT when i write one word then it works fine BUT when i write two words then it is not working. views.py def defining(request): with open('wordlists.txt') as in_file: wordlist = in_file.read().splitlines() posts = Post.exclude.exclude(reduce(operator.and_,(Q(description__contains=x) for x in wordlist))) context = {'posts':posts} return render(request, 'defining.html', context) wordlists.txt good bad When i add good word ( only one word ) then it works fine BUT when i add bad after good then both doesn't work. I have no idea, where is the mistake. Any help would be Appreciated. Thank You in Advance. -
How to update my data on the DOM after updating on Django?
My code seems to work and it updates the likes on the backend and also the innerHTML of the like button changes on click. But How can I display the value of likes after clicking on the button? currently, I need to refresh the page. I have tried to add .then after fetching but I did not succeded to understand it completely and how to put it together with my POST method Thanks for any help! index.js function build_post(post){ // create new div for each thing that needs to be shown current_logged_in_user = document.querySelector('#user_detail').value; const element = document.createElement('div'); const post_username = document.createElement('div'); const post_description = document.createElement('div'); const post_date_added = document.createElement('div'); const post_likes = document.createElement('div'); // add the text for each div post_username.innerHTML = 'Username: ' + post.poster; post_description.innerHTML = 'Content: ' + post.description; post_date_added.innerHTML = 'Date: ' + post.date_added; post_likes.innerHTML = 'Likes: ' + post.likes; // append all divs to display-post element.appendChild(post_username); element.appendChild(post_description); element.appendChild(post_date_added); element.appendChild(post_likes); element.classList.add('element'); post_username.addEventListener('click', function() { load_user_info(post.poster); load_user_posts(post.poster); }); const like_button = document.createElement('button'); fetch(`/like/${post.id}`) .then(response => response.json()) .then(data => { result = data.result if(result == true){ like_button.innerHTML += 'Unlike' element.appendChild(like_button); }else{ like_button.innerHTML += 'Like' element.appendChild(like_button); } like_button.addEventListener('click', function() { if(like_button.innerHTML === 'Like'){ like_button.innerHTML = 'Unlike' }else{ like_button.innerHTML … -
Confused between OPTIONS request and GET request
I am totally new to REST and django-restframework and I am lost. In normal Django forms we have a form with the ForiegnKey field populated as dropdpwn. A user can select any option from that list. But I am not able to grasp how it is supposed to work in django-restframwork. I want to expose APIs for frontend developer so that they can know what options they can make available to a user and what options are already selected, if it is an update, for example. Doing some reading on SO and other sites I came across OPTIONS request and metadata. It does expose available choices for a ForeignKey field when I make OPTIONS request in browseable API. But I am confused and unsure whether it is what my frontend developers would expect or I will have to rework on it. This problem is not related code so I am not posting any code. It is general about my understanding and confusion of how I am supposed to expose available choices to frontend developers. What is wrong with using SerializerMethodField to send available choices instead of using of metadata(for OPTIONS request)? Why shouldn't we send the available choices in GET … -
TypeError: Cannot cast AnonymousUser to int. Are you trying to use it in place of User?
Upon attempting to test an AJAX request with an authenticated user, I'm getting the following error: TypeError: Cannot cast AnonymousUser to int. Are you trying to use it in place of User? Upon debugging the view it's saying that an AnonymousUser is being attached to the request. Even though I have created a custom APIClient that logs in a User. I have used the following method as suggested by the docs: https://www.django-rest-framework.org/api-guide/testing/#authenticating Why is an Anonymous User being attached to the request in the case? Here is the scenario I'm attempting: Login a User through a Django login view; User successfully logs in User accesses a login_required protected view to vote on a topic User upvotes/downvotes the topic API call made to validate the request to a DRF view tests.py class TestQuestionDuplicateUpvote(APITestCase): '''Verify that a client is informed that they already voted on a question posted.''' @classmethod def setUpTestData(cls): cls.user = User.objects.create_user('Mock', password="mocksecret") cls.client = APIClient() cls.client.login(username="Mock", password="mocksecret") def test_user_upvote_posted_question(self): response = self.client.put( reverse("questions_api:vote", kwargs={"id": 1}), data = {'vote': 'upvote'} ) new_vote_tally = self.question.votes.count() self.assertEqual(response.status_code, 400) self.assertEqual(new_vote_tally, self.old_vote_tally) self.assertIn(response.data['error'], "You have already voted") views.py class UserQuestionVoteView(APIView): renderer_classes = [JSONRenderer, ] parser_classes = [JSONParser, ] authentication_classes = [SessionAuthentication, ] throttle_classes = … -
Function returning multiple checkbox inputs not being rendered in Django
I have a database call to retrieve some records in my views.py def database(request): if request.method=="POST": #connect to the database #retrieve the results res = cur.fetchall() area_input = forms.DefineArea() tables_input = forms.DefineArea().print_tables(res) cur.close() con.close() dictionary = {'area_input': area_input, 'tables_input': tables_input} return render(request, "main/tables.html", context=dictionary) In my forms.py I have: from django import forms class DefineArea(forms.Form): area_name = forms.CharField(max_length=150) @staticmethod def print_tables(res): tables = [] for row in res: tables.append((row[0], row[0])) tables_input = forms.MultipleChoiceField(choices=tables, required=False, widget=forms.CheckboxSelectMultiple()) return tables_input I know this is working because if I return tables instead of tables_input, I see all the tables printed in the HTML. But when I test it in Postman I see the object reference to location instead: <django.forms.fields.MultipleChoiceField object at 0x000001DCF24FB828> Object not rendered But if I change it like I mentioned: class DefineArea(forms.Form): area_name = forms.CharField(max_length=150) @staticmethod def print_tables(res): tables = [] for row in res: tables.append((row[0], row[0])) tables_input = forms.MultipleChoiceField(choices=tables, required=False, widget=forms.CheckboxSelectMultiple()) return tables tables is just the list of tables I get from the database: All the records from the database being displayed from the list Do I need to do something to render the Django object? -
Django Install requirement
ERROR: Command errored out with exit status 1: 'C:\Users\mostafafci_1146\Desktop\port\cv\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\mostafafci_1146\AppData\Local\Temp\pip-install-9mgdur4a\pillow_1609587497bb4640864de2290f45836a\setup.py'"'"'; file='"'"'C:\Users\mostafafci_1146\AppData\Local\Temp\pip-install-9mgdur4a\pillow_1609587497bb4640864de2290f45836a\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\mostafafci_1146\AppData\Local\Temp\pip-record-koh1qob_\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\mostafafci_1146\Desktop\port\cv\include\site\python3.8\Pillow' Check the logs for full command output. -
Handling the TypeError: conversion from NoneType to Decimal is not supported
I am trying to get the typed amount from my template to my views in order to calculate the daily exchange rate from a currency to another based on this amount. But it seems that the request.GET.get('amount') method returns None because I am getting a conversion from NoneType to Decimal is not supported error. Bellow is my views: def Add_transfer(request, reference=None): amount = request.GET.get('montant') if request.method=="POST": form = TransferAddFrom(request.POST,request.FILES) if form.is_valid(): form.save() id = form.instance.id return redirect('details', id=id) else: form=TransferAddFrom() # Get conversion rate from USD to USD print(currencies.get_rate('USD','EUR')) # Convert amount from USD to CNY print(currencies.convert('USD','CNY',Decimal(amount))) return render(request, 'indexOld.html',{'form':form}) -
User object to Agent object in django
In my CRM, once the user has signed up it also creates them as agents. My problem is this, in the signup page, the users input their name and details, however once the agent has been created, the agent objects doesn't inherit from the user account. here's my MODEL.PY: from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_techtanium = models.BooleanField(default=False) is_organizer = models.BooleanField(default=False) is_agent = models.BooleanField(default=True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class Client(models.Model): first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) mobile_number = models.CharField(max_length=12) email = models.EmailField() organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) agent = models.ForeignKey("Agent", related_name="clients", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="clients", null=True, blank=True, default=4, on_delete=models.SET_NULL) company_name = models.CharField(max_length=50 , default=None) street_address = models.CharField(max_length=50 , default=None) baranggay = models.CharField(max_length=50 , default=None) city = models.CharField(max_length=50 , default=None) region = models.CharField(max_length=50 , default=None) date_added = models.DateTimeField(auto_now_add=True) phoned = models.BooleanField(default=False) special_files = models.FileField(blank=True , null=True) def __str__(self): return f"{self.first_name} {self.last_name}" class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True, blank=True) middle_name = models.CharField(max_length=20, null=True, blank=True) last_name = models.CharField(max_length=20, null=True, blank=True) agent_type = models.CharField(max_length=20, null=True, blank=True) email = models.EmailField(null=True, blank=True) mobile_number = models.CharField(max_length=12, … -
In Django settings TypeError: 'module' object is not callable
File "D:\Python Development\Django_Broad\blog\blog\settings.py", line 19, in ALLOWED_HOSTS =config('ALLOWED_HOSTS', cast=csv()) TypeError: 'module' object is not callable Why am I getting this error? someone help me..