Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Build-in views?
I installed a module to Django and this module has ceertain views within itself. Also it comes with a demo to see the features. I am looking at the code from the demo for a while now but I cant figure out how a template is rendered over the build in views. The module i'm working with is swingtime: Here is an example: Excerpt from the template: <a class="plain" href="{% url 'swingtime-daily-view' prev_day.year prev_day.month prev_day.day %}"> URL Directory urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='intro.html'), name='demo-home'), url(r'^karate/', include('karate.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^docs/?$', RedirectView.as_view(url='/docs/index.html', permanent=True)), url(r'^docs/(?P<path>.*)$', serve, dict(document_root=doc_root, show_indexes=False)) ] So the url must somehow link to a built-in template i suppose? When I try to implement similar code in my project the url can not be reversed? And also: How would one edit the template for such a build in view? Thank you! -
Heroku Deployment with Django: Webpack Bundle returns content of index.html instead of actual bundle
The application runs fine in development, but once in production the generated webpack bundle file is serving the contents of index.html and not all the bundled modules and dependencies. Whenever I check the bundle file on the server, everything seems alright, but the same path is served differently on the client. webpack.config.js //require our dependencies var path = require('path') var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { //the base directory (absolute path) for resolving the entry option context: __dirname, //the entry point we created earlier. Note that './' means //your current directory. You don't have to specify the extension now, //because you will specify extensions later in the `resolve` section entry: [ './assets/js/index' ], output: { path: path.resolve('./assets/bundles/'), filename: "[name]-[hash].js" }, plugins: [ //tells webpack where to store data about your bundles. new webpack.NoErrorsPlugin(), // don't reload if there is an error new BundleTracker({filename: './webpack-stats.json'}), //makes jQuery available in every module new webpack.ProvidePlugin({ jQuery: 'jquery', 'window.jQuery': 'jquery' }) ], module: { loaders: [ // we pass the output from babel loader to react-hot loader { test: [/\.js$/, /\.es6$/, /\.jsx?$/], exclude: /node_modules/, loaders: ['babel'], }, { test: /\.css$/, loader: "style-loader!css-loader" } ] }, resolve: { //tells webpack where … -
Adapt a class method to another class
@python_2_unicode_compatible class EmployerProfile(AbstractAddress): customer = models.OneToOneField( CustomerProfile, verbose_name=_('Customer'), related_name='employerprofile') company_name = models.CharField(_('Company name'), max_length=50, blank=True, null=True) ... #That function will empty all fields in this model whenever income_source # is different of 'Employed' def empty_fields(self): if self.income_source != 'Employed': to_empty = [f.name for f in EmployerProfile._meta.get_fields()] exclude = [u'id', "has_missing_fields", "manual_validation", "actor_actions", "target_actions", "action_object_actions", ] for field_name in to_empty: if field_name not in exclude: setattr(self, field_name, None) @python_2_unicode_compatible class FinancialProfile(models.Model): customer = models.OneToOneField( CustomerProfile, verbose_name=_('Customer'), related_name='financialprofile') income_source = models.CharField(_('Income source'), max_length=20, choices=settings.LOANWOLF_INCOME_SOURCE_CHOICES, default='employed') I would like to move empty_field() in the class FinancialProfile. In fact, this method must emptied the attributes from EmployerProfile whenever income_source (FinancialProfile) != 'Employed'. Could anyone be able to tell me how could I do such thing? P.S. Please tell me if there's something unclear. Thanks in advance! -
Learning multi tables joining info django
While i find this post Django views.py Version of SQL Join with Multi Table Query helpful. It does not seem to help me with understading joining tables. I had earlier help on a question and I thought I got it. I am trying to do the following show (current) players on the Boston Penguins. Code I have currently trying to pull it is Player.objects.filter(team__all_teams__contains='boston', player__curr_team__contains="Penguins") Which by reasoning anyway puts me in the Player.objects of my model and should be filtering from my team all the teams with Boston which there is on and then should pull all the current players for that team. Even better than just giving me an answer is a link to a video or document that better explains this so I can study it better to learn the call functions. Models.py from django.db import models class League(models.Model): name = models.CharField(max_length=50) sport = models.CharField(max_length=15) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Team(models.Model): location = models.CharField(max_length=50) team_name = models.CharField(max_length=50) league = models.ForeignKey(League, related_name="teams") class Player(models.Model): first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) curr_team = models.ForeignKey(Team, related_name="curr_players") all_teams = models.ManyToManyField(Team, related_name="all_players") views.py only line i need help with rest works fine if i take out that line "bostonp" : … -
No Reverse Match For Some URLs in Django 1.10
I am making an web app in Django 1.10 and am getting an annoying error which I cannot seem to resolve. In this project there are several Django app whose URLs function without problems and seem to have similar setup as the new Account app. However, this authentication app is giving me trouble. What's more, the account/register URL works successfully and inserts a user into the database. I am not sure why some URLs work and other do not. Here is the error: NoReverseMatch at /account/login/ Reverse for 'dashboard' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Request Method: POST Request URL: http://localhost:8000/account/login/ Django Version: 1.10.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'dashboard' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I have the following directory structure: Project's url.py: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^account/', include('account.urls', namespace='account')), url(r'^orders/', include('orders.urls', namespace='orders')), url(r'^shop/', include('shop.urls', namespace='shop')), url(r'^cart/', include('cart.urls', namespace='cart')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Account app urls.py: urlpatterns = [ # url(r'^login/$', views.user_login, name='login'), url(r'^$', views.dashboard, name='dashboard'), url(r'^register/$', views.register, name='register'), url(r'^edit/$', views.edit, name='edit'), … -
Django's custom template tag deletes HTML content
I've created a custom tag to hide zero values from HTML. I use this for hiding currency formatted numbers when its values are zero. This is my custom tag: def hideifz(value): return '' if value == 0 else value The problem is that this tag deletes some of my HTML. This is the relevant part of my template: <div class="price"> <span class="price-new">{{ publication.price_record.low_price|CLP }}</span> <span class="price-old">{{ publication.price_record.high_price|hideifz|CLP }}</span> </div> This HTML is for showing product prices. publication.price_record.low_price and publication.price_record.high_priceare the prices of my product. If the product is in sale, it must have high_price != 0, and this value must be shown in the HTML. CLP is just another tag for currency formatting: def toCLP(value): if not value: return value return '$'+intcomma(int(value)).replace(',', '.') If high_price is not zero, the output HTML is okay. For example: <div class="price"> <span class="price-new">$75.990</span> <span class="price-old">$83.990</span> </div> In the other hand, if high_price is zero, some of my HTML is deleted: <div class="price">$21.990</div> Note that span.price-new and span.price-old were removed. Now, if I remove the hideifz tag, the output of the previous example look like this: <div class="price"> <span class="price-new">$21.990</span> <span class="price-old">0.0</span> </div> The spans are back when I remove the hideifz tag. I just … -
Django REST Framework: nested serializer create methods
What is the correct way to implement the nested create-methods? I have a structure like TopLevelSerializer() HigherMiddleSerializer() LowerMiddleSerializer() BottomSerializer() These are all of type serializers.Serializer, not serializers.ModelSerializer. All of these serializers map to objects I'd like to create and I have implemented the create methods. What I want to achieve is sending the data to TopLevelSerializer() only and it will handle all the rest and return a complete instance of TopLevelObject() with all the nested objects in place. I kinda got this done already, but I seem to be duplicating all the lower level create-method code in the higher level ones and can't seem to understand how to get the objects from the create methods I've implemented for the lower level ones. I tried something like this, but that's what lead me down the code duplication path. What's the correct way to handle this? -
Django JWT token deactivate
I'm creating an API for an android application I'm using Django Rest framework JWT token for API authentication. In perticular case, I want to deactivate the token which is activated for a particular user. -
How to integrate Haystack with Django Rest Framework for making GET REST API for searching?
model.py class Item(models.Model): name=models.CharField(max_length=50) company=models.CharField(max_length=100) search_indexes.py class ItemIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name=indexes.CharField(model_attr='name') company=indexes.CharField(model_attr='company') def get_model(self): return Item def index_queryset(self, using=None): return self.get_model().objects.all() serializer.py class ItemSearchSerializer(serializers.Serializer): text = serializers.CharField() name=serializers.CharField() company=serializers.CharField() views.py class ItemSearchViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = ItemSearchSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def get_queryset(self): request = self.request queryset = EmptySearchQuerySet() if request.GET.get('q', ''): query = request.GET.get('q', '') queryset =SearchQuerySet().filter(content=query); return queryset And in url.py I added : router.register(r'searchquery', views.ItemSearchViewSet, base_name='searchquery') Now on making GET request from postman like : http://127.0.0.1:8000/searchquery/?q=app, I am getting the response as desired as show below. { "count": 2, "next": null, "previous": null, "results": [ { "text": "apple\ndjflkj", "id": 14, "name": "apple", "mrp": "45.000000", "company": "djflkj", "imageid": "jfhi", "edible": false, "discount": "0.000000", "deliverable": true, "seller_uid": "ljhkh", "category": "ldjhgjfdk" }, { "text": "app\nhuhiu", "id": 16, "name": "app", "mrp": "78.000000", "company": "huhiu", "imageid": "iyiugiy", "edible": false, "discount": "45.000000", "deliverable": true, "seller_uid": "hjh", "category": "hhl" } ] } But the reponse time is very slow it takes around 2700 ms everytime , and I want to make it fast. As response of elastic search is much fast but I don't know what I am doing wrong. Not sure but may be due to these reasons I am getting this … -
Use a class method in another class
@python_2_unicode_compatible class EmployerProfile(AbstractAddress): customer = models.OneToOneField( CustomerProfile, verbose_name=_('Customer'), related_name='employerprofile') company_name = models.CharField(_('Company name'), max_length=50, blank=True, null=True) ... #That function will empty all fields in this model whenever income_source # is different of 'Employed' def clean_fields(self): if self.income_source != 'Employed': to_empty = [f.name for f in EmployerProfile._meta.get_fields()] exclude = [u'id', "has_missing_fields", "manual_validation", "actor_actions", "target_actions", "action_object_actions", ] for field_name in to_empty: if field_name not in exclude: setattr(self, field_name, None) @python_2_unicode_compatible class FinancialProfile(models.Model): customer = models.OneToOneField( CustomerProfile, verbose_name=_('Customer'), related_name='financialprofile') income_source = models.CharField(_('Income source'), max_length=20, choices=settings.LOANWOLF_INCOME_SOURCE_CHOICES, default='employed') I would like to access clean_fields() method in the class FinancialProfile. I know we could use the @classmethod, but I am not comfortable with the complexity of the method. Could anyone have time to explain to me how I could modify clean_fields() for such thing works fine? If I modify the function to get @classmethod def empty_fields(cls): if cls.income_source != 'Employed': to_empty = [f.name for f in EmployerProfile._meta.get_fields()] exclude = [u'id', "has_missing_fields", "manual_validation", "actor_actions", "target_actions", "action_object_actions", ] for field_name in to_empty: if field_name not in exclude: setattr(cls, field_name, None) and I insert in FinancialProfile def empty_fields_employerprofile(self): return self.FinancialProfile().empty_fields() is it correct? -
Dynamic number of columns in Django template
I have recently tried to solve the challenge of handling a dynamic number of columns in my Django template (essentially working through a list containing lists that isnt standerdized). I pass two things to my view: test_array: an array that looks something like the following [[1,2,3],[1,2,3],[1,2,3]] numbers: in this case 3 (indicating the number of attributes in the sub lists I thought to solve this as follows: <tbody> {% for t in test_array %} <tr> {% for x in numbers %} <td>{{ t.x }}</td> {% endfor %} </tr> {% endfor %} </tbody> But the above returns no output. When I reference t.1, t.2 etc hardcoded this returns output. As such, what is the best way to handle a dynamic number of columns in Django? Or, is there a more elegant way to solve the above? -
Django Static File handling error
I am having an error while handling static files in django. Whenever I load the webpage the images don't load in the .html file {%for i in all_memes%} <div class="memes"> {%load static%} <a href="{%url 'meme_detail' i.id%}"><img style="width:150px;height:150px;" src="{%static '/photos/static/uploaded_files/{{i.photo_link}}' %}" /></a> </div> {%endfor%} the urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns=[ #all my urls ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py STATIC_URL = '/static/' MEDIA_ROOT=os.path.join(BASE_DIR,'photos/static') STATIC_ROOT="/photos/static/uploaded_files" -
Ordering and slicing a django queryset
I'm trying to make a query which orders the objects and then returns the first 100. Orders.objects.order_by('date', 'time')[:100] However I get this error. Cannot reorder a query once a slice has been taken. How would I make this query? -
Joining two tables django newbie qustion
mysqllite table joining in django is new to me. I can query just fine on one table. and somewhat at joining via just raw mysql. What i need is an example of how to code to tables together Ie below the models and the first qustion on my project is to find all the teams that are in Atlantic confrence I have this in view "atlanticsoccer": League.objects.filter(name__contains="atlantic") this in html <h5>Question 1</h5> {% for whatever in atlanticsoccer %} <li>{{whatever.name}}</li> <li></li> {% endfor %} </ol> which gives me all my Atlantic conference leauges. But i can't seem to find an example of how to join the teams by id . I have linked below the models view If i can get an example of how to do the first I can figure out the html. Thanks in advance for helping a new coder. Models.py from django.db import models class League(models.Model): name = models.CharField(max_length=50) sport = models.CharField(max_length=15) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Team(models.Model): location = models.CharField(max_length=50) team_name = models.CharField(max_length=50) league = models.ForeignKey(League, related_name="teams") class Player(models.Model): first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) curr_team = models.ForeignKey(Team, related_name="curr_players") all_teams = models.ManyToManyField(Team, related_name="all_players") views.py from django.shortcuts import render, redirect from .models import League, Team, … -
how to deploy a dijango website on to a specific IP or domain name
i bought a godaddy linux hosting for my django website. I was not aware of that they do not provide any platform for python in there cPanel. When i have bought then i came to know about what mistake i have made. Reading about number of solutions on net i have fixed the problem to some extent. I installed python3 then pip and after that i installed django and virtual environment. Firstly i have error with sqlite i changed setting.py and used mysql instead of it. After that no databases error occurred. But now my main problem start though i was able to start my server by "python manage.py runserver" but it is starting on a ip which is default not to the domain i bought.When i am opening my site with my domain i am getting this "Forbidden You don't have permission to access / on this server. Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request." when in trying to reach it by the ip of my domain/panel i m getting the default page which was set by the host providers or i was getting internal 500 error Can anyone … -
Running a Django management command on Elastic Beanstalk using cron
I'm running a small Django web application on Elastic Beanstalk. It uses django-background-tasks to run some asynchronous tasks. This works locally, as I can run python manage.py process_tasks to run the tasks. However, I've been having a little more trouble getting this to work as desired after deploying to Elastic Beanstalk. I managed to get it working by including this "99_process_tasks.config" file in my .ebextensions folder (based on this link in the AWS documentation): files: "/etc/cron.d/process_tasks_cron": mode: "000644" owner: root group: root content: | * * * * * root /usr/local/bin/99_process_tasks.sh "/usr/local/bin/99_process_tasks.sh": mode: "000755" owner: root group: root content: | #!/bin/bash date > /tmp/date source /opt/python/run/venv/bin/activate cd /opt/python/current/app python manage.py process_tasks commands: remove_old_cron: command: "rm -f /etc/cron.d/*.bak" This worked, in that the asynchronous tasks were running and executing their code as expected. However, as a relative novice in this field (particularly when it comes to cron) I suspect that this probably isn't doing exactly what I want, as I'm envisioning that this is causing a new python manage.py process_tasks command to be run every minute. What I really want to be doing is running the command just the once (or ensuring that it's run if it's no longer running). I … -
Django - not getting the value from database to show in dropdown list
I have a calendar which is suppose to be connected to the current admins-association. When admin picks a date in the calendar and need to fill the form. Association-dropdown-list won't show any data from database. I only want it to show association name of the current admins-association. Is there something i'm missing? Still a newbie so appreciate all your help, folks! models.py class Administrator(AbstractUser): ... association = models.ForeignKey(Association) class Event(models.Model): ... association = models.ForeignKey(Association) class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) views.py def event_add_edit(request): if request.method == 'POST': res = {'success': False} if paramMissing(request.POST, 'name', res) \ ... or paramMissing(request.POST, 'association', res) \ or paramMissing(request.POST, 'synced', res): return JsonResponse(res) ... association = Association.objects.filter(asoc_name=request.user.association) asoc = request.POST[association] if action == 'add': Event.objects.create( ... association=asoc ) res['success'] = True res['message'] = 'added' eid = Event.objects.latest('id').id res['eid'] = eid res['data'] = Event.objects.values().get(id=eid) calendar.js ... $addEventAsoc: $("#add-event-asoc") showAddForm: function () { cal.$addEventAction.val("add"); cal.$addEventSynced.val("false"); ... var association = $(this).val("association"); alert (association); $.ajax ({ type: "GET", url: '/calendar/', data: association, success: function(data) { cal.$addEventAsoc.val(data); }, error: function (error_data) { console.log("error"); console.log(error_data) } }); calendar.html ... <li class="form-li"> <label for="add-event-asoc" class="input-name"> Association</label> <select id="add-event-asoc" name="association"><option value="{{ association.id }}">{{ association.asoc_name }} </option> </select> </li> -
WidgetListACL matching query does not exist
I'm trying to have a serializer display a filtered list in a field as a drop down like so: class WidgetListSerializer(TaggitSerializer, ModelSerializer): parent = SlugRelatedField( slug_field='name', queryset=WidgetList.objects.all(), allow_null=True) tags = TagListSerializerField() def create(self, validated_data): user = ProjectUser.objects.get(username=self.context['request'].user) widgetlist = super(WidgetListSerializer, self).create(validated_data) level = AccessLevel.objects.get(pk=1) WidgetListACL.objects.create(user=user, list=widgetlist, level=level) return passwordlist class Meta: model=WidgetList fields = ('id', 'name', 'description', 'parent', 'tags', 'created', 'modified') def __init__(self, *args, **kwargs): user = kwargs['context']['request'].user super(WidgetListSerializer, self).__init__(*args, **kwargs) self.fields['parent'].queryset = WidgetListACL.objects.select_related('list').get(user_id=user) Unfortunately I get the following traceback: File "D:\Python35\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "D:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "D:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python35\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "D:\Python35\lib\site-packages\rest_framework\viewsets.py" in view 83. return self.dispatch(request, *args, **kwargs) File "D:\Python35\lib\site-packages\rest_framework\views.py" in dispatch 477. response = self.handle_exception(exc) File "D:\Python35\lib\site-packages\rest_framework\views.py" in handle_exceptiona 437. self.raise_uncaught_exception(exc) File "D:\Python35\lib\site-packages\rest_framework\views.py" in dispatch 474. response = handler(request, *args, **kwargs) File "D:\Projects\enterpass\api\widgetlists\views.py" in list 24. serializer = WidgetListSerializer(queryset, many=True, context={'request': request}) File "D:\Python35\lib\site-packages\rest_framework\serializers.py" in __new__ 124. return cls.many_init(*args, **kwargs) File "D:\Python35\lib\site-packages\rest_framework\serializers.py" in many_init 145. child_serializer = cls(*args, **kwargs) File "D:\Projects\enterpass\api\widgetlists\serializers.py" in __init__ 29. self.fields['parent'].queryset = WidgetListACL.objects.select_related('list').get(user_id=user) File "D:\Python35\lib\site-packages\django\db\models\query.py" in get 385. self.model._meta.object_name Exception Type: DoesNotExist at /api/v1/widgetlists/ Exception Value: WidgetListACL matching query … -
Error in loading static files in django project
I've created django project and in settings.py configured all the necessary assets BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) STATICFILES_DIRS = [ "~/<project_name>/static", ] I have all of my static files based in the folder static in the project directory. Inside this folder I have css, js, images folders accordingly. In my base template (that is inherited by others) called base.html I have template tag {% load staticfiles %}. I can't figure out why the page still loads without any static attached, because everything seems to be made properly. -
Add a for loop variable with another variable in Django Template
{% for user in users %} <tr> <td>{{ user.teammembers }}</td> <td>{{ user.level }}</td> <td>{{ user.skillset }}</td> <td>{{ user.id }}</td> {% for dat in finaldatod %} <td>{{ user.dat }}</td> {% endfor %} </tr> {% endfor %} Here 'user' and 'dat' are two dictionaries passed from my 'view'. 'user' has all the users available in the database. 'dat' has all the dates of the month. Now am able to fetch the username, skillset, level and id of all the users. But unable to fetch the shifts of the user for all the dates of the month. Here {{ user.dat }} is not working as its unable to substitute 'user' value and 'dat' value together. Kindly advise how I can pass the values from first for loop to the second and get the data from the database. Thanks in advance!! -
Ajax data not properly being sent to views.py (Django)
Hello I'm quite new to django sorry. I'm trying to make a user object using the User class of django.contrib.auth.model I'm trying to use ajax to transfer the data from jQuery to views.py. For some reason, when I added the datatype: 'JSON' it stops executing the ajax and when I remove it the HttpResponse just gives me the entire html file. Not a single instance where a user was created. HTML <form action = "" method="post"> {% csrf_token %} <p class="label" id="l1"> Name: </p> <input type="text" class="textbox" id="name"><br> <p class="label" id="l2"> Username: </p> <input type="text" class="textbox" id="username"><br> <p class="label" id="l3"> Password: </p> <input type="password" class="textbox" id="password"><br> <p class="label" id="l4"> Confirm Password: </p> <input type="password" class="textbox" id="confirm"><br> <button id="signupbutton">Sign Up</button> </form> jQuery $("#signupbutton").click(function () { var username = $("#username").val(); var password = $("#password").val(); var confirm = $("#confirm").val(); var name = $("#name").val(); errorval = errorCheck(); if (errorval == 0) { // transform data input to dictionary const infoset = { "name": name, "username": username, "password": password }; console.log(infoset); var csrftoken = $.cookie('csrftoken'); $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax({ url: "create_user/", type: "POST", dataType: 'JSON', data: JSON.stringify(infoset), success: function (data) { console.log(JSON.parse(data)); … -
Django model forms - order of dynamically created fields
how can i set order fields in Django ModelForm, when i dont know the number and exact name of the fields? I have model FormEntry for which i want t ocreate ModelForm. The only displaced Field should be plugin_data and dynamically created custom derivatives of it (label, initial,..) with language prefix (based on languages settings). So if i have in the settings set languages cs and en, then there are fields: plugin_data, label_cs,label_en,initial_cs,initial_en,... The new fields are dynamically created in init, and i dont know how can i use new feature (Form.field_order) in Django 1.9 when i don know names of fields. -
save all invited friends to inviter database
I am struggling whole day to develop a referral program to meet my application need. First of all, i would like to brief my custom referral feature. There is two model, one Invitation and another JoinInvitation. Invitation model is for saving email addresses of the user who has requested for invitation(Only those user who has requested for invitation can refer other and they can refer as much user as they can). So the initial step is to request an invitation and the form for requesting an invitation is working properly. Second, now the user has requested for invitation. They are redirected to refer invitation page. There will be two form field, one their email, second the email of that user whom they want to invite. Since the user email address is already saved in Invitation table because he has already requested for invitation. Now the work left is to save the email addresses of those user he/she has invited to join so that his point will increase by 5 per user. Here is what i have done First my models (a user can invite as much user as they can and counting is done accordingly) class Invitation(models.Model): email = models.EmailField(unique=True, … -
Django. Get primary key of object after save form in database
I need to get pk of object after post and save form. Can help me, please? View: def form_valid(self, form): new_ticket = form.save() address = form.cleaned_data['address'].encode('utf8') title = form.cleaned_data['title'].encode('utf8') recipient = form.cleaned_data['email'].encode('utf8') name = form.cleaned_data['name'].encode('utf8') room = form.cleaned_data['room'].encode('utf8') return super(CreateTicket, self).form_valid(form) -
Django REST Framework: serializing a list of objects
I want to accept a JSON data like below: { 'id': 166, 'data_lines': [ { 'name': 'string', 'quantity': '1', 'id': '1' }, { 'name': 'string', 'quantity': '2', 'id': '12' }, { 'name': 'string', 'quantity': '3', 'id': '18' } ], } and I want to be able to build a simple shopping basket out of it by deserializing the data The issue is, I have at this point three serializers that are involved. In one of them, let's call it MiddleSerializer, I have: class MiddleSerializer(serializers.Serializer): thing = ThingSerializer() I just want to pass that ThingsSerializer an incoming id and let it handle its own stuff. It all works fine and dandy, when I pass a dict with the key 'thing' in it. Howevever, I want to be able to have a list of these and I have a serializer that this MiddleSerializer one is nested inside. It looks like below: class TopSerializer(serializers.Serializer): some_other_id = serializers.IntegerField() things = serializers.ListField(child=MiddleSerializer()) # I also tried the above with (many=True) But when I pass this TopSerializer my data, it gives me an error about missing keyword 'thing' which is required. How should I set the serializers up so that i can pass the list of …