Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using a frontend JS framework with Django
I am looking to start a SPA project that will be data intensive. I am comfortable with Django and decided to use it for this project. I want to use a javascript technology to handle the front end and essentially replace the django templates. I know this is possible as I've seen people discuss integrating Angular/Vue/React with Django. I have yet to see discussion on which one is best. The two major factors: 1. relatively easy to learn 2. quick to implement Is there a general consensus on this? Thanks -
Dynamic Chart using django and Chart.js
Hi Guys I have a question or a request that I do not really know how to achieve. I am using chart.js in my django app in order to retrieve data and render it in great graphs. I followed the tutorial and I managed to make it work but I would like my chart to add dataset dynamically. I would like to create a radar chart showing data from a team of x numbers. I created a test for a team of 2 people manually HTML/Script: labels_list = data.labels info_data1 = data.data1 info_data1 = data.data2 var radar1 = { labels: labels, datasets: [{ label: "Team-member1", fillColor: "rgba(255,255,255,0)", strokeColor: "rgba(63,169,245,1)", pointColor: "rgba(63,169,245,1)", pointStrokeColor: "#fff", data: info_data1 }, { label: "Team-member2", fillColor: "rgba(255,255,255,0)", strokeColor: "rgba(102,45,145,1)", pointColor: "rgba(102,45,145,1)", pointStrokeColor: "#fff", data: info_data2 }] } views.py: def get(self, request, format=None, *args, **kwargs): team_member_list = Project.objects.get(id=kwargs['pk']).team_id.members.all() labels = ["Janv","Fev","March","April","May"] data1 = [35,56,45,34,25] data2 = [43,41,56,28,45] data = { "labels":labels, "data1":data1, "data2":data2 } return Response(data) How can I create the same kind of graph for X team members using dynamic data ?? ps: I just want to understand the logique.. so if someone can help me to render dynamically the dataset label (now "team member1/2") it … -
Customizing permissions and responses for detail routes in Django rest framework
Overview - I am creating a Django REST API that returns data from nested url routes. The best way I have found to do this so far is by manually adding in the url regexes to the urls.py and then using @detail_route in my views to retrieve the filtered serializer data. Right now I have user objects and goal objects that will need different data responses based on authentication, etc... How do I customize the detail routes to do this? For example: If a user is an admin they can use the 'post' method at the /api/v2/users url. If they are not authenticated they get a bad request 400 response. If a user is an admin they can use the 'get' method to retrieve all users names, emails, and passwords, but if they are not they can only get usernames. urls.py urlpatterns = [ url(r'^api/v2/users/$', UserViewSet.as_view({'get': 'users', 'post': 'users', 'put': 'users', 'patch': 'users', 'delete': 'users'}), name='user_list'), url(r'^api/v2/user/(?P<uid>\d+)/goals/$', UserViewSet.as_view({'get': 'user_goals', 'post': 'user_goals', 'put': 'user_goals', 'patch': 'user_goals', 'delete': 'user_goals'}), name='user_goals_list'), ] serializers.py class GoalSerializer(serializers.ModelSerializer): class Meta: model = Goal fields = ('id', 'user_id', 'name', 'amount', 'start_date', 'end_date', ) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'id', 'password') read_only_fields … -
How to safely give an object the next highest value in a model - Django
I want to assign a position parameter to each user created in my Django app. The position is modified at various points down the line, however when a user is created I need the position parameter to be set to the next highest value. The model is as follows: from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.OneToOneField(User) position = models.PositiveIntegerField(null=False, default=0, unique=True) At the moment I am assigning this parameter as follows: user_count = User.objects.all().count() new_user = User() new_user.profile.position = user_count + 1 new_user.save() Clearly if two users are registered at the same time, then there is a potential for them both to get the same value of user_count assigned, if that occurs before the save is made. Given the uniqueness constraint this would raise an error, but I'm not sure how to resolve it safely. How should I do this to ensure uniqueness (and deal with any unique conflicts that might arise)? -
Django testing function with request.user
I'm trying to write a test for a custom function in my Django model and having some issues. The function works correctly tested manually so this is a test code issue. I have read all the related questions on this but they have not solved my problem. I am using pytest. Code examples below: models.py - I want to test this function def save(self, *args, **kwargs): if self.in_progress: MyModel.objects.filter(user=request.user, flag=True).update(flag=False) super(MyModel, self).save(*args, **kwargs) tests.py class MyTest(TestCase): def setUp(self): self.factory = RequestFactory() self.user = UserFactory.create() def test_that_works(self): request = self.factory.get('/mypage/') request.user = self.user response = my_view(request) self.assertEqual(response.status_code, 200) def test_that_doesnt_work(self): request = self.factory.get('/') request.user = self.user myitem = MyModelFactory.create() myitem.flag = True myitem.save() assert myitem.flag is True When I run these tests, the first test works, but the second says NameError: global name 'request' is not defined The full traceback makes it clear that it is getting to myitem.save() in the test and the error is something to do with passing the request.user into the save() function. Can anyone help please? -
Django: url in "form action" doesn't work
In html: <form id="answer_form" class="form-horizontal" action="{% url 'puzzle:update' puzzle.id %}" method="POST" onSubmit="return ValidateAnswer();"> {% csrf_token %} <p>Please entry your answer below: (Case insensitive)</p> <div class="form-group col-xs-12"> <input id="player_answer" maxlength="30" name="player_answer" type="text"> </div> <div class="form-group col-xs-12"> <button id="submit_answer_btn" class="btn btn-success" type="submit">Submit</button> </div> </form> In url.py app_name = 'puzzle' urlpatterns = [ url(r'^(?P<pk>[0-9]+)/$', login_required(views.PuzzleDetailView.as_view()), name='detail'), url(r'^(?P<puzzle_id>[0-9]+)/update/$', views.update_user_game_history, name='update'), ] In views.py class PuzzleDetailView(DetailView): model = Puzzle template_name = 'puzzle/detail.html' def update_user_game_history(request, puzzle_id): player_game_history = PlayerGameHistory.objects.get(user=request.user) solved_puzzle = Puzzle.objects.get(id=puzzle_id) player_game_history.score += solved_puzzle.point player_game_history.save() return HttpResponseRedirect('/') What I am trying to do is to click on Submit button, via 2nd url, go to the update_user_game_history function in views.py. However, everytime I submit, the flow tries to, via 1st url, go to the PuzzleDetailView. And I get Method Not Allowed (POST): /2/ in terminal -
Django dynamic form values not storing
def signup_view(request): if request.method == 'POST': form = SignUpForm(request.POST) // user = authenticate(username=username, password=password) if form.is_valid(): form.save() token = jwt.encode({'user_id': user.id}, SECRET_KEY) My query is how do I store form details from this just created dynamic form unlike under: def login_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) -
ImportError: No module named 'datasets'
I'm using inception_v3 inside my django app. I have cloned this repository "https://github.com/tensorflow/models.git" and have made a incep.py file and written a function **generator():** as instructed on this link: "https://github.com/tensorflow/models/blob/master/research/slim/slim_walkthrough.ipynb" have changed the inception_v1 to v3 in the code. when called the incep.py returns the tags generated from the given image. i have cloned the git repository inside my django app folder and have also made a incepTest.py file where i'm calling the incep.py file. I'm facing the error "ImportError: No module named 'datasets'". I have already tried the solutions provided here: "ImportError: No module named datasets" but i'm still getting the error of no module named 'datasets'. i have imported the incep.py file as follows: from models.research.slim.incep import generator Also i have placed a blank init.py file in every working folder of models. Any help would be helpful. -
Data access between application Django / Cart - Products
Hi guys I have a question. I am trying to implement Cart application in my simple online shop. I created a cart model with ManyToManyField(Product, blank=true). Now, I want to access all the products, from the CartManager Level. cart_obj.products.all(), but it display empty query set :(. When in my admin site cart contains 3 items. I tested function all(), which is in ProductManager class, and it works fine in "Product" application. CartModel: from django.conf import settings from django.db import models from products.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): #creates new cart or gets cart based on the session #example: user was logged off added to the cart then he logs in # app will automatically updates this cart and assign it to the user def new_or_get(self, request): cart_id = request.session.get('cart_id', None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = self.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): print(user) user_obj = None if user is not None: if user.is_authenticated(): user_obj = user return self.model.objects.create(user=user_obj) # Create your models here. class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) products … -
Bad Request when deploying Django app on heroku
I just completed my first Django app and having extreme troubles deploying it on Heroku. I had to set DISABLE_COLLECTSTATIC=0. Procfile web: gunicorn linky.wsgi:application --log-file - WSGI_APPLICATION = 'linky.wsgi.application' 2017-11-30T12:36:14.432878+00:00 app[api]: Release v1 created by user namangupta111@gmail.com 2017-11-30T12:36:14.432878+00:00 app[api]: Initial release by user namangupta111@gmail.com 2017-11-30T12:36:14.620376+00:00 app[api]: Release v2 created by user namangupta111@gmail.com 2017-11-30T12:36:14.620376+00:00 app[api]: Enable Logplex by user namangupta111@gmail.com 2017-11-30T12:36:53.000000+00:00 app[api]: Build started by user namangupta111@gmail.com 2017-11-30T12:36:53.000000+00:00 app[api]: Build failed -- check your build logs 2017-11-30T12:40:30.000000+00:00 app[api]: Build started by user namangupta111@gmail.com 2017-11-30T12:40:30.000000+00:00 app[api]: Build failed -- check your build logs 2017-11-30T12:42:38.000000+00:00 app[api]: Build started by user namangupta111@gmail.com 2017-11-30T12:42:38.000000+00:00 app[api]: Build failed -- check your build logs 2017-11-30T12:45:35.467417+00:00 app[api]: Release v3 created by user namangupta111@gmail.com 2017-11-30T12:45:35.467417+00:00 app[api]: Set DISABLE_COLLECTSTATIC config vars by user namangupta111@gmail.com 2017-11-30T12:45:45.000000+00:00 app[api]: Build started by user namangupta111@gmail.com 2017-11-30T12:47:42.708932+00:00 app[api]: Attach DATABASE (@ref:postgresql-solid-33244) by user namangupta111@gmail.com 2017-11-30T12:47:43.038119+00:00 app[api]: Release v5 created by user namangupta111@gmail.com 2017-11-30T12:47:42.708932+00:00 app[api]: Release v4 created by user namangupta111@gmail.com 2017-11-30T12:47:43.038119+00:00 app[api]: Deploy a591e78d by user namangupta111@gmail.com 2017-11-30T12:47:43.061780+00:00 app[api]: Scaled to web@1:Free by user namangupta111@gmail.com 2017-11-30T12:45:45.000000+00:00 app[api]: Build succeeded 2017-11-30T12:47:56.253034+00:00 heroku[web.1]: Starting process with command `gunicorn linky.wsgi:linkey --log-file -` 2017-11-30T12:47:58.504110+00:00 heroku[web.1]: Process exited with status 127 2017-11-30T12:47:58.443015+00:00 app[web.1]: bash: gunicorn: command not found 2017-11-30T12:47:58.521776+00:00 heroku[web.1]: … -
django-admin runserver throws error
I have installed Django==1.10.0 pymongo==2.7.1 MongoDB 2.6 Python==2.7 six==1.10.0 MongoDB 2.6 mongoengine==0.9.0 in mysite/mysite/settings.py i have, # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { #'ENGINE': 'django_mongodb_engine', 'ENGINE': 'django.db.backends.dummy', 'NAME': 'test', 'USER': 'admin', 'PASSWORD': 'smmis@123#', } } #start AUTHENTICATION_BACKENDS = ( 'mongoengine.django.auth.MongoEngineBackend', ) from mongoengine import * connect('test') # connect('test', host='mongodb://127.0.0.1', port=50226) #end when i run django-admin runserver it throws error Traceback (most recent call last): File "/opt/VirEnv_p2.7/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/core/management/base.py", line 317, in run_from_argv connections.close_all() File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/db/utils.py", line 229, in close_all for alias in self: File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/db/utils.py", line 223, in __iter__ return iter(self.databases) File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/db/utils.py", line 156, in databases self._databases = settings.DATABASES File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/conf/__init__.py", line 116, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Even though SECRET_KEY = '9&q3vm=wpl3&r_8vgqch3*$+h*kp+urol&z=!gk*79lhwvjx' in mysite/settings.py What am i missing i am new to Django -
django form - raising specific field validation error from clean()
I have a validation check on a form which depends on more than one field, but it would be good to have the validation error show the user specifically which fields are causing the issue, rather than just an error message at the top of the form. (the form has many fields so it would be clearer to show specifically where the error is). As a work around I tried to create the same validation in each of the relevant fields clean_field() method so the user would see the error next to those fields. However I only seem to be able to access that particular field from self.cleaned_data and not any other? Alternatively is it possible to raise a field error from the forms clean() method? Attempt 1: def clean_supply_months(self): if not self.cleaned_data.get('same_address') and not self.cleaned_data.get('supply_months'): raise forms.ValidationError('Please specify time at address if less than 3 years.') def clean_supply_years(self): if not self.cleaned_data.get('same_address') and not self.cleaned_data.get('supply_years'): raise forms.ValidationError('Please specify time at address if less than 3 years.') def clean_same_address(self): ..... -
Redirect not working django
I've a problem about Django URL-redirection. The structure of the code is the following : The reactor view displays an HTML page with a list of elements. When clicking on one of them, an ajax request is done to the view. The ajax request is calling an another view with necessary informations The measurementReactor is called and displays details about one reactor. All functions are correctly called, the GET request is done but the page doesn't redirect in browser... Http requests #urls.py urlpatterns = [ url(r'^reactors/$', views.reactors, name = 'reactors'), url(r'^measurements/reactor/$', views.measurementReactor, name='measureReact'), ] #views.py @login_required def reactor(request): if request.method == "POST" and request.is_ajax(): if request.POST.get('type') == "measurement" : return redirect('/measurements/reactor/?ref='+request.POST.get('id')) @login_required def measurementReactor(request): reactobj = reactor.objects.get(id=request.GET['ref']) query = measurements.objects.filter(id_reactor=reactobj.id) return render(request, "measureReact.html",{"query":query}) #reactor.js var table1 = $('#datatable').DataTable(); $('#datatable tbody').on('click', 'tr>th:not(.controls.mdl-data-table__cell--non-numeric)', function () { var data = $(this).parent().find("[name=pk]").text(); $.ajax({ type : "POST", data : {'csrfmiddlewaretoken' : csrftoken, 'id':data, 'type':"measurement"}, }); }); -
Deploying django app to production server, should I include environment (env) in git clone?
I have a working django app running on mý localhost. It is running inside a virtual environment. No I want to deploy the same project into a Google Compute Engine. For that I have a question. After I set up the production server including starting the virutal environment with vritualenv env do I need to clone in the project code from git including the env directory or only the source code including manage.py? The process is described differently and so it is a bit confusing. Main problem is the clarity of deploying the django app to production and the virtual environment setup using git for the code transfer. Thank you for flow explanation. -
Django hello world page not found on virtual machine OPENSTACK
The problem is that I test the django helloworld in two virtual (ubuntu server) machine. one's virtual ip is xxx.xxx.xxx.xxx(example 123.4.5.6), physical ip is yyy.yyy.yyy.yyy(example 9.87.6.5), another is xxx.xxx.xxx.xxx(example 123.4.5.7) physical ip is yyy.yyy.yyy.yyy(example 9.87.6.4), all these are static "virtual ip" and static ip The problem is, while loading the page of the first django helloworld, everything is fine (this two helloworld are same code and independent to each other), but when I try building the second django helloworld and connect to the server it said Page not found (404) Request Method: GET Request URL: http://9.87.6.4/http:/9.87.6.4/ {'path': 'http://9.87.6.4/'} You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. and the server debugger said Performing system checks... System check identified no issues (0 silenced). November 30, 2017 - 12:13:18 Django version 1.11.7, using settings 'helloworld.settings' Starting development server at http://123.4.5.7:80/ Quit the server with CONTROL-C. Not Found: /http:/9.87.6.4:80/ [30/Nov/2017 12:13:19] "GET http://9.87.6.4:80/ HTTP/1.1" 404 1666 Notice that there's an extra http:/9.87.6.4/ in the Request URL I have tried reinstall the apache2 (but most likely it is not related to apache2 but to the virtual … -
Angular V5 with Django rest framework url not laoding
I am working on Angular5 with Django rest framework. I am trying to integrate the Django url with angular5. it is working only for index page. and if we change the state by clicking on any Button its working good but on page load it showing "Page not found (404)". The url for index page is: url(r'^$',TemplateView.as_view(template_name="index.html"),name="index") -
View not returning an HttpResponse object
def signup_view(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() token = jwt.encode({'user_id': form.cleaned_data.get( 'username').id}, SECRET_KEY) return HttpResponse(request, {'token': token.decode( "utf-8")}) This logic forms a part of my back-end that has to send response to front-end (just being explicit). But the error being thrown is: The view core.views.signup_view didn't return an HttpResponse object. It returned None instead. Please help me. -
Angular variable inside Django url
I'm using django with angular, so I need to pass slug which is angular variable inside in django url. urls.py url(r'^clinics/(?P<slug>[-\w]+)/$',clinicDetail,name="clinic-detail") in template <a href='{% url "clinic-detail" slug=ANGULAR_VARIABLE %}'>Read More</a> I receive ANGULAR_VARIABLE as {% verbatim %}{{ clinic.slug }}{% endverbatim %} I saw {$ $} tag, but couldnt manage to apply -
How to update parameter of all objects in a model - Django
I want to update a parameter in a Django model for all objects in the DB. The values will be different for each object, and I'm trying to work out whether I can do this as a batch update, or whether I have to iterate through each item and save each one separately. The model I'm using is an extension of the Django auth user model: from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.OneToOneField(User) position = models.PositiveIntegerField(null=False, default=0) If I get all objects as follows: queryset = User.objects.all() then loop through these and update position: for user in queryset: user.position = #SOME FUNCTION do I have to do user.save() within the for loop? Or can I update each item and then save all at once to the DB? -
Clear selection from django-autocomplete-light widget in a formset
I have a page which has two Django formsets which can both be added to dynmaically, so they can be of any length. Each formset has two fields, both of which are django-autocomplete-light widgets. I want to make it so that the autocomplete lists that are rendered by the widget are mutually exclusive. After reading the django-autocomplete-light docs I want to try something like this. However, I'm not sure if it is possible if I want to do it between autocompletes rather than a field input and an autocomplete (as suggested in the docs), and the autocompletes will not have the same prefix, as it will be the next form in the formset, rather than two fields in the same form. Previously I was trying to directly access the list when it is rendered: $(document).on('click', '.select2-container.select2-container--default.select2-container--open', function () { let text = $('.select2-results__option--highlighted').text(); $('.select2-results__option').each(function () { if ($(this).attr('class') !== 'select2-results__option select2-results__option--highlighted' && $(this).text() === text) { $(this).remove(); } }); }); However, there are two points to note here: 1). This doesn't work. I think because the autocomplete fields are rendering the list fresh every time, so any changes are not reflected, 2). I want to change the way I am … -
Update Django object field without refresh the page
How can I call a view function that change object field without refresh the page? views.py def add_like(request, pk): book = Book.objects.get(pk=pk) book.like = True book.save() return redirect('book_list') urls.py url(r'^add_like/(?P<pk>[0-9]+)/$', views.add_like, name='add_like'), list.html [...] <td><a href="{% url 'add_like' pk=book.pk %}" class="btn btn-default"><span class="glyphicon glyphicon-heart" style="color: grey;"></span></a></td> [...] Once user click the button, I want to change like status and the tag content to: <td><a href="{% url 'remove_like' pk=book.pk %}" class="btn btn-default"><span class="glyphicon glyphicon-heart" style="color: red;"></span></a></td> I know Ajax can be the answer, but I don't know how to implement it. Thanks. -
Bell Curve with django is not working
I am trying to create bell curve using django and highcharts but its not looking like i expected, Here is the image what exactly i want currently I'm working on this var data = [ 2.7, 2.7, 3, 3.4, 3.1, 2.3, 3, 2.5, 2.6, 3, 2.6, 2.3, 2.7, 3, 2.9, 2.9, 2.5, 2.8, 3.3, 2.7, 3, 2.9, 3, 3, 2.5, 2.9, 2.5, 3.6, 3.2, 2.7, 3, 2.5, 2.8, 3.2, 3, 3.8, 2.6, 2.2, 3.2, 2.8, 2.8, 2.7, 3.3, 3.2, 2.8, 3, 2.8, 3, 2.8, 3.8, 2.8, 2.8, 2.6, 3, 3.4, 3.1, 3, 3.1, 3.1, 3.1, 2.7, 3.2, 3.3, 3, 2.5, 3, 3.4, 3]; Highcharts.chart('container', { title: { text: 'Bell curve' }, xAxis: [{ title: { text: 'Data' } }, { title: { text: 'Bell curve' }, opposite: true }], yAxis: [{ title: { text: 'Data' } }, { title: { text: 'Bell curve' }, opposite: true }], series: [{ name: 'Bell curve', type: 'bellcurve', xAxis: 1, yAxis: 1, baseSeries: 1, zIndex: -1 }, { name: 'Data', type: 'scatter', data: data, marker: { radius: 1.5 } }] }); Click here to see -
Django Staticfiles used with Reportlab
I have a situation where I have a view that is creating a pdf using reportlab. I have to register a font file and I can do so with the following code: pdfmetrics.registerFont(TTFont('Arial', settings.STATIC_ROOT + '/fonts/Arial.ttf')) my static_root is set to : STATIC_ROOT = str(ROOT_DIR('staticfiles')) This will work but it means I have to run ./manage.py collectstatic in development in order for the static file which I understand as incorrect practice but I notice you doing it. As this is an edge case where Im not calling a static file through a url I should just copy the font file manually into the STATIC_ROOT in dev and not run collectstatic. Or should I try grab the file via the static_url? This static file business really bakes my noodle :( -
In Django can I use get absolute url with if statements to refer to other apps?
Can I use get_absolute_url with if statements to refer to other apps? Another django newbie question: My django project has a customer model that I'd like to share across multiple products that are each contained in an app (e.g. mobile, fixed). Currently, I have this customer model within the mobile app: # mobile/models.py class Client(models.Model): client_code = models.CharField(max_length=6, unique=True, db_index=True,) company_name = models.CharField(max_length=200, blank=False, null=False) slug = models.SlugField(db_index=True, unique=True, max_length=200) def get_absolute_url(self): return reverse('mobile:mobile_list_by_client',args=[self.slug]) The absolute url yields a path e.g.: '127.0.0.1:8000/mobile/AAA001' to customer AAA001. This is the mobile product model in the mobile app: # mobile.models.py class MobileLineIdentifiers(models.Model): client_code_1 = models.ForeignKey(Client, related_name = 'client_mobile' ) mtn = models.CharField(max_length=11, blank=False, null=False, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) def get_absolute_url(self): return reverse('mobile:mtn_detail', args=[self.id, self.slug]) I have Client as foriegn key in the fixed app: # fixed/models.py from mobile.models import Client class FixedLineIdentifiers(models.Model): client_code_3 = models.ForeignKey(Client, related_name = 'client_fixed' ) fixed_cli = models.CharField(max_length=11, blank=False, null=False, db_index=True) def get_absolute_url(self): return reverse('fixed:fixed_detail', args=[self.id, self.slug]) Can I simply re-use the mobile client model across apps using 'if' statements within the get_absolute_url function? What I'd like to achive: # mobile/models.py class Client(models.Model): #.... def get_absolute_url(self): # IF mobile: return reverse('mobile:mobile_list_by_client',args=[self.slug]) # IF fixed: return reverse('fixed:fixed_list_by_client',args=[self.slug]) I'm … -
How can I do some stuff after the save data to database immediately?
I have a WorkOrderCreateAPIView and WorkOrderCreateSerializer: # views class WorkOrderCreateAPIView(CreateAPIView): serializer_class = WorkOrderCreateSerializer permission_classes = [] queryset = WorkOrder.objects.all() # serializers class WorkOrderCreateSerializer(ModelSerializer): """ Create the work order """ class Meta: model = WorkOrder exclude = ("workorder_num","to_group","user", "workorder_status") def create(self, validated_data): user = getUserFormSerializer(self) to_group = Group.objects.filter(name=ADMIN_GROUP_CHOICES.售后组).first() return WorkOrder.objects.create( user=user, workorder_num = generateWorkorderNum(userid=user.id), to_group=to_group, workorder_status = WORKORDER_STATUS_CHOICES.已提交, **validated_data, ) I can access the WorkOrderCreateAPIView to create work order, but, I want to do some stuff after save the WorkOrder instance immediately. You see, in the create(self, validated_data) method, the last line is return WorkOrder.objects.create(xxx), it is not save data, so, how can I know when serializer or view save data? and after save data to database, I want to do some other things immediately, such as send email.