Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse Inlines in Django Admin for Many to Many
Apologies if this has been asked before and my searches have not uncovered the solution. I'm looking to include admin inlines for two models. Django version is 4.1.4 class Book(models.Model): title = models.CharField(max_length=100) author_series = models.CharField(max_length=100, blank=True, null=True) series = models.ManyToManyField(Series) class Series(models.Model): name = models.CharField(max_length=100, blank=True, null=True) category = models.CharField(max_length=50) publisher = models.CharField(max_length=100,blank=True, null=True) I'm able to complete the forward relationship successfully using Model.field.through format: class SeriesInline(admin.TabularInline): model = Book.series.through class BookAdmin(admin.ModelAdmin): inlines = [SeriesInline,] but would like the reverse as well. class InlineSeriesBooks(admin.TabularInline): model = Series.book_set ... class SeriesAdmin(admin.ModelAdmin): ... inlines = [InlineSeriesBooks] I know model = Series.book_set is wrong but all the links seem to be suggesting the former through solution such as Django Admin, accessing reverse many to many. So far I have tried: Series.book_set = The value of 'biblio.admin.InlineSeriesBooks.model' must be a Model. Series.book_set.though = AttributeError: 'ManyToManyDescriptor' object has no attribute 'though' Book.series_set.though = AttributeError: type object 'Book' has no attribute 'series_set' Thanks in advance. -
How To fix django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'localhost'")
I have tried too mch but cannot solve it i have also run the query to identified the user but still getting the error. i am stucked need some help to get out of this will be grateful i have search every where but cannot come to the specific solution -
Django-Paypal - Trying to create an instance of my order and handle payments
I've been trying to use Paypal for my e-commerce project and have not got very far over the last few days. The issue I am having is that I have the Paypal SDK script in my checkout.html, which works fine and processes the payments as expected. What I want however, is to save the details of the order(and my shipping details in checkout.html) and create a new instance in my order model. I'm getting lost with this and not sure how to proceed, so any help would be much appreciated. Views.py: from django.shortcuts import render, redirect, reverse from django.contrib import messages from django.urls import reverse from profiles.models import UserProfile from django.views.decorators.csrf import csrf_exempt from .forms import OrderForm def checkout(request): bag = request.session.get('bag', {}) if not bag: messages.error(request, "There's nothing in your bag at the moment") return redirect(reverse('products:products_list')) order_form = OrderForm() # Attempt to prefill the form with any info the user maintains in # their profile if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) order_form = OrderForm(initial={ 'first_name': profile.default_first_name, 'last_name': profile.default_last_name, 'email': profile.default_email, 'phone_number': profile.default_phone_number, 'country': profile.default_country, 'postcode': profile.default_postcode, 'city': profile.default_city, 'street_address_1': profile.default_street_address_1, 'street_address_2': profile.default_street_address_2, 'county': profile.default_county, }) template = 'checkout/checkout.html' success_url = 'https://8000-bend2525-therescuersp5-77ck14x21o2.ws-eu82.gitpod.io/checkout/thankyou' context = { 'order_form': order_form, 'success_url': success_url } return … -
Use of Django login_required decorator, how can I resume my paused view after the login succeeded?
As the title mentioned and please refer to code below. When the user is going to my_view_1 page, he will firstly be redirected to /login for a page of (user/password) input. The view function loginSub will get the user's submit and check. I didn't know how to go back to my_view_1 view after the authentication is met. @login_required(login_url='/login') def my_view_1(request ): #do sth return displaySomething(request) def login(request): context = {} #input username and password return render(request, "logpage.html", context) def loginSub(request): #check password return my_view_1(request) -
"Connection reset by peer" in python gRPC
We are sending multiple requests to a gRPC server. But every once in a while we come across "Connection reset by peer" error with UNAVAILABLE status. GRPC server: NestJS Client: Python Python version: 3.8 gRPCio version: 1.50.0 Code: # Connect to server from client: def connect_to_user_manager_server() -> AuthorizationControllerStub: channel = grpc.insecure_channel(envs.USER_MANAGER_GRPC_URL, options=( ('grpc.keepalive_time_ms', 120000), ('grpc.keepalive_permit_without_calls', True), )) stub = AuthorizationControllerStub(channel) return stub client = connect_to_user_manager_server() user_response = client.CheckAuthorization(authorizationData(authorization=token, requiredRoles=roles)) -
Dynamic Sidebar - How to add data from database to my sidebar automatically
This is my first project with Django. I am working on a scholarship system whereby the admin has the power to add new countries, which offer scholarships, to the system. Everything works well at the level of the database. I am able to add a new country and save it. However, it is automatically supposed to be added to the sidebar of the admin dashboard (templates). But this does not happen. Here is my views.py code for adding and saving a new country def add_country(request): user = request.user if request.method == 'POST': form = CountryForm(request.POST) if form.is_valid(): form.save() print(form.cleaned_data) return redirect('dashboard.html') #redirect to be changed else: form = CountryForm() return render(request, 'add-country.html', { "form":form }) class CountryListView(ListView): template_name = "base.html" models = Country context_object_name = "countrys" HTML CODE <li><a href="#" class="ttr-material-button"> <span class="ttr-icon"><i class="ti-email"></i></span> <span class="ttr-label">Countries</span> <span class="ttr-arrow-icon"><i class="fa fa-angle-down"></i></span> </a> <ul> {% for country in countrys %} <li><a href="#" class="ttr-material-button"><span class="ttr-label">{{ countrys.name }}</span></a </li> {% endfor %} -
Dockerize PostgreSQL database with existing data
I'm trying to dockerize my Django project, but my database container seems to not be working. When I initialize docker-compose up the server starts but there is a message telling me I have 53 unapplied migrations (all), and run python manage.py migrate to migrate (like it is a blank database). My docker-compose looks like this: services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=database_name - POSTGRES_USER=database_admin - POSTGRES_PASSWORD=pskfnbiu42834h web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_DB=database_name - POSTGRES_USER=database_admin - POSTGRES_PASSWORD=pskfnbiu42834h depends_on: - db And I changed my settings.py DATABASE to this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': '5432', } } I think the problem might have to do with the volumes part. Docker created a data folder in my project directory with PostgreSQL related files. Where do those /var/lib/ folder live? Anyone can give any orientation? -
Django media isn't loading
I am trying to dynamically show media files which are uploaded with admin page. I am able to save the files and view it on the directory and database, however its not showing on the webpage. My settings.py MEDIA_ROOT = os.path.join(BASE_DIR, '') MEDIA_URL = '/uploads/' Urls.py path('xxxxx/', include('xxxxx.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Filepath on database media/2023/01/17/3.png Filepath in directory /project/media/2023/01/17 -
How to add a new pip package to the project?
I'm working in a project generated by cookiecutter-django localy using docker, I wanted to add new packeges, what is the best aproche to perform this? I'm actually copying the version of the package and pasting into the base requirements file and building the local.yaml contener again and it's seams to be rebuilding the entire containers in the project instead of building only the container that changes has been detected. So i don't if my aproche is the best, so please help me acheive this -
Data Base Sharding In django using MySQL
Hi I have been trying to improve the db performance and had done some basic research regarding having a db partition and db sharding and also having 2 dbs one for write and other for read . However i found out that the db sharding is the best way out of all as the mapping provided by sharding is dynamic that is one of the requirement to put it bluntly i have provided the 2 cases below Case 1:- we need to get all the transaction of a user (which is huge) Case 2:- we need all the data for a particular time interval for all the user (which is again huge) Because of the above scenerios I'm looking to implement db sharding Note:- I have already segregated some db into multiple databases already and they sit on different machines so i want it to be applied to all those multiple databases What I'm Looking for : Any link that could be helpful Any snippet code that could be helpful Django==3.2.13 MySql == 5.7 -
Dynamic Model in Django from fields data in another model
I am working on a project where I have 2 models model class Customer(models.Model): name = models.CharField(...) ... class CustomerProperty(models.Model): name = models.CharField(...) type = models.CharField(...) code = models.CharField(...) The CustomerProperty table has rows inside based on a parquet file (created at database init, not changed later on). For column in the parquet file, CustomerProperty has a row with column name from parquet as name in the table. Now for some other purpose, I need to copy over all the data in the parquet file inside the db. So, for each row in the CustomerProperty table, this new table will have a column (plus one column for foreign key to Customer) so I can run filters based on property values. This will also be copied over at db init and not change later on, so it is an unmanaged django model. I can't find any good docs on this, how to create a django model dynamically or how to add fields to that model dynamically. I don't need it to be managed, no need of migrations or django admin view support. I only need it to work with django ORM and be able to join and filter on it. I've … -
i can't display image on my Django admin page
i'm having trouble displaying images on my Djnago admin page. i read https://stackoverflow.com/questions/2443752/how-to-display-uploaded-images-in-change-list-page-in-django-admin/51181825#51181825 this article but still didn't get what i want :( this is my codes models.py from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin ) from django.db import models from django.utils.html import mark_safe class User(AbstractBaseUser, PermissionsMixin): image = models.ImageField( upload_to='media/profile_image/', null=True ) admin.py class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserChangeForm add_form = UserCreationForm def image_tag(self, obj): # Here return format_html( f'''<a href="{obj.image.url}" target="_blank"> <img src="{obj.image.url}" alt="{obj.image}" width="50" height="50" style="object-fit: cover;" /> </a>''') list_display = ('uid','get_full_name', 'email', 'nickname', 'introduce','image', 'birth','is_active', 'is_superuser', 'date_joined', 'image_tag') ... this is what i got admin page the image is in my PROJECTNAME/media/profile_image but i cant' display it on my admin page :( -
ImageField is not updating when update() method is used in Django Serializer
I want to give a Admin the ability to update the image associated to a Product record. I have an edit class that allows the admin to update various elements of a record all of which are updating correctly except for the image fields. The problem is uploading image is working in Creating but not in Updating. Model: image1 = models.ImageField(db_column='product_image1', null=True, blank=True, upload_to='media/images/') Serializer : class products_update(serializers.ModelSerializer): class Meta: model = Product fields =['category','product_name','description','unit_price','dis_price','image1','image2','image3'] Views : POST Product.objects.create(product_name=productname, description=description, quantity=quantity, unit_price=unitprice, dis_price=discountprice,user=usertable, category=categoryid, image1=image1) Image is successfully uploaded to media folder and path is stored in Database. PUT Product.objects.filter(id=pid, user=userdata).update(category = category, product_name=productname, description=description,unit_price=unitprice, dis_price=discountprice, image1=image1 When i use Update method image path is storing in DB, but Image is not storing in Media folder. can anyone have an idea how to solve this issue -
Django filters two fields in different records with the same value
In Django, I have a large amount of data(real data is about tens of thousands). I want to find all records with the same amount of income and expenditure. What should I do? Mysql: id income expenses 1 0.00 50.00 2 0.00 43.00 3 50.00 0.00 4 50.00 0.00 5 29.00 0.00 6 23.00 0.00 7 0.00 23.00 8 0.00 5.00 9 0.00 12.00 I want to filter out data 13467. All expenses and income amounts have the same data (excluding the amount is 0.00) id income expenses 1 0.00 50.00 3 50.00 0.00 4 50.00 0.00 6 23.00 0.00 7 0.00 23.00 -
need to calculate total time month wise in django
I have created function to calculate total time. def emp_attendance(request): attendance_list_ad = Attendance.objects.all() total = None for item in attendance_list_ad: if item.total_time is not None: if total is None: total = item.total_time else: total += item.total_time return render(request, 'employee/emp_attendance.html', {'attendance_list_ad': attendance_list_ad, 'total': total}) while print: attendance date = 2023-01-09 2023-01-10 2023-01-11 2023-01-12 2023-01-16 total_time = 1: 00: 00 11: 44: 11 0: 34: 44 0: 00: 14 4: 21: 20 0: 00: 24 so my question is in front page this function is calculating total time of all enteries which are in data base . But i want to calculate total time month wise as in attendance date we have month 01 . then total time will be calculated -
In Django models I have 6 question, if user answered 5 questions and submitted it should save 5 values in database as of now my code is not saving ito
def api_page(request): if request.method == "POST": if request.POST.get('q34_employeeId') and request.POST.get('q37_domain') and request.POST.get('q35_howLong') and request.POST.get('q103_typeA') and request.POST.get('q104_howSatisfied') and request.POST.get('q105_howSatisfied105') and request.POST.get('q106_howSatisfied106') and request.POST.get('q89_typeA89'): post = Employee() post.Employee_ID = request.POST.get('q34_employeeId') post.Domain = request.POST.get('q37_domain') post.Working_years = request.POST.get('q35_howLong') post.Satisfied_with_company = request.POST.get('q103_typeA') post.Satisfied_with_manager = request.POST.get('q104_howSatisfied') post.Satisfied_with_management = request.POST.get('q105_howSatisfied105') post.Satisfied_with_HR = request.POST.get('q106_howSatisfied106') post.Overall_experience = request.POST.get('q89_typeA89') sc=Employee.objects.filter(Employee_ID=post.Employee_ID) if sc.count() > 0: Employee.objects.filter(Employee_ID=post.Employee_ID).update(Domain=post.Domain, Working_years=post.Working_years,Satisfied_with_company=post.Satisfied_with_company,Satisfied_with_manager=post.Satisfied_with_manager,Satisfied_with_management=post.Satisfied_with_management,Satisfied_with_HR=post.Satisfied_with_HR,Overall_experience=post.Overall_experience) elif post.Overall_experience: post.save() elif not post.Overall_experience: post.save(update_fields=[post.Employee_ID,post.Domain,post.Working_years, post.Satisfied_with_company,post.Satisfied_with_manager,post.Satisfied_with_management,post.Satisfied_with_HR]) return HttpResponseRedirect('success/') Here is my above code I have tried with if user submit with 5 questions it is not saving in database but when user submit all 6 questions it is adding to database. Please help with this, Thanks in advance -
How to go back from virtual environment in windows?
I created an virtual environment and activate it but now I want to go back to my global environment, how I can do this using a comand? .\geek\Scripts\deactivate.bat I run this command to deactivate my environment but I still in that Virtual Environment. -
Django ForeignKey TypeError only in migrations (Field "id" expected a number but got <Model Instance>")
So i have a User model which has a ForeignKey to store the Department from where it belongs. It is something like this: class Department(models.Model): name = models.CharField(max_length=250) ... class User(models.Model): ... department = models.ForeignKey(Department, on_delete=models.CASCADE, null=True, blank=True) ... And i have some users registered. But anyways, i got the task to make it so that now the department option is no longer optional, it must be obligatory, and if the user doesn't choose one, the system must use a Default one, so i made the current changes by using a function to get or create the Default department: def get_default_department(): try: default_department = Department.objects.get(name="Default") except Department.DoesNotExist: default_department = Department.objects.create(name="Default", ...) return default_department And adding the function as the default parameter on my User model "department"'s attribute (as well as changing the null and blank options to False): class User(models.Model): department = models.ForeignKey(Department, on_delete=models.CASCADE, null=False, blank=False, default=get_default_department) Ok, perfect, then i ran makemigrations and everything worked well, until i ran the migrate command, wich resulted me in the following error message: "TypeError: Field 'id' expected a number but got <Department: Default>" Just by looking at it, i understood that the problem was that my function was returning an instance of … -
How to add pagination to data received from google big query in django rest framework
I have some data that is received from google big query and I'm trying to pagination to this data in django rest frame work. Also I'm not using serializers to achieve the correct output. Is there any ideal way to add pagination as I mention at the bottom? class CashFlowList(generics.ListAPIView): permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] pagination_class = PageNumberPagination @staticmethod def cash_flow_list(self, rows, info, *args, **kwargs): data = {'invoices': rows} message = {'info': info, 'data': data} return message def get(self, request): try: dataset = 'dummy_dataset' get_cashflow_query = f" SELECT ref_no AS invoice_number, party_name AS customer_name,credit_amount, pending_amount," \ f" DATE_ADD(date, INTERVAL credit_period DAY) AS due_date, DATE_DIFF(CURRENT_TIMESTAMP(), " \ f" DATE_ADD(date, INTERVAL credit_period DAY) , DAY) AS due_days FROM {dataset}.{CASH_FLOW_TABLE}" cashflow_list_data = cashflow_summary_obj.get_cash_values(get_cashflow_query) data = [] for row in cashflow_list_data: data.append({'invoice_number':row[0], 'customer_name': row[1], 'credit_amount': row[2], 'pending_amount': row[3], 'due_date': row[4], 'due_days': row[5]}) info = {'status_code': '131', 'status': 'SUCCESS', 'message': "cash flow data list."} message = self.cash_flow_list(self, info=info, rows=data) except NotFound: info = {'status_code': '711', 'status': 'FAIL', 'message': 'Unknown dataset, Please call Administrator...!'} data = {'total_receivables': 0, 'total_pending_receivables': 0, 'customers_overdue': 0} message = self.cash_flow_list(self, info=info, rows=data) return Response(data=message, status=status.HTTP_200_OK) This is the views.py file and the current output is as folows: { "info": { "status_code": "131", … -
how to get user's last login with OneToOneField and display it on admin panel?
Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/core/management/base.py", line 436, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'portal_users.admin.ProfileAdmin'>: (admin.E108) The value of 'list_display[10]' refers to 'user__last_login', which is not a callable, an attribute of 'ProfileAdmin', or an attribute or method on 'portal_users.Profile'. System check identified 1 issue (0 silenced). There is my code models.py: class Profile(models.Model): user = models.OneToOneField( User, null=True, related_name='profile', on_delete=CUSTOM_SET_NULL, ) student_id = models.IntegerField( blank=True, null=True, verbose_name='ID студента/преподавателя', help_text='Из 1С', ) first_name = models.CharField( max_length=200, verbose_name='Имя', blank=True, ) last_name = models.CharField( max_length=200, verbose_name='Фамилия', blank=True, ) admin.py: @admin.register(models.Profile) class ProfileAdmin(admin.ModelAdmin): list_display = [ 'user', 'first_name', 'last_name', 'user__last_login', ] -
How to Access Remote PostgreSQL Database Server Through VPN
I'm currently working with my office server, when i want to connect to the server, i have to use their VPN. I have installed PostgreSQL database in their server and have succesfully migrate data to database from Django project. But, when i want to remote access from HeidiSQL, it always gives me Connection Timed Out Error eventhough i have already connected to their VPN. I've tried to this code below /var/lib/pgsql/14/data/pg_hba.conf host all all 0.0.0.0/0 md5 host all all ::/0 md5 /var/lib/pgsql/14/data/postgresql.conf listen_addresses = '*' i have tried to refresh everytime i change files and see if i'm in the correct port but it still gives me Connection Timed Out Error this is the full error message could not connect to server: Connection Timed out (0x0000274C/10060). Is the server running on host "xxx.xxx.xxx.xxx" and accepting TCP/IP connections on port 5432 ? NOTES OS : CentOS 8 DB : PostgreSQL 14 -
DRF - Authentication credentials were not provided. (Djoser + SimpleJWT)
I am currently getting an error when making a request to /users/me to receive back my user's data. From what I have been reading, I am not sending the token, though I'm not sure how to store it when I receive it from the jwt/create endpoint when signing in. This is from my Auth-Test/nuxt-auth/pages/index.vue file: onMounted(async () => { const cookie = useCookie('jwt'); console.log('COOKIE: ' + JSON.stringify(cookie)); const response = await fetch('http://localhost:8000/api/auth/users/me/', { headers: { 'Content-Type': 'application/json', 'Authorization': `JWT ${JSON.stringify(cookie)}`, }, credentials: 'include' }) const content = await response.json(); console.log(content); }) and this is from my Auth-Test/nuxt-auth/pages/login.vue const router = useRouter(); async function submit() { console.log(JSON.stringify({ email: user.email, password: user.password })) await fetch('http://localhost:8000/api/auth/jwt/create/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ email: user.email, password: user.password }) }); await router.push({ path: '/' }); } Could anyone help me realize what I might be (am) doing wrong? I can't seem to figure out it myself through the use of documentation after a lot of reading. In case you might need to access the other files (front and back end), here is the Github repo. -
how to call form method from template for dynamic form in django
I have a model that one of it's field is CharField, use to store a JSON (list of dictionary) called 'schema' SCHEMA_DATA_TYPES=( (1, 'Integer'), (2, 'String'), (3, 'Date'), ) class MailTemplate(models.Model): name = models.CharField(max_length=20) tfile = models.FileField(upload_to='uploads/mailtemplate', null=True, blank=True) schema = models.CharField(max_length=256, blank=True, null=True, editable=False) def __str__(self) -> str: return self.name Currently, it only have one record and the 'schema' value is : [{"name": "date", "label": null, "type": 2, "format": ""}, {"name": "invoiceNumber", "label": null, "type": 2, "format": ""}, {"name": "company", "label": null, "type": 2, "format": ""}, {"name": "total", "label": null, "type": 2, "format": ""}, {"name": "items", "label": null, "type": 2, "format": ""}] I need to build a dynamic form that have additional fields contructed from that 'schema' field. first try I use htmx. The form is showed prefectly, but additional fields could read by forms.py as suggested by SO user @vinkomlacic at my post How to read additional data posted by form in django forms.py , I serach for doc on how to play with init of form to do it. I found https://www.caktusgroup.com/blog/2018/05/07/creating-dynamic-forms-django/ looks informative. so my admin.py is class MailTemplateAdmin(admin.ModelAdmin): change_form_template = 'mailtemplate_form.html' form = MailTemplateForm admin.site.register(MailTemplate,MailTemplateAdmin) and mailtemplate_form.html is {% extends "admin/change_form.html" %} {% block after_field_sets … -
Refrehing the Django model after save and 5 second sleep get me old state, what's wrong?
I was able to save the data to a Django model without any errors, but data not reflected in db. But after a sleep time I was able to save the data again with same method. What might be causing this ? I suspect use of the Google API, but was able to print the data before performing the save operation. def update_channel(): client = Client.objects.get(name="name") print(f"Existing channel: {data['id']}") # 123 # fetch channel data from google api data = google_drive.subscribe_new_channel() client.channel_id = data["id"] client.channel_resource_id = data["resourceId"] client.save() client.refresh_from_db() print(f"New channel: {data['id']}") # 456 print(f"New channel in db: {client.channel_id}") # 456 time.sleep(5) client.refresh_from_db() print(f"channel in db: {client.changes_channel_id}") # 123 -
add image from model in background:url()
hello i have in my model images and i store it inside media and i want to show image in html code using background:url() so , what i must write in background:url() to show image for each post my code in models : image = models.ImageField(upload_to='images/',null=True, blank=True) in css in html file : background: black url(what i must write here) no-repeat center center; in views : def mods_posts(request,slug): mods_posts = get_object_or_404(Mods, slug=slug) context = {'mods_posts':mods_posts} return render(request,'mods/mods_posts_page.html', { 'mods_posts': mods_posts }) so i need preview images in html page for each post