Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Disable next button in last imgage in image slider Java script
I'm building an image slider with Java script with next button to toggle between the images. So automatically when reach the last image it begins from the first. I want to disable the next button in last image. or change it with another button like submit or something HTML: <div class="slider"> <!-- fade css --> <div class="myslide fade"> <div class="txt"> <h1>IMAGE 1</h1> <p>Web Devoloper<br>Subscribe To My Channel For More Videos</p> </div> <img src="img1.jpg" style="width: 100%; height: 100%;"> </div> <div class="myslide fade"> <div class="txt"> <h1>IMAGE 2</h1> <p>Web Devoloper<br>Subscribe To My Channel For More Videos</p> </div> <img src="img2.jpg" style="width: 100%; height: 100%;"> </div> <div class="myslide fade"> <div class="txt"> <h1>IMAGE 3</h1> <p>Web Devoloper<br>Subscribe To My Channel For More Videos</p> </div> <img src="img3.jpg" style="width: 100%; height: 100%;"> </div> </div> a class="next" onclick="plusSlides(1)">&#10095;</a> JS: const myslide = document.querySelectorAll('.myslide'), dot = document.querySelectorAll('.dot'); let counter = 1; slidefun(counter); let timer = setInterval(autoSlide, 8000); function autoSlide() { counter += 1; slidefun(counter); } function plusSlides(n) { counter += n; slidefun(counter); resetTimer(); } function currentSlide(n) { counter = n; slidefun(counter); resetTimer(); } function resetTimer() { clearInterval(timer); timer = setInterval(autoSlide, 8000); } function slidefun(n) { let i; for(i = 0;i<myslide.length;i++){ myslide[i].style.display = "none"; } for(i = 0;i<dot.length;i++) { dot[i].className = dot[i].className.replace(' … -
How can I display my in save to create new playlist on side bar in django just like youtube playlist?
The button has now been renamed to "Save," and a single tap will automatically add the video to your most recently selected playlist (or your Watch Later list, if you haven't used the feature before).then my question is how can we display the list on side bar? -
"Attribute error: module "myApp.views" has no attribute symbol " - Django
I'm using django framework for my app backend, I want to use the attribute (fetched using request.get()) from views.py file into another py file into same directory as views.py . I am getting the following two errors. -
Difference between creating custom Django token generator and using the default PasswordResetTokenGenerator
I'm creating a verification email users app, which as the name may suggest verify users' emails before activating their accounts. I've seen in many tutorials that they use the following code to create a custom token generator for account activation: class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return text_type(user.is_active) + text_type(user.pk) + text_type(timestamp) token_generator = TokenGenerator() However, I don't see why I should use this over the default PasswordResetTokenGenerator. I've tried to implement both, the custom and the default and the result is the same. Why do they suggest inheriting PasswordResetTokenGenerator and create an AccountActivationTokenGenerator. Is there any security issue if I use the same token generator for two tasks? -
! [remote rejected] main -> main (pre-receive hook declined)
name@pop-os:~/project/projectname$ git push heroku main Enumerating objects: 521, done. Counting objects: 100% (521/521), done. Delta compression using up to 4 threads Compressing objects: 100% (417/417), done. Writing objects: 100% (521/521), 235.54 MiB | 411.00 KiB/s, done. Total 521 (delta 37), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python- 3.9.6 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.9.6 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting aniso8601==7.0.0 remote: Downloading aniso8601-7.0.0-py2.py3-none-any.whl (42 kB) remote: Collecting anyascii==0.1.7 remote: Downloading anyascii-0.1.7-py3-none-any.whl (260 kB) remote: Collecting appdirs==1.4.4 remote: Downloading appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB) remote: ERROR: Could not find a version that satisfies the requirement apsw==3.28.0.post1 (from -r /tmp/build_40fef6ac/requirements.txt (line 4)) (from versions: 3.8.2.post1, 3.8.5.post1, 3.8.6.post1, 3.8.7.1.post1, 3.8.7.2.post1, 3.8.7.3.post1, 3.8.8.1.post1, 3.8.8.2.post1, 3.8.9.post1, 3.8.10.1.post1, 3.8.11.1.post1, 3.9.2.post1) remote: ERROR: No matching distribution found for apsw==3.28.0.post1 (from -r /tmp/build_40fef6ac/requirements.txt (line 4)) remote: ! Push rejected, failed to compile Python app. remote: … -
Django authentication login
I am building a Django app. I have customized the User model. My models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from phonenumber_field.modelfields import PhoneNumberField from phonenumber_field.phonenumber import PhoneNumber # Create your models here. class UserManager(BaseUserManager): def create_user(self, phone_number,username,email=None, password=None): if not phone_number: raise ValueError("You must specify your phone number") if not username: raise ValueError("You must specify your username") try: user = self.model(phone_number= PhoneNumber.from_string(phone_number=phone_number,region="BD").as_national, username=username, email=self.normalize_email(email)) except : user = self.model(phone_number= PhoneNumber.from_string(phone_number=phone_number,region="BD").as_national, username=username) user.save(using=self._db) return user def create_stuffuser(self, phone_number,username,email,password): user = self.create_user(phone_number,username,email=email,password=password) user.staff = True user.save(using=self._db) return user def create_superuser(self, phone_number,username,email,password): user = self.create_user(phone_number,username,email=email,password=password) user.staff = True user.admin= True user.save(using=self._db) return user class User(AbstractBaseUser): phone_number = PhoneNumberField(unique=True) username = models.CharField(unique=False,max_length=50) REQUIRED_FIELDS = ['username'] email = models.EmailField(unique=False) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'phone_number' def get_full_name(self): return self.username def get_short_name(self): return self.username def get_email(self): return self.email def __str__(self): return str(self.phone_number) def has_perm(self, perm, obj=None): return True def has_module_perms(self,app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin objects = UserManager() Now, @login_required is not working. I have tried to authenticate user and login with the built-in authenticate and login function: def loginfunc(response): if response.method == 'POST': ph = response.POST['ph'] pw = … -
Local settings not found : ModuleNotFoundError: No module named 'account'
I'm getting error in cmd : ModuleNotFoundError: No module named 'account' Below is my code in which i am facing some issue please help and suggest me any change needed in command or the codeenter image description here import account.form from django import forms class SignupForm(account.forms.SignupForm): def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) del self.fields["username"] class UploadFileForm(forms.Form): file = forms.FileField() -
Django: Can't fetch records for the current date
I know you might be thinking that this is some stupid & trivial question by reading the heading but I can't make it work. I have one model called Survey which has one field called survey_date which is of type DATE. What I want to do is that fetch all the records by today's date & I really don't know why this easy looking thing became the pain in the a**. The simplest way I tried was this, def get_initial_queryset(self): today = datetime.date.today() qs = Survey.objects.filter(survey_date=today) print(qs.query) return qs I thought this should work but it did not, So tried googling it and found this Query datetime by today's date in Django It was very similar to my problem but believe me I tried every single answer from it and nothing worked. I even tried to get the actual query from the queryset I tried to run it manually via phpmyadmin but it returned no rows.I am pasting that generated query also here(I made it little shorter by removing other columns), SELECT `survey`.`id`, `survey`.`uid`, `survey`.`currency`, `survey`.`survey_type`, `survey`.`survey_subtype`, `survey`.`transit_type`, `survey`.`survey_date`, `survey`.`survey_time`, `survey`.`live_survey_type` FROM `survey` WHERE `survey`.`survey_date` = 2021-08-17 Any help would appreciated.I am using Django version 3.1.6. -
How to auto populate a read-only serializer field in django rest framework?
I have a question regarding django rest framework. Most of the time, I have a serializer which has some read-only fields. For example, consider this simple model below: class PersonalMessage(models.Model): sender = models.ForeignKey(User, related_name="sent_messages", ...) recipient = models.ForeignKey(User, related_name="recieved_messages", ...) text = models.CharField(...) def __str__(self) -> str: return f"{self.text} (sender={self.sender})" In this model, the value of sender and recipient should be automatically provided by the application itself and the user shouldn't be able to edit those fields. Alright, now take a look at this serializer: class PersonalMessageSerializer(serializers.ModelSerializer): class Meta: model = PersonalMessage fields = '__all__' read_only_fields = ('sender', 'recipient') It perfectly prevents users from setting an arbitrary value on the sender and recipient fields. But the problem is, when these fields are marked as read-only in the serializer, the serializer will completely ignore all the values that are passed into the constructor for these fields. So when I try to create a model, no values would be set for these fields: PersonalMessageSerializer(data={**request.data, 'sender': ..., 'recipient': ...) # Won't work What's the best way to prevent users from setting an arbitrary value and at the same time auto-populate those restricted fields in django rest framework? -
Django error when trying to migrate models with foreignkeys that don't have null=True or default set
I have this model that is a post like on Twitter, that has a creator. I'd ideally like the post to always require a creator_id and if the creator gets deleted then delete the post as well class Post(AbstractBaseModel): creator_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post_creator_id") body = models.CharField(max_length=511) Whenever I try to run 'python manage.py migrate' I get this error "You are trying to change the nullable field 'creator_id' on cheerpost to non-nullable without a default; we can't do that (the database needs something to populate existing rows)." The options to solve this are are 1) provide a one off default or 2) ignore for now. Neither of these seem to fulfill my constraint that I want to enforce, which is creator_id must exist and is the person who created the post or the entity gets deleted. -
How does a django project use multiple databases with the same structure to read and write, distinguished by url
I have a django project and want to divide it into multiple databases with the same structure. Use url to distinguish different databases. When the admin management page logs in, log in to different databases according to different urls. For example: 127.0.0.1/admin uses the admin database, 127.0.0.1/admin2 uses the admin2 database. Does django implement this function? What do I need to do, Can you give me some suggestions or ideas? thank you very much -
Stripe Integration with Django giving a type error saying __init__() takes 1 positional argument but 2 were given
Hi I've been trying to learn how to integrate the Stripe prebuilt checkout page into my django project. The stripe docs are for flask so I'm trying to read or watch youtube tutorials on how to convert them into django but I'm not really getting anywhere. The code in the tutorials are different from the current stripe docs https://stripe.com/docs/checkout/integration-builder from django.shortcuts import render, redirect import stripe from django.conf import settings from django.http import JsonResponse # Create your views here. from django.views import View from django.views.generic import TemplateView stripe.api_key = settings.STRIPE_SECRET_KEY class ProductLandingPageView(TemplateView): template_name = "landing.html" class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): YOUR_DOMAIN = "http://127.0.0.1:8000" checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[ { # TODO: replace this with the `price` of the product you want to sell 'price': '{{PRICE_ID}}', 'quantity': 1, }, ], mode='payment', success_url=YOUR_DOMAIN + "/success", cancel_url=YOUR_DOMAIN + "/cancel", ) return redirect(checkout_session.url, code=303) class Successview(TemplateView): template_name = "success.html" class Cancelview(TemplateView): template_name = "cancel.html" I can get the checkout.html to show but when I click on the checkout button I get this error TypeError at /create-checkout-session __init__() takes 1 positional argument but 2 were given Request Method: POST Request URL: http://127.0.0.1:8000/create-checkout-session Django Version: 3.2.5 Exception Type: TypeError Exception Value: __init__() takes 1 … -
checkbox inputs are only submitted when is checked
This is my first Django project I have this simple form which I would like to submit all row values (checked or unchecked), The error I am facing is that it only sends row{num} value if it is checked. <script> function calc(elemId) { var elem = document.getElementsByName(elemId)[0]; if (elem.checked) { elem.value = 1; } else { elem.value = 0; } } </script> <div class="container pt-3"> <form action="." method="post"> <table class="table table-hover"> <thead> <tr> <th scope="col">#</th> <th scope="col">Keyword</th> <th scope="col">seller_items</th> <th scope="col">Total</th> <th scope="col">checked</th> </tr> </thead> {% csrf_token %} {{ form|crispy }} {%for i in data%} <tr > <th scope="row">{{forloop.counter}}</th> <td>{{i.keyword}}</td> <td>{{i.seller_items}}</td> <td>{{i.total_found}}</td> <td> {% if i.checked %} <input type="checkbox" name="row{{i.id}}" value="1" checked="checked" onclick="calc('row{{i.id}}')"/> {%else%} <input type="checkbox" name="row{{i.id}}" value="0" onclick="calc('row{{i.id}}')"/> {%endif%} </td> </tr> {% endfor %} </table> <div class="row"> <div class="col-12"> <button class="btn btn-primary float-right" type="submit">Update</button> </div> </div> </form> the form is submitted when the button is pushed but only checked boxes rows are in the post request -
This code is the part of my Django project, my task is to find company name from the job description parsing, but I am unable to get the company name?
from .CleanJdTextData import Cleaned_Text, ReadModule from resume_app.Config_Reader import Config_Dict from jd_app.Designation_Extract import Designation_Extract nlp_Company_Module = ReadModule(Config_Dict['company_aliases_resume_parsing']) nlp_designation_module = ReadModule(Config_Dict['designation_saveLoc']) added class CompanyExtract(): def __init__(self, cleaned_data, nlp_cn): self.cleaned_data = cleaned_data self.nlp_cn = nlp_cn def company_extract(self): company_designation_dict = dict() if all([self.cleaned_data, isinstance(self.cleaned_data, tuple)]): try: area_to_search = self.cleaned_data[:10] except: area_to_search = self.cleaned_data area_to_search = self.cleaned_data for index, data in enumerate(area_to_search): # for data in area_to_search: company_data = self.apply_Nlp_On_Data(data) if any([company_data]): company_designation_dict.update({'company_name':company_data}) designation = Designation_Extract(self.cleaned_data, nlp_designation_module()).extract_designation(index) if any([designation]): company_designation_dict.update({'designation':designation}) return company_designation_dict def lemma_Add_In_data(self, str_data): lemma_add = ' '.join([x.lemma_ if x.text != "limited" else x.text for x in self.nlp_cn(str_data)]) data = [str_data, lemma_add] if lemma_add != str_data else [str_data] if any([data]): return data def replace_Pvt_Ltd(self, str_data): if all([str_data, isinstance(str_data, str)]): replace_dict = {"pvt": "private", "ltd": "limited", "co":"company", "inc":"incorporated", "corp": "corporation"} data = ' '.join([replace_dict[x] if x in replace_dict.keys() else x for x in str_data.split()]) if any([data]): return self.lemma_Add_In_data(data) def apply_Nlp_On_Data(self, str_data): if all([str_data, isinstance(str_data, str)]): replace_pvt_ltd_ = self.replace_Pvt_Ltd(str_data) if any([replace_pvt_ltd_]): for company_name in replace_pvt_ltd_: doc = self.nlp_cn(company_name) company_name_s = [x.text.title() for x in doc] if any([company_name_s]): return company_name_s[0] class ExtractCompanyName: def init(self, text_data): self.text_data = text_data def extract_company_name(self): if all([self.text_data, isinstance(self.text_data, tuple)]): company_designation_dict = dict() global obj_Of_clean_Data obj_Of_clean_Data = Cleaned_Text(self.text_data, ['+', '&']) company_designation_dict = CompanyExtract(obj_Of_clean_Data(), … -
Django - Ensure 2 fields in a table of the same model type don't have the same value for an entity
So I have a user class and a user can follow another user, but I don't want the user to be able to follow themselves. Is there a way to add this constraint to Django? class FollowUser(AbstractSimpleModel): follower_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower_id') followee_id = models.OneToOneField(User, on_delete=models.CASCADE, related_name='followee_id') -
Input Variable for Slice in html Forloop - Django
I have a Django website and in one of the HTML files I have a for-loop with a slice functionality to display just the attributes within the slice range. {% for post in filter.qs|slice:"2:11" %} <div class="title">Morgan Hall</div> <div class="inspection_num">Inspection #</div> <div class="inspect_num">{{ post.count_building }}</div> <div class="inspection_date">Inspection Date</div> <div class="current_date_small" id="myDiv"></div> {% if post.image %} <img class="pdf_field_img" src="{{ post.image.url }}"/> {% else %} {% endif %} {% endfor %} I need to have the users have a simple integer input on the same page that defines the range the slice will be at. The input will basically fill a variable in the slice values and define it that way. I have been working on this for a long time with no luck, It is very far beyond me. Any help is greatly appreciated. Thanks! -
STUN/TURN server configuration for Django channels with WebRTC
I developed using django channels to implement video chat and message chat.(I was referring to a YouTuber's course.) When I first completed the development, I noticed that webrtc works only in the local network, and I found out that a stun/turn server was needed. So, I created a separate EC2 and built the stun/turn server and set this to the RTCPeerconnection in the web server. Stun/turn server test in Trickle ICE is good. But My video call still works only within the local network. And even within the same network, the connection was very slow. Server overall configuration.(Webserver with SSL application loadbalancer) Coturn config # /etc/default/coturn TURNSERVER_ENABLED=1 # /etc/turnserver.conf # STUN server port is 3478 for UDP and TCP, and 5349 for TLS. # Allow connection on the UDP port 3478 listening-port=3478 # and 5349 for TLS (secure) tls-listening-port=5349 # Require authentication fingerprint lt-cred-mech server-name=mysite.com realm=mysite.com # Important: # Create a test user if you want # You can remove this user after testing user=myuser:userpassword total-quota=100 stale-nonce=600 # Path to the SSL certificate and private key. In this example we will use # the letsencrypt generated certificate files. cert=/etc/letsencrypt/live/stun.mysite.com/cert.pem pkey=/etc/letsencrypt/live/stun.mysite.com/privkey.pem # Specify the allowed OpenSSL cipher list for TLS/DTLS connections … -
Can't deploy EB Django Application
Here's my full error after I run eb deploy: Creating application version archive "app-210816_201313". Uploading: [##################################################] 100% Done... 2021-08-17 01:13:46 INFO Environment update is starting. 2021-08-17 01:13:51 INFO Deploying new version to instance(s). 2021-08-17 01:14:06 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2021-08-17 01:14:10 ERROR [Instance: i-0995f885df1f382cb] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2021-08-17 01:14:10 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2021-08-17 01:14:10 ERROR Unsuccessful command execution on instance id(s) 'i-0995f885df1f382cb'. Aborting the operation. 2021-08-17 01:14:10 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. Here's my requirements.txt file: asgiref==3.4.1 autopep8==1.5.7 awsebcli==3.20.1 backports.entry-points-selectable==1.1.0 botocore==1.21.22 cement==2.8.2 certifi==2021.5.30 charset-normalizer==2.0.4 colorama==0.4.3 distlib==0.3.2 Django==3.2.6 filelock==3.0.12 future==0.16.0 idna==3.2 jmespath==0.10.0 pathspec==0.5.9 pipenv==2021.5.29 platformdirs==2.2.0 pycodestyle==2.7.0 pypiwin32==223 python-dateutil==2.8.2 pytz==2021.1 pywin32==301 PyYAML==5.4.1 requests==2.26.0 semantic-version==2.8.5 six==1.14.0 sqlparse==0.4.1 termcolor==1.1.0 toml==0.10.2 urllib3==1.25.11 virtualenv==20.7.0 virtualenv-clone==0.5.6 wcwidth==0.1.9 I tried pip3 install -r requirements.txt and then deploying again, but same error as shown above. How do I fix this? How do I access my logs? thanks in … -
Conditionally require password when creating user in Django Admin page
I am using LDAP for authentication in my Django app so when adding a user in the admin page I don't need to set a password since the user will be authenticated against the LDAP backend. I'd like to modify the 'Add user' page in the admin views to have a boolean selector to identify when I am trying to add an LDAP user so that the password field is not required. I'd like to retain the option of supplying a password in case I need to add a local user that authenticates against Django's backend. Here is what I've cobbled together so far: models.py Modified the save method so that the user gets populated in the CustomUser model if isLdap is True. class CustomUser(AbstractUser): pass isLdap = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.isLdap: user = LDAPBackend().populate_user(self.username) else: super().save(*args, **kwargs) def __str__(self): return self.username admin.py I successfully added a check box to identify if the new user is an LDAP user but the value isn't being saved to the CustomUser model and I need to change save_model so it saves the actual password if it is valid otherwise set_unusable_password(). class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm add_fieldsets = ( (None, { … -
Django ModuleNotFoundError: No module named 'PIL'
I looked at a lot of SO posts for this error and none of the answers address or resolve the error. Here is the pipfile: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "*" boto3 = "*" psycopg2 = "*" pillow = "*" django-storages = "*" django-crispy-forms = "*" django-s3-storage = "*" zappa-django-utils = "*" psycopg2-binary = "==2.8.6" django-environ = "*" django-mptt = "*" djangorestframework = "*" mortgage = "*" stripe = "*" django-phonenumber-field = "*" phonenumbers = "*" django-mathfilters = "*" image = "*" [dev-packages] mock = "*" model-mommy = "*" django-debug-toolbar = "*" [requires] python_version = "3.8" As you can see, I have both the pillow and image packages installed. But, when I run py manage.py shell, I get this error: import PIL ModuleNotFoundError: No module named 'PIL' In my user_profile app, I have the following: import PIL from PIL import Image ... -
eb : The term 'eb' is not recognized as the name of a cmdlet, function, script file, or operable program
I'm trying to deploy my Django Application with AWS beanstalk following this documentation: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html Everything works up till this point: ~/ebdjango$ eb init -p python-3.6 student-archive When I run that line of code I get this error: eb : The term 'eb' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + eb init -p python-3.6 studentarchive + ~~ + CategoryInfo : ObjectNotFound: (eb:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException What could be some causes of this? Here's my django.config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: StudentArchive/wsgi.py Here's my requirements.txt: asgiref==3.4.1 autopep8==1.5.7 backports.entry-points-selectable==1.1.0 certifi==2021.5.30 distlib==0.3.2 Django==3.2.6 filelock==3.0.12 pipenv==2021.5.29 platformdirs==2.2.0 pycodestyle==2.7.0 pytz==2021.1 six==1.16.0 sqlparse==0.4.1 toml==0.10.2 virtualenv==20.7.0 virtualenv-clone==0.5.6 -
login_required decorator gives "object has no attribute 'user'" error
New to Django. I have a view that works well without @login_required decorator. urls.py urlpatterns = [ path('play/', play.as_view(), name='play'), view.py with @login_required commented out from django.contrib.auth.decorators import login_required . . class play(View): #@login_required def get(self, request, *args, **kwargs): print("GET request: ", request) return render(request, 'play.html', {}) The page load correctly in the browser and the request is printed on the console as follows GET request: <WSGIRequest: GET '/play/'> [16/Aug/2021 23:17:23] "GET /play/ HTTP/1.1" 200 3591 [16/Aug/2021 23:17:23] "GET /static/css/home.css HTTP/1.1" 200 96 [16/Aug/2021 23:17:23] "GET /static/js/home.js HTTP/1.1" 200 3544 [16/Aug/2021 23:17:23] "GET /static/js/main.js HTTP/1.1" 200 1451443 [16/Aug/2021 23:17:23] "GET /static/images/BlankPicture.png HTTP/1.1" 200 16272 Not Found: /favicon.ico [16/Aug/2021 23:17:24] "GET /favicon.ico HTTP/1.1" 404 7793 OTOH, if I uncomment the @login_required line, I get following error. AttributeError at /play/ 'play' object has no attribute 'user' Request Method: GET Request URL: http://127.0.0.1:8000/play/ Django Version: 2.2.12 Exception Type: AttributeError Exception Value: 'play' object has no attribute 'user' Exception Location: /usr/lib/python3/dist-packages/django/contrib/auth/decorators.py in _wrapped_view, line 20 Python Executable: /usr/bin/python3 Python Version: 3.8.10 Python Path: ['/home/<username>/workspace/djangoapp/src', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Mon, 16 Aug 2021 23:20:17 +0000 play.html is a vanilla html page with only static html in it. The error happens even if … -
django-allauth No module named 'django.core.email'
I installed django-allauth and I'm able to login and logout with my admin superuser account. However, when I try to sign up, I get the following error: ModuleNotFoundError at /accounts/signup/ No module named 'django.core.email' Included config in my settings.py: SITE_ID = 1 # django-allauth configuration LOGIN_REDIRECT_URL = 'home' ACCOUNT_LOGOUT_REDIRECT = 'home' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False # configure email EMAIL_BACKEND = 'django.core.email.backends.console.EmailBackend' I don't have a urls.py or views.py file for the accounts since this is taken care of by the allauth plugin. The full traceback is: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 3.2.6 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_select2', 'crispy_forms', 'rest_framework', 'allauth', 'allauth.account', 'accounts', 'gradebook'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\allauth\account\views.py", line 230, in dispatch return super(SignupView, self).dispatch(request, *args, **kwargs) File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\allauth\account\views.py", line 74, in dispatch … -
Django error: 404 Page not found on get method
I am trying to get serialized data from endpoint localhost:8000/v1/test/uuid, but hitting a 404 error - what is wrong with below? views.py from uuid in response, get site object class Test(APIView): def get(self, request, *args, **kwargs): uuid = kwargs.get('uuid') resp = {'site': None} site = Site.objects.get(uuid=uuid) resp['site'] = SiteSerializer(site).data return Response(resp) urls.py urlpatterns = [ re_path(r'^v1/', include(router.urls)), re_path(r'test/', views.Test.as_view(), name='test'), ] models.py site id as the pk class Site(models.Model): """ Model that represents a Site """ uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) domain_name = models.CharField(max_length=255, unique=True) created = models.DateTimeField(editable=False, auto_now_add=True) modified = models.DateTimeField(editable=False, auto_now=True) serializers.py class SiteSerializer(serializers.ModelSerializer): class Meta: model = Site fields = [ 'uuid', 'domain_name' ] -
How to encrypt or Obfuscate REST API URL in Django
Hello Django REST API Experts, We are building University Course portals where app offers various user types like Professor, Students and Admins using DJANGO/REACT. We are using REST API to connect between backend and frontend. So, far we are able to perform some basic operation and it really works great. However now I need help from this group to do following: When students enrolled in course it generates an acknowledge document stating course description, and its prerequisite which needs to get signed by students to ensure student acknowledge they fulfill these requirements. In order to do this we have following: Model for each course which contains the Content, Description and Prerequisite for each course. StudentCourseAck Model which has FK to Course, Signed Boolean field, Binary field to store signed doc. User flow: Student logins to portal, Select the Course, which generate StudentCourseAck entry. Let Student review document and signed the document (on client side using sign pad). The Signature gets stored in PDF (as binary field). So far so good… Now we want to enhance the featureset which allows admin to email student the link of studentcouseack document incase its not signed before course start. Also this link should only …