Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I'm getting a 500 internal error when validate Recaptcha V2, Django?
I'm using Django and when I want to submit my contact form, i have to validate my google recaptcha. It's working locally but in production I have a 500 internal error and the mail is not sent when the form is correctly fill with the correct captcha. I added my domain name to the google recaptcha website... I have correct secret key... Again it's working locally -
Form data not saving when use DateField
I am saving the form data into database but no success. Actually when I include DateField in forms.py, its not saving any data but when excluded this field, it works fine. Any possible reason for this problem.? Model: class CoWorker_Data(models.Model): name = models.CharField('Name', max_length=50, help_text='Co-worker name.') email = models.EmailField('Email', help_text='Co-worker email.') address = models.TextField('Address', help_text='Co-worker address.') phone = models.CharField('Phone Number', max_length=20, help_text='Co-worker phone number.') companyName = models.CharField('Company Name', max_length=80, help_text='Co-worker company name.', null=True, blank=True) workingLocation = models.CharField('Working Location', max_length=50, help_text='Co-worker working ' 'location.') workingShift = models.CharField('Working Shift', max_length=50, help_text='Co-worker working shift.', default='') workingSpace = models.CharField('Working Space', max_length=50, help_text='Co-worker working space.', default='') teamMembers = models.CharField('Team Members', max_length=15, help_text="Co-Worker's Team Size.", default='') coworkerPicture = models.ImageField('Co-Worker Picture', upload_to='../media/images/co-woker-pictures' , help_text='Co-worker Picture.', default='', null=True, blank=True) joiningDate = models.DateField('Joining Date', help_text='Joining Date of Co-worker', auto_now_add=False,) Form class addCoWorkerForm(forms.ModelForm): teamMembers = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control formInput', 'placeholder': 'Team Members', 'required': 'True' })) coworkerPicture = forms.ImageField(widget=forms.FileInput(attrs={ 'class': 'form-control formInput', })) joiningDate = forms.DateField(widget=forms.DateInput(attrs={ 'class': 'form-control formInput', 'id': 'datePicker', })) View def Coworkers(request): if request.method == 'POST': form = addCoWorkerForm(request.POST, request.FILES) if form.is_valid(): u = form.save() messages.success(request, 'Co-Worker added successfully.') return redirect('admin/co-workers') else: form = addCoWorkerForm(request.GET) please suggest best solution...? -
How to implement 'others' in django models choices-charfield
was wondering if anyone here know of a good implementation for 'others' choice (where user can input custom text) in django models multi-select .... say for instance i have a multiple choice model field 'options' with pre-set a and b choices. options = models.CharField ( max_length=2, choices=[(a,'a'), (b,'b')], default=a, ) What if I want the user to be able to select a choice 'others' and thereon key in his custom text i.e. 'd' The only way I can think of really, is to use a different field , say options_custom (without getting into the specifics of the model etc...the dummy snippet below is just for discussion sake) options = models.CharField ( max_length=2, choices=[(a,'a'), (b,'b'), ('others', 'others')], default=a, ) # added this.. options_custom = models.CharField(max_length=2, blank=True, verbose_name="Input custom text here" ) # and put a conditional... if others then return options_custom if choices == 'others': return options_custom # something like this.... What do you think? I'd appreciate any pointers. -
Django charfield regex
Consider a charfield with a max_length of 5. I want to put hours and minutes in this CharField like HH:MM. I don't want to use the models.TimeField as it stores the time, not the amount hours and minutes. I want my CharField to hold, let's say, 8:45 (8hrs and 45minutes) which is why I want to add a regex validator that makes sure that the number before the colon : is less than 24 and the number after it less than 60. How would I do that in regex? Thank you for your time. -
UndefinedError: 'url_for' is undefined; while using Jinja2 in Django
I'm trying to use Jinja2 templating language with Django. While trying to render a template I got the error "jinja2.exceptions.UndefinedError: 'url_for' is undefined". 'url_for()' works absolutely fine when used with templates in Flask Applications. The Traceback is as follows: File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ParserMouth/folder1/folder2/ProjectName/ProjectName/login_auth/views.py" in index 10. return render(request,"login_auth/index.html") # index.html will be welcome screen File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/template/loader.py" in render_to_string 62. return template.render(context, request) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/template/backends/jinja2.py" in render 71. return self.template.render(context) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/jinja2/asyncsupport.py" in render 76. return original_render(self, *args, **kwargs) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/jinja2/environment.py" in render 1008. return self.environment.handle_exception(exc_info, True) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/jinja2/environment.py" in handle_exception 780. reraise(exc_type, exc_value, tb) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/jinja2/_compat.py" in reraise 37. raise value.with_traceback(tb) File "/home/ParserMouth/folder1/folder2/ProjectName/ProjectName/login_auth/jinja2/login_auth/index.html" in top-level template folder2 1. {% extends "login_auth/base.html" %} File "/home/ParserMouth/folder1/folder2/ProjectName/ProjectName/login_auth/jinja2/login_auth/base.html" in top-level template folder2 12. {% block style %} {% endblock %} File "/home/ParserMouth/folder1/folder2/ProjectName/ProjectName/login_auth/jinja2/login_auth/index.html" in block "style" 4. <link rel="stylesheet" href="{{ url_for('static/login_auth', filename='index_stl.css') }}"> Exception Type: UndefinedError at / Exception Value: 'url_for' is undefined I want to know how to solve this problem. Thanks in advance. -
How to create proxy-http-server
I write a proxy-http-server on the Django using django-revproxy. re_path(r'^(?P<path>.*)$', ProxyView.as_view(upstream='https://example.com')) It works. When I open 127.0.0.1:8000 I get content of example.com. But I have a two nuance: How can I change text on the page (for example, change every word, length which equals 6 letters) How can I change links on the page (at current moment all links go to the example.com, but not to 127.0.0.1:800) -
django-tables2 - show all per page
Good afternoon, im using Django-tables2, I know in the query string I can set per_page and have used the below template tag to create some urls {% querystring "per_page"=20 %} however is it possible to show all items per page via a url? ive tried using -1 and 0 but it does not work, the only thing I can think to is put a ridiculous number like a billon which works, but I dont think thats a clean implementation? Thanks -
django-tables2/django-filter - pagination with filterclass
Good Afternoon, I am using a custom django-filter in django-tables2 to search all fields with a single input. Ive just noticed that when I search I lose my pagination menu. this is the link to the filter code https://spapas.github.io/2016/09/12/django-split-query/ here's my filter class SiteFilterEx(django_filters.FilterSet): ex = django_filters.CharFilter(label='Ex filter', method='filter_ex') search_fields = ['location', 'bgp_as', 'opening_date','town','postcode'] def filter_ex(self, qs, name, value): if value: q_parts = value.split() # Use a global q_totals q_totals = Q() # This part will get us all possible segmantiation of the query parts and put it in the possibilities list combinatorics = itertools.product([True, False], repeat=len(q_parts) - 1) possibilities = [] for combination in combinatorics: i = 0 one_such_combination = [q_parts[i]] for slab in combination: i += 1 if not slab: # there is a join one_such_combination[-1] += ' ' + q_parts[i] else: one_such_combination += [q_parts[i]] possibilities.append(one_such_combination) # Now, for all possiblities we'll append all the Q objects using OR for p in possibilities: list1=self.search_fields list2=p perms = [zip(x,list2) for x in itertools.permutations(list1,len(list2))] for perm in perms: q_part = Q() for p in perm: q_part = q_part & Q(**{p[0]+'__icontains': p[1]}) q_totals = q_totals | q_part qs = qs.filter(q_totals) return qs class Meta: model = Site fields = ['ex'] form … -
How to show what changed in a model using Django simple-history?
I am using django-simple-history to track changes in a model. This is working fine. I can also create a view for the admin site. When I do not derive the class for the admin view from SimpleHistoryAdmin I get this history view showing what changed in the model under the column ACTION (last column). However, I cannot revert the values for the object to a previous time point. If I derive the admin view class from SimpleHistoryAdmin I can revert the instance but the history view changes and I no longer have the ACTION column. This makes this view almost useless since there is no way to tell what changes from one-time point to the other. So my question is: How can I have the column ACTION in the history view when I derive the admin view from SimpleHistoryAdmin? If by any chance this is not possible I will be happy by changing CHANGE REASON from None to the values in the column ACTION in the first image. -
How to fix UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 5: invalid continuation byte
I am trying to run a newly created environment on a server and get UnicodeDecodeError. Windows 7, 64-bit. I have created a virtual environment and directed code to the source folder. Here are django, python and virtualenv versions installed. I have tried installing older versions of django and python and got the same error. When searching for troubleshooting recommendations I only find articles related to .csv and pandas. Django==2.2.7 pytz==2019.3 virtualenv==16.7.7 PS: C:\Users\User\Dev\Selectia\src> python manage.py runserver Here is the output: Watching for file changes with StartReloader Performing system checks... System checkidentified no issues (0 silenced). November 05, 2019 - 12:02:31 Django version 2.2.7, using setings 'foodie.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREALK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run self._target(*self.args, **self._kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54 in wrapper fn(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 203, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 67, in __init__ super().__init__(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 452, in __init__ self.server_bind() File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\http\server.py", line 139, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\socket.py", line 676, in getfqdn hostname, aliases, ipaddrs = … -
Django - How to create many to one relation
In my application there is many-to-one relation, such as one teacher can teach more than one subject. So in admin panel I can't simulate it. Can't add more than one subject: Here are my codes: models.py: class Subject(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200) credit = models.IntegerField() class Teacher(models.Model): def __str__(self): return self.name name = models.CharField(max_length=100) email = models.CharField(max_length=100, null=True) chair = models.ForeignKey(Chair, on_delete=models.CASCADE) academic_degree = models.CharField(max_length=100) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) -
Django problem accessing Admin while my main DB is Mongo
my name is Víctor. I'm quite new using Django and Python and I'm working in a project that is yet started. Default Database is MongoDB where I have users and I can authenticate in the login page of the app. Now we installed 'helpdesk' app that is a ticketing system and we would like to use Admin that is disabled in our project. I added Admin app in Settings and Url but I dont have any access to any user. I tried to create a superuser with python manage.py createsuperuser but it gives me this error: TypeError at /admin/ int() argument must be a string, a bytes-like object or a number, not 'ObjectId' In django/contrib/auth we made some changes for example: def _get_user_session_key(request): # This value in the session is always serialized to a string, so we need # to convert it back to Python whenever we access it. if SESSION_KEY in request.session: return ObjectId(request.session[SESSION_KEY]) Where appears this ObjectId, it seems that Admin is trying to access user from MongoDB and not from helpdesk DB that is sqlite. Probably my problem is that I dont understand about mixing databases and accessing. I created a router with functions like: class RouterDB: … -
moving python backend to django for Yahoo Fiannce APİ
Hi i am good with Python but my Django skills is beginner. I developed a program in Tkinter as GUI but decided to put in Django. Here is my backend and GUI shorted: from tkinter import* import numpy as np import pandas as pd from scipy.stats import norm from pandas_datareader import data as wb from yahoofinancials import YahooFinancials The user insert ticker in input field and the variable helped to get ticker symbol through tickers = [self.entry_stock.get()] then i used the below to get stock's price yahoo_financials = YahooFinancials(tickers) new_data = pd.DataFrame() for t in tickers :new_data[t] = wb.DataReader(t, data_source ='yahoo', start = '2004-1-1')['Adj Close'] a = new_data[t] In Django i am confused how to convert input data to index symbol: <form class="ticker_area form-control-lg" method="POST"> {% csrf_token %} <input class="ticker_button" type="text" placeholder="Ticker" aria-label="Search"> <button class="btn btn-outline-warning btn-rounded btn-sm my-1" type="submit">OK</form> in backend the symbol= ['AAPL']which allow to get company data in such format. In tkinter i used `tickers = [self.entry_stock.get()] to get stock value and use further. But i do not know how how to make in Django the form to pass ticker data to this format `tickers = [self.entry_stock.get()] so that i can further use it to get price … -
Determine the source of the API request from which it is coming from?
How can I determine the source of the request? I am using django. For example, if I send a request from POSTMAN to some API like http://example/api/, I need to get POSTMAN as an answer. If I do the same from Chrome, I need to get Chrome as an answer. -
How to run javascript in view only after specific post request?
I am trying to run javascript code after specific post. I will explain what is happening. I got some forms on my page and checking which POST request is "released" I will make something. So I made this, it will change state of that specific object in database and reload the page. if request.method == 'POST': if 'acceptresults' in request.POST: t = Pools.objects.get(pk=Pools_id) t.Status = "Testing_closed" t.save() return HttpResponseRedirect('#') How am I able to run the specific javascript which could be call startConfetti(); and after 5 seconds call stopConfetti();. Can someone please help me? -
Edit the session inside Django form_valid gives "Object is not JSON serializable"
I'm using class based views in Django to create an entry in db. I want the saved object to be stored in session, so that it could be passed to the next view. My view looks like class CreateCommission(BaseContext, CreateView): # boring staff... model = Commissions def form_valid(self, form): object = form.save(commit=False) self.request.session['created_object'] = object return super().form_valid(form) This raise an Object of type Commissions is not JSON serializable error. What's wrong with that? -
OTP only login for Django
I would like to have OTP only for authentication. I read about django-otp and django-two-factor-auth but they are both for two-factor authentication. I read the examples in the github and unfortunately do not know if it is possible to make if OTP authenticated only based on limited experience. I was thinking about using native python and Javascript for this, but I guess decorators @login-required requires Django Login? I would also like to log the user activity with Matomodjango-analytics in the future. I am not sure if I have to use Django Login in order to track activities later. Thanks for your suggestion! -
How do I connect my django project with a pycharm as code editor and Mysql Database using MySqlWorkbench
I am very new with python, just started today. I'm trying to connect and migrate django project database apps to my MYSQL Database using MYSQL Workbench I have tried a several steps, but I keep getting error from one solution to another. My mysqlserver and workbench is running perfectly. enter image description here I tried to follow the steps from this website on how to connect django project to a mysql database https://www.dev2qa.com/how-to-connect-mysql-database-in-django-project/. And a couple other more steps from youtube and other sites. Now, when I try to migrate Django project apps database with this code. python manage.py migrate the first error I got was something like a version error mysqlclient 1.2.13 or newer is required; you have 0.9.3 So I read the forum Django - installing mysqlclient error: mysqlclient 1.3.13 or newer is required; you have 0.9.3 and followed all the steps that was in the forum. but nothing seems to worked. in my settings.py I have already edited the code to: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'NewConnection', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'mypassword', } } and also edited the code in init.py to import pymysql pymysql.install_as_MySQLdb() but still I keep getting those … -
Cannot assign "'1'": "dropdown.drp1" must be a "basedrop" instance
I am new to django, I know similar type of error have been posted on stackoverflow but, still not able to understand what I am missing in my code.I am stuck on this from a while. I am including all my code down below. models.py class basedrop(models.Model): name = models.CharField(max_length=50,blank=False,null=False) def __str__(self): return self.name class subdrop(models.Model): name = models.CharField(max_length=100,blank=False,null=False) bsdrop = models.ForeignKey(basedrop,null=False,blank=False,on_delete=models.CASCADE) def __str__(self): return self.name class lastdrop(models.Model): name = models.CharField(max_length=100,blank=False,null=False) sbdrop = models.ForeignKey(subdrop,null=False,blank=False,on_delete=models.CASCADE) def __str__(self): return self.name class dropdown(models.Model): name = models.CharField(max_length=50,blank=False,null=False) drp1 = models.ForeignKey(basedrop,max_length=50,on_delete=models.CASCADE) drp2 = models.ForeignKey(subdrop,max_length=50,on_delete=models.CASCADE) drp3 = models.ForeignKey(lastdrop,max_length=50,on_delete=models.CASCADE) def __str__(self): return self.name forms.py class dropdownForm(forms.ModelForm): bdrop_choices = [('---------','---------')] bdrop_choices.extend([(bs.get('id'),bs.get('name')) for bs in basedrop.objects.all().values('id','name')]) drp1 = forms.ChoiceField(choices=bdrop_choices) class Meta: model = dropdown fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['drp2'].queryset = subdrop.objects.none() self.fields['drp3'].queryset = lastdrop.objects.none() self.fields['name'].required = True if 'drp1' in self.data: try: country_id = int(self.data.get('drp1')) self.fields['drp2'].queryset = subdrop.objects.filter(id=country_id).order_by('name') except (ValueError, TypeError): pass elif 'drp2' in self.data: try: country_id = int(self.data.get('drp2')) self.fields['drp3'].queryset = lastdrop.objects.filter(id=country_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['drp2'].queryset = self.instance.drp1.city_set.order_by('name') self.fields['drp3'].queryset = self.instance.drp2.city_set.order_by('name') views.py def create_drop(request): if request.method == 'POST': form = dropdownForm(request.POST) if form.is_valid(): form.save() return HttpResponse('<p>this is working</p>') form = dropdownForm() return render(request,'drop.html',{'form':form}) def load_subdrop(request): drp1_id = request.GET.get('drp1') subd = … -
how to add bg video file in js using Django
I'm trying to add background video to my Django website using Bideo library but when I load the page it returns 404 error for my video file here's my code how can I point to bgvideo.mp4 in video directory? /mywebsite /ctrlcntr /static /video bgvideo.mp4 /js Bideo.js theme.js (function () { var bv = new Bideo(); bv.init({ // Video element videoEl: document.querySelector('#home_main_pic'), // Container element container: document.querySelector('body'), // Resize resize: true, // autoplay: false, isMobile: window.matchMedia('(max-width: 768px)').matches, playButton: document.querySelector('#play'), pauseButton: document.querySelector('#pause'), // Array of objects containing the src and type // of different video formats to add src: [ { src: '../video/bgvideo.mp4', type: 'video/mp4' }, { src: '../video/bgvideo.webm', type: 'video/webm;codecs="vp8, vorbis"' } ], // What to do once video loads (initial frame) onLoad: function () { document.querySelector('#video_cover').style.display = 'none'; } }); }()); -
Django select_related with condition "and"
I have a query with SELF JOINed table payment_source in views.py paymentsss = Transaction.objects.all().select_related('currency', 'payment_source__payer', 'deal__service', 'deal__service__contractor',).filter( payment_date__range=[date1, date2], ).order_by('-id') Which turns into: SELECT "processing"."transaction"."id", "processing"."transaction"."currency_id", "processing"."transaction"."deal_id", "processing"."transaction"."payment_source_id", "processing"."transaction"."payment_date", "processing"."transaction"."amount", "processing"."transaction"."status", "processing"."transaction"."context", "processing"."currency"."id", "processing"."currency"."iso_name", "processing"."currency"."minor_unit", "processing"."deal"."id", "processing"."deal"."service_id", "processing"."service"."id", "processing"."service"."contractor_id", "processing"."service"."name", "processing"."service"."description", "processing"."contractor"."id", "processing"."contractor"."name", "processing"."payer_payment_source"."id", "processing"."payer_payment_source"."payer_id", "processing"."payer_payment_source"."payment_type_id", "processing"."payer_payment_source"."source_details", T7."id", T7."payer_id", T7."payment_type_id", T7."source_details" FROM "processing"."transaction" LEFT OUTER JOIN "processing"."currency" ON ("processing"."transaction"."currency_id" = "processing"."currency"."id") LEFT OUTER JOIN "processing"."deal" ON ("processing"."transaction"."deal_id" = "processing"."deal"."id") LEFT OUTER JOIN "processing"."service" ON ("processing"."deal"."service_id" = "processing"."service"."id") LEFT OUTER JOIN "processing"."contractor" ON ("processing"."service"."contractor_id" = "processing"."contractor"."id") LEFT OUTER JOIN "processing"."payer_payment_source" ON ("processing"."transaction"."payment_source_id" = "processing"."payer_payment_source"."id") LEFT OUTER JOIN "processing"."payer_payment_source" T7 ON ("processing"."payer_payment_source"."payer_id" = T7."id") I want to add a condition and, to get it: LEFT OUTER JOIN "processing"."payer_payment_source" T7 ON ("processing"."payer_payment_source"."payer_id" = T7."id" and T7."payment_type_id" = 'bank_card_details') models.py class PayerPaymentSource(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) payer = models.ForeignKey("self", null=True, on_delete=models.CASCADE, ) payment_type = models.ForeignKey(PaymentType, max_length=64, blank=True, null=True, on_delete=models.CASCADE) source_details = models.TextField(blank=True, null=True) class Meta: managed = False db_table = '"processing"."payer_payment_source"' class Transaction(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) currency = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE) deal = models.ForeignKey(Deal, null=True, on_delete=models.CASCADE) # service_instance = models.ForeignKey(ServiceInstance, null=True, on_delete=models.CASCADE) payment_source = models.ForeignKey(PayerPaymentSource, null=True, on_delete=models.CASCADE) payment_date = models.DateTimeField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table … -
Password Reset activation Link
I have 2 views . 1) For user Registration . 2) For Password Reset. Activation Link for both task is generated and send to mail. My activation link for first time registration is working fine . When I create my activation Link for password Reset , It is not get expired after use. @csrf_protect def changing_password_confirmation(request, uidb64, token): try: uid = force_bytes(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and passord_reset_token.check_token(user, token): print('user is not None and passord_reset_token.check_token(user, token)') if request.method == 'POST': password1 = request.POST.get('password1') password2 = request.POST.get('password2') if password1 == password2: user.set_password(password1) user.save() return render(request=request, template_name='website/password_reset_complete.html') else: return HttpResponse('<h1>Password doesnt match</h1>') return render(request=request, template_name='website/password_reset_confirm.html') else: print('User', user) result = 'Activation link is invalid!' return render(request=request, template_name='website/password_reset_confirm.html', context={'result': result}) from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) class PasswordTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() passord_reset_token = PasswordTokenGenerator() Reset Password Template {% extends "website/header.html" %} {% block title %}Enter new password{% endblock %} {% block content %} {% if validlink %} <h1>Set a new password!</h1> <form method="POST"> {% … -
Change src attribute in <img> tag created by ckeditor in django
I am using django-ckeditor which includes image upload. Code created by editor is following: <p><img alt="" class="img-fluid" height="687" src="/media/uploads/2019/11/04/yoga_m.jpg" width="1030" /></p> I have added class="img-fluid" by this JS code: CKEDITOR.on('instanceReady', function (ev) { ev.editor.dataProcessor.htmlFilter.addRules( { elements : { img: function( el ) { // Add bootstrap "img-responsive" class to each inserted image el.addClass('img-fluid'); } } }); }); problem is I have to send content in API and I need absolute path in src (src="http://127.0.0.1:8000/media/uploads/2019/11/04/yoga_m.jpg" not src="/media/uploads/2019/11/04/yoga_m.jpg") Can anyone help please? -
Unique filename of uploaded file using the django FORM
I'm trying to generate a unique filename for the uploaded file using the Django forms. I've tried uuid_upload_path app but that app doesn't work with the form. Below is my code Forms.py class HelpGuideForm(forms.ModelForm): title = forms.CharField(max_length = 50) image = forms.ImageField(required = False) class Meta: model = Helpguide fields = ['title', 'image'] I want a unique name for all uploaded files. something like sd564sadasd61.jpg. I'm using Django 2.2 -
Django refrence non field value at database level
class Author(models.Model): ... class Book(models.Model): author = models.ForeignKey(Author) book_seq = models.PositiveIntegerField() class Meta: unique_together = ('author', 'book_seq') def create_book_for_author(cls, author): book_seq = Book.objects.filter(author=author).count() + 1 Book.objects.create(author=author, book_seq=book_seq) Is there any way to reference this book_seq = Book.objects.filter(author=author).count() + 1 at database level because if this line concurrently then the unique constraint will fail and the second one to reach the database with insert query will fail. I know one option is transaction but is there any other way? F() object only works with concrete field not with database query.