Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Formset Not Saving on UpdateView Django
I'm having problem on formset not saving on UpdateView. This has been discussed in several SO post, and so far I can summarized them to following Make sure to pass an instance. Hence. Reference context['formset'] = journal_entry_formset(self.request.POST, instance=self.object) Override the POST method. Reference Another One My UpdateView is an exact replica of my CreateView except for two changes above. Here is my CreateView: class JournalEntryUpdateView(UpdateView): model = JournalEntry template_name = 'add-journal-entry.html' success_url = reverse_lazy('index') form_class = JournalEntryForm def get_context_data(self, *args, **kwargs): context = super(JournalEntryUpdateView, self).get_context_data(*args, **kwargs) if self.request.POST: context['formset'] = journal_entry_formset(self.request.POST, instance=self.object) else: context['formset'] = journal_entry_formset(instance=self.object) return context def form_valid(self, form): context = self.get_context_data(form=form) formset = context['formset'] if formset.is_valid(): response = super().form_valid(form) formset.instance = self.object formset.save() return response else: return super().form_invalid(form) def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) formset = journal_entry_formset(self.request.POST, instance=self.object) print ("form:", form.is_valid() ) # True print ("formset:", formset.is_valid() ) # False print(formset.non_form_errors()) # No Entry print(formset.errors) # {'id': ['This field is required.']} if (form.is_valid() and formset.is_valid()): return self.form_valid(form) else: return self.form_invalid(form) When I click submit, the page just refreshes and nothing happens. (i.e. I don't have that typical yellow error debug screen page). I check the value in the database … -
Django mail sending in very slow
I have implemented a password reset view and it sends a link to an e-mail account. But it takes more time to send. How can I make send faster e-mail using multi-threading class ResetPasswordView(SuccessMessageMixin, PasswordResetView): email_template_name = 'accounts/password_reset_email.html' form_class = CustomPasswordResetForm template_name = 'accounts/password_reset.html' success_message = mark_safe( """<li>We emailed you instructions for setting new password.</li> <br> <li>if an account exists with the email you entered. You should receive them shortly.</li> <br> <li>If you don’t receive an email, please make sure you’ve entered the address you registered with, and check your spam</li> """ ) success_url = reverse_lazy('accounts:reset_password') -
Checkboxes are not the same height as input boxes - Bootstrap
I want the checkboxes on the left side to be the same height as the text input boxes on the right. Not set to proper height HTML: {% block content %} <h1>{{ls.name}}</h1> <form method="post" action="#"> {% csrf_token %} {% for item in ls.item_set.all %} <div class="input-group mb-3"> <div class="input-group-prepend"> <div class="input-group-text"> {% if item.complete == True %} <input type="checkbox", value="clicked", name="c{{item.id}}" checked> {% else %} <input type="checkbox", value="clicked", name="c{{item.id}}"> {% endif %} </div> </div> <input type="text", value="{{item.text}}" class="form-control"> </div> {% endfor %} <div class="input-group mb-3"> <div class="input-group-prepend"> <button type="submit", name = "newItem", value="newItem" class="btn btn-primary">Add Item</button> </div> <input type="text", name="new"> </div> <button type="submit", name = "save", value="save" class="btn btn-primary">Save</button> </form> {% endblock %} -
why do i get `DoesNotExist at /admin/auth/user/2/delete/` error in django
Whenever I try to delete a user from the Django admin panel I get this error: why do I get this error -
Getting List of user's followers in Django Social Media project
In my project I am trying to show a list of other user's followers and following. Right now it only has the requesting user's. Here are my models and views: Models class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) followers = models.ManyToManyField(User, related_name='following', blank=True) Views class FollowersPageView(LoginRequiredMixin, ListView): model = Profile paginate_by = 20 template_name = 'users/followers.html' context_object_name = 'users' def get_queryset(self, **kwargs): return self.request.user.profile.followers.all() class FollowingPageView(LoginRequiredMixin, ListView): model = User paginate_by = 20 template_name = 'users/following.html' context_object_name = 'profiles' def get_queryset(self, **kwargs): return self.request.user.following.all() URLS **(Old url)** re_path(r'^u/followers$', users_views.FollowersPageView.as_view(), name='view_all_followers'), **(New url)** re_path(r'^u/(?P<username>[\w.@+-]+)/followers$', users_views.FollowersPageView.as_view(), name='view_all_followers'), I was trying to change the get_queryset of FollowersPageView to the following but was getting error messages: def get_queryset(self, **kwargs): user_username = self.kwargs['username'] user_followers = Profile.objects.filter(followers=user_username) return user_followers Thank you -
Random <a></a> appeared in HTML code after site went live
Basically my problem is what my question is saying. Before some time we had build a site using Django and it's build in DB. The site had some problems but we fixed the and we got it live. After that we saw a major mistake in the footer where all the three sections where out of place. This was do to a random in the HTML code after we incpect element: This is how the footer is implemented in every page. </body> {% include "main/footer.html" %} </html> Footer code in server <div class="content"> <section> <img class="footer-logo" src="{% static 'material/imgs/logo_banner_inverted.svg' %}" alt="" srcset=""> <!-- <p><i class="fa fa-folder">&nbsp;</i>dummy@gmail.com</p> --> </section> <section class="inline"> <h4 >Our Social Media</h4> <ul class=""> <li class="no-bottom"><a href="https://www.facebook.com/UNSOCLawAUTh"><i class="fa fa-facebook">&nbsp;&nbsp;</i>Facebook</a></li> <li class="no-bottom"><a href="https://www.instagram.com/unsoc.law.auth/"><i class="fa fa-instagram">&nbsp;</i>Instagram</a></li> <li class="no-bottom"><a href="#"><i class="fa fa-linkedin ">&nbsp;</i>Linkedin</a></li> </ul> </section> <section> <h4 >Menu</h4> <ul> <li><a href="{% url 'home' %}"><i class="">&nbsp;</i>Home</a></li> <li><a href="{% url 'about-us' %}"><i class="">&nbsp;</i>About us</a></li> <li><a href="{% url 'contact_form' %}"><i class="">&nbsp;</i>Contact</a></li> </ul> </section> </div> Footer code presented in live site <a> </a><div class="content"><a> <section> <img class="footer-logo" src="/static/material/imgs/logo_banner_inverted.svg" alt="" srcset=""> <!-- <p><i class="fa fa-folder">&nbsp;</i>dummy@gmail.com</p> --> </section> </a><section class="inline"><a> <h4>Our Social Media</h4> </a><ul class=""><a> </a><li class="no-bottom"><a></a><a href="https://www.facebook.com/UNSOCLawAUTh"><i class="fa fa-facebook">&nbsp;&nbsp;</i>Facebook</a></li> <li class="no-bottom"><a href="https://www.instagram.com/unsoc.law.auth/"><i class="fa fa-instagram">&nbsp;</i>Instagram</a></li> <li class="no-bottom"><a … -
access value dynamically in pandas dataframe row pandas()
any help in dynamically accessing pandas() object from a dataframe table in django, not sure where am going wrong, do i need to convert the pandas row into a dict? any help will be much appreciated note: I am using column_dict = {'a':'column A Name', 'b':'Column B Name'} as the columns presented are dynamic and not set template: {% for r in data.itertuples %} <tr> {% for c in columns_dict %} <td>{{ r|lookup:c }}</td> {% endfor %} </tr> {% endfor %} template tags: @register.filter(name='lookup') def lookup(row, key): return row[key] error: tuple indices must be integers or slices, not str r (the pandas row) when printed is in this format: pandas(index=0, a=10, b=20, c=30 .... ) -
Google Drive API in Celery Task is Failing
I am trying using Celery Task to Upload Files to Google Drive once the Files have been Uploaded to Local Web Web Server for Backup. Implementation and Information: Server: Django Development Server (localhost) Celery: Working with RabbitMQ Database: Postgres GoogleDriveAPI: V3 I was able to get credentials and token for accessing drive files and display first ten files,If the quickstart file is run seperately. Google Drive API Quickstart.py Running this Quickstart.py shows files and folder list of drive. So i added the same code with all included imports in tasks.py task name create_upload_folder() to test whether task will work and show list of files. I am running it with a Ajax Call but i keep getting this error. So tracing back show that this above error occured due to: Root of the Error is : [2021-07-13 21:10:03,979: WARNING/MainProcess] [2021-07-13 21:10:04,052: ERROR/MainProcess] Task create_upload_folder[2463ad5b-4c7c-4eba-b862-9417c01e8314] raised unexpected: ServerNotFoundError('Unable to find the server at www.googleapis.com') Traceback (most recent call last): File "f:\repos\vuetransfer\vuenv\lib\site-packages\httplib2\__init__.py", line 1346, in _conn_request conn.connect() File "f:\repos\vuetransfer\vuenv\lib\site-packages\httplib2\__init__.py", line 1136, in connect sock.connect((self.host, self.port)) File "f:\repos\vuetransfer\vuenv\lib\site-packages\eventlet\greenio\base.py", line 257, in connect if socket_connect(fd, address): File "f:\repos\vuetransfer\vuenv\lib\site-packages\eventlet\greenio\base.py", line 40, in socket_connect err = descriptor.connect_ex(address) -
How to add .00 in FloatField of Django?
I did this in my models.py selling_price = models.FloatField() discounted_price = models.FloatField() & my prices are looking like 14,999.0 but i want it to look like 14,999.00 So how can i add that extra zero after decimal ? -
Only getting the below in the admin page only
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ food/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
jQuery closing a modal when a try to click anywhere
jQuery is showing unpredictable behavior, the following code displays a custom modal with a form inside but if I try to click anywhere, including the form inputs it calls the jQuery function and closes it. What may I be doing wrong? let fecharModal = $('#fecharModal'); let conteudoModal = $('#conteudoModal'); let modal = $('#modal'); let fora = $('#fora'); $(modal).on('click', [fecharModal, fora], function () { $(modal).hide(); $(conteudoModal).html(""); return false; }); <div id="modal" class="fixed z-10 inset-0 overflow-y-auto hidden"> <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"> <div id="fora" class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true"></div> <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span> <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"> <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4"> <div class="sm:flex sm:items-start"> <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left" id="conteudoModal"> </div> </div> </div> </div> </div> </div> -
Django How can I order_by queryset with condition
class Order(models.Model): ..... payment_no = models.CharField(max_length=32, blank=True) ..... my model has field payment_no to store string that have 2 syntax prefix string + '-' + 8 digit number only 8 digit number for example 'stk-00000001', 'fad-00000002', '00000003'. I wanna know how to order only the 8 digit number. please guide me how to order it -
Django Aggregate on related set
I have following models in Django REST: class Transaction(models.Model): ... account = models.ForeignKey('transactions.Account', on_delete=models.CASCADE) charged_amount = MoneyField(max_digits=14, decimal_places=2, default_currency=None) datetime = models.DateTimeField() ... class Account(models.Model): name = models.CharField(max_length=255) ... I successfully received an expected aggregated list of periods by this query: GROUP_CASTING_MAP = { 'day': Cast(TruncDate('datetime'), output_field=DateTimeField()), 'month': Cast(TruncMonth('datetime'), output_field=DateTimeField()), 'week': Cast(TruncWeek('datetime'), output_field=DateTimeField()), 'year': Cast(TruncYear('datetime'), output_field=DateTimeField()), } GROUP_ANNOTATIONS_MAP = { 'day': { 'day': TruncDay('datetime'), 'month': TruncMonth('datetime'), 'year': TruncYear('datetime'), }, 'week': { 'week': TruncWeek('datetime') }, 'month': { 'month': TruncMonth('datetime'), 'year': TruncYear('datetime'), }, 'year': { 'year': TruncYear('datetime'), }, } group_by_field = 'month' periods = Transaction.objects \ .annotate(**self.GROUP_ANNOTATIONS_MAP[group_by_field]) \ .values(*self.GROUP_ANNOTATIONS_MAP[group_by_field]) \ .annotate(total_amount=Sum('charged_amount'), period=self.GROUP_CASTING_MAP[group_by_field]) \ .values('total_amount', 'period') But I am looking for a way to get a list of accounts with aggregated periods: [ { "id": 1, "name": "accountName", "periods": [ { "period": "2021-05-01T00:00:00+00:00" "total_amount": 152 }, { "period": "2021-06-01T00:00:00+00:00" "total_amount": 1333 } ] } ] How to connect annotated transactions to Account queryset? Thanks -
ModuleNotFoundError: No module named 'application' error in AWS
I am trying to deploy a django's app to aws. I am getting the error " ModuleNotFoundError: No module named 'application'" when I try to create the app (django create django-env). I don't know why. My django.config file is: option_settings: "aws:elasticbeanstalk:projectlication:environment": DJANGO_SETTINGS_MODULE: project.settings "aws:elasticbeanstalk:container:python": WSGIPath: project.wsgi:application My application name is project, so I don't know what is wrong. Thank you -
'CountryPDF' object has no attribute 'data'
Please help!What I am doing wrong? I have views.py to generate PDF. It is generate PDF success if context: 'Sometext'.It open me PDF link. But When I take django models.It output me : 'CountryPDF' object has no attribute 'data' my views.py class CountryPDF(core.PDFView): template_name = 'application_pdf.html' def get_context_data(self, **kwargs): return {'data': self.data} def get_file_name(self, context): return 'test1.pdf' So HTML file: application_pdf.html {% for item in data %} <td>{{ item.name }}</td> <td>{{ item.address }}</td> {% endfor %} url: path('cabinet/<int:pk>/download-pdf/', views.CountryPDF.as_view(), name='country-download_pdf'), What is the problem with context data? What I am doing wrong? -
Is possible get value by name of column in Pandas-Python without order?
I have a csv make in Python where I have different names of columns: response['Content-Disposition'] = 'attachment; filename="upload.csv"' writer = csv.writer(response) writer.writerow(['whatever1','whatever2','whatever3','whatever4','whatever5']) I am trying to get the values of these columns by name, but I can only by the order that I have configured. data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) cols = ['whatever1','whatever2','whatever3','whatever4','whatever5'] df = pd.read_csv(io_string, names=cols) I mean, If I change the order of the columns in excel, it not respect the name of the column, it take the value of the column in order. For example, in excel, if I change the order, Pandas take the column with name whatever2, like whatever1. whatever2 whatever1 1 0 1 0 2 14 3 20 So, Can I take the values of the column by the name of the column, regardless of the order? Thanks. -
Please how can get the number of listings in a category, i have tried
here is my complete model class Category(models.Model): name = models.CharField(max_length=500) icon = models.ImageField(upload_to='photos/icons/%Y/%m/%d/') def __str__ (self): return self.name class Listing(models.Model): name = models.CharField(max_length=300) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=False, null=True) email = models.EmailField(max_length=300) description = RichTextField(blank=False, null=False) photo_main = models.ImageField(upload_to = 'photos/%Y/%m/%d/') photo_1 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True) photo_2 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True) photo_3 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True) photo_4 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True) location = models.CharField(max_length=500, null=True) phone_number = models.CharField(max_length=11, default = "#") website = models.CharField(max_length=150, blank=True, default="#") facebook = models.CharField(max_length=150, blank=True, default="#") instagram = models.CharField(max_length=150, blank=True, default="#") opening_time = models.CharField(max_length=7) closing_time = models.CharField(max_length=7) is_published = models.BooleanField(default=False) posted_date = models.DateTimeField(auto_now_add=True) user_id = models.IntegerField(blank=True) def __str__ (self): return self.name here is my views from django.shortcuts import render from listings.models import Listing from listings.models import Category from testimonies.models import Testimony from our_team.models import Team_Mate from testimonies.models import Testimony from django.db.models import Count def index(request): the part is working perfectly. listings = Listing.objects.order_by('-posted_date').filter(is_published=True)[:6] category = request.GET.get('category') categories = Category.objects.all()[:7] counting listings in a category count_cate = Category.objects.all() cate_count = count_cate.count() if category == None: listings = Listing.objects.order_by('-posted_date').filter(is_published=True)[:6] else: listings = Listing.objects.filter(Category__name=category) here is my context context ={ 'listings': listings, 'categories': categories, 'cate_count': cate_count, } return render(request, 'pages/index.html', … -
Replacing Django's Primary Relational Database with a NOSQL database
I am building a Django application that is similar to a social media website. I am using firebase's library **Pyrebase** for Auth and storing various user-based data into it. But there are some tables, for example. **django.sessions** which I am not able to replace and migrate totally to Firebase. Under the ```settings.py```, I am unable to understand what needs to be changed, so that the inbuilt tables that are created after performing ```python manage.py migrate``` would create objects in the firebase rather than in SQL. I surely can use firebase tokens as sessions id's but is this the authentic way to perform such actions as that way I am making no changes to the Middlewares present in the Django settings? I am aware that Django uses ORM but is there any way to completely change the Django primary databaseCan a Django app could run completely without using SQL for any type of data storage? -
How to make "next" and "back" in Django forms?
I have a form by which I add hotels to the site (as on Booking.com). In order to complete the form of adding a hotel, I need the form to be two or more pages, where everything will be filled in in more detail. I wonder how I can do this? Should I use AJAX? For example, I will use my model, form and function. Also, when I go "back" I should be able to edit my form. models.py from django.db import models from account.models import Account class Hotel(models.Model): customer = models.ForeignKey(Account, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) short_description = models.TextField(max_length=250) long_description = models.TextField(max_length=2000, null=True) HOTEL_STAR = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) star = models.TextField(max_length=1, default=5, choices=HOTEL_STAR, null=True) picture = models.ImageField(upload_to='images/%Y/%m/%d/',default="images/default.jpg" , blank=True) created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.name) forms.py from django.forms import ModelForm from .models import Hotel class HotelForm(ModelForm): class Meta: model = Hotel exclude = ('customer',) views.py @login_required def add_hotel(request): form = HotelForm() if request.method == "POST": form = HotelForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.customer = request.user data.save() return redirect('/') context = {'form':form,} return render(request, 'add_hotel.html', context) html {% extends 'base.html' %} {% load static %} {% block … -
How to refresh the JWT token in nuxt.js?
I want to use JWT authentication in my nuxtjs app but it's not refreshing the token. For testing purposes, I set the access token expire time 5 seconds and refresh token for 30 minutes. Access token expire after 5 seconds but the token is not refreshing after 5 second its logged-out I'm using the Django rest framework and in nuxt I'm using nuxt auth v5 settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), 'ACCESS_TOKEN_LIFETIME': timedelta(seconds=5), 'REFRESH_TOKEN_LIFETIME': timedelta(minutes=30), } nuxt.config.js auth: { localStorage: false, strategies: { local: { scheme: 'refresh', token: { property: 'access', type: 'JWT', required: true }, refreshToken: { property: 'refresh', }, user: { property: false, autoFetch: true }, endpoints: { login: { url: '/jwt/create/', method: 'post',}, refresh: { url: '/jwt/refresh/', method: 'post',}, user: {url: '/users/me/', method: 'get' }, logout: false }, } } } } I'm little new in JWT and nuxt. Correct me if I'm wrong. My main goal is just to refresh the token automatically when access toke is expired. -
Slack API how to get conversations.list for different workspaces that installed the app?
Using this app as an example, how could I call conversations_list method while differentiating the conversations list I want for different workspaces? Do I have to construct a different WebClient with some specific token? If so, how do I store OAuth tokens generated for each workspace (as in I don't think the code example linked above handles storing OAuth tokens)? Thanks so much in advance! -
How to capture dynamic URL part to return a list in Django
I need to code an API which will be used by dropdowns in a react form. There are multiple dropdowns and exposed API url also follow similar pattern. For example - /api/trend/foo?bar=0 /api/trend/foo?bar=1 /api/trend/baz?bar=0 /api/trend/baz?bar=0 /api/trend/fish?foss=1 /api/trend/baz?foss=2 So it boils down to /api/trend/{table}?{filter}={val} which will return a list {col}, which further boils down to SELECT col FROM table WHERE filter=val I don't want to write multiple functions for same pattern. I am looking for something like this # in views.py def dropdown_api(request, table, filter): # fire the SQL statement # get the result in a df/list # serialize the result # return the response to consume by react # in urls.py path('api/trend/{table}?{filter}={val}', views.dropdown_api) #something like this to capture the dynamic url content -
how to add images int database in django with out showing the path of images in choosen button
class ProductForms(forms.ModelForm): images1 = forms.ImageField(widget=forms.FileInput,) class Meta: model = Product fields = 'all' -
Error after user creation using Django allauth
After setting up Django-allauth using Microsoft sql as the backend database i get the following error after registering a new user. However user is created and can log in as long as account_email_verification is set to optional django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]An expression of non-boolean type specified in a context where a condition is expected, near ')'. (4145) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") also get the same error when trying to verify email address through emailed link any help is appreciated thanks -
TypeError at /show_cart/ can only concatenate str (not "int") to str
I am building an e-commerce site and i'm working on a quantity & price section. What I want to do is, when the user increses the quantity of the product the price should also change depending upon the quantity. This is views.py def show_cart(request): if request.user.is_authenticated: user = request.user cart = Cart.objects.filter(user=user) amount = 0 shipping_amount = 70 total_amount = 0 cart_product = [p for p in Cart.objects.all() if p.user == user] if cart_product: for p in cart_product: temp_amount = (p.quantity * p.product.discounted_price) amount = temp_amount + amount total_amount = amount + shipping_amount return render(request, 'app/addtocart.html', {'carts':cart, 'amount':amount, 'total_amount':total_amount}) this is models.py: Here is have added comma sepeated integers. coz i wanted the products price to look like this: 14,999 insted of 14999 this. class Product(models.Model): title = models.CharField(max_length = 100) selling_price = models.CharField(validators=[validate_comma_separated_integer_list],max_length=200, blank=True, null=True,default='') discounted_price = models.CharField(validators=[validate_comma_separated_integer_list],max_length=200, blank=True, null=True,default='') I know i am getting this error coz coma seperated interger is considered as a String & quantity is an integer field. So, i want to know that how can i solve this problem, when the user increases the quantity of the product the price should also change depending upon the quantity.