Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO: request.COOKIES['sessionid'] does not exist on Firefox browser
I'm writing a module to store comments for specific article. My model contains a column unique_session which is intended to store the commenter's browsing session id. Within my view function, I'm trying to initialize a variable bearing the value of request.COOKIES['sessionid'] which I later assign to unique_session column of the model. So far, I'm doing good with Chrome. I'm able to get it as the key exists when I inspect it, and obviously it stores to db just fine. But when I go to Firefox, the sessionid cookie does not exist and Django throws in a KeyError. Anyone have any idea what could be missing? -
A future-oriented code upgrade. Avoid exiting the function if an error occurs
I've to pass some data from incoming object, but I cannot be sure about the values that this object contains. Some(or each) of the object value may be defined or not. I'll not end the function with a lot of try: except: code. So here is my function that exports the data as csv file. And in case that one of the value of the incoming object undefined this code fails. def export_data(output, queryset, dialect=csv.excel): writer = csv.writer(output, dialect=dialect) writer.writerow(['Name', 'Email', 'Tool', 'Location', 'Box', 'Booking timestamp', 'Checkout timestamp', 'Return timestamp', 'Loan costs incl. VAT', 'Loan costs excl. VAT', 'VAT percentage', 'Feedback overall rating', 'Feedback remarks']) for event in events: row = ["{} {}".format(event.userprofile.firstname, event.userprofile.lastname), event.userprofile.user.email, event.toolitem.tool.name, event.toolitem.box.location.name, event.toolitem.box.number, event.booking_ts, event.checkout_ts, event.return_ts] if event.state in (event.RETURNED, event.PAYED): row += [event.loan_costs, (event.loan_costs / (event.vat_percentage / Decimal(100) + Decimal(1)) ).quantize(Decimal('.01')), event.vat_percentage] else: row += ['', '', ''] try: row += [event.feedback.get_overall_rating_display(), event.feedback.remarks] except: row += ['', ''] writer.writerow(row) return output This function should be more flexible and if a value does not exist, replace it with an empty string. -
filtering data from db by logged in user
I'm writing a queryset for data and result needs to be list of objects of that particular user. (logged in user) This is what I've got so far: class List(ListView): def get_queryset(self): qry = House.objects.filter(user__user_id=self.request.user).all() return qry models.py: from django.contrib.auth.models import User class House(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) ... ... I suspect that the very filtering condition is wrong because the traceback says no such field user What can I try to solve this ? -
How to create a webhook in python to store data in db?
I am unable to understand on how to create a webhook python. Can't find suitable examples too. I want to create a webhook to store the data in my db whenever the event is triggered. Also, the url for webhook has to be generated because i have to integrate it in some webiste. Just found this example but how to proceed further? from webhooks import webhook >>> from webhooks.senders import targeted >>> @webhook(sender_callable=targeted.sender) >>> def basic(url, wife, husband): >>> return {"husband": husband, "wife": wife} >>> r = basic(url="http://httpbin.org/post", husband="Danny", wife="Audrey") >>> import pprint >>> pprint.pprint(r) -
django-storages upload to S3 closes server with no error
I'm using Django 2.x and django-storages to upload media files to the S3 Bucket. My model is like class Media(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, default=None) file = models.FileField(upload_to=get_media_upload_path) The Django settings have DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_STORAGE_BUCKET_NAME = os.environ.get('S3_STORAGE', 'test-bucket') AWS_DEFAULT_ACL = 'public-read' and the environment variable is set for AWS_ACCESS_KEY_ID=my-key AWS_SECRET_ACCESS_KEY=my-secret When I upload a file from the postman, it closes the server without any error. I tried debugging DRF Serializer's save method def save(self, **kwargs): log.info('Saving with kwargs: {}'.format(kwargs)) new = super().save(**kwargs) log.info('Saved: {}'.format(new)) return new It prints the first line, but no output after the super().save() line. Removing django-storages configuration from the settings file is working fine and uploading files in the local directory. -
I want to change the display of SnippetChooserPanel of BlogIndexPage by Client in Wagtail site
I want to change the display of SnippetChooserPanel of BlogIndexPage by Client. However, I don't have an idea to change the display. I want to display only the contract of the same client. But now all contracts are visible. What I investigated: Filter query set wagtail-ModelAdmin.get_queryset() def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(client=request.client) -
Couldn't set up mod_wsgi for my Apache and Django
Need guides to set up mod_wsgi on Windows for my XAMPP Apache and Django project. I'm using Python 3.7.3(win32), Django 2.2.3 and Apache 2.4.39(win64). Errors appear when after i set "MOD_WSGI_APACHE_ROOTDIR=C:\xampp\apache\bin" and pip install mod_wsgi. I'm not sure what i did wrong at this step? Read about Visual Code 14.0. Downloaded it and i still got error. ERROR: Command errored out with exit status 1: command: 'c:\program files (x86)\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\CHEEHO~1\\AppData\\Local\\Temp\\pip-install-41s5l0d2\\mod-wsgi\\setup.py'"'"'; __file__='"'"'C:\\Users\\CHEEHO~1\\AppData\\Local\\Temp\\pip-install-41s5l0d2\\mod-wsgi\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\CHEEHO~1\AppData\Local\Temp\pip-record-um32pphd\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\CHEEHO~1\AppData\Local\Temp\pip-install-41s5l0d2\mod-wsgi\ Complete output (33 lines): c:\program files (x86)\python37-32\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg) running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\mod_wsgi copying src\__init__.py -> build\lib.win32-3.7\mod_wsgi creating build\lib.win32-3.7\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win32-3.7\mod_wsgi\server copying src\server\environ.py -> build\lib.win32-3.7\mod_wsgi\server copying src\server\__init__.py -> build\lib.win32-3.7\mod_wsgi\server creating build\lib.win32-3.7\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win32-3.7\mod_wsgi\server\management creating build\lib.win32-3.7\mod_wsgi\server\management\commands copying src\server\management\commands\runmodwsgi.py -> build\lib.win32-3.7\mod_wsgi\server\management\commands copying src\server\management\commands\__init__.py -> build\lib.win32-3.7\mod_wsgi\server\management\commands creating build\lib.win32-3.7\mod_wsgi\docs copying docs\_build\html\__init__.py -> build\lib.win32-3.7\mod_wsgi\docs creating build\lib.win32-3.7\mod_wsgi\images copying images\__init__.py -> build\lib.win32-3.7\mod_wsgi\images copying images\snake-whiskey.jpg -> build\lib.win32-3.7\mod_wsgi\images running build_ext building 'mod_wsgi.server.mod_wsgi' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\src creating build\temp.win32-3.7\Release\src\server C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.22.27905\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -IC:\xampp\apache\bin/include "-Ic:\program files (x86)\python37-32\include" "-Ic:\program files (x86)\python37-32\include" "-IC:\Program Files … -
unable to open pdf file in django
my file directory is : site -search -factfinder -pdf_reports test.pdf in my base.html file, i have : <a class="linkbtn" href='/factfinder/pdf_reports/{{ab.0.file_name}}.pdf' >open pdf</a> but on clicking the link, i get redirected to http://localhost:8000/factfinder/pdf_reports/test.pdf and i get an error stating page not found. i also get following details to error : Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ elasticsearch_results/ [name='elasticsearch_results'] pdf_open [name='pdf_open'] pdf_open_2 [name='pdf_open_2'] rating [name='rating'] parse_pdf [name='parse_pdf'] filters [name='filters'] run_model [name='run_model'] The current path, factfinder/pdf_reports/test.pdf, didn't match any of these. -
Get UID and token obtain from password reset in react form
I am working on password reset and I have used django rest-auth, I have successfully got the token and uid from email link by hitting rest-auth/password/reset/, but for to confirm I want the token and uid in react form so I can change it how can I get the uid and token which the rest auth return in email link in react js form axios.post('http://127.0.0.1:8000/rest-auth/password/reset/',payload) .then(res=>{ console.log(res) }) .catch(err=>{ console.log(err) }) its working perfect and it returns me: http://127.0.0.1:8000/rest-auth/password/reset/confirm/MQ/594-5faaa46be4277e6a1879/ how can I get the uid and token from url in react form? -
DJANGO - ModuleNotFoundError No module named "[MY PROJECT, not an app]"
Lots of questions about it here, but nothing seems to answer mine. I am trying to host my django website in linux server with apache, using the mod_wsgi. I am getting the error: ModuleNotFoundError: No module named 'bnboats_webproject': /home/bnboats/public_html/python/bnboats_webproject/wsgi.py The mentioned 'bnboats_webproject' is my project, which has settings, wsgi, urls ... Not an app to be installed. My folder structure is like this: - PYTHON/ - bnboats_webproject/ (my project) - bnboats_app/ (my app) - venv/ (my virtual env) - mod_wsgi-4.6.5/ - manage.py - ... In httpd.conf, I have entered: WSGIScriptAlias / /home/bnboats/public_html/python/bnboats_webproject/wsgi.py WSGIDaemonProcess bnboats.com python-path=/home/bnboats/public_html/python:/home/bnboats/public_html/python/venv WSGIProcessGroup bnboats.com <Directory /home/bnboats/public_html/python/bnboats_webproject> <Files wsgi.py> Require all granted </Files> </Directory> It returns a 500 Internal Error, the host company debugged for me and sent me this log: [Thu Aug 22 11:38:29.461405 2019] [cgi:error] [pid 28312] [client xxx.xx.xxx.xx] AH01215: Traceback (most recent call last):: /home/bnboats/public_html/python/bnboats_webproject/wsgi.py [Thu Aug 22 11:38:29.461575 2019] [cgi:error] [pid 28312] [client xxx.xx.xxx.xx] AH01215: File "/home/bnboats/public_html/python/bnboats_webproject/wsgi.py", line 20, in <module>: /home/bnboats/public_html/python/bnboats_webproject/wsgi.py [Thu Aug 22 11:38:29.461627 2019] [cgi:error] [pid 28312] [client xxx.xx.xxx.xx] AH01215: application = Cling(get_wsgi_application()): /home/bnboats/public_html/python/bnboats_webproject/wsgi.py [Thu Aug 22 11:38:29.461713 2019] [cgi:error] [pid 28312] [client xxx.xx.xxx.xx] AH01215: File "/usr/lib64/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application: /home/bnboats/public_html/python/bnboats_webproject/wsgi.py [Thu Aug 22 11:38:29.461749 2019] [cgi:error] [pid 28312] [client … -
Django Module for FusionCharts: CORB issue
I am trying to use a simple Django Module for FusionCharts example given in the documentation but I am getting CORB issue. I am using exact code and it seems to run fine, but instead of graph I get this error: Cross-Origin Read Blocking (CORB) blocked cross-origin response https://fusioncharts.github.io/fusioncharts-jquery-plugin/ with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details. -
How do I create a single instance of a model through multiple html pages?
I've just gotten started with Django and I'm having trouble creating the flow I have in mind for a Q&A type application where users choose who they want to answer their question. I have a single Request model as below: models.py class Request(models.Model): user = models.ForeignKey('auth.User') topic = models.ForeignKey(Topic) description = models.TextField() responder = models.ForeignKey(Responder) created_date = models.DateTimeField() published_date = models.DateTimeField(blank=True, null=True) The flow would be as follows: on first page, user chooses what topic they want (general knowledge, movies, etc.) on second page, user fills out a form describing their question on third page, user chooses a responder out of a list of available responders on fourth page (if user is not logged in), they log in So the instance of the object is created through four separate pages. What I currently have is the instance created all in one form/html page: forms.py class UserRequestForm(forms.ModelForm): class Meta: model = Request fields = ('user','topic','description',) widgets = { 'description': forms.Textarea(attrs={'class': 'form-control'), 'user': forms.HiddenInput(), } html page {% load bootstrap3 %} {% block content %} <form method="POST"> {% bootstrap_form form %} {% csrf_token %} <button type="submit" class="btn btn-primary btn-block">Ask</button> </form> {% endblock %} I haven't been able to find any documentation to … -
How to create multivalued field using django rest framework
i want to create a user registration api using django rest-framework,having fields name,email,address and other. I want to make the other field multivalued input field so that this field can take multple input in api. i used this model class User(models.Model): Name=models.CharField(max_length=20) email=models.EmailField(max_length=50) address=models.CharField(max_length=50) otherAddress=models.ForeignKey('self') i want my api field should be like 1)Name 2)email 3)address 4)other-->taking more than one or two inputs -
django queryset cannot run function inside annotate and Sum
I have two queryset and I want to do Addition from those two queryset but one query value are Int type (e.g. 1.5, 2.75 ) but others have time like string (e.g. 12:20:59). I need to convert that string to Int type so I can do use Sum Function in Annotate. First queryset timesheet_total_by_project = TimesheetEntry.objects.filter(created_by_id=current_user, timesheet__for_date__gte=start_tim, timesheet__for_date__lte=end_date, project__is_visible=True).values('project__name', 'project__id').distinct().annotate(totalsum=Sum('minutes', output_field=FloatField()) / 60.0) 2nd Queryset ticket_total_time = Ticket.objects.filter(assigned_to=user,total_time__isnull=False,project__is_visible=True).values('title','project__id').distinct().annotate(totalsum=Sum('total_time', output_field=FloatField()) / 60.0) I have tried def get_sec(time_str): print("string",time_str) """Get Seconds from time.""" h, m, s = time_str.split(':') return int(h) * 3600 + int(m) * 60 + int(s) ticket_total_time = Ticket.objects.filter(assigned_to=user,total_time__isnull=False,project__is_visible=True).values('title','project__id').distinct().annotate(totalsum=Sum(get_sec('total_time'), output_field=FloatField()) / 3600.0) Expected Output is would be 12.5 but output for print("string",time_str) string total_time Also says ValueError: not enough values to unpack (expected 3, got 1) -
AttributeError: 'list' object has no attribute 'lstrip'
For the past 3 hours I'm trying to send an email with csv attachment to a list of emails fetched from the database, but I'm getting an error which I am not really sure why is it occurring. I double checked my code for mistakes if there was any unicode getting passed etc, to avoid that I converted the fetched data into str but no use. If I run the script independently it executes and sends the email with the attachment without a problem but in Django it's giving an error. The emails in the list are made for Checking whether if this error was only for database related but it's not. It shoes up for the pre-defined list as well. I got the code snippet from Here: Here ERROR Performing system checks... Unhandled exception in thread started by Traceback (most recent call last): File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\BITSWI~1\Desktop\LCRPRO~1\VE\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File … -
Where to host wagtail/django
Hi I have a bit of experience in WordPress but none in PHP however, I do in python. As you can imagine editing plugins to suit my needs is a bit hit and miss. I recently discovered wagtail and saw it ran on django, for me this would be far better. I researched how to host django remotely and got thousands of tutorials on python 2.7. The website says # in a Python 3 virtual environment pip install wagtail wagtail start mysite cd mysite pip install -r requirements.txt python manage.py migrate python manage.py createsuperuser python manage.py runserver Do you just ssh in and do this as you would on a local machine, if so which host should I use and how do you even ssh a web server. Thanks in advance -
How can i add auto counter to model objects?
I had 4 objects but when i deleted one, i shown based on object id not actual numbers of objects ? Model objects https://i.stack.imgur.com/QBbCV.png -
How to create separate URL in Django using Ajax
Here, There are 3 button in single template, How to call the separate URL for each button in views and ulrs.py The 3 buttons are Save Delete Copy We write the functionality for copy button, We clicking the save button the copy functionalities working 3 buttons image -
Updating data into multiple Table -> MultipleObjectsReturned at /client/update-client
I am trying to update the data into 3 tables. I have not set up the primary-foreign key relation bcoz of project requirement. I got this error - MultipleObjectsReturned at /client/update-client get() returned more than one BankDetails -- it returned 2! from views, I'm sending the data into 3 models but its updating one table only. Views.py @csrf_exempt def update_client_details(request): # try: client_master_dict = [] client_master_dict = json.loads(request.body) client_data_bank = client_master_dict['data'][0]['bank_details'] client_data_doc = client_master_dict['data'][0]['document_details'] records, client_id = ClientDetails.update_client(client_master_dict['data'][0]) for i in range(len(client_master_dict['data'][0]['bank_details'])): bank_data = BankDetails.update_bank_detail(client_data_bank[i],client_id) for j in range(len(client_master_dict['data'][0]['document_details'])): document_data = DocumentDetails.update_document_detail(client_data_doc[j],client_id) datum = json.dumps(records) data = json.loads(datum) returnObject = { "status" : messages.SUCCESS, "message" : messages.CLIENT_UPDATE_SUCCESS, "results" : data } return JsonResponse(returnObject,safe=False) Models.py (ClientDetails Table) @classmethod def insert_client_details(cls, cilent_master_dict): try: client_obj = ClientDetails() client_obj.client_id = "CL"+str(int(time.time_ns() * 10)) client_obj.client_name = cilent_master_dict['client_name'] client_obj.client_pan_no = cilent_master_dict['client_pan_no'] client_obj.client_adhar_no = cilent_master_dict['client_adhar_no'] client_obj.legal_entity_name = cilent_master_dict['legal_entity_name'] client_obj.credit_period = cilent_master_dict['credit_period'] client_obj.client_tin_no = cilent_master_dict['client_tin_no'] client_obj.client_email_id = cilent_master_dict['client_email_id'] client_obj.head_office_name = cilent_master_dict['head_office_name'] client_obj.office_contact = cilent_master_dict['office_contact'] client_obj.office_name = cilent_master_dict['office_name'] client_obj.office_email_id = cilent_master_dict['office_email_id'] client_obj.gst_number = cilent_master_dict['gst_number'] client_obj.office_country = cilent_master_dict['office_country'] client_obj.office_state = cilent_master_dict['office_state'] client_obj.office_district = cilent_master_dict['office_district'] client_obj.office_taluka = cilent_master_dict['office_taluka'] client_obj.office_city = cilent_master_dict['office_city'] client_obj.office_street = cilent_master_dict['office_street'] client_obj.office_pincode = cilent_master_dict['office_pincode'] client_obj.contact_person_name = cilent_master_dict['contact_person_name'] client_obj.contact_person_designation = cilent_master_dict['contact_person_designation'] client_obj.contact_person_number = cilent_master_dict['contact_person_number'] client_obj.contact_person_email = cilent_master_dict['contact_person_email'] client_obj.contact_person_mobile = … -
ERROR: Command errored out with exit status 1:
ERROR: Failed building wheel for mysqlclient ERROR: Command errored out with exit status 1 error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ RROR: Command errored out with exit status 1: 'c:\python\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Admin\AppData\Local\Temp\pip-install-sxz0ni7x\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\Admin\AppData\Local\Temp\pip-install-sxz0ni7x\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-li2rtx7t\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output -
Django form instance test fail
I used datetime picker in front end. author creation form class AuthorCreationForm(forms.ModelForm): class Meta: model = Author fields = ('first_name', 'last_name', 'born', 'died', 'image', ) ====================================================================== FAIL: test_author_form (book.tests.test_view.TestAuthorCreatePage) Traceback (most recent call last): File "/home/kaung/workspace/library-management-system/config/book/tests/test_view.py", line 460, in test_author_form self.assertIsInstance(form, self.creation_form) AssertionError: is not an instance of -
i am getting an NoreverseMatch at / ,
I am trying to improve my models and html files for my project and while finding the solution on internet ive got this particular error. i've tried importing render and resolvers, and also trying looking out for solution on stackoverflow but nothing works for me. #here's urls.py from django.contrib import admin from django.urls import path from accounts import views as accounts_views from django.contrib.auth import views as auth_views from boards import views urlpatterns = [ path('boards/<int:pk>/topics/<topic_pk>/', views.topic_posts, name='topic_posts'), path('boards.<int:pk>/topics/<topic_pk>/reply/', views.reply_topic, name='reply_topic'), ] #here's line from base.html where its showing error <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#mainMenu" aria-controls="mainMenu" aria- expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> #here are my models.py file from django.contrib.auth.models import User from django.db import models from django.utils.text import Truncator class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) def __str__(self): return self.name def get_posts_count(self): return Post.objects.filter(topic__board=self).count() def get_last_post(self): return Post.objects.filter(topic__board=self).order_by('- created_at').first() and i am getting this error "Reverse for 'topic_posts' with arguments '(2, '')' not found. 1 pattern(s) tried: ['boards/(?P<pk>[0- 9]+)/topics/(?P<topic_pk>[^/]+)/$']" -
How to alter label tag of fieldset in admin.tabularinline
I customized my add user form in my django admin, using admin.tabularinline. So whenever the admin adds a user, information about Usermodel and UserProfile model is saved at the same time. However, the label tag of the UserProfile form says 'Staff Profiles'(with 's'). And it doesn't look good because there is only one profile for one user. Any ideas how to change the "Staff Profiles" into "Staff Profile"? See the picture for refenrce: -
Normalize Django Field's Value
I wrote a custom django field to normalize the urls our system received. However, the url will only return normalized value after reload. from django.db import models def _rewrite_internal_url(url): # return 'http://www.google.com/1.jpg' class NormalizedURLField(models.URLField): def to_python(self, value): value = super().to_python(value) return _rewrite_internal_url(value) def from_db_value(self, value, expression, connection): if value is None: return value return _rewrite_internal_url(value) class DjangoTest(models.Model): url = NormalizedURLField() instance = DjangoTest.objects.create(url="http://www.google.com/2.jpg") print(instance.url) # still http://www.google.com/2.jpg instance.referesh_from_db() print(instance.url) # update to http://www.google.com/1.jpg -
How to remove the error when migrate in django?
I have a code which is to show the balance 0 in html page by default when someone new register itself. After makemigrations it works but after typing migrate it didn't work. Instead it gives me error. How to deal with this? models.py class Balance(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=2, default=0) owner = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) views.py @login_required def balance(request): try: balance = request.user.balance except Balance.DoesNotExist: balance = None return render(request, 'nextone/balance.html', {'balance': balance}) Html page {% if balance.amount %} <h2>Your Balance is Rs. {{balance.amount}}</h2> {% else %} <h2>Your Balance is Rs. 0</h2> {% endif %} Error after I migrate File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle fake_initial=fake_initial, File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File …