Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to calculate sums and multiplications in a django formset without using javascript?
I am a newbie in django and more in javasript, the question is that I am trying to do calculations in my formset with javascript but it does not come out, is there any way to do addition and multiplication in django formsets in an easier way? -
local variable 'verify_payment' referenced before assignment
i;m having the local variable renfrenced before assign and i have tried a lot of ways that i can use to fix this. any help would be greatly appreciated let me show some code views.py (the error after the top of the second if statement) def call_back_url(request): reference = request.GET.get('reference') # We need to fetch the reference from PAYMENT check_pay = PayHistory.objects.filter(paystack_charge_id=reference).exists() if check_pay == False: # This means payment was not made error should be thrown here... print("Error") else: payment = PayHistory.objects.get(paystack_charge_id=reference) # We need to fetch this to verify if the payment was successful. def verify_payment(request): url = 'https://api.paystack.co/transaction/verify/'+reference headers = { 'Authorization': 'Bearer '+settings.PAYSTACK_SECRET_KEY, 'Content-Type' : 'application/json', 'Accept': 'application/json', } datum = { "reference": payment.paystack_charge_id } x = requests.get(url, data=json.dumps(datum), headers=headers) if x.status_code != 200: return str(x.status_code) results = x.json() return results initialized = verify_payment(request) if initialized['data']['status'] == 'success': PayHistory.objects.filter(paystack_charge_id=initialized['data']['reference']).update(paid=True) new_payment = PayHistory.objects.get(paystack_charge_id=initialized['data']['reference']) instance = Membership.objects.get(id=new_payment.payment_for.id) sub = UserMembership.objects.filter(reference_code=initialized['data']['reference']).update(membership=instance) user_membership = UserMembership.objects.get(reference_code=initialized['data']['reference']) Subscription.objects.create(user_membership=user_membership, expires_in=dt.now().date() + timedelta(days=user_membership.membership.duration)) return redirect('subscribed') return render(request, 'payment.html') def subscribed(request): return render(request, 'subscribed.html') traceback System check identified 1 issue (0 silenced). November 26, 2021 - 18:50:42 Django version 3.2.9, using settings 'dexxapikprj.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Error Internal … -
Google App Engine Django Project Infinite Loading and error 500 does not raise any error in logs
Im am trying to deploy a Django project on Google Cloud App Engine. I deployed my app using the command gcloud app deploy. As I try to load the page in my browser, there is an infinite loading until the page finally returns a "Server 500 Error". I decited then to see if there is something weird in the logs by executing gcloud app logs tail but it does not raise any type of error, this is what i get. 2021-11-26 17:38:31 default[version_code] [2021-11-26 17:38:31 +0000] [11] [INFO] Starting gunicorn 20.1.0 2021-11-26 17:38:31 default[version_code] [2021-11-26 17:38:31 +0000] [11] [INFO] Listening at: http://0.0.0.0:5432 (11) 2021-11-26 17:38:31 default[version_code] [2021-11-26 17:38:31 +0000] [11] [INFO] Using worker: sync 2021-11-26 17:38:31 default[version_code] [2021-11-26 17:38:31 +0000] [16] [INFO] Booting worker with pid: 16 This is my Python Django settings.py: if os.getenv('GAE_APPLICATION', None): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'cloudsql/<my-google-cloudsql-connection-string>', 'NAME': 'database_name', 'USER': 'username', 'PASSWORD': 'password', 'PORT': '5432', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } This is my app.yaml file: runtime: python39 env: standard app_engine_apis: true handlers: - url: /static static_dir: static/ - url: /.* script: auto entrypoint: gunicorn -b :5432 NG.wsgi I also get this … -
Django MANAGERS and ADMINS settings, do we need it configured?
I know ADMINS can be used to receive error notifications on email Something that can be better handled by datadog or sentry For manager seems to be something even more specific, since you need t use BrokenLinkEmailsMiddleware as well # MANAGER CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins ADMINS = [ ("Admin", "admin@mail.com"), ] # See: https://docs.djangoproject.com/en/dev/ref/settings/#managers MANAGERS = ADMINS Does it have any other purpose? Any reason to keep it on the Django settings? -
insert data through django automatically
I have made crawler and I want to link it with my django app so i can see this data in admin panel , but my problem is I do not know how do I insert crawled data automatically to django database. -
python Django middleware to check license. How to avoid code cracking
I wanted to have a license key to use the django application I am creating a signed file using pub and private keys This singed file will contain the details of the license, like username, date of expiry, version number etc. One after purchasing the software they will download the signed file. They have to place the file at a location mentioned Basically i will have a middleware in the Django which will read the signed file and it also has the pubkey. Using that it will verify the signed document, and if it passes, then checked the expiry date and allow to continue class CheckDate: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. current_date = datetime.datetime.now() pub_key = "key is passed here" allowed_date = get from signed document the expiry date if current_date < allowed_date: return response else: #return render(request, 'licence_expired.html') return HttpResponse(json.dumps({"message":f"License Expired on {allowed_date}"}),content_type='application/json',status="401") return response Now using nuitka i am trying to obfuscate the code of … -
Django: how store multiple data types to the same model field
I want to create a database model somewhat similar to the example below: The idea is that User (or any model) can have multiple different features (or whatever) with different values. Feature can be anything, for example integer (salary), date (birthdate), or multiple selection (competences like C, Python, etc.). To keep the database design simple, I've tried an approach where I have only one Feature table which has optional choices via Choice table, instead of having separate database table for each feature type. User selection for feature value is stored to a User_has_Feature table "value" field, which is a CharField which can store multiple different data types, like integer, date, choice, multiple choice etc. My question is, how can I validate all data so that it validates against the field data type, and also shows everything correctly in admin or UI (having different UI widgets for different types)? I've tried an approach where I store the field type for each feature to Field table, which can be CharField, IntegerField, DateField, etc. Then in User_has_Feature model clean() I can dynamically validate against the field type, for example: FIELDS = { 'DateField': DateField, 'IntegerField': IntegerField, etc. } def clean(self): class_ = FIELDS.get(self.feature.field) … -
Django: Group and then Calculate the Sum of the column values through query
I have a model: bill_status_choice = ( ('Paid','Paid'), ('Pending','Pending'), ('Partially Paid','Partially Paid'), ) class Bill(models.Model): company_name = models.ForeignKey(Contact, on_delete=models.CASCADE) grand_tot = models.DecimalField(max_digits=9, decimal_places=2) status = models.CharField(max_length=100, choices=bill_status_choice) ... which has a fk to: class Contact(models.Model): associated_company = models.CharField(max_length=100) ... In my Views.py ... from bills.models import Bill from django.db.models import Sum def home(request): total = Bill.objects.filter(status='Paid').aggregate(Sum('grand_tot'))['grand_tot__sum'] context = { 'total':total, } return render(request, 'home.html',context) The problem: I am using charts.js in my front end template and I am trying to display a chart in which as a user creates new company names the chart should display the total amount grouped by company names how would I achieve that? eg: I create two invoices for "xyz" company with amounts: $100 & $200 || & create one invoice for "abc" company with amount $100 I want the chart to group the "xyz" invoice amounts and display $300 (ie:100+200) || & "abc" = $100 FYI I'm aware I'm using something completely wrong in the view function but its just something that I tried. Thanks -
How do I implement a login system in Django with GRPC?
I read GRPC documentations but it was not clear for me: How do I implement a registration form and then login with username and password? In JWT requests (REST) we always send the token with each request, but what is authentication in GRPC? -
Any way to figure out the reverse chain of Django relationship string?
Imagine you have a valid model relation string b__c__d__e for some model modelA, so that,say, the expression ModelA.objects.filter(b__c__d__e__in=[...]) is valid. My goal is to come up with a sort of "reverse" string which defines the "path" of relation from ModelE to ModelA. Is there any built-in way to do that? I am going to write such a function myself. But before dwelving into that, I wonder if there's any built-in way to do that. -
TypeError: Cannot read properties of undefined (reading 'params') when using match.params.id to fetch json data React Django rest API
I am trying to access specific data from my django backend based on using the unique id in the url for my react app on the frontend. I expect to see the body of the journal Instead i get this error: TypeError: Cannot read properties of undefined (reading 'params') I tried to use, 'useParams' instead but it lead to more errors. I also found similar questions on SO but they mentioned using 'props', is this the method i should be attempting instead? my App.js import { BrowserRouter, Routes, Route, Router, } from "react-router-dom"; import './App.css'; import Header from './components/Header' import JournalDashboard from './pages/JournalDashboard' import JournalPage from './pages/JournalPage' function App() { return ( <div className="App"> <BrowserRouter> <Header /> <Routes> <Route path="/" exact element={<JournalDashboard/>}></Route> <Route path="/journals/:id" element={<JournalPage/>} ></Route> </Routes> </BrowserRouter> </div> ); } export default App; my JournalPage.js import React, { useState, useEffect } from 'react' const JournalPage = ({ match }) => { let journalId = match.params.id let [journal, setJournal] = useState(null) useEffect(() => { getJournal() }, [journalId]) let getJournal = async () => { let response = await fetch(`/api/journals/${journalId}/`) let data = await response.json() setJournal(data) } return ( <div> <p>{journal?.body}</p> </div> ) } export default JournalPage Thanks in advance -
Django - show and verify email domains in registration form
I am using crispy forms to display the registration form and I have an issue with label_suffix in my form because it is not showing in the register.html file. When I change {{form|crispy}} to {{form}} then I can see it. Could you please tell me what am I doing wrong? Moreover, I'd like to limit the email domains that my registration system will accept and I want to check if the email is @companyname.com, @companyname2.com, @companyname3.com and it will accept only these emails in the registration process. Could you please tell me how can I do it? register.html <form method="post" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-secondary">Register</button> </form> views.py class SignUpView(View): form_class = SignUpForm template_name = 'user/register.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your Account' message = render_to_string('user/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) messages.success(request, ('Please Confirm your email to complete registration.')) return redirect('login') return render(request, self.template_name, {'form': form}) forms.py TRUSTED_EMAILS = ['@companyname.com','@companyname2.com', … -
Django - TypeError: object of type 'method' has no len()
I was trying add paginator to my website using some online code but I'm getting this error return len(self.object_list) TypeError: object of type 'method' has no len() Views.py def sample(request): WAllPAPER_PER_PAGE = 2 wallpapers = Wallpaper.objects.all page = request.GET.get('page', 1) wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE) try: wallpapers = wallpaper_paginator.page(page) except EmptyPage: wallpapers = wallpaper_paginator.page(wallpaper_paginator.num_pages) except: wallpapers = wallpaper_paginator.page(WAllPAPER_PER_PAGE) context = {"wallpapers": wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator} return render(request, "Wallpaper/sample.html", context ) Models.py class Wallpaper(models.Model): name = models.CharField(max_length=100, null=True) size = models.CharField(max_length=50, null=True) pub_date = models.DateField('date published', null=True) resolution = models.CharField(max_length=100, null=True) category = models.ManyToManyField(Category) tags = models.ManyToManyField(Tags) Device_Choices = [ ('PC', 'pc'), ('mobile', 'mobile') ] Devices = models.CharField(max_length=20,choices=Device_Choices, default= 'PC') image = models.ImageField(upload_to='Wallpaper/Images/', default="") def __str__(self): return self.name -
How to reuse a serializer in Django (Python)
I have a service in a Django app I am building where I want to hanlde get and post requests. I though I should reuse a serializer I ve build but in the examples I find whenever someone want to use a serializer they create a new object. This is an implementation where the serializer class is called multiple tiems to create multiple instanses one each time a request arrives: from django.http.response import JsonResponse from django.http.request import RAISE_ERROR, HttpRequest from rest_framework.parsers import JSONParser from rest_framework import status from models import Instrument from serializers import InstrumentsSerializer class InstrumentsService(): def __init__(self): self.serializer: InstrumentsSerializer = None def get_instruments_by_type(self, instrument_type: str): if instrument_type is not None: instruments = Instrument.objects.all() instruments.filter(instrument_type__icontains=instrument_type) instruments_serializer = InstrumentsSerializer(instruments, many=True) else: raise ValueError("Value type None is not acceptable for 'instrument_type'") return instruments_serializer.data def add_instrument(self, instrument_data: Instrument): instrument_serializer = InstrumentsSerializer(data=instrument_data) if instrument_serializer.is_valid(): instrument_serializer.save() How can I use the same serializer and pass different data to it each time? Because in the example I presented the data are being passed in during initialization. -
How to dump and restore correctly a postgresql db from docker
I stuck with this error when trying to backup and restory my database from a docker django app environnement : [error :(][1] [1]: https://i.stack.imgur.com/G8P4V.jpg I first did this command to backup my whole DB docker exec -t project_final-db-1 pg_dumpall -c -U fred2020 > ./db/dump.sql And then trying to restory with this command cat dump.sql | docker exec -i --user fred2020 catsitting-db-1 psql -U fred2020 -d postgres I have two containers, one for my django app named catsitting-web-1 and one for my postgresql named catsitting-db-1 I don't understand why it gaves me that error, my db user is the same that I specified on the dockerfile... Any clue ? -
Django: NoneType' object has no attribute 'user' error
I've this two models: MODEL class File(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) filename = models.CharField(max_length=250) file_upload = models.FileField(upload_to=path) upload_date = models.DateField(default=datetime.now) def __str__(self): return self.user.name + 'file' class Dataset(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) file_uploaded = models.OneToOneField(File, on_delete=models.CASCADE) name_user_A = models.CharField(max_length=250) code_user_A = models.PositiveIntegerField(null=True) total_user_A = models.PositiveIntegerField(null=True) sd_user_A = models.PositiveIntegerField(null=True) name_user_B = models.CharField(max_length=250) code_user_B = models.PositiveIntegerField(null=True) total_user_B = models.PositiveIntegerField(null=True) sd_user_B = models.PositiveIntegerField(null=True) With File model it should be uploaded a csv file and then the information in the file should be saved in the Dataset model. After that I'd like to show some chart to my user so I need my File and Dataset models linked. This is my view: VIEWS def file_upload(request): data = None if request.method == 'POST': form = FileForm(request.POST, request.FILES) raw_file= request.FILES if form.is_valid(): form.instance.user = request.user.profile form.instance.filename = raw_file['file_upload'].name form.save() data = request.FILES['file_upload'] data = pd.read_csv(data, header=0, encoding="UTF-8") data_form.instance.user = request.user.profile Dataset.objects.create( name_user_A = data.iloc[0,1], name_user_B = data.iloc[1,1], [...] ) return redirect('upload_file') else: return redirect('home') else: form = FileForm() context = { 'data': data, 'form': form, } return render(request, 'upload_file.html', context) When I try to access the Dataset database in the admin area I get this error: 'NoneType' object has no attribute 'user'. I cannot also access … -
Update an item using a django model instance
Is it a good idea to update an item by saving a model instance with the same id? Lets say there is an Person item in the database: id: 4 name: Foo surename: Bar tel: 0000000000 Is it a good idea to update that item like: p = Person( name='Foo' surename='Bar' tel='0000000111' ) old_p = Person.objects.get(name='Foo', surname='Bar') p.id = old_p.id p.save() -
Which setup is the best for remote authentication using Django REST Framework?
I currently have two different Django projects. One that handles the API; one that handles the front-end. Which way is best for authenticating users using the API from my front-end? For example, the users will log in on my front-end app and all the subsequent requests, that are made to the API from the front-end, should be done using the authenticated user. None of the authentication methods provided by DRF seems to suit my use case. Is there a way to do this or is my entire setup wrong? -
django-mptt sort order not as expected - and can't apply filtering
I am using Django 3.2 and django-mptt 0.13.4 I have the following objects: class Comment(models.Model): parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') created_at = models.DateTimeField(auto_now=True) # ... other fields and methods class MPTTMeta: order_insertion_by = ['created_at'] class Meta: permissions = [('perm_1', 'Permission 1'), ('perm2', 'Permission 2'),] class Commentable(models.Model): comments = GenericRelation(Comment) # ... other fields and methods class Meta: abstract = True class Foo(Commentable): class Meta: abstract = False In my view code, I access the comments as follows: class FooDetailView(DetailView): def get_context_data(self, **kwargs): context = super(FooDetailView, self).get_context_data(**kwargs) foo = self.get_object() context['comments'] = foo.comments.all() # I want to use a Models Manager instead # ... In my template (I am not using the mptt templatetags - for reasons too long to go into here), I do something like this: {% for comment in comments %} {% render_comment comment %} <!-- my own templatetag that renders as I wish --> {% endfor %} However, the comments are displayed with the earliest comment first - why?! I tried the following - and the sorting remained unchanged: Added ordering attribute of `['-created_at'] to Comment::Meta Chained method order_by('-created_at') to the all() method invocation in FooDetailView::get_context_data() My questions are: How can I get the comments … -
Application error and json.decoder.JSONDecodeError after django on heroku
I have created one django website which helps user to download instagram videos , profile pic etc. Here's the hosted LINK. On my local device this website works completely fine but after hosting it on heroku it displayed the home page but after clicking eg: get the user profile pic button it gives this error and sometime this : This is requirements.txt Django==3.2.5 requests==2.25.1 gunicorn==20.1.0 django-heroku==0.3.1 This is the python function to get that profile pic from insta from django.shortcuts import render import requests # get the profile pic function def Get_Profile_Pic(request): if request.method == "POST": header = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36" } # get message USER_NAME = request.POST['msg'] USERNAME = USER_NAME.replace("@", "") PROFILE_USERNAME = link + USERNAME + TAIL # validation # if fields empty if not PROFILE_USERNAME or link not in PROFILE_USERNAME: Error = "Invalid Link!" return render(request, 'home.html', {"profile_Error": Error}) # output else: try: resp = f"https://www.instagram.com/{USERNAME}/?__a=1" response = requests.get(resp, headers=header) responsex = response.json() PROFILE_IMG = responsex["graphql"]["user"]["profile_pic_url_hd"] return render(request, 'home.html', {"profile_result": PROFILE_IMG}) except ValueError or KeyError and Exception as e: Error = f"Invalid Link! {e}" return render(request, 'home.html', {"profile_Error": Error}) else: return render(request, 'home.html') Procfile web: gunicorn … -
nested ModelSerializer inside Serializer: Expected a dictionary, but got int
Getting "Invalid data. Expected a dictionary, but got int." on model serializer. How to serializer model inside custom serializers.Serializer class UserAddressSerializer(serializers.ModelSerializer): class Meta: fields = "__all__" model = UserAddress class OrderDetailSerializer(serializers.Serializer): address_id = UserAddressSerializer() total_cost = serializers.FloatField() ... class ServiceOrderDetailSerializer(serializers.Serializer): service_name = serializers.CharField(max_length=100) ... class PlaceOrderSerializer(serializers.Serializer): order_detail = OrderDetailSerializer() service_order = ServiceOrderDetailSerializer(many=True) view.py: serializer = PlaceOrderSerializer(data=request.data) Request: { "order_detail": { "address_id": 5, "total_cost": 432, "user_id": 2 }, "service_order": [ { "service_name": "1212ser345", ... ... Above code gives Bad Request: { "data": { "order_detail": { "address_id": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got int." ] } } } } -
LIKE button in a Django project
There is a view in the Django project (a paginated blog) that is responsible for how likes work. It has one drawback: when a user likes a post, it is redirected to the main page of the site. How can I fix this so that the user would remain on the page where they liked. views.py class AddLikeView(View): def post(self, request, *args, **kwargs): blog_post_id = int(request.POST.get('blog_post_id')) user_id = int(request.POST.get('user_id')) url_from = request.POST.get('url_from') user_inst = User.objects.get(id=user_id) blog_post_inst = News.objects.get(id=blog_post_id) try: blog_like_inst = BlogLikes.objects.get(blog_post=blog_post_inst, liked_by=user_inst) except Exception as e: blog_like = BlogLikes(blog_post=blog_post_inst, liked_by=user_inst, like=True) blog_like.save() return redirect(url_from) template.py -
Django remove all default migration
Is there a way to remove all default django migration? My app doesn't use any of the default migration so I think it's a good idea to remove all unused migration -
Django abstract models: how to use a parent method in a child class?
Abstract base classes are useful to put some common information into a number of other models. Now, I would like to build methods in my abstract base classes that I could call from every child class. Something like that, for instance: # models.py from django.db import models class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) @property def full_name(self): "Returns the person's full name." return '%s %s' % (self.first_name, self.last_name) class Meta: abstract = True class Student(Person): school = models.CharField(max_length=50) class Employee(Person): work = models.CharField(max_length=50) # any HTML template rendered by a view returning a *Student* instance to the template engine {{ student_instance.full_name }} # any HTML template rendered by a view returning a *Employee* instance to the template engine {{ employee_instance.full_name }} This, however, does not work. Why? Note that moving the method full_name into the Student and into the Employee would fix the problem. However, following the DRY principle, I would like to find a better solution. What could I do? -
Django elastic beanstalk CLI deployment failure after adding .env files to gitignore
I'm new to Django/EB/Git and been working on a django project and have successfully separated my setttings and separated .env files for both development and production which all works as expected and deployed- see the following project structure: Project Structure project root myapp settings __init__ base.py dev.py prod.py .env.dev .env.prod .gitignore manage.py requiremnts.txt However the moment I add my my .env files to the .gitignore file I now received the following error with deployment within eb logs (cfn-init-cmd.log): .gitignore # Elastic Beanstalk Files .elasticbeanstalk/* !.elasticbeanstalk/*.cfg.yml !.elasticbeanstalk/*.global.yml .env.dev .env.prod Error: eb logs (cfn-init-cmd.log) FileNotFoundError: [Errno 2] No such file or directory: '.env.prod' If i remove .env.prod from the .gitignore file then my project deploys successfully. Moreoever, I read online that might be due to me git adding and comitting the .env.prod file to the repo however believe I have also excluded git add/commit when I started fresh and re-created the git repo with the following command (commands run on local project): git add --all -- :!.env.dev :!.env.prod git commit -m "Initial commit" Followed by: eb deploy myproject-env See my .ebextensions config file as follows: .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: myproject.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "myproject.settings.prod" aws:elasticbeanstalk:environment:proxy:staticfiles: "/static": "static/" packages: yum: python3-devel: [] mariadb-devel: [] …