Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unit test to assertRedirects of login?
I have custom login page for admin in my Django project. I am trying to write unit-test but it raise error. After successful login Django redirect user to other page (dashboard page). In my unit test dont work assertRedirects. How to fix this problem? print reverse('administration:dashboard') return me /administration/ but I have strange error. Can someone say whats wrong I did? tests.py: class AdministrationViewTestCase(TestCase): def setUp(self): self.client = Client() def test_administration_login(self): response = self.client.get( reverse('administration:administration_login'), follow=True ) self.assertEquals(response.status_code, 200) title = "Login" self.assertTrue(title in response.content) user = User.objects.create( username='user', password=make_password('password') ) self.assertTrue(user) logged_in = self.client.login(username='user', password="password") self.assertTrue(logged_in) response = self.client.post( reverse('administration:administration_login') ) self.assertEqual(response.status_code, 302) self.assertRedirects( response, expected_url=reverse('administration:dashboard'), status_code=302, target_status_code=200 ) ERROR: Traceback (most recent call last): File "/home/nurzhan/CA/administration/tests.py", line 41, in test_administration_login target_status_code=200 File "/srv/envs/py27/lib/python2.7/site-packages/django/test/testcases.py", line 324, in assertRedirects % (path, redirect_response.status_code, target_status_code) AssertionError: Couldn't retrieve redirection page '/accounts/profile/': response code was 404 (expected 200) urls.py of app: urlpatterns = [ # Administration Dashboard url(r'^$', login_required( login_url=reverse_lazy('administration:administration_login')) (DashboardView.as_view()), name='dashboard'), # Administration Login url(r'^login/$', authentication_views.login, { 'template_name': 'administration/login.html', 'authentication_form': AdministrationAuthenticationForm, 'extra_context': { 'next': reverse_lazy('administration:dashboard') }, 'redirect_authenticated_user': True }, name='administration_login'), ] urls.py of project: urlpatterns = [ # Administration Page url(r'^administration/', include('administration.urls', namespace='administration')), ] -
name 'category_id' is not defined
I am trying to get the id of the category but this error keeps up poping. Here is my models class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='category_created') name = models.CharField(max_length=500, db_index=True) slug = models.CharField(max_length=500, blank=True) images = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='product') category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=500, db_index=True) slug = models.CharField(max_length=500, blank=True) images = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField(blank=True) available = models.CharField(max_length=25) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(Product, self).save(*args, **kwargs) This is my views where by errors is occuring from and don't know how to fix the views and i am sure the problem is from my views @login_required def product(request): if request.method == 'POST': category = Category.objects.get(pk = category_id) product_form = ProductForm(data=request.POST, files=request.FILES) if product_form.is_valid(): new_item = product_form.save(commit=False) new_item.category = category new_item.save() messages.success(request, 'Product created') else: messages.error(request, 'Product Failed to be created') else: product_form = ProductForm() return render(request, 'shop/product/product_create.html', {'product_form':product_form}) Here is my url for the view urlpatterns = [ url(r'^category-create/$', … -
How to get collectstatic to collect the static files of an external App
I'm working on a project that requires an external fileupload package, which is a separate project. 'collectstatic' does not include the static files of that external package. Do I need to change the external package or can I use the settings.py of my project to include the static files? It works if I do: STATICFILES_DIRS = ( str(APPS_DIR.path('my_app/static')), str(APPS_DIR.path('../other_app/fileupload/static')) ) But this will not work on the deployment server. -
Tranforming buttons - works in development, not deployment
I have a sign out form. Users click a button to secure a reservation. That button changes from “free” to “reserved”, the reserved button includes the user’s name. I’m using Django, but added JS so that the button will change without a refresh. This works fine on my local server, but when I deploy to PythonAnywhere it doesn’t. Instead, the button transforms, but displays “none” and my console check is “undefined”. Any idea what went wrong? Abridged code below: Main.JS $( 'button' ).click(function() { console.log( 'we clicked!' ); // Sanity Check II var pk = this.id var button = $(this) var user = $( 'button' ).attr("user") console.log( pk, user) // Sanity Check III $.ajax({ url: "/reserve/", type: "POST", //Send the info to reserve view data: { pk : pk}, success: function(data) { var number = JSON.parse(data); console.log(number, number.result) if (number.result == 1 ) { if (number.result == 2) { console.log(user) $(button).toggleClass( "free reserved") $(button).children("div.tchr").html(user); //Send user info to button, reverts on refresh $.toast({ heading: "Reservation Complete!", icon: 'success', stack: 4, hideAfter: 2000 }); } And a button home.html {% for p in periods %} <td class="slots"> Period {{p}} <br>{% for x in this_week %} {% with d=x.day|date:"w" %} {% if … -
Django Material Autocomplete
Has anyone managed to get an Autocomplete working for Django Material https://github.com/viewflow/django-material? I really like the look of the interface for the admin and all I require is an autocomplete widget to work as my tables are too big. I have tried Django Select2 and Autocomplete-light but it seems like the django-material doesn't render the widgets. The error I get for autocomplete-light is the same as Django material with django smart select error and then for django-select2 there is no error, but the widget doesn't render. -
Django Channels Ngix production
I have a django project and recently added channels to use websockets. This seems to all work fine, but the problem I have is to get the production ready. My setup is as follows: Nginx web server Gunicorn for django SSL enabled Since I have added channels to the mix. I have spent the last day trying to get it to work. On all the turtotials they say you run daphne on some port then show how to setup nginx for that. But what about having gunicorn serving django? So now I have guncorn running this django app on 8001 If I run daphne on another port, lets say 8002 - how should it know its par of this django project? And what about run workers? Should Gunicorn, Daphne and runworkers all run together? -
django with basic Jquery not responding
I have a django project which I implemented a jquery function to toggle a link but it is not working. the link does not display the hidden contect i want it to display on toggle. my code is written below. <a href="#" class="comment-reply-btn">REP</a> <div class="comment-reply" style="display: None;"> {% for child_comment in comment.children%} {{ child_comment.timestamp|timesince } {% endfor %} </div> <script type="text/javascript"> $(document).ready(function(){ $(".comment-reply-btn").click(function(event){ event.preventDefault(); $(this).parent().next("comment-reply").fadeToggle(); }) }) </script> -
Unable to create nested data in sending form data on post man
enter image description hereenter image description here I wants to create rewards and rewards question by sending the dto in form data. But i am unable to create rewards question. While i am consoling the request, it is showing Blank rewards question array -
Getting error while storing the file into folder using Django and Python
I am getting error while storing the file into folder using Django and Python. I am explaining the error below. Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/lampp/htdocs/rework/Nuclear/RFI15/vlnerable/plant/views.py", line 267, in downloadfile fyl.write(response) TypeError: expected a character buffer object [12/Sep/2017 10:52:35] "POST /downloadfile/ HTTP/1.1" 500 71558 Performing system checks... I am explaining my code below. def downloadfile(request): """ This function helps to download the file from remote site""" if request.method == 'POST': URL = request.POST.get('file') filename = "status.txt" response = HttpResponse(content_type='text/plain') response['Content-Disposition'] = 'attachment; filename='+filename with open(settings.FILE_PATH + filename, 'w') as fyl: fyl.write(urllib2.urlopen(URL).read()) fyl.write(response) return response I am getting that error in this fyl.write(response) line. Here I am including the remote file and download it. After downloading its storing inside the folder. Please help me to resolve this error. -
How to clear browser cache with python django?
I want to clear users browser cache using django. what i have tried i have simple function from django.core.cache import cache def clear(request): cache.clear() return Httpresponse('cleared') but it won't clears the cache is there any better option to this -
Disallow generic inline to add extra content object
I have a generic foreign key which is restricted to a single content object by setting the unique_together in metaclass as explained here. class Image(models.Model): image = models.ImageField(upload_to="images") content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") class Meta: unique_together = ('content_type', 'object_id') class Product(models.Model): name = models.CharField(max_length=100) And I'm using GenericInlineModelAdmin to render my admin page. But looks like GenericInlineModelAdmin is just made for many to one relationship. class ImageInline(GenericTabularInline): model = Image class ProductAdmin(admin.ModelAdmin): inlines = [ ImageInline, ] My admin page has multiple inline forms for Image #1, Image #2, Image #3 and also has a button to add another Image. Adding multiple images does not work (as expected) and results in error but I'm looking for a way to tell GenericInlineModelAdmin that this is a OneToOne relationship. I could add this to get rid of 3 inline Image forms on page render. class ImageInline(GenericTabularInline): model = Image extra = 0 Is there any way to remove the "add another image" button from my admin page? -
How to call the tables dynamically?
In my project there are 'n' n.o of dashboards and for one dashboard one table is required for querying(i.e; for example if i have 100 dashboards i will have 100 tables) Now if i click on one dashboard how can i call particular table only, is it possible without using if condition. Note: Whenever you click on dashboard one string will passed from frontend Example: If i have dasboard called 'Admin' if anyone clicks on it, it should hit and query from one table and same as for every dashboard -
Record create and Update time not stored in localtime django
I have a model "Member" where there are two fields "created_at" and "updated_at". Originally, they were defined as below : created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now_add=True, null=True) my settings.py have USE_TZ = True and TIME_ZONE = "America/New_York". I have a custom middleware defined to activate the timezone as selected by the user. current_tz = pytz.timezone("<user defined timezone>") timezone.activate(current_tz) Then, I update the fields to store the user localtime: created_at = models.DateTimeField(default= lambda: timezone.localtime(timezone.now()), null=True) updated_at = models.DateTimeField(default= lambda: timezone.localtime(timezone.now()), null=True) Now, when I update the Member record and check the updated_at time, its showing the same UTC timezone instead of the localtime of the user. Is it that django always stores datetime values in DB in UTC or am I missing something here -
Overview over possible excpetions thrown by boto3
I am developing a django app which communicates with several Amazon Web Services. So far I am having trouble dealing with and catching exceptions thrown by the boto3 client. What I am doing seems unnecessarily tedious: Example: client = boto3.client('sns') client.create_platform_endpoint(PlatformApplicationArn=SNS_APP_ARN, Token=token) this might throw an botocore.errorfactory.InvalidParameterException if e.g. the token is bad. client.get_endpoint_attributes(EndpointArn=endpoint_arn) might throw an botocore.errorfactory.NotFoundException. First, I can't find these Errors anywhere in code, so they are probably generated somewhere. Bottom line: I can't import it and catch it as usual. Second, I found one way to catch the error here using: try: # boto3 stuff except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == 'NotFound': # handle exception else: raise e But I have to remove the Exception part of the error name. Seems very random and I have no clue whether I would remove the Error in botocore.exceptions.ParamValidationError if I wanted to catch that one. So it's hard to generalize. Another way to catch the error is using the boto3 client object I got: try: # boto3 stuff except client.exceptions.NotFoundException as e: # handle exception This seems the cleanest way so far. But I don't always have the boto3 client object at hand where I want to … -
AttributeError: 'QuerySet' object has no attribute 'area'
I got an error,AttributeError: 'QuerySet' object has no attribute 'area' . I wanna parse excel and put it to the model(City&Prefecture&Area&User) . I wrote fourrows_transpose = list(map(list, zip(*fourrows))) val3 = sheet3.cell_value(rowx=0, colx=9) user3 = Companyransaction.objects.filter(corporation_id=val3) print(user3) if user3: area = Area.objects.filter(name="America") pref = Prefecture.objects.create(name="prefecture", area=user3.area) city = City.objects.create(name="city", prefecture=pref) price_u1000 = Price.upper1000.objects.get(city=city) price_500_1000 = Price.from500to1000.objects.get(city=city) price_u500 = Price.under500.objects.get(city=city) pref.name = "NY" pref.save() for i in range(len(fourrows_transpose)): city.name = fourrows_transpose[i][1] city.save() print(fourrows_transpose[i][1]) price_u1000.name = fourrows_transpose[i][2] price_u1000.save() print(fourrows_transpose[i][2]) price_500_1000.name = fourrows_transpose[i][3] price_500_1000.save() print(fourrows_transpose[i][3]) price_u500.name = fourrows_transpose[i][4] price_u500.save() print(fourrows_transpose[i][4]) models.py is class Area(models.Model): name = models.CharField(max_length=20, verbose_name='area', null=True) class User(models.Model): user_id = models.CharField(max_length=200,null=True) area = models.ForeignKey('Area',null=True, blank=True) class Prefecture(models.Model): name = models.CharField(max_length=20, verbose_name='prefecture') area = models.ForeignKey('Area', null=True, blank=True) class City(models.Model): name = models.CharField(max_length=20, verbose_name='city') prefecture = models.ForeignKey('Prefecture', null=True, blank=True) class Price(models.Model): name = models.CharField(max_length=20, verbose_name='price') city = models.ForeignKey('City', null=True, blank=True) I wanna put these data [['America', '', '', '', ''], ['', '', 'u1000', '500~1000', 'd500'], ['NY', 'City A', '×', '×', '×'], ['', 'City B', '×', '×', '×'], ['', 'City C', '×', '×', '×'], ['', 'City D', '×', '×', '×'], ['', 'City E', '×', '×', '×']] to models which is like 'America' to Prefecture's area and City A to City's name and × to … -
AttributeError in my django rest project
class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') class Meta: model = Snippet fields = ('url', 'id', 'highlight', 'owner', 'title', 'code', 'linenos', 'language', 'style') it is my SnippetSerializer class and also defined owner = serializers.ReadOnlyField(source='owner.username') i grts an error that AttributeError at /snippets/3/highlight/ 'Snippet' object has no attribute 'highlighted' could you solve it? -
How to download the file from remote source and saving it into local folder using Python
I need one help. I need to download the file from remote source and storing it into local folder using Python. I am explaining my code below. def downloadfile(request): """ This function helps to download the file from remote site""" if request.method == 'POST': URL = request.POST.get('file') #i.e-http://koolfeedback.com/beta/about-us.php filename = "status" with open(filename,'wb') as fyl: fyl.write(urllib2.urlopen(URL).read()) fyl.close() Here I need to download the page and store into the local download folder using zip format.Please help me. -
Validate specific field in DRF serializer
I have a model with a JSONField. model.py class Categories(models.Model): type = models.CharField(max_length=20) name = models.CharField(max_length=500) details = JSONField(blank=True, null=True) Currently I'm using serializers.ModelSerializer for serializing this above model: serializers.py class CategoriesSerializer(serializers.ModelSerializer): class Meta: model = Categories fields = ('id', 'type', 'name', 'details') Due to this, the details field is only checked to contain valid json. What i really need to do is to perform some custom validation based on the Json Schema defined for details field. However since I don't want any other custom validations for rest of the fields, I would like to keep using the validations provided by serializers.ModelSerializer. Is there any way I can override a validation for just one field, probably by writing a custom serializer for just the details field? Note question is not about how to write a custom Validator, but about how to use that custom validator on a field in the serializer inheriting ModelSerializer -
Django UserProfile signals create user, first_name, last_name
When i'm creating a UserProfile using the User data, i want to pass to first_name and last_name aswell. models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) first_name = models.CharField(max_length=200, blank=True, null=True, default=None) last_name = models.CharField(max_length=200, blank=True, null=True, default=None) def post_save_user(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(post_save_user, sender=settings.AUTH_USER_MODEL) I've tryed this using UserProfile.objects.create(user=instance, first_name=instance.first_name, last_name=instance.last_name) , it's creating the profile but it's not adding the first_name and last_name. Question: How can i add first_name and last_name to profile using the user data? -
Django models and relationships . error [duplicate]
This question already has an answer here: Django: Why do some model fields clash with each other? 7 answers Hi guys I have I guess a simple proving that I am missing something using models and relationships I have two models models one is a Team, that can have multiple user, and a user can be part of multiple teams and a project which get a name and is tied to on Team class Team(models.Model): member1 = models.ForeignKey(MyUser, blank= False) member2 = models.ForeignKey(MyUser, blank= False) member3 = models.ForeignKey(MyUser, blank= True) member4 = models.ForeignKey(MyUser, blank= True) member5 = models.ForeignKey(MyUser, blank= True) member6 = models.ForeignKey(MyUser, blank= True) class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team) When I try to migrate a get a big error website.Team.member1: (fields.E304) Reverse accessor for 'Team.member1' clashes with reverse accessor for 'Team.m ember2'. HINT: Add or change a related_name argument to the definition for 'Team.member1' or 'Team.member2'. website.Team.member1: (fields.E304) Reverse accessor for 'Team.member1' clashes with reverse accessor for 'Team.m ember3'. HINT: Add or change a related_name argument to the definition for 'Team.member1' or 'Team.member3'. website.Team.member1: (fields.E304) Reverse accessor for 'Team.member1' clashes with reverse accessor for 'Team.m ember4'. I know that I am missing something, could you help … -
creating one model for many apps in Django
I am developing a rest_api app, so i want to create a Users model for teacher_app, student_app and in future i ll add extra apps also. So i am stuck in that confusion, where the Users model i can create so i can use that in each app. here is my file structure. . ├── learnwiz │ ├── __init__.py │ ├── old_settings.py │ ├── __pycache__ │ │ ├── __init__.cpython-35.pyc │ │ ├── urls.cpython-35.pyc │ │ └── wsgi.cpython-35.pyc │ ├── settings │ │ ├── base.py │ │ ├── __init__.py │ │ ├── local.py │ │ ├── production.py │ │ └── __pycache__ │ │ ├── base.cpython-35.pyc │ │ └── __init__.cpython-35.pyc │ ├── urls.py │ └── wsgi.py ├── manage.py ├── requirements.txt └── teacher_app ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── __init__.py │ └── __pycache__ │ └── __init__.cpython-35.pyc ├── models.py ├── __pycache__ │ ├── admin.cpython-35.pyc │ ├── __init__.cpython-35.pyc │ ├── models.cpython-35.pyc │ ├── serializers.cpython-35.pyc │ └── views.cpython-35.pyc ├── serializers.py ├── tests.py └── views.py -
form_valid cannot be called in Django
I followed an excellent guide (https://matthewdaly.co.uk/blog/2016/03/26/building-a-location-aware-web-app-with-geodjango/ ) and developed an application in Django 1.9 / Python 3 which works fine. Now I'm trying to integrate the above application in a real django project in Django 1.8 / Python 2.7. I followed again the above guide modifying the code for Django 1.8 / python 2.7. I have an issue when I submit the data. The form_valid cannot be called. My models.py: from django.contrib.gis.db import models class Venue(models.Model): name = models.CharField(max_length=200) location = models.PointField() def __str__(self): return self.name class Event(models.Model): name = models.CharField(max_length=200) datetime = models.DateTimeField() venue = models.ForeignKey(Venue) def __str__(self): return "%s - %s" % (self.name, self.venue.name) My views.py: class LookupView(FormView): template_name = 'gigs/lookupresults.html' form_class = LookupForm success_url = '/' def get(self, request): self.form_valid(form) return render_to_response('gigs/lookup.html', RequestContext(request)) def form_valid(self, form): # Get data latitude = form.cleaned_data['latitude'] longitude = form.cleaned_data['longitude'] # Get today's date now = timezone.now() # Get next week's date next_week = now + timezone.timedelta(weeks=1) # Get Point location = Point(longitude, latitude, srid=4326) # Look up events events = Event.objects.filter(datetime__gte=timezone.now()).filter(datetime__lte=next_week) # Render the template return render_to_response('gigs/lookupresults.html', { 'events': events }) my urls.py: urlpatterns = patterns( 'my_project.gigs.views', url(r'^$', LookupView.as_view(), name='lookup'), ) my forms.py: from django.forms import Form, FloatField class LookupForm(Form): latitude … -
send image using http post to django restfull api
fileChange(event) { debugger; let fileList: FileList = event.target.files; if (fileList.length > 0) { let file: File = fileList[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() headers.append('Authorization', this.token); headers.append('Content-Type', 'application/json'); headers.append('Content-Disposition', 'form-data; filename="'+file.name+'"'); // Content-Disposition: form-data; name="fieldName"; filename="filename.jpg" headers.append('Content-Type', 'multipart/form-data'); let options = new RequestOptions({ headers: headers }); // let apiUrl1 = "/api/UploadFileApi"; this.http.post('http://192.168.1.160:8000/profilepic/', {FormData:formData}, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => alert('success'), error => alert(error) ) } // window.location.reload(); } <input class="uploadfile-style" [(ngModel)]="FilePath" (change)="fileChange($event)" name="CContractorFPath" size="10" type="file" enctype="multipart/form-data"> Hii I have write this code for post image in angular 2...but it shows error Unsupported media type \"application/json,multipart/form-data\" in request same file accepted when i post it from Postman following are two different curl commands 1. This is accepted by Json curl -X POST \ http://192.168.1.223:8010/profilepic/ \ -H 'authorization: Basic YWRtaW46YWRtaW4=' \ -H 'cache-control: no-cache' \ -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \ -H 'postman-token: 794107c3-791d-e198-fe36-48f407a3ec8c' \ -F datafile=@/home/ashwini/Pictures/b.jpeg 2. This is not accepted by API curl 'http://192.168.1.223:8010/profilepic/' -H 'Authorization: 6df62b2d808c15acbdd8598d0153c8ca7e9ea28a' -H 'Origin: http://localhost:4201' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-GB,en-US;q=0.8,en;q=0.6' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36' -H 'Content-Type: application/json,multipart/form-data' -H 'Accept: application/json, text/plain, */*' -H 'Referer: … -
Recursive many-to-many relationship with Django RestFramework
I want to make a recursive many to many relationship. I have games and each game promote another games. And each game got a list of assets. I'm using Django and Django RestFramework. my models.py class Game(models.Model): name = models.CharField(max_length=30, unique=True, blank=False, null=False) promote_games = models.ManyToManyField("self", through='GamePromoted', symmetrical=False, ) class Meta: db_table = 'Game' class GamePromoted(models.Model): game = models.ForeignKey(Game, related_name='games_promoted') game_promoted = models.ForeignKey(Game, related_name='games') class Meta: db_table = 'Game_Promoted' unique_together = ('game', 'game_promoted') and my serializers.py class GamePromotedSerializer(serializers.ModelSerializer): ??????? class Meta: model = GamePromoted fields = ('id', 'game_id', 'name', 'assets') class GameSerializer(serializers.ModelSerializer): assets = AssetSerializer(many=True, read_only=True) games_promoted = GamePromotedSerializer(many=True, read_only=True) class Meta: model = Game fields = ('id', 'name', 'assets', 'games_promoted') and I want this kind of result GET /games/1 { "id": 1, "name": "Game1", "assets": [{...}], "games_promoted": [ { "id": 1, "game_id": 2, "name": "Game2" "assets": [{...}] }, { "id": 2, "game_id": 3, "name": "Game3" "assets": [{...}] } ] } And I want to add a game to promote in a game with POST /games/1/ (game_id=1&game_promoted_id=5) for exemple So I'm stuck in the serializers.py, I think my models are good. Thanks for help. -
Can anybody explain me how celery group worked?
When I use celery group and chains to schedule the tasks as below (group([group_task]) | sum_task).apply_async() the group tasks can be executed in many workers, after all group tasks finished, sum_task begin to execute(maybe in the other worker), so who can tell me how celery known the group tasks are all finished and then started the sum_task?