Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, render a model in template
How can I render a model from a template? Lets say I have: class A(models.Model): title = models.CharField() class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) class C(B): text = models.TextField() integer = models.IntegerField() class D(B): image = models.ImageField() comment = models.CharField(max_length=300) Current template for A: <h1> {{ a.title }}</h1> <div> {% for b in a.b_set.all %} <!-- What do I put here? --> {% endfor %} </div> In the template for A I would like to render all instances of C and D, but since they have different fields their HTML will have to be different. How do I specify how each model should be rendered? Do I need to create a special method in the models? -
NoReverseMatch - Reverse for 'step-autocomplete' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
First of all I realize this question has been asked several times prior, but I've looked at several solutions and have been unable to fix my issue. Furthermore, I have tried several things that have worked for me before when I've had this error, including using various 'return redirect/reverse/httpresponse' with arguments, and these haven't worked either. I'm following this tutorial https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.rst#id5 to create autocomplete fields, and in the second stage where I go into the shell and check if the url can be reversed I get the NoReverseMatch error. My view and url are below. View: class StepAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Step.objects.none() qs = Step.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs form: url(r'^step-autocomplete/$', StepAutoComplete.as_view(), name='step-autocomplete'), traceback: File "<console>", line 1, in <module> File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py", line 600, in reverse return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py", line 508, in _reverse_with_prefix (lookup_view_s, args, kwargs, len(patterns), patterns)) NoReverseMatch: Reverse for 'step-autocomplete' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] -
csrf token missing in django ajax post request working using get request
I am working with metronic datatables in which i have a file where ajax function works. The problem is that when I use type in ajax function "GET" it works but in POST it does not work and it gives CSRF token missing error in console, but in case of GET it does not give any error, I am using django framework for my site and my ajax function is :- "ajax": { // define ajax settings "url": document.URL, // ajax URL "type": "POST", // request type "timeout": 20000, "data": function(data) { // add request parameters before submit $.each(ajaxParams, function(key, value) { data[key] = value; }); Metronic.blockUI({ message: tableOptions.loadingMessage, target: tableContainer, overlayColor: 'none', cenrerY: true, boxed: true }); }, } -
ModelForm won't validate because missing value, but model field has null=True
I have a problem where my ModelForm is trying to assign '' to a field (it saves fine if I actually provide the primary key of the Product, but it's not a compulsory field, and won't save if the field is left blank). I take it that the ORM it's trying to set that field to ''but: Shouldn't '' be coerced to None, and; Why isn't the model form trying to set that field to None in the first place instead of ''? models.py class Question(models.model): fk_product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, related_name="product_question") forms.py class QuestionForm(forms.ModelForm): fk_product=forms.ChoiceField(required=False) class Meta: model = Question fields = ['fk_product',] The error: Cannot assign "''": "Question.fk_product" must be a "Product" instance. The view code that produces the error: QuestionModelFormset = modelformset_factory(Question, form=QuestionForm, extra=1) question_formset = QuestionModelFormset( data=request.POST, files=request.FILES, queryset=Question.objects.all()) if not question_formset.is_valid(): #error occurs on this line -
nginx connection error with gunicorn
I am learning nginx and configuring nginx.conf with gunicorn, but i am not able to do. I am running gunicorn on 8000 port and niginx listening on 80 port. Sometimes it works fine, sometimes it gives unable to connect error. here is my nginx.conf file user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; -
The user gets logged in but still shows login in navbar
I am using DRF and DOT(Django oAuth Toolkit) for backend and authentication. I have created a login system where user are logged in using token. I get Http 200 ok when logging in but still shows login in the navbar. Why is that so? Is not my login functionality fully functional? class UserLoginAPI(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): access_token = request.GET.get('access_token') data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data if new_data: app = Application.objects.get(name="myapp") user = User.objects.get(username=new_data['username']) print('user',user) try: print('trying to fetch old token if exists') old_token = AccessToken.objects.get(user=new_data, appliction=app) print('old_token',old_token) except: pass else: old_token.delete() new_token = generate_token() print('new_token',new_token) AccessToken.objects.create(user=user, application=app, expires=datetime.now() + timedelta(days=365),token=new_token) print('aceess',AccessToken) return Response(new_data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class UserLoginSerializer(ModelSerializer): username = CharField() # email = EmailField(label='Email Address') class Meta: model = User fields = [ 'username', 'password', ] -
MySQL django backend unknown system variable
I have the following in my settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': '/etc/django/mysql_client.cnf' }, }, } and in the default file - [client] database = lab_website host = myschoolhost.edu user = myuser password = ********* default-character-set = utf8 port = 21 #using this port because its not being used by ftp I can use django manage.py runserver just fine, so the credentials are validating. However when it's time to migrate: File "/Users/jordanwillis/anaconda/lib/python2.7/site-packages/django/db/backends/mysql/validation.py", line 14, in _check_sql_mode cursor.execute("SELECT @@sql_mode") File "/Users/jordanwillis/anaconda/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/Users/jordanwillis/anaconda/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/jordanwillis/anaconda/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Users/jordanwillis/anaconda/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "/Users/jordanwillis/anaconda/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 112, in execute return self.cursor.execute(query, args) File "/Users/jordanwillis/anaconda/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute self.errorhandler(self, exc, value) File "/Users/jordanwillis/anaconda/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue django.db.utils.OperationalError: (1193, "Unknown system variable 'sql_mod_'") It looks to me that it's trying to get the SQL_MODE and failing. I have tried setting the SQL_MODE for this database to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 'read_default_file': '/etc/django/mysql_client.cnf' }, }, } as it's specified here in the django but … -
pypi pakcage automatically uninstalling and upgrading other things?
I have a pypi package that I distribute that requires django, in my setup.py I have this... install_requires = ["Django"] then in the egg I have a requires.txt file that is like this... Django Now I just made a new version and uploaded it to pypi and did pip install -U mypackage and it uninstalled my current django 1.10 and reinstalled django 1.10.1. How can I make it leave the users Django version alone? -
Django Rest Framework ManyToMany Filter
I have two models, one defining users, the other defining labels on these users. I am using Django Rest Framework to create an API. I would like to be able to query users for with labels ids 1 and 2. So far, I've managed to query users with a given label (let's say id=1) by doing: /api/users/?labels=1, but I am unable to query users with labels 1 and 2. I've tried /api/users/?labels=1,2 or /api/users/?labels=1&labels=2 but it return some invalid users, i.e. users without labels 1 or 2... Any help is welcome. Thanks, Dimitry Here is my code: models.py class Label(models.Model): name = models.CharField(max_length = 60) class User(models.Model): labels = models.ManyToManyField(Label) filters.py class UserFilter(django_filters.FilterSet): labels = django_filters.filters.BaseInFilter( name='labels', lookup_type='in', ) class Meta: model = User fields = ('labels',) serializers.py class LabelSerializer(serializers.ModelSerializer): class Meta: model = Label fields = ('id','name') class UserSerializer(serializers.ModelSerializer): labels = LabelSerializer(many = True) class Meta: model = User fields = ('labels',) filter_class = UserFilter views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = UserFilter filter_fields = ('labels',) -
Django 1.95 template i18n not working
I am trying to translate the string from English to zh-hans In the settings.py LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I have run the python manage.py makemessages -l zh-hans and python manage.py makemessages -a for many times. The .po file is simple as following: msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-09-07 09:53+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: blog/views.py:18 msgid "author" msgstr "作者" In the html file: <div id = "info"> <p> {% trans "author" %} : {{ blog.author }} </p> </div> The tag returns "author" instead of Chinese characters. Also I have tried ugettext in view.py def detail(request, slug): blog = get_object_or_404(Post, slug=slug) msg = _("author") print(msg) context = { 'blog': blog, 'author': msg, } return render(request, 'blog/detail.html', context) The msg is still "author". Using {% get_current_language as LANGUAGE_CODE %} {{ LANGUAGE_CODE }} The language code is zh-hans. So what's going wrong here? How to show the translated string in the template? Thank you -
Using named arguments as variables
I am using django but I think this question primarily belongs to Python itself. I have something like: def get(self, request, arg, *args, **kwargs): if kwargs['m0'] == 'death': if kwargs['m1'] == 'year': result = Artists.objects.filter(death_year=arg) elif kwargs['m1'] == 'month': result = Artists.objects.filter(death_month=arg) elif kwargs['m1'] == 'day': result = Artists.objects.filter(death_day=arg) elif kwargs['m0'] == 'birth': if kwargs['m1'] == 'year': result = Artists.objects.filter(birth_year=arg) elif kwargs['m1'] == 'month': result = Artists.objects.filter(birth_month=arg) elif kwargs['m1'] == 'day': result = Artists.objects.filter(birthh_day=arg) Where death_year is a named argument that is a field in my model Artists representing a column in my database. The variables 'm0' and m1 are passed from the urlconf to my get function (it is actually a get method in my view class). Can I control the name value of the variable death_year without using an if else if chain (i.e. make it death_month or birth_year)? Since I have many choices, I will have to use a ridiculously very long conditional chain that leads to this same line but with just a different named argument. I strongly doubt that you should understand this whole problem to answer the question. The original question is simple: Can I use a named argument and its corresponding value as … -
Django form and many2many.through field
I'm building a wizard (using Django Formtools) that would allow one to order one or several items, with the possibility for each selected item to specify the quantity desired. I'd like to avoid the classical cart system and make the purchase as simple as possible. My navigation proposal is to have only 3 pages/steps: the first page show a form with all the available items. those items can be selected and visitors can specify a quantity. the second page makes a summary of the order and visitors are asked to fill their details the last page confirms the order I'm having troubles creating the form for the first step and I'm looking for help to find a middleground between the two options I tried. My Django models look like this (simplified for the demonstration): class Item(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=5, decimal_places=2) class Order(TransactionBase): items = models.ManyToManyField(Item, through='OrderedItem') class OrderedItem(models.Model): order = models.ForeignKey(Order) item = models.ForeignKey(Item) quantity = models.PositiveSmallIntegerField() Using the following ModelForm I'm able to list all the available Items: class OrderSelectionForm(forms.ModelForm): class Meta: model = Order fields = ('items',) widgets = { 'items': forms.CheckboxSelectMultiple(), } But it doesn't allow for specifing the quantity... Using the following code, … -
Use django models objects in AngularJs javascript file
How can I use my django Models objects in a AngularJS javascript file? I think I did al the necessary things but still can't use them in my angularjs file. On google & stackoverflow there isn't a clear post about this so maybe this would be good for many people angularjs file: app = angular.module("coco",[]); app.config(function($interpolateProvider) { $interpolateProvider.startSymbol('[['); $interpolateProvider.endSymbol(']]'); }); app.controller('cocoCtrl',['$scope',function($scope){ $scope.cashflows = {}; $scope.pvBond = {}; $scope.num = 0; $scope.save = function(cashflow){ //$scope.newCashflow = new Cashflow(index,value,date) or other things like .create or .save doesn't work. tried them all.. $scope.pvBond[$scope.num] = cashflow.value; $(".data").html("Click" + cashflow.value); $scope.num += 1; }; }]) Models.py: from django.db import models class Cashflow(models.Model): value = models.FloatField(); date = models.DateField(); serializer.py: class CashflowSerializer(serializers.ModelSerializer): class Meta: model = Cashflow fields = ('index', 'value', 'date') views.py: class CashflowViewSet(viewsets.ModelViewSet): queryset = Cashflow.objects.all() serializer_class = CashflowSerializer urls: from django.conf.urls import url, include from pricing import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'cashflows', views.CashflowViewSet) urlpatterns = [ url(r'^$', views.calc,name='calc'), url(r'^api/', include(router.urls)), ] -
What are some open-source projects that will help me build a REST API in Python?
I have some Python modules that I want to make available on the web through a URL that will pass some parameters to the modules and return some results. What are some open source packages/ projects that will help me do that? -
How to localize date in Jinja2 + Django?
I have Jinja 2.8 and Django 1.9.9 and want to localize month as: June -> Июнь Django settings.py: LANGUAGE_CODE = 'ru-ru' TIME_ZONE = 'Europe/Moscow' USE_I18N = True USE_L10N = True USE_TZ = True Jinja2 config.py: def environment(**options): env = Environment( extensions=[ 'jinja2.ext.with_', 'jinja2.ext.loopcontrols', 'jinja2.ext.i18n' ], **options ) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse }) return env Template: {% trans %} foo.date.strftime('%B') {% endtrans %} I had installed i18n extension for Jinja2, configured Django for localization, write template, and has this error: I'm used official Jinja2 docs (link1, link2), but this doesn't work for me. How I can do it? -
django inspectdb 'unique_together' refers to the non-existent field
I have a legacy database that I wish to use as a second database in my django project. I added the database to my settings file, and ran: python manage.py inspectdb --database=images The script finished in less than a second, and the results were astounding. It understood all my tables - or so I thought at first. When I tried to run: python manage.py migrate --database=images I got errors like this: 'unique_together' refers to the non-existent field 'commentaryId'. All of the tables that raised errors were many-to-many linking tables containing two id fields that together formed the primary key (and thus had to be 'unique together'). Here is one of the models, created by inspectdb, that raised this error: class Pagescanannotationscommentaries(models.Model): pagescanannotationid = models.IntegerField(db_column='pageScanAnnotationId') # Field name made lowercase. commentaryid = models.IntegerField(db_column='commentaryId') # Field name made lowercase. class Meta: managed = False db_table = 'PageScanAnnotationsCommentaries' unique_together = (('pageScanAnnotationId', 'commentaryId'),) I found several questions like mine in stackoverflow, but the suggestions did not help me, or were obviously not relevant. But I did find a post in google groups that gave me the tip that fixed it: https://groups.google.com/forum/#!topic/django-users/_phTiifN3K0 But even then, my problem was a bit different, I found, and I … -
MultiValueDictKeyError after trying to log in
Whenever I log in inside a Django webapp I made, I'm getting a MultiValueDictKey error. This is my views.url: from django.shortcuts import render from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse, HttpResponseRedirect from bookonshelf import settings from django.contrib.auth.decorators import login_required def Login(request): next = request.GET.get('next', '/home/') if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect(next) else: return HttpResponse("Inactive user.") else: return HttpResponseRedirect(settings.LOGIN_URL) return render(request, "index/login.html", {'redirect_to': next}) def Logout(request): logout(request) return HttpResponseRedirect(settings.LOGIN_URL) @login_required def Home(request): return render(request, "index/home.html", {}) def Blog(request): return render(request, "index/blog.html", {}) I already tried changing request.POST to request.POST.get after reading some similar problems online, but that's not working for me. How do I solve this? -
javascript event handler not correctly work in django inline formset
I designed a inline formset as follows: class EventForm(ModelForm): class Meta: model = Event exclude = ['created'] class GalleryForm(ModelForm): class Meta: model= Gallery exclude = ['pub_date'] GalleryFormSet = inlineformset_factory(Event, Gallery, extra=0, min_num=1, fields=('title','image' )) It worked correctly when used 'extra = some number' and saved gallery form data correctly. But when I used javascript handler to add additional gallery form below the main Event form, it creates two Gallery form instead of 1 and data and photo not saved from the newly added form. Here is my event handler: <script type="text/html" id="gallery-template"> <div id="gallery-__prefix__"> {{ formset.empty_form }} </div> </script> <script> $(function() { $('.add-photo').click(function(ev){ ev.preventDefault(); var count = parseInt($('#id_gallery_set-TOTAL_FORMS').attr('value'), 10); var tmplMarkup = $('#gallery-template').html(); var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count) console.log(compiledTmpl); $('div.gallery').append(compiledTmpl); $('#id_gallery_set-TOTAL_FORMS').attr('value', count); }); }); </script> My formset template: <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {{ formset.management_form }} {% csrf_token %} <legend>Events</legend> <div class="author"> {{ form.as_p}} </div> <legend> <div class="pull-right"><a href="#" class="btn btn-inverse add-photo"><i class="icon-plus icon-white"></i> Add Photo</a></div> Gallery </legend> <div class="gallery form-inline"> {% for form in formset %} {{ form.as_p }} {% endfor %} </div> <div class="form-group"> <div class="col-sm-offset-6 col-sm-6"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> For your information, when I edit this formset then data and image saved correctly. … -
JS/Jquery issue when deploying Django site on with Gunicorn/Nginx (on DigitalOcean)
TL;DR. Main question at the bottom. I've made a django website and wanted to dynamically make an image fill in a div tag. Here's the JS/JQuery function I wrote: function changeBGSize(){ $(document).ready(function(){ var posX = -1 * (($("#myPic").width())/2); var posY = -1 * ($("#myPic").height() - $(window).outerHeight())/2; $("#myPic").css("margin-left", (posX + "px")); $("#myPic").css("margin-top", (posY + "px")); }) } Inside the HTML I have an image with the ID myPic nested in divs. It might be useful to add that I'm also using Bootstrap v3. I call the above function in 2 ways: window.onload = changeBGSize; in the main JS <body onresize="changeBGSize();"> in the HTML WHen I deploy the website on local host using python manage.py runserver the website works fine and the picture is centered as I want it. But the problem is when I deploy it to my DigitalOcean droplet. My droplet is a linux ubuntu 14 machine, and uses Gunicorn and Nginx to serve static files. For some reason the JQuery function above does not work when the screen is loaded, but it works when called through the onresize event. After debugging I've come to realize that $("#myPic").height() gives the wrong value when first called. In fact its value is … -
Server error occurs when returning a rendered response in django
When trying to run the code on the book tango with django, i came accross a server error problem when i got to the install template section. please find the code below. from django.shortcuts import render def index(request): # Construct a dictionary to pass to the template engine as its context. # Note the key boldmessage is the same as {{ boldmessage }} in the template! context_dict = {'boldmessage': "Crunchy, creamy, cookie, candy, cupcake!"} # Return a rendered response to send to the client. # We make use of the shortcut function to make our lives easier. # Note that the first parameter is the template we wish to use. return render(request, 'rango/index.html', context=context_dict) And at the settings.py file i made changes to the template section. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') And this is the template i installed: <!DOCTYPE html> <html> <head> <title>Rango</title> </head> <body> <h1>Rango says...</h1> <div> hey there partner! <br /> <strong>{{ boldmessage }}</strong><br /> </div> <div> <a href="/rango/about/">About</a><br /> </div> </body> </html> I have check countless times but i can't seem to find any places that'd be causing an error. Please any help would be appreciated. Bare in mind that i'm still kind of a … -
Two way upload image in ImageField
I want to create widget for django-admin for upload images from url or use default file-input. class ImageFieldFromUrlWidget(ClearableFileInput) : def render(self, name, value, attrs=None): base_content = super(ImageFieldFromUrlWidget, self).render(name, value, attrs=attrs) ps_input = URLInput().render(name='ps_%s'%name, value='', attrs={}) return mark_safe(ps_input + base_content) def value_from_datadict(self, data, files, name): if data.get('ps_%s' % name, False) : import io, requests from urllib import request raw_image = requests.get(data.get('ps_%s' % name)).content new_file = InMemoryUploadedFile(io.BytesIO(raw_image), None, 'temp.jpg', 'jpeg', None, None) files[name] = new_file return super(ImageFieldFromUrlWidget, self).value_from_datadict(data, files, name) I want to download file and put it to files-array for process default save. But when I send data, I get the error "The submitted file is empty". How do this? Any ideas? PS I need to control get-request, for download image (set cookie) -
Django admin site customize to display group filters
I am trying to customise the admin site of django and was trying to display the group included for a particular user and found out the below working code . As I am new to this environment. can anyone please explain how this class works line by line . bonus: display group as a user filter: class SBUserAdmin(UserAdmin): list_filter = UserAdmin.list_filter + ('groups__name',) list_display = ('username','custom_group', ) def custom_group(self, obj): """ get group, separate by comma, and display empty string if user has no group """ return ','.join([g.name for g in obj.groups.all()]) if obj.groups.count() else '' admin.site.unregister(User) admin.site.register(User, SBUserAdmin) in def custom_group(self, obj): what is passed to the obj. -
How to check the raw sql statement of getting the foreign key set of a model instance?
In Django I have two models User and Post like this: class User(models.Model): username = models.CharField('username', max_length=10) class Post(models.Model): user = models.ForeignKey(User) u1 = User.objects.get(pk=1) Now, I want to know the raw sql statement of u1.post_set, but there seems no api for this. -
Use Django model class in javascript (angularjs)
Like the title is saying i'm trying to use my model class in model.py in my javascript file to CREATE a object. I looked around and tried things like: b = Cashflow.objects.create(value=cashflow.value, date= cashflow.date); and b = Cashflow(value=cashflow.value, date= cashflow.date); b.save(); and b = Cashflow(value=cashflow.value, date= cashflow.date); but nothing works. The values are correct. I found this question on stackoverflow with the same issue but it got no good answer: Create javascript object (class) from django model -
How to add different product to an ad from product sets in facebook marketing?
I have completely read out the documentation of dynamic facebook marketing.Also successfully created an ad based on custom audience and pixel events.But the problem is that every time i am creating an ad it shows same product in ad templates. Here is the code for setting up the Product set product_set = ProductSet(None, <CATALOG ID>) # <CATALOG ID> product_set[ProductSet.Field.name] = 'Product Set' product_set[ProductSet.Field.filter] = { 'product_type': { 'i_contains': 'example product type', }, } product_set.remote_create() product_set_id = product_set[ProductSet.Field.id] And Code for creating AD after setting campaign and adset : adset = AdSet(parent_id='<ACCOUNT_ID>') adset[AdSet.Field.name] = 'Product Adset' adset[AdSet.Field.bid_amount] = 9100 adset[AdSet.Field.billing_event] = AdSet.BillingEvent.link_clicks adset[AdSet.Field.optimization_goal] = AdSet.OptimizationGoal.link_clicks adset[AdSet.Field.daily_budget] = 45500 adset[AdSet.Field.campaign_id] = campaign_id adset[AdSet.Field.targeting] = { Targeting.Field.publisher_platforms: ['facebook', 'audience_network'], Targeting.Field.device_platforms: ['desktop','mobile'], Targeting.Field.geo_locations: { Targeting.Field.countries: ['IN'], }, Targeting.Field.product_audience_specs: [ { 'product_set_id': product_set_id, 'inclusions': [ { 'retention_seconds': 2592000, 'rule': { 'event': { 'eq': 'ViewContent', }, }, }, ], 'exclusions': [ { 'retention_seconds': 259200, 'rule': { 'event': { 'eq': 'Purchase', }, }, }, ], }, ], Targeting.Field.excluded_product_audience_specs: [ { 'product_set_id': product_set_id, 'inclusions': [ { 'retention_seconds': 259200, 'rule': { 'event': { 'eq': 'ViewContent', }, }, }, ], }, ], } adset[AdSet.Field.promoted_object] = { 'product_set_id': product_set_id, } adset.remote_create() adset_id = adset[AdSet.Field.id]