Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Combine django mptt TreeNodeChoiceField with django-autocomplete-light ModelSelect2 widget
A django-mptt TreeNodeChoiceField gives indented select options, whereas I can filter my results using django-autocomplete-light. However, the ModelSelect2 widget overwrites the rendered html, which removes the indentation. I would like to combine the two. Any idea how I could achieve this? models.py: class Foo(MPTTModel): name = models.CharField(max_length=50) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) class MPTTMeta: order_insertion_by = ['name'] forms.py: class FooForm(forms.ModelForm): parent = TreeNodeChoiceField(queryset=Foo.objects.all(), widget=autocomplete.ModelSelect2(url='foo-autocomplete')) class Meta: model = Foo fields = ('name', 'parent', ) -
Python: Model.objects.all() - how to iterate through it using POST checkboxes
I have been building a CSV export using Python/Django. While sending all items listed in the change list everything works like a charm. Now, I've been trying to use Action dropdown and export only those items selected via the checkboxes, but I cannot make it work. My current code, the one that works even with the Action dropdown yet exporting ALL items, regardless of what was checked: def export_this_list(self, request, queryset): """Generates participants list in Excel sheet.""" csv_elements = Enrolment.objects.all().order_by('-training__date') for elem in csv_elements: When csv_elements is swapped with request.POST.getlist obviously nothing works. def export_this_list(self, request, queryset): """Generates participants list in Excel sheet.""" csv_elements = request.POST.getlist('_selected_action') or csv_elements = [] for o in request.POST.getlist('_selected_action'): Question: what is the syntax to combine my Model with the POST action? -
IntegrityError with DateField - when creating objects with get_or_create
I'm having an issue with Django's get_or_create, when ever I create same objects with same dates integrity error pops up. I have field in my model as follows. class Cart(models.Model): created = models.DateTimeField( pgettext_lazy('Cart field', 'created'), auto_now_add=True) last_status_change = models.DateTimeField( pgettext_lazy('Cart field', 'last status change'), auto_now_add=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, related_name='carts', verbose_name=pgettext_lazy('Cart field', 'user')) email = models.EmailField( pgettext_lazy('Cart field', 'email'), blank=True, null=True) def add(self,hoarding, date_from, date_until): cart_line, created = self.lines.get_or_create( hoarding=hoarding,date_from=date_from,date_until=date_until) class CartLine(models.Model): cart = models.ForeignKey( Cart, related_name='lines', verbose_name=pgettext_lazy('Cart line field', 'cart')) hoarding = models.ForeignKey( Hoarding, related_name='+',blank=True, null=True, verbose_name=pgettext_lazy('Cart line field', 'hoarding')) date_from = models.DateField(blank=True, null=True, verbose_name=pgettext_lazy('Cart line field', 'from')) date_until = models.DateField(blank=True, null=True, verbose_name=pgettext_lazy('Cart line field', 'until')) error arises when i try to add same objects to cart with same from-date and until-date: IntegrityError at /hoardings/hoardings-demo-2-5/add/ UNIQUE constraint failed: cart_cartline.cart_id, cart_cartline.date_from, cart_cartline.date_until get_or_create will return an IntegrityError when creating objects with same dates.I added unique features in datefield but got the same error. I use Django 1.11 and Python 2.7 I reset database few times but it doesn`t help, db is Postgres/sqlite. -
Validate count() constraint in many to many relation before saving an instance in django
I would like to prevent a save in a django model when a certain constraint is not met and give a validation error so that a django staff user knows what went wrong. The constraint is the count() from an intermediate table specified using the through parameter. models.py: class Goal(models.Model): name = models.CharField(max_length=128) class UserProfile(models.Model): goals = models.ManyToManyField(Goal, through=UserProfileGoals, blank=True) class UserProfileGoal(models.Model): goal = models.ForeignKey(Goals) user_profile = models.ForeignKey(UserProfile) class UserGoalConstraint(models.Model): user_profile = models.OneToOneField(UserProfile) max_goals = models.PositiveIntegerField() So the UserGoalConstraint.max_goals gives me the number of the maximum definable UserProfile.goal which are stored in the UserProfileGoal model (same UserGoal can be stored more often to the UserProfile) I have read and tried solutions from several posts, which are using ModelForm's clean(), Model's clean() and pre_save signal events, but the actual problem I have is, how do I know if it is just an update or a new database entry, because class UserProfileGoal(models.Model): goal = models.ForeignKey(Goals) user_profile = models.ForeignKey(UserProfile) def clean(self): goal_counter = self.user_profile.goals.count() + 1 try: qs = UserGoalConstraint.objects.get(user_profile=self.user_profile) except UserGoalConstraint.DoesNotExist: raise ObjectDoesNotExist('Goal Constraint does not exist') if goal_counter > qs.max_goals: raise ValidationError('There are more goals than allowed goals') does not really work, as clean() can also be an update and the … -
django-pipeline FileNotFoundError when i perform manage.py collectstatic
It's last some lines of traceback : File "C:\PycharmDev\TestVirtualEnv\testEnv1\lib\site-packages\pipeline\compressors\__init__.py", line 247, in execute_command stdin=subprocess.PIPE, stderr=subprocess.PIPE) File "C:\Python34\Lib\subprocess.py", line 859, in __init__ restore_signals, start_new_session) File "C:\Python34\Lib\subprocess.py", line 1112, in _execute_child startupinfo) FileNotFoundError: [WinError 2] ... And in settings.py : BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATIC_URL = '/static_prepared/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_prepared'), ] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) PIPELINE = { 'STYLESHEETS': { 'static_prepared': { 'source_filenames': ( '*.css', ), 'output_filename': 'colors.css' }, }, 'JAVASCRIPT': { 'static_prepared': { 'source_filenames': ( '*.js', ), 'output_filename': 'stats.js', } } } What's wrong with me? When i use manage.py collectstatic, it doesn't work at all with pipeline. It seems like only works like there's no pipeline. The same as without pipeline. Normal manage.py collectstatic. Why that error has been occurred? I already made static and static_prepared directory on os.path.join(BASE_DIR, ...) manually. How can i set pipeline correctly? -
how to use single button in html forms to store the inputs from the for loop in django
I am working on Quiz application and I am facing issue while submitting the form. only 1st question answer is saving and answers of remaining questions is not saving in the database. can anyone help me in solving this. Below is my code: views.py: import random def candidate_test(request): user=request.user profile=Profile.objects.get(user=user) list=[] post=Invidulator.objects.filter(candidate=profile) for items in post: list.append(items) testnumber=list[-1] print testnumber.id questions=UserAnswer.objects.filter(invidulator=testnumber.id) print questions print questions.count() if request.method == 'POST': form = AnswerForm(request.POST) print "inside" print form.is_valid() if form.is_valid(): print "profile" #candidate = form.save(commit=False) b=form.cleaned_data['answer'] a= form.cleaned_data['correct_answer'] print ("a",a) print ("b",b) answersave=UserAnswer.objects.get(id=a) answersave.answer=b answersave.save() return redirect(candidate_test) else: form = AnswerForm() return render(request, 'blog/user.html', {'posts':questions,'form':form}) user.html: {% for q in posts %} <table> <form method="POST" class="options" id="options" >{% csrf_token %} <ul> <div> <tr> <td> <p >{{q.question}}</p> <input class="option" type="radio" name="answer" value="option1" onclick="check();" />{{q.option1}}<br> <input class="option" type="radio" name="answer" value="option2" onclick="check();" />{{q.option2}}<br> <input class="option" type="radio" name="answer" value="option3" onclick="check();" />{{q.option3}}<br> <input class="option" type="radio" name="answer" value="option4" onclick="check();"/>{{q.option4}}</br> <input id="id_correct_answer" type="hidden" name="correct_answer" maxlength="100" value={{q.id}} required /></p> </td> </tr> </div> </ul> </form> {% endfor %} </table> <script> function check() { { document.getElementById('options').submit(); } } </script> {% endblock %} This is my code and i want to save the answers of all the questions without using submit button and … -
Count rows of a subquery in Django 1.11
I have a couple models class Order(models.Model): user = models.ForeignKey(User) class Lot(models.Model): order = models.ForeignKey(Order) buyer = models.ForeignKey(User) What I'm trying to do is to annotate Lot objects with a number of buys made by a given user to the same seller. (it's not a mistake, Order.user is really a seller). Like “you’ve bought 4 items from this user recently”. The closest I get was recent_sold_lots = Lot.objects.filter( order__user_id=OuterRef('order__user_id'), status=Lot.STATUS_SOLD, buyer_id=self.user_id, date_sold__gte=now() - timedelta(hours=24), ) qs = Lot.objects.filter( status=Lot.STATUS_READY, date_ready__lte=now() - timedelta(seconds=self.lag) ).annotate(same_user_recent_buys=Count(Subquery(recent_sold_lots.values('id')))) But it fails when recent_sold_lots count is more than one: more than one row returned by a subquery used as an expression. .annotate(same_user_recent_buys=Subquery(recent_sold_lots.aggregate(Count('id'))) doesn't seem to work also: This queryset contains a reference to an outer query and may only be used in a subquery. .annotate(same_user_recent_buys=Subquery(recent_sold_lots.annotate(c=Count('id')).values('c')) is giving me Expression contains mixed types. You must set output_field.. If I add output_field=models.IntegerField() to the subquery call, it throws more than one row returned by a subquery used as an expression. I'm stuck with this one. I feel I'm close to the solution, but what am I missing here? -
KeyError: 'name' Why can't I user 'name'?
I wanna make a dictionary has name's key & data.In views.py I wrote data_dict ={} def try_to_int(arg): try: return int(arg) except: return arg def main(): book4 = xlrd.open_workbook('./data/excel1.xlsx') sheet4 = book4.sheet_by_index(0) data_dict_origin = OrderedDict() tag_list = sheet4.row_values(0)[1:] for row_index in range(1, sheet4.nrows): row = sheet4.row_values(row_index)[1:] row = list(map(try_to_int, row)) data_dict_origin[row_index] = dict(zip(tag_list, row)) if data_dict_origin['name'] in data_dict: data_dict[data_dict_origin['name']].update(data_dict_origin) else: data_dict[data_dict_origin['name']] = data_dict_origin main() When I printed out data_dict,it is OrderedDict([(1, {'user_id': '100', 'group': 'A', 'name': 'Tom', 'dormitory': 'C'}), (2, {'user_id': '50', 'group': 'B', 'name': 'Blear', 'dormitory': 'E'})]) My ideal dictionary is dicts = { Tom: { 'user_id': '100', 'group': 'A', 'name': 'Tom', 'dormitory': 'C' }, 2: { }, } How should I fix this?What should I write it? -
Count number of Views/Hits
Here's the code, class Music(models.Model): visits = models.IntegerField(default=0, blank=True) def music(request) ...... Though it's not a good way of doing it but how can I increase 'visits' by +1 whenever view 'music' is requested ? Please help me, thanks in advance! -
Show cached pages only to logged in user
Django 1.11.4 I wanted to cache a page, but show it to a logged in user with a special permission. But I failed (the code below). Could you tell me whether it is possible with Django? If not, is it possible with some other software (like Varnish or something)? settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } views.py class SearchEngineView(LoginRequiredMixin, PermissionRequiredMixin, View): permission_required = 'general.can_observe' template_name = 'search/search.html' def get(self, request): return render(request, ... -
can Oauth2 server developed in python be accessed from php Oauth client
i have a python django Oauth server and website configured and i need to login via this website from another php website.I cannot find anything regarding this subject anywhere python/php combination oauth login. Php Client Code: $clientConfig = new ClientConfig( array( "authorize_endpoint" => "http://localhost/oauth/php- oauth/authorize.php", "client_id" => "foo", "client_secret" => "foobar", "token_endpoint" => "http://localhost/oauth/php-oauth/token.php", ) ); -
Django registration, primary key issue
I have an issue with my authentication process. I create a SignIN process giving a user the ability to create an a new account using only his mail, account that will be inactive until he edits it providing his first name, last name and a password. I gave it a try but I go to the URL for edit profile I receive an error related to the PK .. error: TypeError: update_profile() got an unexpected keyword argument 'pk' urls: from django.conf.urls import url, include from registration import views app_name = 'registration' urlpatterns = [ url(r'^register/$', views.register, name='register'), url(r'^users/(?P<pk>\d+)/edit/$', views.update_profile, name="edit-user-profile"), ] form.py: from django import forms from django.contrib.auth.models import User from .models import MyUser from django.contrib.auth import get_user_model User = get_user_model() class Form(forms.ModelForm): password = forms.CharField(widget= forms.PasswordInput()) class Meta(): model = User fields= ('first_name','last_name','email','password','company') class InactiveForm(forms.ModelForm): class Meta(): model = User fields= ('email',) class UpdateProfile(forms.ModelForm): email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) password = forms.CharField(widget= forms.PasswordInput()) class Meta: model = User fields = ('email', 'first_name', 'last_name','password') def clean_email(self): email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).count(): raise forms.ValidationError('This email address is already in use. Please supply a different email address.') return email def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) … -
Django admin limit foreign key filters to entries within the table
I have a couple models as below. class Department(models.Model): id = models.CharField(max_length=100,primary_key=true) name = models.CharField(max_length=100) class User(models.Model): id = models.CharField(max_length=100) dept= models.ForeignKey(Department,on_delete=models.SET_NULL,null=True) class UserDisplay(VersionAdmin): list_display = ['id','dept'] list_filter=['dept'] Say I have about 100 departments and only 3 Users. If I click on filter on the Django admin panel for the User model it shows all 100 departments. How can I limit the filters only to show the 3 departments used by this table ? -
Django class-based view doesn't display query result
I'm trying to improve my Django view with classes in order to get a better script. I don't why but I don't overcome to display query result with the new syntax. Maybe someone could help me to find a solution ? This is my view : class IdentityIndividuForm(TemplateView) : template_name= "Identity_Individu_Form.html" model = Individu def ID_Recherche (request) : if 'recherche' in request.GET: query_Nom_ID = request.GET.get('q1NomID') query_Prenom_ID = request.GET.get('q1PrenomID') query_DateNaissance_ID = request.GET.get('q1DateNaissanceID') query_VilleNaissance_ID = request.GET.get('q1VilleNaissanceID') sort_params = {} Individu_Recherche.set_if_not_none(sort_params, 'Nom__icontains', query_Nom_ID) Individu_Recherche.set_if_not_none(sort_params, 'Prenom__icontains', query_Prenom_ID) Individu_Recherche.set_if_not_none(sort_params, 'DateNaissance__icontains', query_DateNaissance_ID) Individu_Recherche.set_if_not_none(sort_params, 'VilleNaissance__icontains', query_VilleNaissance_ID) query_ID_list = Individu_Recherche.Recherche_Filter(Individu, sort_params) context = { "query_Nom_ID" : query_Nom_ID, "query_Prenom_ID" : query_Prenom_ID, "query_DateNaissance_ID" : query_DateNaissance_ID, "query_VilleNaissanceID" : query_VilleNaissance_ID, "query_ID_list" : query_ID_list, } return render(request, 'Identity_Individu_Form.html', context) My url.py file : urlpatterns = [ url(r'^Formulaire/Individus$', IdentityIndividuForm.as_view(), name="IndividuFormulaire"), ] And my template : <div class="subtitle-form"> <h4> <span class="glyphicon glyphicon-user"></span></span> Rechercher le n° identification d'un individu <a><span title="Outil permettant de vérifier si un individu est déjà enregistré dans la Base de Données Nationale. Saisir au minimum Nom et Prénom (entièrement ou en partie). Si la personne recherchée est trouvée, ne pas remplir le formulaire de création de fiche !" class="glyphicon glyphicon-info-sign"></a> </h4> </div> <div class="form"> <form autocomplete="off" method="GET" action=""> <input type="text" name="q1NomID" placeholder="Nom … -
How to use multiple settings files with sites framework in django
I am trying to setup multiple sites from a single project in django. I was trying to set this up following sites framework but there is no mention of how to use multiple settings files for all of the instances on the live server, it just said: In order to serve different sites in production, you’d create a separate settings file with each SITE_ID (perhaps importing from a common settings file to avoid duplicating shared settings) and then specify the appropriate DJANGO_SETTINGS_MODULE for each site. my wsgi.py : import os os.environ["DJANGO_SETTINGS_MODULE"] = "ProjectName.settings" #On the live server #os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") #On the local host from django.core.wsgi import get_wsgi_application application = get_wsgi_application() this is my Settings files : ├── Site1_settings.py └── Site2_settings.py So, how wsgi will use the appropriate settings file for each instance when open it using this line os.environ["DJANGO_SETTINGS_MODULE"] = "ProjectName.settings" What am i missing to run it on the live server? thanks -
how Django view get the post data?
I have a question about update html when I use view.py. This is my part of html,I have many buttons,and when I click one of buttons, it will pass just the corresponds data to view. $.ajax({ url:"/file_parse/", type:"POST", contentType: "application/json", data:JSON.stringify({ 'data':dataname }) You can see I post some data ,and get the Post data in my view's function, finally I save the result to my model(database). When I click one button, and my view's function will do something,so I get a different result every time when I click a different button.This is the first view, dopase is a function to save data and it is doing right: @login_required(login_url='/login') @api_view(['GET', 'POST'])`def file_parse(request): uploadfile_info = upload_document.objects.all() if request.method == 'POST': info_name = request.data.get('data') doparse(info_name) file_name = re.findall(r'[^/]+(?!.*\/)', str(info_name)) data_list = ES_device.objects.filter(device_name = file_name) # data_list = ES_device.objects.values('device_name', 'device_type').distinct() context = {'data_list': data_list} # return Response(context, None, 'logfile/data_bi.html') return render(request, 'logfile/data_bi.html', context) # return render_to_response('logfile/data_bi.html', locals()) else: context = {'uploadfile_info': uploadfile_info} return render(request, 'logfile/file_parse.html', context)` This is url url(r'^file_parse/$', file_parse), url(r'^data_bi/$', data_to_list), This is the view I want to show the result: def data_to_list(request): data_list = ES_device.objects.all() context = {'data_list': data_list} #return render(request, 'logfile/data_bi.html', context) return render_to_response('logfile/data_bi.html', locals()) But when I click … -
Django: how to poll a django application for updates? (noob edition)
I have a simple application in Django which consists of a form and a results page. After the form is submitted there is some processing which can take quite some time. Naturally, it would be nice would be to run the computation asynchronously to get the user to the results page faster provide updates for the user of the progress of their request. So I have tried figuring out how to do this and I can not figure it out. To my understanding I should do the following: install celery make an app in celery with a task to do the computation have that task output the progess either to a log file or update the model (if the model has a status field) use JS and JQuery or angular.js or node.js and socket.io to somehow poll my application for this progress. and from there whatever else I am told or I can find either glosses over how this works, assumes I know how this works and can adapt it to my use case, or if they try to explain it, I just dont understand. I made a demo project. In this demo project we have two views index and … -
Dropdown Selection with loop in Django
i have a variable called production_numbers that contains a list of ints in my html template. Now i need to select one of those numbers out of the list. For that I want to use a textfield with a dropdown menu where you can select one of the numbers. To access one of the numbers I use {{ production_numbers.1 }}. I searched a bit and do I rly need to use php or JS for the for loop and i´m a bit confused how i can iterate trough the list. It would be nice if someone can help me with this basic question. Greetings -
KeyError: 'user_id'
I wanna put dictionary data to the model(User) .I wrote like for row_number, row_data in dict_data.items(): user1 = User.objects.filter(corporation_id=row_data['corporation_id']) if user1: user1.update(user_id=dict_data['user_id']) dict_data is dictionary type like {'00010': OrderedDict([('corporation_id', '00001aB3D4'), ('user_id', '11111'), ('name', 'Tom'), ('age', '20')])} I wanna put dict_data data's user_id to user_id column of User model.Definitely,dict_data has 'user_id',but I really cannot understand why this error happens.How can I fix this? -
Django, How to make symmetric relationship between self with extra field?
I had a model in symmetric relationship: class person(models.Model): name = models.CharField(max_length=20) friends = models.ManyToManyField('self', blank= True) And I need a extra field to explain their relationship, for example: they be friend since 1980. be_friend_since = models.DateField(blank = True) How to add this extra field in my models? Thanks! :) -
Django channels - update active connections
I have setup channels to update connected mobile app users. I have a Group model that owns users and also IoT sensors. If the authenticated user is connected an is in a Group, any sensor update in that group will be sent to those users. If add a user to a group after he has connected to the server, he wont get any updates in the new group until he connects again. Should they reconnect once the groups are updated? Or how should this be done? Then second question - if the user lost connectivity and in that time a message was sent to the group. How could I ensure that the users who connected late does also get the messages? Im thinking I should create a table that keeps a log of users and messages. I would like to follow the best practice for both these questions! Thanks! -
Django, django-ckeditor, Google MDL: Cannot read property 'getSelection' of undefined
I am using Django 1.11 and django-ckeditor for text fields in admin panel, and also for some inputs outside the admin (in public forms). As a CSS framework - Google material design lite. When I trying to integrate ckeditor to public forms, charfield with ckeditor does not working at all. Something like I can't focus to this field, and when I click to any of ckeditor control elements I got errors Uncaught TypeError: Cannot read property 'getSelection' of undefined at CKEDITOR.dom.selection.getNative (ckeditor.js:445) at CKEDITOR.dom.selection (ckeditor.js:443) at a.CKEDITOR.editor.getSelection (ckeditor.js:440) at CKEDITOR.plugins.undo.Image (ckeditor.js:1174) at CKEDITOR.plugins.undo.UndoManager.save (ckeditor.js:1169) at a.b (ckeditor.js:1164) at a.n (ckeditor.js:10) at a.CKEDITOR.event.CKEDITOR.event.fire (ckeditor.js:12) at a.CKEDITOR.editor.CKEDITOR.editor.fire (ckeditor.js:13) at a.execCommand (ckeditor.js:271) And in Firefox: TypeError: this.document.getWindow(...).$ is undefined getNative http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:445:29 CKEDITOR.dom.selection http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:443:54 CKEDITOR.editor.prototype.getSelection http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:440:319 CKEDITOR.plugins.undo.Image http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:1174:458 save http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:1169:123 b http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:1164:291 n http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:10:222 CKEDITOR.event.prototype</<.fire</< http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:12:42 CKEDITOR.editor.prototype.fire http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:13:212 execCommand http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:271:120 CKEDITOR.ui.button/<.click< http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:654:417 execute http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:655:478 render/q< http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:656:324 addFunction/< http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:31:216 callFunction http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js:31:332 onclick http://127.0.0.1:8000/accounts/trip/2/:1:1 ckeditor.js 445 line: x?this.document.$.selection:this.document.getWindow().$.getSelection()},getType:x?function(){var a=this._.cache;if(a.type)return a.type;var b=CKEDITOR.SELECTION_NONE;try{var c=this.getNative(),d=c.type;"Text"==d&&(b=CKEDITOR.SELECTION_TEXT);"Control"==d&&(b=CKEDITOR.SELECTION_ELEMENT);c.createRange().parentElement()&&(b=CKEDITOR.SELECTION_TEXT)}catch(e){}return a.type=b}:function(){var a=this._.cache;if(a.type)return a.type;var b=CKEDITOR.SELECTION_TEXT,c=this.getNative();if(!c||!c.rangeCount)b=CKEDITOR.SELECTION_NONE; Forms.py: from ckeditor_uploader.widgets import CKEditorUploadingWidget class PaymentForm(forms.Form): comments = forms.CharField(widget=CKEditorUploadingWidget()) To integrate ckeditor js scripts I'm using {{ form.media }} in template. First of all I tried to search info about this errors and any know fixes, but any of … -
Create object models from external JSON link- Django
So I'm building this small app that lets you vote for a specific person whose information such as name, title, bio, etc, comes from an URL containing JSON. I'm using DJANGO for the back end and a little Angular in the front end as I would like to save the votes for each person that have been submitted by different users. Here is my HTML: <!DOCTYPE html> {% load staticfiles %} <html lang="en-us" ng-app="myApp"> <head> <title>Voting App</title> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta charset="UTF-8"> <!-- load bootstrap and fontawesome via CDN --> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" /> <link rel="stylesheet" href="{% static "css/styles.css" %}" /> </head> <body> <header> <nav class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="/">G2 Crowd Team Roster</a> </div> </div> </nav> </header> {% verbatim %} <div class="container"> <div ng-controller="mainController"> <div class="row" ng-cloak ng-repeat="person in data"> <div class="col-xs-12 col-sm-5 col-md-3"> <img ng-src="{{person.image_url}}"/> </div> <div class="col-xs-12 col-sm-7 col-md-9"> <h2>{{ person.name }}</h2> <h3>{{ person.title }}</h3> <p>{{ person.bio }}</p> <h4>Want to work with {{ person.name }}? <a href="" ng-click="add_vote()"><img src="../static/svg/thumbs-up.svg">Yes!</a></h4> <h5><b>{{ vote }}</b> people have said Yes!</h5> </div> </div> </div> </div> {% endverbatim %} <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <!-- Load angular via CDN --> … -
Getting error while reading the file content using Python and Django
I need some help. I am trying to read the file content using URL and return that the content as response in html format but getting the following error. Error: Exception Type: KeyError Exception Value: u'id' Exception Location: /usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py in __getitem__, line 57 I am explaining my code below. site = 'http://127.0.0.1:8000/' my_list = [] my_list.extend(['home', 'view_reactor']) if request.GET.get('file') is not None and request.GET.get('file') != '': file = request.GET.get('file') if file in my_list: full_path = site+file response = urllib.urlopen(full_path) lines = response.readlines() return HttpResponse(content=lines, content_type="text/html") else: return render(request, 'plant/home.html', {'count': 1}) else: return render(request, 'plant/home.html', {'count': 1}) Here I am passing the the value in query string like this http://127.0.0.1:8000/createfile/?file=view_reactor and finally I need the response of http://127.0.0.1:8000/view_reactor page in html format. But in my code I am getting this error. Please help. -
How to send data from multiple blocks to backend in Django?
My current template structure contains 2 blocks, "page_content" and "sidebar". There is an html-form with "POST" method in "page_content" block that sends data to backend, but the problem is that this form is working with mobile-size screen only, and for the desktop there is a second block - "sidebar". This hole thing has point in terms of template structure, but has zero point in terms of logic, because anytime i want to send data via that "sidebar" block - it just won't be sent to backend. That is my problem, unfortunately i can't change template structure, i mean i'm not allowed to get rid of that 2-blocks structure, i must keep them but i also have to make that "sidebar" block to actually send data to backend like "page_content" does. How can i accomplish that ? Here is the code: {% block page_content %} <form id="main_form" class="form-horizontal" action="." method="POST">{% csrf_token %} {{ order_form_set.management_form }} <div class="mobile-order-wrapper"> <div class="mobile-order-container"> <p class="mobile-cart-header text-center">Cart</p> <div class="mobile-cart-items"> {% for i in order_form_set %} {% include 'orders/includes/order_mobile_form.html' with data=i.initial %} {% endfor %} </div> </div> </div> <button>Order!</button> </form> {% endblock page_content %} {% block sidebar %} <div class="cart-container" data-spy="affix" data-offset-top="195"> <div class="cart-title">Cart</div> <div class="cart-items-container"> {% …