Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to open a file in itertools.islice() function in python?
I am tried some script in that i catch pdf file and then convert that file to txt file . I got type of text file as _io.textIoWrapper . Now i call itertools.isslice() with _io.textIoWrapper object . That produce ValueError: I/O operation on closed file. If file format plain io.textIoWrapper didn't give any error. I tried to open textIoWrapper object but that gives expect only str , bytes or None not TextIoWrapper type views.py def save_file(cls, user, file, file_format, project_id,file1): project = get_object_or_404(Project, pk=project_id) parser = cls.select_parser(file_format) if file_format == 'pdf': path = default_storage.save('text_pdf_file.pdf', ContentFile(file.read())) return_file = convert_pdf_txt(path,file_format) print(type(return_file)) # _io.textIoWrapper file = return_file data = parser.parse(file,file_format) storage = project.get_storage(data) storage.save(user) utils.py class PlainTextParser(FileParser): def parse(self, file,file_format): if file_format == 'plain': file = EncodedIO(file) file = io.TextIOWrapper(file, encoding=file.encoding) while True: batch = list(itertools.islice(file, settings.IMPORT_BATCH_SIZE)) if not batch: break yield [{'text': line.strip()} for line in batch] convert.py import os from docx import Document import pdfplumber as pp import io import unidecode import re def remove_accented_chars(text): text = unidecode.unidecode(text) return text def remove_extra_spaces(line): return re.sub(' +|\t+',' ',line) def remove_special_char(line): return re.sub(r"[^a-zA-Z0-9%.@]+",' ', line) def preprocessing(lines,fileExtension): example_text_file = "ex_txt.txt" for line in lines: if fileExtension == "docx": x=str(line.text) elif fileExtension == "pdf": x … -
Django ModelForm. Select a valid choice. That choice is not one of the valid choices
I have a Model and a ModelForm. The ModelForm has a dependent dropdown list implemented with JQuery. Whenever I try to save the ModelForm in my views, I get an error saying that the choice that I have selected is not valid. Does it have to do with the choices/options to the individual_kata_event, individual_kumite_event, team_kata_event & team_kumite_event dropdowns being added after a choice from the gender dropdown has been selected? In models.py, class Athlete(models.Model): name = models.CharField(max_length=100) gender = models.CharField(max_length=100, choices=GENDER_CHOICES) date_of_birth = models.DateField() feet_height = models.PositiveIntegerField(default=0) inch_height = models.PositiveIntegerField(default=0) weight = models.FloatField(default=0.0, help_text='Weight in kg') club = models.CharField(max_length=100, choices={ ('Arrianna Academy' , 'Arrianna Academy'), ('Bangladesh Shitoryu Karate-do Union' , 'Bangladesh Shitoryu Karate-do Union') }) team = models.CharField(max_length=100, choices={ ('Bangladesh Ansar & VDP' , 'Bangladesh Ansar & VDP'), ('Bangladesh Army' , 'Bangladesh Army') }) individual_kata_event = models.CharField(max_length=22, choices=[('', ''), ], default='None') individual_kumite_event = models.CharField(max_length=22, choices=[('', ''), ], default='None') team_kata_event = models.CharField(max_length=22, choices=[('', ''), ], default='None') team_kumite_event = models.CharField(max_length=22, choices=[('', ''), ], default='None') gold = models.PositiveIntegerField(default=0) silver = models.PositiveIntegerField(default=0) bronze = models.PositiveIntegerField(default=0) picture = models.ImageField(upload_to='athlete_images', blank=True) In forms.py, class AthleteForm(forms.ModelForm): class Meta: model = Athlete fields = '__all__' widgets = { 'date_of_birth': forms.DateInput( format=('%m/%d/%Y'), attrs={ 'class': 'form-control', 'placeholder': 'Select a date', … -
convert pandas excel output to json drf django
i have this api. it returns excel header data and i want to dump pandas data to json but its showing error...................................................................... @api_view(['POST', ]) def bulkUploadPolicyMember(request): data = json.loads(request.data['data']) data = decode_data(data) data["uploaded_by"] = request.user.uid data['status'] = 0 data['uploaded_date'] = datetime.datetime.now() data['sheet'] = data['sheet'] if 'sheet' in data and data['sheet'] != '' else None data['docket_id'] = data['docket_id'] if data['docket_id'] != '' else None if data['docket_id'] is None: return CustomeResponse(request=request, comment=DOCKET_REQUIRED, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1, message=DOCKET_REQUIRED) try: doc_obj = InwardDocument.objects.values('insurer_id').get(uid=data['docket_id']) except InwardDocument.DoesNotExist: return CustomeResponse(request=request, comment=DOCKET_REQUIRED, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1, message=DOCKET_REQUIRED) policy_file_path = settings.BULK_POLICY_FILE_UPLOAD+'insurers/'+str(doc_obj['insurer_id']) try: if 'file' in request.FILES and request.FILES['file'] != "": policy_file = request.FILES['file'] # check extension if validateFileExtension(policy_file) is True: if (getFileExtByFileName(policy_file) == 'xlsx' or getFileExtByFileName(policy_file) == 'xls') and data['sheet'] is None: return CustomeResponse(request=request, comment=SHEET_NAME_CHECK, message=SHEET_NAME_CHECK, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST,validate_errors=1) policy_file_name = file_save_by_source(request, policy_file_path, policy_file) if policy_file_name != "": data['file_name'] = policy_file_name else: return CustomeResponse(request=request, comment=COULD_NOT_UPLOAD_FILE, message=COULD_NOT_UPLOAD_FILE, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST,validate_errors=1) try: upload_path = settings.MEDIA_URL+policy_file_path+'/'+policy_file_name try: pd_data = pd.read_excel(upload_path).columns except Exception as e: print(e) return CustomeResponse(request=request, comment=BULK_DATA_NOT_FOUND,message=BULK_DATA_NOT_FOUND, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1) except Exception as e: #print(e) return CustomeResponse(request=request, log_data=json.dumps(str(e), cls=UUIDEncoder), message=SOMETHING_WENT_WRONG, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) else: return CustomeResponse(request=request, comment=ALLOWED_POLICY_FILES, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1, message=ALLOWED_POLICY_FILES) else: print("->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") return CustomeResponse(request=request, comment=POLICY_FILE_REQUIRED, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1, message=POLICY_FILE_REQUIRED) except KeyError: return CustomeResponse(request=request, comment=KEY_MISSING, message=KEY_MISSING, data=json.dumps({}, … -
Django Rest Framework - Envelope a Paginated Response
I want to wrap an paginated response in an envelope. The Result should look like this. { "data": ["datum 1", "datum 2", "datum 3"], "meta": { "some": "meta", "data": "foo", }, "page": { "total": 12345, "count": 3, "from": 3, "to": 6, "next": "http://example.com?page=2", "prev": "http://example.com?page=0", } } The custom page format can be achieved by inheriting from PageNumberPagination. My question is about passing the Metadata. I do not see any way to pass it to the Pagination except some form of in band signaling. Is there a clean(er) way to do this? -
Define FileField upload_to directory in Django model
I have a model Audiopart with field filename = models.FileField(upload_to=get_upload_path, blank=True) and function for generating upload path def get_upload_path(instance, filename): return os.path.join( 'audio', instance.book_id.folder, filename ) So file uploads to directory (for ex. "audio\mybook\a1.mp3"), that's good. And in database in field "filename" stores path "audio\mybook\a1.mp3". Is any way to save in DB just filename "a1.mp3", without "audio\mybook\"? -
how to use django-redis hset operation in redis cache
I am using django 3.0.4 and python 3.6.9. I have to use hset operation to set some values in redis cache. My try: from django.core.cache import caches cache.set(), cache.get() // these operation are working But I am not able to use hset and hget operation using this library. There is no proper documentation about this in Django official docs. Note: I have referred this (Not A copy) -
django: Use different configuration for test database?
Can I specific a different configuration for the test database? Or alternatives simply use a different user in production?(how to manage that as settings file needs to be updated as well?) The testing requirements for postgresql require in my opinion too many privs like create DB and in my case I also need to create an extension upon db creation which means superuser privileges. -
matching query does not exist django heroku
i have deployed my app to heroku.. But when i try to go to the page, i get this error from log: apps.adminview.models.Templates.DoesNotExist: Templates matching query does not exist. This is from my adminview models, as you can see it is created correctly: ... class Templates(models.Model): description = models.TextField(null=True, blank=True) template_name = models.TextField(null=True, blank=True) isSelected = models.BooleanField(default=False) temp_selected = models.BooleanField(default=False) width_field = models.IntegerField(default=0, null=True) height_field = models.IntegerField(default=0, null=True) image_path = models.ImageField( width_field="width_field", height_field="height_field" ) def __str__(self): return "("+str(self.id)+") " + self.template_name Anyone could help me with this? Thank you!. -
Why can't I display more fields in django?
I'm Trying to develop a social website, and I want to display the bio and blood group of the user on their profile page along with their name and email. While the name and email are being Displayed in the profile page, their bio and blood group are not being displayed although I wrote the same code for them as their name and email. Can anyone please help me out? My models.py : from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' my forms.py : from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() CHOICES = ( ('type', 'AB+'), ('type', 'AB-'), ('type', 'A+'), ('type', 'A-'), ('type', 'B+'), ('type', 'B-'), ('type', 'O+'), ('type', 'O-'), ) bloodgroup = forms.CharField(widget=forms.Select(choices=CHOICES)) bio = forms.CharField() class Meta: model = User fields = ['username', 'email', 'bio', 'bloodgroup', 'password1', 'password2'] my profile.html: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> <p class="text-primary">{{ user.bio }}</p> <p2 class="text-info">Blood Group - {{ … -
Django raw sql insert query in triple quotation: Django interprets null values from ajax request data as None column
I am working on a Django/React project. Using DRF, I am throwing an API route for performing SQL queries in my PostgreSQL database. But I am having issues with my current code setup. I have setup my INSERT query in the API as raw queries (using cursor) enclosed in a triple quote multi-line string """INSERT...""", then format my values using string formatting %s. In my API, I capture each request body into a variable. Everything works fine if all request data are filled. But, if it is null, Django obviously assigns None to the variable. Now back to my sql query, Django will treat the null %s as None and as a table column instead of a correct null value, thus throwing a ProgrammingError column "none" does not exist. Here are sample codes: React Frontend const [lastName, setLastName] = useState('') const [firstName, setFirstName] = useState('') const [middleName, setMiddleName] = useState('') const [nameExtn, setNameExtn] = useState('') const [sex, setSex] = useState('') const [civilStatus, setCivilStatus] = useState('') const [bloodType, setBloodType] = useState('') const [height, setHeight] = useState('') const [weight, setWeight] = useState('') const newPersonalInfo = (token, data) => { let endpoint = "/jobnet/api/profile/pds/basic/personal/" let lookupOptions = { method: "POST", headers: { 'Content-Type': … -
How do I add my custom field in django filter?
I am creating an API to return posts on a user profile. The posts can be public, friends only or with custom privacy. Here is my filter: posts = Post.objects.filter( Q(created_by=user, privacy='PUBLIC') | Q(created_by=user, privacy='FRIENDS')| Q(created_by=instance, privacy='CUSTOM', custom_list=requested_by.pk)) Here I want to get the 'friends_only' posts if the requested user is friend of the user whose profile I am showing. Problem is I don't have any relation between Post and Friend. I am using a Friend model as shown below: class Friend(models.Model): sender = models.ForeignKey(UserProfile, related_name="sender", on_delete=models.CASCADE) receiver = models.ForeignKey(UserProfile, related_name="receiver", on_delete=models.CASCADE) accepted = models.NullBooleanField(default=None) and Post model as: class Post(BaseModel, models.Model): PRIVACY_CHOICES = [ ('PUBLIC', 'Public'), ('PRIVATE', 'Private'), ('FRIENDS', 'Friends only'), ('CUSTOM', 'Custom') ] text = models.TextField() image = models.ImageField(upload_to="assets/posts/", null=True, blank=True) created_by = models.ForeignKey(UserProfile, related_name="posts", on_delete=models.CASCADE) privacy = models.CharField(max_length=10, choices=PRIVACY_CHOICES) custom_list = models.ManyToManyField(UserProfile, related_name="post_by_friends", blank=True) liked_by = models.ManyToManyField(UserProfile, related_name="likes", blank=True) My question is how can I filter the Post model by providing my condition in filter is_friend = True -
Unable to import Django model into Python shell
I am recently trying to lean APIs using DJango Rest. I have a model to work with: class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) def __str__(self): return self.question I want work with the model in the python shell, but whenever I do: from polls.models import Poll in python shell, it shows: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. could anyone help? I am also working on a virtual env -
is Django 'app' equal to 'component' in Angular?
Just started learning Django, as an Angular developer can we say that apps in Django are similar to Angular components ? -
How to override default formats in the data and time fields using Django rest framework?
I tried to override the default formats in time and date fields using the Django rest framework but it's not working. So I added to format and input_format parameter in fields. still, I facing that issue. I refer to the many documentation and many StackOverflow answers. Still, it's not working. anyone can help me. How to solve this error Models.py class Showss(models.Model): show_Time = models.TimeField() Serializer.py class ShowSerializer(serializers.ModelSerializer): show_Time = serializers.TimeField(format='%H:%M:%S', input_formats='%H:%M:%S') class Meta: model = Showss fields = '__all__' settings.py REST_FRAMEWORK = { "TIME_INPUT_FORMATS": [("%H:%M:%S"),] } -
How do I auto login after registration in Django?
So, I'm trying to let the user be automatically logged in as soon as he/she registers. Here's my register function. def register(response): if response.method == 'POST': form = RegisterForm(response.POST) if form.is_valid: form.save() return redirect('/main/inputuserinfo') else: form = RegisterForm() return render(response, 'register/register.html', {'form' : form}) As I mentioned, I'd like to log the user in right after he/she registers, then redirect him/her to '/main/inputuserinfo'. But I have no idea on how I can create it. I very much appreciate your help. :) -
unable to save model form data in database. gives patientmedinfo.errors = none and patientmedinfo.is_valid() = false
'I am new to django , trying to save my form data in the database.created two model classes PatientInfo and patientHist, which is inheriting PatientInfo class. I do not understand where i am going wrong. models.py from django.db import models # Create your models here. class PatientInfo(models.Model): sex = ( ('M', 'Male'), ('F', 'Female') ) first_name = models.CharField(max_length=35) middle_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length= 30) sex = models.CharField(max_length=1,choices=sex) date_of_birth = models.DateField() height = models.FloatField() weight = models.FloatField() phone_no =models.CharField(max_length=15) class PatientHist(PatientInfo): Yes_No = ( (True, 'Yes'), (False, 'No'), ) Veg_nonveg =( (True,'Veg'), (False,'Non-Veg'), ) diabetes = models.BooleanField(default=False,choices=Yes_No) diabetes_long = models.CharField(max_length=20) hypertension = models.BooleanField(default=False,choices=Yes_No) hypertension_long = models.CharField(max_length=20) obesity = models.BooleanField(default=False,choices=Yes_No) obesity_long = models.CharField(max_length=20) pcod = models.BooleanField(default=False,choices=Yes_No) pcod_long= models.CharField(max_length=20) thyroid = models.BooleanField(default=False,choices=Yes_No) thyroid_long = models.CharField(max_length=20) heartdiease = models.BooleanField(default=False,choices=Yes_No) heartdiease_long = models.CharField(max_length=20) liverdisease = models.BooleanField(default=False,choices=Yes_No) liverdisease_long = models.CharField(max_length=20) kidney = models.BooleanField(default=False,choices=Yes_No) kidney_long = models.CharField(max_length=20) familyhistory = models.BooleanField(default=False,choices=Yes_No) currentmed = models.CharField(max_length=20) foodhabit= models.BooleanField(default=False,choices= Veg_nonveg) hba1c = models.FloatField(max_length=20) fasting = models.FloatField(max_length=20) pp = models.FloatField(max_length=20) forms.py from django import forms from .models import * class Patient_form(forms.ModelForm): class Meta: model = PatientInfo fields = "__all__" class PatientHistory_form(forms.ModelForm): class Meta: model = PatientHist widgets = { 'diabetes': forms.RadioSelect, 'hypertension': forms.RadioSelect, 'obesity': forms.RadioSelect, 'pcod': forms.RadioSelect, 'thyroid': … -
mypy gives an error while importing submodule : Module has no attribute
When I am checking my modules through mypy it gives me this error: Module 'django.contrib.gis' has no attribute 'forms' and I am importing forms like this " from django.contrib.gis import forms ". I know it is correct but mypy shows this error message. I could import like this: from django.contrib import gis and use forms as gis.forms but I do not want to. Can anyone help me to fix this? Thanks. -
What is difference between django-bootstrap4 and bootstrap4?
I am beginner in Django web development & currently I am using using bootstrap4 by loading bootstrap.min.css & bootstrap.min.js as below in html files. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> Recently I have found that there been module in Django named django-bootstrap4 & I am reading its documentation also. https://django-bootstrap4.readthedocs.io/ I have tried to find difference between those but not found any. Which will be suitable to use in web development? Tried to find answer on google but not found any so please can someone explain me difference between these two? -
How to append values in a tabular format from JSON in Django Template?
I am making a small web application that allow user to perform OCR on the selected image and provides the JSON output in a tabular Format like this. What I'm facing now is when I'm selected new image to add values in the table, it overrides the values instead of appending. And what I want is to append new value in the table by choosing another image, the previous row show me stay as it is and new will get append. So that finally I can submit all the values to the database all together by clicking on the submit button. Here is my template code : <form method="post">{% csrf_token %} <div class="table-responsive"> <table id="datatable2" class="table order-column hover"> <thead> <tr> <th>Investigation Name</th> <th>Result</th> <th>UOM</th> <th>Low Range</th> <th>High Range</th> </tr> </thead> <tbody> {% for key, value in data.items %} {% for key2,value2 in value.items %} <tr class="gradeX"> <td>{{ value2.test_name }}</td> <td>{{ value2.results }}</td> <td>{{ value2.units }}</td> <td>{{ value2.low_range }}</td> <td>{{ value2.high_range }}</td> </tr> {% endfor %} {% endfor %} </tbody> </table> </div> <!--end .table-responsive --> <button type="submit" class="btn btn-primary" name="data">Submit</button> </form> How can we use list in DTL to store the previous values and stay as it is and the new … -
Does django caches queryset results if those querysets are used (or deleted) later?
a = SampleModel.objects.filter(Id=2) b = SampleModel.objects.filter(Id=3) If a and b: print(true) a.delete() b.delete() Now in above code...how many time is database hit? It will be hit when calling a and b in if statement. But will database also be hit on .delete() operations. Or django has some cache mechanism which caches the queryset results? -
Getting ImportError on Django3.0.4 while running runserver [duplicate]
I have been trying to run the latest versionof django3.0.4, but I'm getting error while trying to run the local server. I tried installing the package six eventhough it was already installed. pip install six current version being used is six-1.14.0 pip install --upgrade django-cors-headers current versio being used is django-cors-headers-3.2.1 Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/home/username/Documents/Projects/VirtualEnv/lib/python3.6/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/username/Documents/Projects/VirtualEnv/lib/python3.6/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/username/Documents/Projects/VirtualEnv/lib/python3.6/site-packages/rest_framework/templatetags/rest_framework.py", line 9, in <module> from django.utils import six ImportError: cannot import name 'six' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/username/Documents/Projects/VirtualEnv/lib/python3.6/site-packages/django/utils/autoreload.py", … -
how to change input durationfield format using forms like 3w 3h 3m. I tried several ways.Please help .I am fresher
Forms.py class Meta: model = Issues fields ='__all__' exclude=['CREATOR','UPDATOR','CREATED_DATE_TIME','UPDATED_DATE_TIME','EPIC_LINK','WATCHER','PARENT','ORDER','SERIAL_NUMBER','COLOR','DEFECT_TYPE','STATUS','EPIC_NAME'] widgets = { 'START_DATE': DateInput(), 'DUE_DATE': DateInput(), 'ESTIMATION_TIME': DurationInput(), } class DurationInput(TextInput): def _format_value(self, value): duration = parse_duration(value) seconds = duration.seconds minutes = seconds // 60 seconds = seconds % 60 minutes = minutes % 60 return '{02w}{02d}{02h}{02m}'.format(minutes, seconds) models.py ESTIMATION_TIME = models.DurationField(null=True, blank=True) -
Email to Register Confirmation Django
The confirmation email is arriving normal at test@hotmail.com. But whenever I click the message appears:'Activation link is invalid!' ever. Can someone help me? Views.py def register(request): if not request.user.is_authenticated: if request.method == 'POST': register_status = register_user(request) if register_status != 1: messages.error(request, register_status) return redirect('register') #Register Success else: user = get_user_model() subject = 'Confirm your account' current_site = get_current_site(request) message = render_to_string('users/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) from_email = 'myacount@gmail.com' to_list = [from_email , 'test@hotmail.com'] send_mail( subject, message, from_email, to_list, fail_silently=False, ) messages.success(request, 'Please confirm your email') return redirect('login') else: return render(request, 'users/register.html') else: messages.error(request, 'You are already logged in') return redirect('index') def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) User = get_user_model() user = User.objects.get(pk=uid) print(user) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') tokens.py 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) ) account_activation_token = TokenGenerator() url.py from django.urls import path from . import views urlpatterns … -
Why django PermissionRequiredMixin is not working as it intended to be
Here i have got a Django view that should normally redirect me to the Settings.LOGIN_URL if user has not the required permission but the issue is it's always displaying the 403 FORBIDDEN page. the url defined in Settings.LOGIN_URL is 'accounts/login/'. class LibrairianListView(PermissionRequiredMixin, View): model = BookInstance template_name = 'catalog/librairian_list_borrowed.html' permission_required = 'catalog.can_mark_returned' def get_queryset(self): return BookInstance.objects.filter(status__exact='o').order_by('due_back') def get_context_data(self, **kwargs): print(self.raise_exception) context = {} context['bookinstance_list'] = self.get_queryset() return context def get(self, request, *args, **kwargs): return render(request, self.template_name, self.get_context_data()) And i change this to a function based view and everything is working fine, but i wanted to use class base view since this should do the same work -
Django: Where to go from "pinax.notifications?"
With regards to a deployed web-site I am rudely confronted with unexpected upgrade problems. "pinax.notifications" in particular is throwing problems such as a dependency on a package named "six" and inability to understand the decorator @python_2_unicode_compatible. The Django version that this app has been running was 2.1.11 and now the latest is 3.0.4 and this seems to have caused me a boatload of problems all of the sudden. Any advice appreciated ...