Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying an Angular 4 frontend with a Django Rest Framework backend on Heroku
I have built the front end using Angular 4 (using the angular CLI) and the backend using Django and the Django Rest Framework. The development environment is set up in such a way that the static assets, HTML,JS etc are all part of the Angular app. The angular app runs on a server spun up by the CLI at localhost:4200 and and it communicates with the rest framework backend through a series of HTTP calls through CORS to the DRF API which is live at another localhost:8000 only to obtain and serve information. How do I go about deploying this as a production-ready application on Heroku? The heroku guides illustrate how to deploy a Django app separately or an Angular app separately (running on a node server). Do i deploy them as two separate instances or do I combine them. If so , how do I go about doing that? -
How can I show the django version in pycharm?
I want to see the django version in my Pycharm terminal, but I don't get the correct method. I tried bellow methods in pycharm terminal: 1) django --version and django version 2) import django, and print the version by: import django print django.VERSION But I still can not get it. -
django rest framework how to add entries for multiple tables with one request?
I'm trying to add genres to the Genre model at the same time as adding a Movie to the movie model, however I get the following response object when trying to add a Genre entry that doesn't already exist (works fine if it exists in the table already): {'genres': ['Object with genre=Mystery does not exist.']} I thought it should work using the object.get_or_create() in the create() method of the MovieSerializer but it doesn't seem to work. Also I'm sending data by POST request in the format: {'tmdb_id': 14, 'title': 'some movie', 'release_date': '2011-12-12', 'genres': ['Action', 'Mystery']} not sure if that matters. Here's the code: Views.py class CreateMovieView(generics.ListCreateAPIView): queryset = Movie.objects.all() serializer_class = MovieSerializer def perform_create(self, serializer): """Save the post data when creating a new movie.""" serializer.save() class MovieDetailsView(generics.RetrieveUpdateDestroyAPIView): queryset = Movie.objects.all() serializer_class = MovieSerializer Models.py class Genre(models.Model): genre = models.CharField(max_length=65) def __str__(self): return "{}".format(self.genre) class Movie(models.Model): tmdb_id = models.IntegerField(primary_key=True) title = models.CharField(max_length=255) release_date = models.DateField() imdb_id = models.CharField(max_length=255, blank=True) img_path = models.CharField(max_length=255, blank=True) runtime = models.CharField(max_length=65, blank=True) synopsis = models.TextField(blank=True) imdb_rating = models.DecimalField(max_digits=3, decimal_places=1, blank=True, null=True) metascore = models.IntegerField(blank=True, null=True) genres = models.ManyToManyField(Genre, related_name='genres', blank=True) def __str__(self): return "{}".format(self.title) serializers.py class MovieSerializer(serializers.ModelSerializer): """Serializer to map the Model instance into JSON … -
Django - Docker - The Application Default Credentials are not available
I would like to use Google Cloud SDK with Django project in Docker container. Let's assume that I would like to use from google.cloud import vision from google.cloud.vision import types When I install google-cloud using requirements.txt file I get error shown below. On my local machine without container it works properly. Does anyone have an idea how can I solve it? django_1 | oauth2client.client.ApplicationDefaultCredentialsError: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information. -
Django form and redirect
It is a double question ;) My code is the follwing : in views.py: def create_invite(request): if request.method == "POST": invite_form = InviteForm(data=request.POST) if invite_form.is_valid(): email1 = invite_form.cleaned_data['email1'] email2 = invite_form.cleaned_data['email2'] email3 = invite_form.cleaned_data['email3'] email4 = invite_form.cleaned_data['email4'] email5 = invite_form.cleaned_data['email5'] for i in invite_form.cleaned_data: invite = Invitation.create(i) invite.send_invitation(request) print("The mail was went") return reverse('website:ProjectDetails', kwargs = {'pk' : project.pk} ) else: print("Your form is not valid") else: invite_form = InviteForm() return render(request, 'team_invite.html', {'invite_form': invite_form}) in form.py: from django import forms class InviteForm(forms.Form): email1 = forms.EmailField(label='Email 1') email2 = forms.EmailField(label='Email 2') email3 = forms.EmailField(label='Email 3') email4 = forms.EmailField(label='Email 4') email5 = forms.EmailField(label='Email 5') urls.py: from django.conf.urls import url from website import views app_name = 'website' urlpatterns = [ url(r'^candidateIndex/$', views.CandidateIndex.as_view(), name='candidate_index'), url(r'^HRcreate/$', views.ProjectCreate.as_view(), name='HR_create'), url(r'^project/(?P<pk>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails'), url(r'^project/add/$',views.ProjectCreate.as_view(), name='addproject'), url(r'^invite/$',views.create_invite, name='addteam'), ] Like you can see: I have a form that send email invites to user. Using that form I have two issues : 1) it seems that instead of taking the value in the input which is the email, it seems to take only the variable which is Email1 or Email2 ect.. 2) when I try to redirect to the detail page using the project pk I get an error … -
python save file directly from path
Hi I'm trying to test mock django-filer save() that trigger post_save signal. models.py import filer.fields.file import FilerFileField class DeliveryInvoice(TimeStampedModel): invoice_excel = FilerFileField(null=True, blank=True) tests.py from filer.models.filemodels import File as FilerFile from django.core.files import File def test_if_delivery_invoice_number_updated_on_file_save_through_admin(self): with patch("orders.utils.apply_invoice_number_to_orders") as signal_mock_handler: post_save.connect(signal_mock_handler, sender=DeliveryInvoice) filename = 'test_invoice_excel' filepath = 'orders/fixtures/delivery_invoices.xlsx' with open(filepath, 'rb') as f: file_obj = File(f, name=filename) error -> invoice_excel = FilerFile.objects.create(owner=self.user, file=file_obj, original_filename=filename) instance = DeliveryInvoice(invoice_excel=invoice_excel) instance.save() self.assertTrue(signal_mock_handler.called) Error Message .... File "/Users/mhjeon/.pyenv/versions/3.6.0/envs/modernlab/lib/python3.6/site-packages/boto/auth.py", line 1070, in _wrapper if test in self.host: TypeError: argument of type 'NoneType' is not iterable The code used to work a few days ago, but after some code refactoring which I believe is not related to the orders models, it suddenly fail to calle the django-filer's FilerModel.save() method. What could be wrong?/ -
Django query group by month and year
I have a Django model like this: class EVENT(models.Model): user = models.CharField(max_length=255) pay_time = models.DateTimeField(default=timezone.now) I need to calculate the average number of records per month I have for a certain group of users. I have the user names in a list and I want to group by month and year to use in the average calculation. My query is like this: from django.db import models from django.db.models import Func, F, Count class Month(Func): function = 'EXTRACT' template = '%(function)s(MONTH from %(expressions)s)' output_field = models.IntegerField() class Year(Func): function = 'EXTRACT' template = '%(function)s(YEAR from %(expressions)s)' output_field = models.IntegerField() #ru is the list of usernames I want to get the average per month for trx = EVENT.objects.filter(user__in=ru).annotate(m=Month('pay_time'), y=Year('pay_time')).values('m', 'y').annotate(c=Count('id')) When I run this query I get the results I thought I wanted. That's a sample of what I got: <QuerySet [{'y': 2016, 'c': 61098, 'm': 4}, {'y': 2016, 'c': 104632, 'm': 5}]> I wanted to make sure so I ran this query: trx2 = EVENT.objects.filter(user__in=ru, pay_time__year=2016, pay_time__month=4) And I got the result 60990 records. This means that the results I got from the first query are incorrect. I know I can use the second query in a loop to get what … -
django auth class views vs function views
I am creating a website using django version 1.11.5, I was wondering is it better to use the auth class best views (LoginView, PasswordChangeView) or writing my own function based views. Thank you in advance. -
Warming Django's per-view cache
Django 1.11.4 Could you tell me whether there is a tool to warm Django's per-view cache? I am planning to do something like this urlpatterns = [ url(r'^$', cache_page(60 * 60 * 24)(SearchEngineView.as_view()), name='form'), ] The pages are perfectly static. But I need to check whether the user has a permission. That is why I decided to use Django's per-view cache. class FrameListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): permission_required = 'general.can_observe' ... End every day I'd like to clear the existing cache and warm it again pages. There are a couple of thousands of such pages. If the cache is warm, the page will render in about 50 ms. It is Ok. No Varnish is necessary here. But without warming the whole idea will be useless. Could you give me a piece of advice here: how to warm the cache. -
Allow django to force overwrite a file without permission
I have to repetitively run a code which has to generate the same file again. filename = 'file'+str(counter)+'.txt' with open(filename, 'wb+') as destination: destination.write(temp_result) Django asks me permission to overwrite every time. file10.txt' already exists. Overwrite ? [y/N] y How can I force it to overwrite without requiring permission. -
JS Datetime picker with support for JS files at the bottom of the page
I'm developing a website, which requires a datetime field within it. I've seen a lot of really nice ones. However, my current HTML loads ALL JS (Such as jQuery) at the bottom of the page, and this cannot be changed. All of the current Datetime Pickers I've looked at require an inline script to start it. Are they any datetime pickers that do not require this? Bonus points if it is available as a django forms widget -
Notification with Django Channels
I am trying to use Django Channels to show notification. As per the documentation I have done everything step-by-step. But still i get no notification. Since I have currently started to use Channels and am not getting a proper output. My settings and codes are as follows: execution/consumer.py from channels.generic.websockets import JsonWebsocketConsumer from channels import Group class NotificationWS(JsonWebsocketConsumer): """ Websocket consumer class to handle the notification """ strict_ordering = False def connection_groups(self, **kwargs): """ Called to return the list of groups to automatically add/remove this connection to/from. """ return ["notification"] def connect(self, message, **kwargs): """ Perform things on connection start """ # Accept the connection; this is done by default if you don't override # the connect function. # print "reply channels" # import json # print json.dumps(dict(message)) self.message.reply_channel.send({"accept": True}) # Group("chat").add(message.reply_channel) Group('notification').add(message.reply_channel) # Group("notification").send({"text": "[1,2,3]" }) def receive(self, text=None, bytes=None, **kwargs): print "Inside notification receive:" print(text) """ Called when a message is received with either text or bytes filled out. """ reply_back = '{"text":"world"}' # self.message.reply_channel.send({"accept": True}) # Simple echo # self.send(text=reply_back) Group("notification").send({"text": reply_back}) def disconnect(self, message, **kwargs): """ Perform things on connection close """ print "client disconnected" routing.py from execution.consumer import NotificationWS from channels.routing import route_class channel_routing = … -
Django poor performance when Counting on multiple related fields
I've recently run into a performance problem with one of my Django views. I use models that resemble these example models: class User(models.Model): name = models.CharField(max_length=32) class Post(models.Model): author = models.ForeignKey('User', related_name='posts') class Comment(models.Model): author = models.ForeignKey('User', related_name='comments') In my view I need to display how many posts and comments each user has written, and I get the queryset like so: User.objects.annotate(post_count=Count('posts', distinct=True), comment_count=Count('comments', distinct=True)) This works as expected, however recently performance has become really poor with increased number of rows in the database. I have approximately: Users: 1300 Comments: 4300 Posts: 6200 And the query takes approximately 400ms. If I remove either post_count or comment_count from the query, execution time drops down to an acceptable 10ms. I suspect this comes from joining the extra table, which raises the total number of rows to 1300 * 4300 * 6200 instead of eg. 1300 * 4300. But how do I circumvent this problem, is the best solution to simply store the number of comments and posts in the database as a field and make application logic take care of updating it when needed? -
Django Integrity Error using invite app
Hi guys I am receiving the following error that I do not know how to interpret : django.db.utils.IntegrityError: UNIQUE constraint failed: invitations_invitation.email my app give the user the ability to create a new project and then is redirected to an invite page where he can invite his team using mails. I get the error when I click POST to my mails list I use the external app :https://github.com/bee-keeper/django-invitations view.py: from django.shortcuts import render from django.views import generic from django.views.generic import TemplateView from django.views.generic.edit import CreateView, UpdateView, DeleteView from .forms import InviteForm from invitations.models import Invitation from .models import project # Create your views here. class HomePage(TemplateView): template_name= 'index.html' class CandidateIndex(TemplateView): template_name= 'candidateIndex.html' class HRIndex(TemplateView): template_name= 'HRindex.html' class ProjectDetailView(generic.DetailView): model = project template_name = 'project_details.html' class ProjectCreate(CreateView): model = project fields = ['project_name'] template_name = 'project_form.html' def create_invite(request): if request.method == "POST": invite_form = InviteForm(data=request.POST) if invite_form.is_valid(): email1 = invite_form.cleaned_data['email1'] email2 = invite_form.cleaned_data['email2'] email3 = invite_form.cleaned_data['email3'] email4 = invite_form.cleaned_data['email4'] email5 = invite_form.cleaned_data['email5'] for i in invite_form.cleaned_data: invite = Invitation.create(i) invite.send_invitation(request) print("The mail was went") return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk} ) else: print("Your form is not valid") else: invite_form = InviteForm() return render(request, 'team_invite.html', {'invite_form': invite_form}) urls.py: from django.conf.urls import … -
How can I use Google Cloud SDK with Django project in Docker container?
I would like to use for instance from google.cloud import vision from google.cloud.vision import types Normally I install it on my local machine and everything is working correctly, however I have a problem because it seems to me that it is not possible to install it in container using requirements.txt file. Or maybe I am wrong? -
how to use site framework in live server django
I am a beginner in django and i used sites framework to make multiple instances of a website use the same code and database but in the document says: In order to serve different sites in production, you’d create a separate settings file with each SITE_ID (perhaps importing from a common settings file to avoid duplicating shared settings) and then specify the appropriate DJANGO_SETTINGS_MODULE for each site. Is that means in my live server i must create a folder that have diffrenet settings files for each django_site? if yes, what should i name this settings files? thanks. import os os.environ["DJANGO_SETTINGS_MODULE"] = "agileengage.settings" from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Adding a field to a ManyToManyField
So im currently working on a Django app. Where in admin we can create shop packs for people to order. So I've created a model with all the different items that a pack can include. After a little research, i found out that I needed a ManyToManyField to do this. So I created a model with a ManyToManyField to connects to the shop items model. Aka itemsincluded = models.ManyToManyField(shopItems) this works I can get all the items and that. My problem is now that I can add items that I also want to say how many pcs u will get in the back for each item. It should be an IntegerField. I have tried the option though in ManyToManyField. But it didn't work. And now im stuck here because I can't find any things how to do it. Any ideas? Just for reference here are the model and admin model (All imports are correct done) models.py class ShopPakker(models.Model): navn = models.CharField(max_length=255, null=False) description = models.TextField(null=False) pris = models.IntegerField(null=False) Item_include = models.ManyToManyField(KioskItem) def __str__(self): return self.navn admin.py admin.site.register(ShopPakker) Though Method Item_include = models.ManyToManyField(KioskItem, through='PakkeItem') class PakkeItem(models.Model): vare = models.ForeignKey(KioskItem) antal = models.IntegerField(null=False) def __str__(self): return self.navn -
Many autocreated migration files using Django in Docker
Just got started with Docker last week. In my apps, am seeing so many auto created migration files even if I have ran the ./manage.py makemigrations once. In the log below, I just switched on my machine and saw about 30 migration files created in the past 15 minutes. -rw-r--r-- 1 userx admin 788 Sep 9 12:54 0053_auto_20170909_0954.py -rw-r--r-- 1 userx admin 788 Sep 9 12:55 0054_auto_20170909_0955.py -rw-r--r-- 1 userx admin 788 Sep 9 12:55 0055_auto_20170909_0955.py -rw-r--r-- 1 userx admin 788 Sep 9 12:55 0056_auto_20170909_0955.py -rw-r--r-- 1 userx admin 788 Sep 9 12:56 0057_auto_20170909_0956.py -rw-r--r-- 1 userx admin 788 Sep 9 17:57 0058_auto_20170909_0958.py -rw-r--r-- 1 userx admin 788 Sep 9 21:58 0059_auto_20170909_0958.py -rw-r--r-- 1 userx admin 788 Sep 9 23:58 0060_auto_20170909_0959.py -rw-r--r-- 1 userx admin 788 Sep 10 00:58 0061_auto_20170909_0959.py -rw-r--r-- 1 userx admin 788 Sep 10 12:53 0062_auto_20170910_0953.py -rw-r--r-- 1 userx admin 788 Sep 10 12:53 0063_auto_20170910_0953.py -rw-r--r-- 1 userx admin 788 Sep 10 12:53 0064_auto_20170910_0953.py -rw-r--r-- 1 userx admin 788 Sep 10 12:53 0065_auto_20170910_0953.py -rw-r--r-- 1 userx admin 788 Sep 10 12:53 0066_auto_20170910_0953.py -rw-r--r-- 1 userx admin 788 Sep 10 12:53 0067_auto_20170910_0953.py -rw-r--r-- 1 userx admin 788 Sep 10 12:53 0068_auto_20170910_0953.py -rw-r--r-- 1 userx admin 788 Sep 10 … -
Upgrading django from 1.9 to 1.11: reverse accessor clash
models.py: class Societe(models.Model): ... class Client(Societe): ... class Meta(Societe.Meta): proxy = True class Fournisseur(Societe): ... class Meta(Societe.Meta): proxy = True class Commande(models.Model): Client = models.ForeignKey(Client, related_name='Commandes') Fournisseur = models.ForeignKey(Fournisseur, related_name='Commandes') This works in Django 1.9, but in 1.11, I get the error: Commande.Client: (fields.E304) Reverse accessor for 'Commande.Client' clashes with reverse accessor for 'Commande.Fournisseur'. Commande.Client: (fields.E305) Reverse query name for 'Commande.Client' clashes with reverse query name for 'Commande.Fournisseur'. Commande.Fournisseur: (fields.E304) Reverse accessor for 'Commande.Fournisseur' clashes with reverse accessor for 'Commande.Client'. Commande.Fournisseur: (fields.E305) Reverse query name for 'Commande.Fournisseur' clashes with reverse query name for 'Commande.Client'. Django seems to consider that Client and Fournisseur are the same model. I dont't want to change related names, any idea how to fix this problem? -
Passing extra context around a form
I have two models, Board and Problem. Each Board has many Problem linked to it. class Board(models.Model): author = models.ForeignKey(User, unique=False, on_delete=models.CASCADE) create_date = models.DateField(auto_now=False, auto_now_add=True) class Problem(models.Model): board = models.ForeignKey(Board, unique=False, on_delete=models.CASCADE) problem = models.TextField() Then I have a page where I can update values in an individual Problem instance. class ProblemStudyView(UpdateView): model = Problem fields = "__all__" template_name = "board/study.html" def get_success_url(self): success_url = reverse_lazy('board:problem-study', kwargs={'pk': self.kwargs['pk']}) return success_url This makes a fine form for updating the Problem. But I'd like to add two more url's, "previous Problem" and "next Problem". These would be links to the same ProblemStudyView for the next or previous Problem that shares the same parent Board. My problem is that I don't know where in the ProblemStudyView class I can generate this context to feed to the template. I would need to run two queries -- "what is the parent board of this current Problem" and "what is the list of Problems that share this common parent Board?" Then I can indicate the previous and next Problem to consider This seems kind of convoluted, so I am guessing I'm missing some more clever way to do this while still enjoying the use of … -
django.core.exceptions.ValidationError ["'suspend' value must be either True or False."]
i have been exploring the Django framework and its awesome, but i kept on running into errors but managed to get the solution on the internet and mostly on stack overflow However i got this one error that i couldn't fix it on my own. i need some help here i get the above error when i run python manage.py migrate otherwise, the system works fine with no errors. i don't what's wrong here is the error Operations to perform: Apply all migrations: admin, auth, contenttypes, files, report_builder, sessions Running migrations: Applying files.0029_students_status...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python34\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python34\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Python34\lib\site- packages\django\core\management\commands\migrate.py", line 204, in handle fake_initial=fake_initial, File "C:\Python34\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Python34\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Python34\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Python34\lib\site-packages\django\db\migrations\migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Python34\lib\site-packages\django\db\migrations\operations\fields.py", line 87, in database_forwards field, File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\schema.py", line 238, … -
AttributeError at ....... 'NoneType' object has no attribute 'is_valid' while developing django model forms
i get "AttributeError at /giris/markayenikaydet/, 'NoneType' object has no attribute 'is_valid' " error while saving from modelform to database. what may be the cause ??? i am stuck...is it related to modelform generation or is it related not including ant function. thanks all... """" MODEL... ` `from future import unicode_literals from django.db import models from datetime import datetime from django.urls import reverse from django.utils.translation import gettext as _ class marka(models.Model): marka_adi = models.CharField(max_length=200) def __str__(self): return(self.marka_adi) URL... from django.views.generic import RedirectView from django.conf.urls import include, url from . import views from django.utils.translation import gettext as _ urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^demirbas/$', views.DemirbasListView.as_view(), name='demirbas'), url(r'^demirbas/(?P<pk>\d+)$', views.DemirbasDetailView.as_view(), name='demirbas-detail'), url(r'^proje/$', views.ProjeListView.as_view(), name='proje'), url(r'^proje/(?P<pk>\d+)$', views.ProjeDetailView.as_view(), name='proje-detail'), url(r'^marka/$', views.MarkaListView.as_view(), name='marka'), url(r'^marka/(?P<pk>\d+)$', views.MarkaDetailView.as_view(), name='marka-detail'), url(r'^marka/duzeltsil/$', views.markaduzeltsil, name='markaduzeltsil'), url(r'^marka/ekle/$', views.markaekle, name='markaekle'), url(r'^kategori/$', views.KategoriListView.as_view(), name='kategori'), url(r'^kategori/(?P<pk>\d+)$', views.KategoriDetailView.as_view(), name='kategori-detail'), url(r'^musteri/$', views.MusteriListView.as_view(), name='musteri'), url(r'^musteri/(?P<pk>\d+)$', views.MusteriDetailView.as_view(), name='musteri-detail'), url(r'^marka/create/$', views.MarkaCreate.as_view(), name='marka_create'), url(r'^marka/(?P<pk>\d+)/update/$', views.MarkaUpdate.as_view(), name='marka_update'), url(r'^marka/(?P<pk>\d+)/delete/$', views.MarkaDelete.as_view(), name='marka_delete'), url(r'^markayenikaydet/$', views.markayenikaydet, name='markayenikaydet'), ] FORM.... from django import forms from django.forms import ModelForm from giris.models import marka from django.utils.translation import gettext as _ """from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Field from crispy_forms.bootstrap import ( PrependedText, PrependedAppendedText, FormActions)""" def MarkaGirisForm(ModelForm): class Meta: model = marka fields = '__all__' labels = { … -
Django passing arguments through save methods (models)
i have models in django like this: class Client(models.Model): type = (choices) class Bill(models.Model): client = models.ForeignKey(Client) class Detail(models.Model): total = models.MoneyField() # i used currency package bill = models.ForeignKey(Bill) Detail class contains sales detail for the Bill, i already made a transaction to save bill and details at the same time in Bill.save() method but i want to pass Client.type from Bill.save() to Detail.Save(), i want something like that def save(self, *args, **kwargs): #this is Bill save method client = self.Client transaction.atomic: super(Bill, self).save(*args, **kwargs) for detail in self.details detail.save(client) def save(self, *args, **kwargs): #this is Detail save method self.pricing(client) super(Detail, self).save(*args, **kwargs) def pricing(self, client): if client.type = 'value1': self.total = self.total - (self.total*5/100) elif client.type = 'value2': self.total = self.total - (self.total*7/100) else: self.total = self.total - (self.total*10/100) i don't know how passing arguments works on python and Django, what is the cleanest solution to solve this problem? in short i want the bill.save method to pick the client.type value and passe it through detail.save to calculate total with cases. Thanks -
Django admin permissions
Django Admin. I removed admin's Add and Change permissions from my model, but i can not view model why? -
Get unique keys of all matches to access data for tehm in cricAPI
I am working on a python project where I need to store match/player level statistics of all T20 cricket matches. I am using cricAPI and it works great if I have a unique of the match. How can I get unique keys of all the matches?