Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How come Django models not enforcing required model field when not specified?
I created a model: class Example(models.Model): name = models.CharField(max_length=50) code = models.CharField(max_length=10) content = models.TextField() and the corresponding test: from django.test import TestCase from .models import Example class ExampleTestCase(TestCase): def setUp(self): Example.objects.create(name="fff", content="blah blah blah") def test_length_of_toa_model(self): """example model should have length 1 as we created one in setUp""" length_of_toa = len(Example.objects.all()) self.assertEqual(length_of_toa, 1) I remember the default behaviour was it will throw error as code is by default required field and not set to null or blank, so why in this case everything works fine? Also apart from the test, I tried created and saving using django shell and it worked fine. -
How can i create code field to write code and display it to the template in django?
I want to create code field in model to display code to template in django. I saw in blogs they have an area where they can display code and it has the syntax highlight. How can I do it in Django? -
How to get post of only current user in django
i want that all the user can see only their own list and i getting error from django i don't know why. Also i want create view and list view on same page which i am not able to do. i need help in this aswell. Thank You this is my model.py:- from django.db import models from django.contrib.auth import get_user_model from django.conf import settings from django.urls import reverse # Create your models here. class simpleList(models.Model): title = models.CharField(max_length=250) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title this is my views.py:- from django.shortcuts import render from django.views.generic import ListView, CreateView from .models import simpleList from django.urls import reverse_lazy # Create your views here. def ListListView(request): current_user = request.author user_list = simpleList.objects.filter(user=current_user) return render(render, 'templates/list_list.html', {'userlist': user_list}) class CreateList(CreateView): model = simpleList template_name = 'create_list.html' fields = ('title', ) success_url = reverse_lazy('create_list') def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) this is my urls.py:- from django.urls import path from .views import ListListView, CreateList urlpatterns = [ path('', ListListView, name='list_list'), path('create/', CreateList.as_view(), name='create_list'), ] the error i am getting from django console:- AttributeError at /lists/ 'WSGIRequest' object has no attribute 'author' -
ProgrammingError at /admin/login/ : LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user
I've made a django app, and Ive put it live with heroku. I am new with heroku, I am getting this error and I don't know why, and don't seems something wrong with the code. Please help me -
How to add sum of annotate to a column of the original model
I know I can get the groupby sum of a django model with: cluster_id | module_count ------------------------- 1 | 1 1 | 2 2 | 3 2 | 1 sum_mods = clusters.values('cluster_id').annotate(data_sum=Sum('module_count')) cluster_id | module_count ------------------------- 1 | 3 2 | 4 This would give me the sum of each group of grouped by cluster_id. How can I assing this sum to a column in the original model ? Such as: cluster_id | module_count | module_count ---------------------------------------- 1 | 1 |3 1 | 2 |3 2 | 3 |4 2 | 1 |4 -
Merging two PDF generating views in Django
I have two working PDF generating views. I would like to create a view that combines these two views & merges the output PDFs produced by the two views to generate one PDF containing the output PDFs of the two views. I would also like to specify that these two views use different approaches to generate PDFs. The first one renders an HTML template to create PDF & the second creates a PDF from scratch using Reportlab. I am new to Django, How can I do this? View 1 class GenerateAllDocs(View): def allDocGen(request): if request.method == 'POST': all_doc_gen_form = GenerateAllForms(request.POST) if all_doc_gen_form.is_valid(): some_Field_1= all_doc_gen_form.cleaned_data['some_Field_1'] some_Field_2= all_doc_gen_form.cleaned_data['some_Field_2'] template = get_template('PDF_templates/att_pg_pdf_template.html') data = { 'some_Field_1': some_Field_1, 'some_Field_2': some_Field_2, } html = template.render(data) pdf = render_to_pdf('PDF_templates/att_pg_pdf_template.html', data) if pdf: response = HttpResponse(pdf, content_type = 'application/pdf') filename = "something - %s.pdf" %(data.get('zzzzz')) content = "inline; filename=%s" %(filename) download = request.GET.get('download') if download: content = "attachment; filename%s" %(filename) response['Content-Disposition'] = content return response return HttpResponse('Not Found') all_doc_gen_form = GenerateAllForms() return render(request, 'form_UI_templates/pg_att_form_UI_template.html', {'all_doc_gen_form':all_doc_gen_form}) View 2 def template_PDF_view(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; inline; filename="somefilename.pdf"' buffer = BytesIO() # Create the PDF object, using the … -
serialize dictionary in field for a rest API end point django rest framework
I have a serializer where I want to render a dictionary, I am also converting that dictionary to a JSON format, but I am getting the following error: Object of type Job is not JSON serializable. The code looks like this: jobs_by_hour = serializers.SerializerMethodField() def get_jobs_by_hour(self, obj): jobs = Job.objects.annotate(hour=ExtractHour('dt_start')) res = defaultdict(lambda: []) for x in jobs: res[x.hour].append(x) return json.dumps(res) I am a newb at this and I don't know how to fix this issue, any help is welcome. ultimately, with this dictionary i want to display the data grouped by the hour, so i get 24 lists of jobs -
Annotate datatime calculations
How could I cast datetime to seconds and perform calculation on that or directly perform calculation on datetime? for example: User.objects.annotate(min=Min('created'), max=Max('created'), perc=F('created') - min/(max - min)) How to get the value of perc for each user(I'm using postgres)? -
how to use dictionary field in Django?
I need to use dictionary field on a Django Model. for example on a data) name = Kim, user_id = 12902938291, dictionary = {'yo' : 'drop', 'the': 'beat'} I only heard how to convert model to dictionary field... i don't want how to convert model to dictionary field. how to use dictionary field in Django? -
i have string i need to find perticular string from main string object
here is my code i am trying to fetch the substring from main string using regular expressions but i am not able to find the exact.please help me to find this i have tried like this but i am not get exact output import re data="sudheer reddy ( raja sekhar ) venky (murali) 'rajesh reddy' 'mahesh' ('suresk kumar') " regex=r'^(a-zA-Z)+' l=re.findall(regex,data) print(l) output: i am getting output like empty list [] i need output like this ['sudheer reddy','venky','rajesh reddy','mahesh'] -
How to allow users to run jupyter notebooks stored in my database on my server?
I have a problem and I need a hint how to approach the problem. I have django application, in which I have sme jupyter notebooks stored in my database. At this point, users can download notebooks and run them on their compuers. I would like to add functionality, where user could run notebook online. I was thinking of two solutions: first one is to use some free to use online service, like google colab, but I haven't found any with api where I could send file from my database (maybe you know about some?), second is to run jupyter hub on my server. I saw how to run jupyter hub remotely, but I don't know how to grant users the access, so they can run notebooks simultaneously, and they don't have access to server itself thorugh it, and do all of this in django. Do you have any hints that could help me get this functionality? -
How to hint the type of Django's model field `objects` to a dynamically generated class?
I have a Team model in my Django project. I create its custom model manager with QuerySet.as_manager(). class TeamQuerySet(models.QuerySet): def active(self) -> "models.QuerySet[Team]": return self.filter(is_active=True) class Team(models.Model): is_active = models.BooleanField() objects = TeamQuerySet.as_manager() When I try to execute Team.objects.active(), mypy gives the following error: error: "Manager[Any]" has no attribute "active" In [5]: Team.objects Out[5]: <django.db.models.manager.ManagerFromTeamQuerySet at 0x10eee1f70> If I was explicitly defining a TeamManager class, there would be not a problem. How can I hint the type of Django model field objects to a dynamically generated class? -
Django Signal stuck in loop
I have 3 signal functions and one is getting stuck in a loop when it is called. It is called when an object inside of a model class is updated on the Django Admin page... # models.py class Item(models.Model): ... foo = models.BooleanField( default=False, editable=True, blank=True, help_text='Blah Blah...' ) # signals.py @receiver(pre_save, sender=Item) def foobar(sender, instance, **kwargs): try: pass except: pass I literally put pass in each try and except with a call to a log just to see if it is repeating even without code in them, and it is. Constantly with no end. This happens using an if / else statement, too, instead of try / except. How the heck can I stop the signal from getting stuck in a loop? It is supposed to send an email each time, but now when the object is updated, the user gets blasted with infinite emails until I reboot Django. I am really at a loss here... BTW, this doesn't happen on my test server, only on my live/staging server. -
Django @receiver decorator update ForeignKey object when object is edited
I have 2 classes which are standalone. The Trade model calculates many statistics based on the Entry model objects that relate to the Trade object. These stats only get calculated when the trade object is saved. Therefore when updating an Entry object manually due to an import process amendments. I also need that Entry object to send a signal to the related (ForeignKey) Trade object to be saved. Otherwise, a user would need to find that Trade object and click save. This would be massively inefficient. Here's my current setup and error message. Is this the right way to approach this issue or are their problems with this approach/better alternatives? models.py class Trade(models.Model): ... @receiver(post_save, sender='portfolios.Entry') def update_trade_object(sender, **kwargs): trade = Trade.objects.get(pk=kwargs['instance']) trade.save() class Entry(models.Model): ... trade = models.ForeignKey(Trade, on_delete=models.CASCADE, null=True, blank=True) Current Error: TypeError: Field 'id' expected a number but got <Entry: Entry object (605)>. -
Use entered data from another django model
I have two class model, the User and Money Request. I am trying to access the data I entered in the User class so that whenever I requested money using the MoneyRequest class, I can also input my entered email, first and last name together with the withdraw_money. I really need the data from the User class so that whenever I look at the admin page, I can see the name of the user who sent the money request. Here is my models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=100, unique=True) first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) class MoneyRequest(models.Model): date_requested = models.DateTimeField(auto_now_add=True) withdraw_money = models.DecimalField(null=True, blank=True, max_digits=8, decimal_places=2, help_text='Minimum withdrawal is ₱300.00.', validators=[minimum_money]) Here is my views for my MoneyRequest class class UserAccountsView(CreateView): model = MoneyRequest fields = ['withdraw_money',] # Keep listing whatever fields template_name = 'users/accounts.html' def form_valid(self, form): user = form.save() user.save() return redirect('users:user_account', self.request.user.username) What should I put in my MoneyRequest class in order to get the data entered in the User class? Thank you! -
Multi-page dash application on Django server with django-plotly-dash library
I have a multipage dash app that I want to serve it over Django with django-plotly-dash library. The structure of the main dash app is app.py import dash import dash_bootstrap_components as dbc from django_plotly_dash import DjangoDash app = DjangoDash('dash_integration_id', suppress_callback_exceptions=True) The index navigation file of the dash app is index.py import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State import dash_bootstrap_components as dbc from django_dash.app import app # import all pages in the app from django_dash.apps import app1, app2 # embedding the navigation bar app.layout = html.Div([ dcc.Location(id='url', refresh=False), html.Div(id='page-content'), ]) @app.callback(Output('page-content', 'children'), [Input('url', 'pathname')]) def display_page(pathname): if pathname == '/app1/': return app1.layout else: return app2.layout if __name__ == '__main__': app.run_server(8050, debug=True) I call the Djanngo dash app in the app1.html app1.html {%load plotly_dash%} <!DOCTYPE html> <html> <head> .... </head> <body> <main> {% plotly_app name='dash_integration_id' ratio=0.45 %} </main> </body> </html> My url.py in django app is urls.py from django.contrib import admin from django.conf.urls import url from django.urls import path, include from django.views.generic import TemplateView from django.conf import settings from django.conf.urls.static import static # Loading plotly Dash apps script import django_dash.index urlpatterns = [ url('^app1$', TemplateView.as_view(template_name='app1.html'), name="app1"), url('^django_plotly_dash/', include('django_plotly_dash.urls')), path('', TemplateView.as_view(template_name='app1.html')), url('^app2$', TemplateView.as_view(template_name='app2.html'), name="app2"), url('^django_plotly_dash/', include('django_plotly_dash.urls')), … -
Stripe checkout session in python
I am trying integrate stripe checkout in my webpage in Django. I have created the checkout session as bellow: try: checkout_session = stripe.checkout.Session.create( success_url=settings.WEB_DOMAIN + 'payment/success?session_id={CHECKOUT_SESSION_ID}', cancel_url=settings.WEB_DOMAIN+'payment/cancelled', payment_method_types=['card'], mode='payment', line_items=[ { 'name': name, 'images':image_link, 'quantity': 1, 'currency': 'usd', 'amount': price, } ] ) # i tried to update my database from here but evenif the payment fails database gets updated. return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) The checkout work perfectly but i don't know where to update some values in my database after the payment is completed.If some knows about it please give me suggestions. -
Django: Trying to set user as a foreign key in migration raises a ValueError
I have a Member class extending the User model class Member(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) # extra fields When I try to use the following custom migration to prepopulate the database with an initial data set from a file from django.db import migrations from django.contrib.auth.models import User import pandas as pd def add_data_from_file(apps, schema_editor): Member = apps.get_model('persons', 'Member') df = pd.read_excel('path_to_file', sheet_name='sheet_name') for ind in df.index: user = User.objects.create_user( username=df.username[ind], first_name=df.first_name[ind], last_name=df.last_name[ind], email=df.email[ind], password=df.password[ind], ) Member.objects.create( user=user, date_start=df.date_start[ind], date_stop=df.date_stop[ind] ) class Migration(migrations.Migration): dependencies = [ ('persons', '0001_initial'), ] operations = [ migrations.RunPython(add_data_from_file), ] Django raises: ValueError: Cannot assign "<User: testuser>": "Member.user" must be a "User" instance. Any idea why this doesn't work? -
Nested ManytoMany Serialization in Django Rest Framework
In my app I have a nested many to many relation like the following: Models.py class ReturnKitsProducts(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) class ReturnKits(models.Model): kit = models.ForeignKey(Kit, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) items = models.ManyToManyField(ReturnKitsProducts) class Return(models.Model): transaction_date = models.DateTimeField(default=datetime.now) transaction_no = models.IntegerField(default=0, blank=True, null=True) flow = models.ForeignKey(Flow, on_delete=models.CASCADE) kits = models.ManyToManyField(ReturnKits) warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) In this ReturnKitsProducts is connected to ReturnKits as M2M and ReturnKits is connected to Return as M2M. I have handles only single level of M2M serialization for updatation and creation like this: Serializers.py class ReturnKitsSerializer(serializers.ModelSerializer): class Meta: model = ReturnKits fields = "__all__" class ReturnSerializer(serializers.ModelSerializer): kits = ReturnKitsSerializer(many=True) class Meta: model = Return fields = "__all__" def create(self, validated_data): items_objects = validated_data.pop('kits', None) prdcts = [] for item in items_objects: i = ReturnKits.objects.create(**item) prdcts.append(i) instance = Return.objects.create(**validated_data) print("prdcts", prdcts) instance.items.set(prdcts) return instance But I am not sure how to do serialization in the above mentioned scenario. Please Help!! -
How to manage custom response code in web appliication
This question is more into the architectural one rather than code itself. I was curious how response codes are managed in enterprise and other big projects. Techstack: Python 3 Django In any REST based web application we need to have some sort of custom response codes. These codes are different from our HTTP response codes. USE-CASE: Suppose we have an API for creating a Product record in the database. Now depending on some sort of business logic i want to return a custom response code like 2001, 2002 (or something else). HTTP response code will always be 200 but my custom response code could be different. These custom codes might be required for the client application to identify as to what to do next. Generally i have seen people creating a List of dictionaries something else this: codes = {"PRODUCT_CREATE_SUCCESS": 2002, "PRODUCT_CREATE_FAIL": 2005, ......} and same goes with response messages messages = {"PRODUCT_CREATE_SUCCESS": "Product created successfully", "PRODUCT_CREATE_FAIL": "Product already exist"} So whenever they want to return these codes and messages they just do {"code": codes['PRODUCT_CREATE_SUCCESS'], "message": messages['PRODUCT_CREATE_SUCCESS']} I know the above approach suffice with smaller applications but it might be problematic for big ones. The answer can be a subjective … -
I can't edit one field in my Django REST App
I was changing the value of the members field via JSON object { ... "members": [2,3], ... } but after adding the search filter, it stopped working and is not editable. What could be? models.py # Create your models here. class Company(models.Model): members = ArrayField(models.IntegerField(blank=True), blank=True) ... serializers.py class AccountSerializer(serializers.ModelSerializer): user=serializers.StringRelatedField(read_only=False) class Meta: model=Account fields='__all__' class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class CompanySerializer(serializers.ModelSerializer): user = UserSerializer(read_only=False) members = serializers.SerializerMethodField() class Meta: model = Company fields = '__all__' #('id', 'name', 'description', 'date_created', 'user', 'status', 'theme', 'members') def get_members(self, obj): accounts = Account.objects.filter(id__in=obj.members) return AccountSerializer(accounts, many=True).data ... -
searching file upload to Database in Django
I am making a note sharing platform for my college. I have written the following code in the Django python framework. so I want to apply the filter option in my Django code. I have stored pdf in media folder through database entry. now I want to apply the filter option for Pre_Q_Paper to the database file which we show on main page. I want to filter previousYear --> Class --> Department --> Subjects --> now all file list display on my html models.py from django.db import models # Create your models here. class Universitie(models.Model): Universities = [("Savitribai Phule Pune Universities","Savitribai Phule Pune Universities"), ("Gate","Gate"), ("Indian Engineering Services","Indian Engineering Services"),] universitie = models.CharField(max_length=100,choices=Universities) def __str__(self): return self.universitie class Department(models.Model): Departments = [('First Year','First Year'), ('Mechanical Engineering','Mechanical Engineering'), ('Mechanical Sandwitch Engineering','Mechanical Sandwitch Engineering'), ("Electronics And Telecommunication Engineering","Electronics And Telecommunication Engineering"), ("Electrical Engineering","Electrical Engineering"), ("Computer Engineering","Computer Engineering"), ("Civil Engineering","Civil Engineering"), ("Instrumentation Engineering","Instrumentation Engineering"), ("Chemical Engineering","Chemical Engineering"), ("Information Technology Engineering","Information Technology Engineering"),] universities = models.ForeignKey(to=Universitie,null=False, on_delete=models.CASCADE) department = models.CharField(max_length=100,choices=Departments) def __str__(self): return self.department class Subject(models.Model): Class=[("First Year","First Year"), ("Second Year","Second Year"), ("Third Year","Third Year"), ("Fourth Year","Fourth Year"),] SEM = [("Semester 1","Semester 1"), ("Semester 2","Semester 2"), ("Semester 3","Semester 3"), ("Semester 4","Semester 4"), ("Semester 5","Semester … -
NameError: name 'views' is not defined in django 2.2.3 & python 3.7.0
I'm doing login and signup in Django but I'm getting the following error. Please help me in solving it. File "/home/mritunjay/project/pr/fitbit/accounts/urls.py", line 7, in path('', views.home, name="home"), NameError: name 'views' is not defined Here urls.py (app) from django.urls import path from accounts.views import home, SignUpView app_name = "accounts" urlpatterns = [ path('', views.home, name="home"), path('signup/', SignUpView.as_view(), name='signup'), path('login/', views.login, name='login'), ] Here views.py (app) from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView from accounts.forms import SignUpForm from django.contrib.auth.models import User class SignUpView(CreateView): success_url = reverse_lazy('login') template_name = 'templates/signup.html' def home(request): return render(request, "home.html", {}) Here urls.py (project) from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from django.views.generic import TemplateView #from accounts import urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')), # Main Page path('', TemplateView.as_view(template_name='home.html'), name='home'), # Login and Logout path('login/', auth_views.LoginView.as_view(redirect_authenticated_user=True, template_name='templates/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(next_page='home'), name='logout'), ] These are code where **NameError: name 'views' is not defined ** is showing in urls.py(app) Please help me in this. -
Where should I place a Python script that populates my database in Django?
I have a Python script in my project that grabs data from a few APIs and inserts it into my database. Everything runs fine if I run the script manually, but I don't know where I should place the file. I also want to setup a cronjob for the script so that it can run on its own. Where would be the ideal place for the script? Thanks -
access opened html div in javascript
i call ajax request in A.html and when response is ok I want to show message in B.html. (I want to show message in a div with id='mes_div' that contains in B.html ) how can I access B.html and how should I access this div? I use django as server side.