Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to use django template using extends from another app
My Django project templating structure is AuthApp/ login.html MainApp/ base.html I want to use base.html file in login.html file, using below code. {% extends 'MainApp/base.html' %} {% block content %} {% endblock %} But its not inheriting the base template. Please suggest. -
Apexchart graph updateseries function not working?
Working on Apexcharts but my Updateseries in AJAX Call not working kindly help!!! Whenever I am inserting dates in datepicker in front.Data is coming from Backend as I can see in my console but Update Series/Graph is not updating in front end. Working in Django Framework. Please share as many examples of UpdateSeries in Apex Charts as posible -
Update single <td> value in the table row using ajax in django
I am trying to Block/Unblock the user without refreshing the page. If the status=1, it will show Block option, and if the status=0 it will show Unblock option After calling the function, the status will change either 0 or 1 in views.py The function is working fine but it is showing after refreshing the page How to display that value without refreshing the page <table id='usersTable' class="table table-bordered"> <thead> <tr> <th>S.No.</th> <th>Name</th> <th>Email</th> <th>Block/Unblock</th> </tr> </thead> <tbody> {% for userid, name, email, status in comb_lis %} <tr id='usr-{{name}}'> <input type="hidden" id="{{userid}}" name="{{userid}}" value="{{userid}}"> <input type="hidden" id="{{name}}" name="{{name}}" value="{{name}}"> <td>{{forloop.counter}}</td> <td>{{name}}</td> <td>{{email}}</td> <td> <a href="#" onclick="restrictUser(document.getElementById('{{userid}}').value, document.getElementById('{{name}}').value)"> {% if status == "1" %} Block {% else %} Unblock {% endif %} </a></td> </tr> {% endfor %} </tbody> and this is the ajax function function restrictUser(userid, name) { $.ajax({ url: '/restrict-user-ajax/'+userid, dataType: 'json', success: function (data) { if (data.status) { alert("User Blocked!"); } } }); } Any help is appreciated -
Troubles when I pass get_connection to EmailMultiAlternatives (django-post_office)
I need to make the connection dynamic for example: settings.py # EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_BACKEND = 'post_office.EmailBackend' # EMAIL_HOST = 'smtp.office365.com' # EMAIL_USE_TLS = True # EMAIL_PORT = 587 # EMAIL_HOST_USER = '123s@123.sg' # EMAIL_HOST_PASSWORD = '*********' views.py from django.core.mail import EmailMultiAlternatives, get_connection def email_template_participants(): connection = get_connection(host=arg.email_backend.email_host, use_tls=arg.email_backend.use_tls, port=arg.email_backend.port, username=email_back, password=arg.host_password) ....... email_message = EmailMultiAlternatives(subject, body, from_email, to_email, connection=connection) template = get_template('email_participants.html', using='post_office') html = template.render(context_html) email_message.attach_alternative(html, 'text/html') email_message.attach_file(attach_file(id) template.attach_related(email_message) email_message.send() running this code : emails fail. On status: ConnectionRefusedError ( Unable to establish a connection as the target computer expressly denied that connection ) If I uncomment EMAIL_HOST, EMAIL_USE_TLS, etc the connection is denied, because they not always match, only works when they match, 1 in 15. Otherwise. if I only change EMAIL_BACKEND to 'django.core.mail.backends.smtp.EmailBackend'. It works Perfect. What can I do ???? I need all Benefits from post_office, (crons, mails listed, inlined images, etc ) -
Operators can be used to access the fields in the object by Django ORM?
Which of the following Operators can be used to access the fields in the object by Django ORM? (.) Operator (') Operator (,) Operator Both (.) and (') Operator -
! Push rejected, failed to compile Python app. -Heroku
I am trying to depoly my website but I am getting this error I am depolying it with github and the site I am using is called Heroku I am not sure why I am getting this error but I have already done all the steps I need to depoly the My runtime.txt My requirements.txt my Procfile idk if it has annything to do with my apps but here. -
Extending a column in the user table in django is not creating a entry in table
I have extended the Django user table with a boolean variable. class UserLogin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) isFresher = models.BooleanField() I have made changes in the admin inline. class LoginInline(admin.StackedInline): model = UserLogin can_delete = False verbose_name_plural = 'loginTable' class UserAdmin(BaseUserAdmin): inlines = (LoginInline,) I have got the flag in the admin table. When I add a user to the user table I can see the flag. If I check the flag then I can see an entry True with user_id in the UserLogin table. If the flag is not checked then I can not see an entry in the table? How to make this False entry into the table? -
Stylizing ManyToMany Form (Django)
I have a question regarding the stylizing of a ManyToMany field form submission. Currently, I am using the Checkbox widget. The problem is this field will eventually have 80+ options. I was curious if there are any better widgets for this case? If not, how could I go about implementing a search and select for this field on the front end? Thank you! P.S: I do understand the second question could involve a lot of code, so please feel free to provide an approach to the problem instead. class CourseUpdateForm(forms.ModelForm): activesubjects = forms.ModelMultipleChoiceField( queryset=Subject.objects.all(), widget=forms.CheckboxSelectMultiple, required=True) class Meta: model = Profile fields = ['activesubjects'] -
How do you modify the Django Admin UI?
Whenever I see a tutorial customizing the Admin interface this is always the way they customize it like changing the header text and image, changing the color, etc. Is there a better way of making it more like this implementing the Vue Admin Dashboard to the Django Admin? and also, in this website https://djangopackages.org/grids/g/admin-interface/ is this the Only Admin UI you can use? -
Django rate limiting outgoing requests
I'm new to Django and Python, so my understanding of the fundamentals might be wrong. I'm building an app with Django + Nginx + Gunicorn. For every client request, the app needs to call another service to retrieve information. The information is then used to serve the client. Currently, the app does this by: Establishing a TCP connection to the service Exchange data Closes the connection When the request load is high, this connection overhead becomes an issue. On top of that, I should be worried about the number of sockets being created. I think creating a connection pool to rate limit the number of outgoing requests would be a good idea. However, I don't really know how get started...I have a couple of questions: How can I create a ConnectionPool object in Django that is accessible by all of my Django app? Assuming that I'm able to create a connection pool in Django, and I have two Gunicorn workers, will both workers maintain their own separate connection pools? -
django, Changing field values in model before saving to database
models.py class PlayerList(models.Model): name = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HList, related_name="h_code", on_delete=models.CASCADE) d_code = models.CharField(primary_key=True, max_length = 200, editable=False) Serializers.py class PlayerSerializer(serializers.ModelSerializer): class Meta: fields = ["name", "position", "h_code", "d_code"] model = PlayerList view.py class PostPlayer(generics.ListCreateAPIView): queryset = PlayerList.objects.all().order_by('-d_code') serializer_class = PlayerListSerializer def get(self, request, *args, **kwargs): d_code = request.data.get('h_code') + 'test' print(d_code) print(d_code) : h000001test When entering a value through api, I want to implement that the entered value is changed to another value in view.py and saved in the db. I want to save d_code processed by def get in db. I don't know what to do. Can you please let me know? -
In django how to GROUP_BY raw and bellow my question
How to gourp_by() column based on RID. My Actual output HERE IMAGE Whatever values are displayed in the Months Names like [Jan, Feb,...., Des], all the values come from the one table column. I want to display all values in one particular column like the below image. Expected output HERE IMAGE Models.py Here my registration table(primary key table). class Registration(models.Model): Registration_ID = models.IntegerField(auto_created=True,primary_key=True) Surname = models.CharField(max_length=20) FirstName = models.CharField(max_length=20) LastName = models.CharField(max_length=20) MobileNumber = models.IntegerField() Email = models.CharField(max_length=50) Password = models.CharField(max_length=30) Gender = models.CharField(max_length=10) FamilyMembers = models.IntegerField() PlotNumber = models.IntegerField() PlotType = models.CharField(max_length=20) Partition = models.CharField(max_length=10) FlatNumber = models.CharField(max_length=10) Rent = models.CharField(max_length=10) RentalFloor = models.CharField(max_length=10) Is_Active = models.BooleanField(default=0) Is_Admin = models.BooleanField(default=0) Owner_Rent = models.IntegerField(null=True,default=0) Rental_Rent = models.IntegerField(null=True,default=0) Created_Date = models.DateTimeField(auto_now_add=True) Updated_Date = models.DateTimeField(auto_now=True) class Meta: db_table = 'Registration' Here my maintenance table(foreign key table). class Maintenance(models.Model): Maintenance_ID = models.IntegerField(auto_created=True,primary_key=True) Registration_ID = models.ForeignKey(Registration, on_delete=models.CASCADE) ReceiptNumber = models.IntegerField(null=True) ReceiptDate = models.DateField(null=True) FromDate = models.DateField() ToDate = models.DateField() FeeType = models.CharField(max_length=30) PaymentMode = models.CharField(max_length=20) Remark = models.CharField(max_length=20, null=True) BankName = models.CharField(max_length=30,null=True) ChequeNumber = models.CharField(max_length=30,null=True) ChequeDate = models.DateField(null=True) Money = models.IntegerField() Created_Date = models.DateTimeField(auto_now_add=True) Updated_Date = models.DateTimeField(auto_now=True) class Meta: db_table = 'Maintenance' Views.py paginator = Maintenance.objects.all().order_by('Registration_ID_id') page = request.GET.get('page', 1) Qry_All_Maintenance_List = Paginator(paginator, 25) … -
Django --> python manage.py runserver
I had previous django project named 'bike_project'. And i had two settings module for development and production inside settings folder of bike_project. During that project i had set DJANGO_SETTINGS_MODULE = bike_project.settings.development in command prompt. But now when i create new django project (seller bike), the project is created. But when i run python manage.py "command", I get following error. D:\seller_bike>python manage.py runserver Traceback (most recent call last): File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line … -
How do I create a parent user and a child user in Django?
We are building a free education app in Django. I have noticed that if I am logged in as a "superuser" I am able to "switch user" inside the admin app to any of our staff. This education app will have "Parents" who can "Add Child" users. The parents should be able to "switch user" to any of their children. How do we implement this feature on our main app instead of just within the admin. -
Python manage.py runserver is throwing error after Ubuntu upgrade to 20.0
I am getting this error in all the Django projects on my system. I've updated from Ubuntu 18.04 to 20.0 (Focal Fossa). Since then I am getting these errors. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 10, in main from django.core.management import execute_from_command_line File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/site-packages/django/utils/version.py", line 6, in <module> from distutils.version import LooseVersion File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/distutils/__init__.py", line 17, in <module> real_distutils = imp.load_module("_virtualenv_distutils", None, distutils_path, ('', '', imp.PKG_DIRECTORY)) File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/imp.py", line 245, in load_module return load_package(name, filename) File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/imp.py", line 217, in load_package return _load(spec) File "<frozen importlib._bootstrap>", line 683, in _load AttributeError: 'NoneType' object has no attribute 'name' -
How to get the uploaded (generated) file name in django
models.py class client_users(AbstractBaseUser): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.EmailField(_('email address'), unique=True) password = models.CharField(max_length=150) birthday = models.DateField() phone = models.CharField(max_length=15) profile_image = models.ImageField( upload_to='images/', default="noimage.png") USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email views.py def profile(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): try: form.save() except: pass print(client_users.profile_image.field.pre_save) return HttpResponseRedirect('/profile') else: form = UploadFileForm() return render(request, 'profile.html', {'form': form}) This is a picture of the saved files with a code generated by django, because he found an image with the same name Since django generated the code after the name of the picture, i want to get the full file name after the upload so i can update my database, request.FILES['profile_image'] doesn't return the generated value, it returns the name of the file on the upload. Any help, please ? -
Accessing cookie from another sub-domain within my domain
I have two django applications that are deployed at two different sub-domains, for example: data.mysite.com i.mysite.com Both sites use the same django authentication framework and such, setting a cookie called sessionid. I can read the cookie from the current site using: def my_view(request): # suppose this view is within the i.mysite.com application i_session_id = request.COOKIES['sessionid'] data_session_id = ? # how to get this? But then how could I grab the cookies from the -
Django modelform custom widget is_multipart not working
In my modelform, I have used a custom widget. The problem is for some reason the is_multipart returns False, and so I cannot upload the picture class ProjectSetupForm(ModelForm): class Meta: model = Project fields = ['name', 'logo','picture'] widgets = { 'picture': PictureWidget, 'logo': PictureWidget, } def __init__(self, *args, **kwargs): self.fields['logo'].widget.attrs['class'] = 'file_upload blocked' self.fields['picture'].widget.attrs['class'] = 'file_upload blocked' class PictureWidget(forms.widgets.Widget): def render(self, name, value, attrs=None, **kwargs): if value: html = Template("""<img src="$media$link" height=100px width=auto/> <input type="file" name="$name" class=" form-control" style="width: 100%; height: auto" />""") return mark_safe(html.substitute(media=settings.MEDIA_URL, link=value, name=name)) else: html = Template("""<input type="file" name="$name" class=" form-control" style="width: 100%; height: auto" />""") return mark_safe(html.substitute(name=name)) # views.py: class AddProject(View): template_name = 'project.html' model = Project def get(self, request, *args, **kwargs): ... context['form'] = ProjectSetupForm() ... return render(request, self.template_name, context) def post(self, request, *args, **kwargs): ... project_form = ProjectSetupForm(request.POST if any(request.POST) else None, request.FILES or None) if project_form.is_valid() and address_form.is_valid(): ... address_instance = address_form.save() project_instance = project_form.save(commit = False) project_instance.address = address_instance project_instance.save() else: errors = {} if project_form.errors: project_form_errors = project_form.errors errors.update( {'project_form': project_form_errors} ) if address_form.errors: address_form_errors = address_form.errors errors.update( {'address_form': address_form_errors} ) context = {} context['errors'] = errors return render(request, self.template_name, context) # In template: {% if form.is_multipart %} <form action="" … -
Changing a Curl method to a django/DRF view method
I am trying to implement an API but it has only options for cURL, PHP and nodejs, but i feel its possible for me to use python to make the request as the endpoint has been given This is the cURL code, I am hoping to get a way to do it in Django Rest Framework or Django as i am using it to develop and endpoint. curl --location --request GET 'https://api.flutterwave.com/v3/transactions/123456/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer {{SECRET_KEY}}' Thanks in advance. -
Django: After Successful Payment Via PayPal how to redirect user to order completed page
I am setting a PayPal payment for my E-commerce project and everything is working fine except that after the payment is executed and the PayPal windows is closed, the website page remains open and the items remain in the cart. I have set the stripe payment to redirect to a page called "order completed" with some order reference code, which I am trying to implement to PayPal payment option. Here is the views.html: def payment_complete(request): body = json.loads(request.body) order = Order.objects.get( user=request.user, ordered=False, id=body['orderID']) payment = Payment( user=request.user, stripe_charge_id=body['payID'], amount=order.grand_total() ) payment.save() # assign the payment to order order.payment = payment order.ordered = True order.ref_code = create_ref_code() order.save() messages.success(request, "Your Order was Successful ! ") # Email when order is made template = render_to_string("payment_confirmation_email.html", {'first_name': request.user.first_name, 'last_name': request.user.last_name, 'order': order}) msg = EmailMessage('Thanks for Purchasing', template, settings.EMAIL_HOST_USER, [request.user.email]) msg.content_subtype = "html" # Main content is now text/html msg.fail_silently = False msg.send() # End of the email send return render(request, "order_completed.html", {'order': order}) class PaymentView(View): def get(self, *args, **kwargs): # order order = Order.objects.get(user=self.request.user, ordered=False) if order.billing_address: context = { 'order': order, 'DISPLAY_COUPON_FORM': False } return render(self.request, "payment.html", context) else: messages.warning( self.request, "You have not added a billing address") return redirect("core:checkout") … -
Image not being uploaded after posting (DJANGO)
I am working on a project on DJANGO which I need to upload a image of a book on the post created by the user which then will be displayed on the post itself ,but when I click on the post button nothing happens and I am not redirected anywhere,if i create the post on the admin page everything works fine, I have tried everything so far but nothing has solved this problem, bellow I will be posting my code for reference, thank you ! views.py: class BookCreateView(LoginRequiredMixin, CreateView): #sets up form to create new post /post/new model = Book fields=['Title','Author','Publisher','isbn','book_img','course', 'schools','content'] def form_valid(self, form): form.instance.author = self.request.user #get users name to put on the post return super().form_valid(form) models.py class Book(models.Model): Title = models.CharField(max_length=30, default='not declared') Author = models.CharField(max_length=30) Publisher = models.CharField(max_length=30) Year = models.DateTimeField(default=timezone.now) classes = models.ManyToManyField(Class) schools = models.ManyToManyField(School) course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True) book_img = models.ImageField(upload_to='books_image',default='default.jpg',blank=True, null=True) isbn = models.IntegerField(default=000) content = models.TextField(max_length=50, null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) #deleted post if user is deleted class Meta: db_table = '5- Books' def __str__(self): return self.Title def save(self, **kwargs): super().save() img = Image.open(self.book_img.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) … -
Django - Why do I need to specify the user.backend when logging in with a custom backend?
The code works as is, I'm just hoping somebody can provide an explanation here. I set up a custom backend for my app. Code below: from django.contrib.auth.backends import BaseBackend from django.contrib.auth import get_user_model class AuthenticationBackend(BaseBackend): def authenticate(self, request, username=None, password=None, email=None): UserModel = get_user_model() try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None And here is the view: def login_view(request): form = LoginForm(request.POST or None) if request.POST and form.is_valid(): user = form.login(request) if user: user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) print(request.user) return redirect('tasks') context = { 'form': form } return render(request, 'users/login/index.html', context) Along with the form (Note much of the login functionality was abstracted to the form) class LoginForm(forms.Form): email = forms.CharField(max_length=255, required=True, widget=forms.TextInput(attrs={'class': 'form_input'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form_input'}), required=True) def clean(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') user = authenticate(email=email, password=password) if not user or not user.is_active: raise forms.ValidationError("Sorry, that login was invalid. Please try again.") return self.cleaned_data def login(self, request): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') user = authenticate(email=email, password=password) return user In the login_view code, I had an issue. Before adding the "user.backend = ..." line, the system would login the user successfully, however upon redirecting to the 'tasks' view, the … -
Multiple select2 elements on one page not working
I want to have multiple select2 on one page. The app has several posts and each post will have a select element. I am hiding the element until the user clicks on a button which then shows select. The problem is that only one select2 works. Here's my HTML: <button onclick="change_tags({{ file.id }})" class="btn btn-info btn-sm change-tags-btn">Change Tags</button> <select class="custom-select js-example-basic-multiple change-tags-select form-control " id="change-tags" name="usertags1" multiple="multiple"> {% for tag in userTags %} <option value="{{ tag }}" id="{{ tag }}" data-id="{{ tag.color }}" class="options">{{ tag }}</option> {% endfor %} </select> JQuery: $('.change-tags-btn').click(function(){ setTimeout(function(){ $('#change-tags').select2() },1000); }); -
How to set a default to a forms.ChoiceField()?
I am trying to set a default selection for payment choices to be Stripe, but I keep getting an errorTypeError: __init__() got an unexpected keyword argument 'default' Here is the forms.py PAYMENT_CHOICES = ( ('S', 'Stripe'), ('P', 'Paypal') ) class CheckoutForm(forms.Form): payment_option = forms.ChoiceField( widget=forms.RadioSelect, choices=PAYMENT_CHOICES, default='Stripe') -
In Django, when the web app has to send an email it throws same Authentication error after some days of being fixed
It happened three times already. In these three times to fix it I had to do these steps: Go to the allow less secure apps google page and enable it Go to the allow access to your account google page and press the blue button Those two steps, are the ones that I have to do everytime the process of sending the email fails. I do those steps, the error gets fixed, some days pass, and the error shows up again. I don't know what to do. I'll accept the answer of course! Thank you very much beforehand :)