Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Got an error in cpanel column must appear in the GROUP BY clause
My app are working fine in my local pc. But problem arise when I am using this app to c panel. When I do a search query I got this error 'column "acc_installerledger.sales_invoice" must appear in the GROUP BY clause or be used in an aggregate function' Here acc my app, InstallerLedger my table name and sales_invoice is column name. def installerLedger(request): form = DateRangeForm() details = () installer = Installer.objects.order_by('name') if request.method == 'POST': installer_name = request.POST['installer'] form = DateRangeForm(request.POST or None) if form.is_valid(): details = InstallerLedger.objects.filter(name=installer_name, date__range=( form.cleaned_data['start_date'], form.cleaned_data['end_date'])).order_by('- id').annotate(balancecomm=Window(Sum('comm_balance'), order_by=F('id').asc()), balancecable=Window(Sum('cable_balance'), order_by=F('id').asc()), sales_invoicem=Min('sales_invoice'), namem=Min('name'), datem=Min('date') ) return render(request, 'installer/installer_ledger.html', {'tempo': details, 'form': form, 'installer': installer}) I am using Django 3.2 version. -
I can't create super user postgresql and Django
I am doing a project with Django in which I try to change the database from SQLITE to Postqresql. When I try to create the super user I get this error. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\models.py", line 163, in create_superuser return self._create_user(username, email, password, **extra_fields) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\models.py", line 146, in _create_user user.save(using=self._db) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\base.py", line 774, in save_base post_save.send( File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send return [ File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "C:\Users\l\Desktop\django-course\Django(02-09-21)\crm1\accounts\signals.py", line 7, in customer_profile group = Group.objects.get(name='customer') File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\query.py", line 435, in get raise self.model.DoesNotExist( django.contrib.auth.models.DoesNotExist: Group matching query does not exist. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': … -
getting error after submitting form inside detail view
I'm trying to create a dashboard for the staff users to fill in and edit some info regarding their users. the form works saves successfully but when I submit it I get this error: NoReverseMatch at /surveys/scientific/3 Reverse for 'scientific-info' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['surveys/scientific/(?P<pk>[^/]+)$'] this is my views.py: class ScientificInfoView(FormMixin, DetailView): model = ScientificInfo template_name = 'reg/scientific-info.html' form_class = ScientificInfoForm def get_success_url(self): return reverse('scientific-info', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(ScientificInfoView, self).get_context_data(**kwargs) context['form'] = ScientificInfoForm(initial={'post': self.object}) return context def post(self, request, pk): user = get_object_or_404(ScientificInfo, id=pk) if request.method == 'POST': form = ScientificInfoForm(request.POST, instance=user) if form.is_valid(): form.save() redirect('scientific-info') else: form = ScientificInfoForm(instance=user) return render(request, 'reg/scientific-info.html', {'form': form}) def form_valid(self, form, *args, **kwargs): form.save() return super(ScientificInfoView, self).form_valid(form) and my template: <form method="POST" enctype="multipart/form-data" action="{% url 'scientific-info' pk=object.id %}"> {% csrf_token %} {{form}} <button type="submit">submit</button> </form> Im pretty sure that the action part in my form is causing the issue but I dont know how to solve it -
Passing Authenticated User into Model View in Django
I am creating a profile model that needs to pass the current authenticated user as the foreign key. If I do not exclude the user field, I can select from all the users, but I need to hide this field and pass the current authenticated user automatically when the form is submitted. Additional fields like name, dob, etc. will be added to the model by the user. I cannot for the life of me figure out how to add the user to the model form. What I have in my views.py file (below) is the closest I have been able to get. Models class Profile(models.Model): user = models.ForeignKey( get_user_model(), on_delete = models.CASCADE ) first_name = models.CharField(max_length = 200, blank = True) last_name = models.CharField(max_length = 200, blank = True) dob = models.DateField(blank = True) profile_photo = models.ImageField(upload_to = 'profile_photos/', blank = True) def __str__(self): return self.first_name def get_absolute_url(self): return reverse('home') Views class ProfileCreateView(LoginRequiredMixin, generic.CreateView): model = Profile template_name = 'account/profile_creation.html' fields = ['first_name', 'last_name', 'dob', 'profile_photo'] login_url = 'account_login' def form_valid(self, form): user = self.request.user self.object = form.save(commit = False) self.object.save() return super(ProfileCreateView, self).form_valid(form) Forms class CustomProfileForm(forms.Form): class Meta: model = Profile The error I am getting: null value in … -
Is it possible to set django-allauth to accept only google login?
I am implementing a web application using Django framework. In my business I need to let the users have access to the app only by google login. I also don't need to register the users in my database, it isn't a requirement. I just need that the user will uses his google account to enter the site so I will be able to get his real email to send him back the result of the session. It is a one shot app. I am using django-allauth but it exposes by default a way to login and register users locally. Is it a way to disable every kind of local registration/login and let the user enter in the app only by google login? Thank you. -
I want to sent weather conditions sms to the registered users on the website [closed]
I want to send weather condition SMS to the registered users of my website. I have done with the coding but the SMS is not received to the registered users. Please Help me. user_data=extendeduser.objects.values('phone','town','user') def printit(): threading.Timer(10, printit).start() for i in user_data: city = i['town'] src = 'http://api.openweathermap.org/data/2.5/weather?appid=' url = src + city list_of_data = requests.get(url).json() temp = list_of_data['main']['temp'] newtmp = round(temp - 273.15, 3) condition = list_of_data['weather'][0]['description'] humidity = list_of_data['main']['humidity'] data = { "city": city, "temp": newtmp, "humidity": humidity, "condition": condition, "icon": str(list_of_data['weather'][0]['icon']), } print(data) if data['condition']=="overcast clouds": euser = extendeduser.objects.values('phone', 'user') url = "https://www.fast2sms.com/dev/bulk" querystring = { "authorization": "Authorization Code", "sender_id": "Annadata", "message": "Overcast Clouds ", "language": "english", "route": "p", "numbers": phone} headers = { 'cache-control': "no-cache" } response = requests.request("GET", url, headers=headers, params=querystring) print(response.text) print('\n'+city,' user '+str(i['user'])+' overcast condition',end='\n') printit() -
Generate barcode render to template HTML in django
I need to generate barcode in django to view in html for generate PDF particularly scan the generate barcode -
Dev server Django do not run [closed]
Sorry, I need hepl. I try make first django app with guide in your site. Virt. env is started and activated, but dev server not started. comand "python manage.py runserver" returned error "No module 'mysite'" Why???? -
Object placement of app that contains provider which stores all the state (React)
I'm trying to make an authentication on django-react web and came across this tutorial on youtube https://www.youtube.com/watch?v=BxzO2M7QcZw&t=2907s There is an object called app that contain provider which wrap a components and define a store. In that tutorial, app is called inside render function in index.js file. Below is the code const app = ( <Provider store={store}> <App /> </Provider> ) ReactDOM.render(app, document.getElementById('root')); registerServiceWorker(); I'm trying to follow this tutorial but i have a different format of index.js because i create all my routing path inside it while the tutorial create the route inside app.js. My question is, where should i put the app object if i have a code like this inside my index.js file? const composeEnhances = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose const store = createStore(reducer, composeEnhances( applyMiddleware(thunk) )); const app = ( <Provider store={store}> <Homepage></Homepage> <SportsSearch></SportsSearch> </Provider> ) const sports_dict = ['futsal', 'badminton', 'basket', 'sepak-bola', 'voli', 'tenis', 'billiard', 'tenis-meja'] render( <BrowserRouter> <Routes> <Route path="/" element={<Homepage />} /> <Route path="/R1" element={<RecommendationOne />} /> {sports_dict.map(sport => { return ( <Route path={`/${sport}`} element={<SportsSearch variable={sport} />} /> ) })} </Routes> </BrowserRouter>, document.getElementById("root") ); I have tried to put my app inside render but i get an error of Error: Target container is not a … -
Calling values from formA to formB in Django
I am new to Django and I am stuck at a certain problem which I believe to be not that complicated or even simple for some. Here it goes: In views.py, I have declared two methods/function namely, formA and formB, now I wanted to get a variable "username" in formA and automatically place it in the first cell in formB. How can I achieve this, here is the part of that code. By the way, everything is working for now, all I wanted is to pull that particular data. def formA(request): #form A is the User model built-in in Django if request.method == "POST": form_A = myFormA(request.POST) if form_A.is_valid(): form_A.save() else: form_A = myFormA() return render(....) def formB(request): #formB is a custom form that I made. if request.method == "POST": form_B = myFormB(request.POST) if form_B.is_valid(): form_B.save() else: form_B = myFormB(form_B = myFormB(initial={'username':request.user.username})) # this is the part where I am having problems with. return render(....) -
Django path converters not working as expected:
this is my url: URL: https://aws.s3.temp.com/st123/1321******12333123 And this is my path: path('pdf/viewer/<path:path>/', pdf.viewer, name="viewer"), This is my view: def viewer(request, path): context = {'path':path} return render(request, 'pdf_viewer.html', context) When i try to pass a url via this, am getting a wired result. Thus when i pass a url, its trimming up the forward slashes into one. OUTPUT: https:/aws.s3.temp.com/st123/1321******12333123 // check the https doesn't have two slashes But the expected output is https://aws.s3.temp.com/st123/1321******12333123 Why one single forward slash is getting removed ? And this happens only in production server but working correctly in localhost. Please help -
Celery task will not execute in django
I am leraning Django using django 3 by example. I want to launch asynchronous task with celery. I set the settings but the task will not execute. i'm using rabbit mq as broker and i'm using windows. Here is my code: celery.py import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Onlineshop.settings') app = Celery('Onlineshop') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() init.py from .celery import app as celery_app __all__ = ('celery_app',) tasks.py from celery import shared_task from django.core.mail import send_mail from .models import Order @shared_task def order_created(order_id): """Task to send an e-mail notification when order is successfully created.""" order = Order.objects.get(id=order_id) subject = f'Order nr. {order.id}' message = f'Dear {order.first_name},\n\n' \ f' You have successfully placed an order.' \ f'Your order ID is {order.id}' mail_sent = send_mail(subject, message, 'admin@onlineshop.com', [order.email]) return mail_sent views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render from .models import OrderItem from .forms import OrderCreateForm from cart.cart import Cart from .tasks import order_created # Create your views here. @login_required def order_create(request): cart = Cart(request) if request.method == 'POST': user = request.user form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save(commit=False) order.user = user order.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], … -
How to use google drive api in django for authentication and file storage?
How can I use google drive api as authentication as well file storage in django? I want to save files that they upload to their own google drive -
'AnonymousUser' object has no attribute '_meta' in Django
I am writing a website and when the user logs in, I get this error - 'AnonymousUser' object has no attribute '_meta'. How do I fix it? Here is a structure of my project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main │ │ index.html │ │ layout.html │ │ level_magic.html │ │ │ └───__pycache__ │ ├───templates │ └───registration └───users │ admin.py │ apps.py │ forms.py │ models.py │ tests.py │ urls.py │ utils.py │ views.py │ __init__.py │ ├───migrations │ │ 0001_initial.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───static │ └───users │ └───css │ login.css │ register.css │ ├───templates … -
NOT NULL constraint failed: reg_scientificinfo.user_id
Im trying to make a detailview that lets staff users update regulare users information. this is my models: class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) info1 = models.CharField(max_length=64, choices=SURVEY_CHOICES) info2 = models.CharField(max_length=64, choices=SURVEY_CHOICES) info3 = models.CharField(max_length=64, choices=SURVEY_CHOICES) and views: class ScientificInfoView(FormMixin, DetailView): model = ScientificInfo template_name = 'reg/scientific-info.html' form_class = ScientificInfoForm def get_success_url(self): return reverse('scientific-info', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(ScientificInfoView, self).get_context_data(**kwargs) context['form'] = ScientificInfoForm(initial={'post': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form, *args, **kwargs): form.save() return super(ScientificInfoView, self).form_valid(form) but when I try to submit the form it gives me this error: NOT NULL constraint failed: reg_scientificinfo.user_id -
Django Ignoring updates to urls.py
the urls.py file In My Dango Project Is being Ignored, For Exampe I Tried Commenting Out The Admin Urls From the Project And I Could Still Use The Admin. I tried Adding A Name Space And Django Says It Doesn't Exist. mysite/urls.py: """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include from django.conf.urls.static import static from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('',include("Wallet.urls"), path('',include("django.contrib.auth.urls")) ] + static(settings.STATIC_URL, document_root='/home/dh_hemuuv/minicoin.fztl.com/static') Wallet/urls.py: from django.urls import path from .views import signup,viewWallet,transfer,userpage,collectgift urlpatterns = [ path("signup/",signup,name="signup"), path("",viewWallet,name="home"), path("transfer/",transfer,name="transfer"), path("account/<str:username>/",userpage), path("collectgift/<int:id>/",collectgift,name="colgift"), ] Please Help! -
Django path.url with aws s3 gives "https:/" instead of "https://". How to manage this?
I have intergrated pdf js with my django webiste. And by using that, i am using aws s3 as storage. When user uplaod a document and click on a view document button. I am passing the aws url to the pdf js and then it loads. this is the total flow. Everything worked in localhost, but when i switched to pythonanywhere i noticed that the pdf is not opening. And when i checked the source code, i found that the url is coming as "https:/aws.com/a***********"** and actually it should come as "https://" with double slash. I couldnt find the exact mistake. Please help, check the pic with actual path See the https:/ starts with single slash -
how to edit user info inside a custom admin page
Im a rookie python developer and Im trying to add a feature to my app that allows staff users change some information about regular users. the field that are going to be edited are these: class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) info1 = models.CharField(max_length=64, choices=SURVEY_CHOICES) info2 = models.CharField(max_length=64, choices=SURVEY_CHOICES) info3 = models.CharField(max_length=64, choices=SURVEY_CHOICES) I created a dashboard for the admin which displays usernames and by hitting their name it redirects to the detail view of that user. this is the views I wrote for the detail page: class ScientificInfoView(DetailView): model = ScientificInfo template_name = 'reg/scientific-info.html' def edit_form(self, request, user_id): user = get_object_or_404(ScientificInfo, pk=user_id) if request.method == 'POST': form = ScientificInfoForm(request.post, instance=user) if form.is_valid(): form.save() redirect('scientific-info') else: form = ScientificInfoForm(instance=user) return render(request, 'reg/scientific-info.html', {'form': form}) However when inside the detailview, the form is not displayed. only the submit button is visible and when I click it I get a 504 error! for now the template is as simple as this: {{object.info1}} {{object.info2}} {{object.info3}} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <button type="submit">submit</button> </form> and finally this is my form: class ScientificInfoForm(forms.ModelForm): class Meta: model = ScientificInfo fields = ['info1', 'info2', 'info3'] what am I doing wrong? and is … -
Django - Return attribute in response if current logged in user is following queried user
So I have this view that queries for a User via their uuid. Whenever a request is made it must be accompanied by a access token that allows me to know who the current user is. Below I have an endpoint that returns all the queried users info including how many followers they have or number people they are following. I want to be able to return an attribute that determines whether the current user which is pulled from request.user is following the queried user with user uuid user_uuid. I tried the is_following=Count('followee_id', filter=Q(follower_id=str(request.user.uuid)))), but this doesn't seem to be returning the correct value as I have tests that check to see if this is true when it is set in the test database and they are failing. How do I annotated my query to include if the current user is following the user with user_uuid? view.py @api_view(['GET']) def get_user_info(request, user_uuid): query = User.objects.filter(pk=user_uuid) if query.exists(): query_annotated = query.annotate( follower_count=Count('followee_id', distinct=True), followee_count=Count('follower_id', distinct=True), is_following=Count('followee_id', filter=Q(follower_id=str(request.user.uuid)))) else: return Response(dict(error=str('User not found.'), user_message='User not found.'), status=status.HTTP_404_NOT_FOUND) serializer = FullUserSerializer(query_annotated[0]) return Response(serializer.data, status=status.HTTP_200_OK) serializer.py from rest_framework import serializers from cheers.models import User class FullUserSerializer(serializers.ModelSerializer): follower_count = serializers.IntegerField() followee_count = serializers.IntegerField() is_following = serializers.BooleanField() … -
Aggregate values with foreignkey field
I have model property where I sum foreign key field product_price and model field spend: @property def price_total(self): queryset = self.product.all().aggregate( total_price=models.Sum('price')) return queryset["total_price"] or 0 + self.spend Thats work good, but i need change filter query: @property def total_purchases(self): qs = super(PurchasesFilter, self).qs return qs.filter(regular='False', paid='True').aggregate(total_price=Sum(F('spend') + F('product__price')))['total_price'] This query only adds spend if a product price is added and duplicates value of spend for each product added. I need a query that always sum all the spends and adds the prices of the products, only if are added to the spend. And the value of the spend will not duplicate with each added product. -
How to give permission to AnnonymousUser to get room data using a passkey with django resr framework
I'm new to django and i'm trying to create an app with rooms that can only be created by a user, but anyone can "login" into a room with room Id and a passkey. the thing is, I don't know how to approch this, I read something about overriding AnonymousUser but, since I'm using simplejwt to authenticate a User, I thought maybe it will be better to create json token with room id and passkey instead of username and password, and then let anyone with this token acsses the room... But I dont know how to do it and I would like to get some pointers to what I should do or look up, since I havn't been able to find anything about it myself. -
with the help of django, what are the steps to show data in the website from Apache Solr?
Here I need to show the TEXT and URL in the website from apache solr. what will be the query or ORM? -
Django URL not mapping even there is no error why?
django startproject folder (URLS.PY):- from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('sub.urls')), ] django startapp folder (URLS.PY):- from django.urls import path from . import views urlpatterns = [ path('', views.home, name= 'home'), ] django startapp folder (VIEWS.PY):- from django.http import HttpResponse def home(request): return HttpResponse("hello world") -
How can i do multiple values filter for multiple fields in Django?
for loc,deg,dept,key,job_role,insti_loc,insti_name,mark,gen,job_type in zip(lst2,lst5,lst6,lst1,lst4,lst8,lst9,lst10,lst11,lst12): if sample_register.objects.filter(city=loc,job_role_1=job_role,qualification=deg,qualification_dept=dept).exists(): print("Inside location and jobrole1 and qualification and department search") for i,j,k,l in zip(lst5,lst2,lst6,lst4): pro_log=sample_register.objects.filter(Q(city=j) & Q(job_role_1=l) & Q(qualification=i) & Q(qualification_dept=k)) -
Django -Display a list of post's categories with a number of post
Hi i am trying to make a template in django that displays a post categories table and has a number of posts with it. I can't seem to make it right using annotate when making queries on my model. like this views.py categorylistcount = Post.objects.all().annotate(posts_count=Count('category')) for obj in categorylistcount: print(obj.category + ' : ' + obj.categories_count) #test im receiving list of posts instead and has a posts_count key with value of 1 models.py class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE ) body = models.TextField() category = models.CharField(max_length=64, default="Uncategorized") date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('blog:post-detail', kwargs={"pk": self.pk}) class Category(models.Model): name = models.CharField(max_length=225) def __str__(self): return self.name where did i miss? thanks