Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to disable cache on Django?
I have a problem with my first django app and I can not find the solution. I send this to my controller: http://localhost:8000/fun1_get_data/?param1_qty=10 The controller: @never_cache def func1_get_data(request): result = request.GET['param1_qty'] return HttpResponse(json.dumps(result), content_type = "application/json") Only return the same parameter...very easy...but doesn't work.Only works the first time after restart de server or 'save changes' on archive .py. The first time OK: http://localhost:8000/fun1_get_data/?param1_qty=10 10 And then.... http://localhost:8000/fun1_get_data/?param1_qty=999 10 panic!! Extra: the template: url(r'^func1_get_data/', controlador.func1_get_data) -
FreeTDS with Django causing Denial of Service on SQL Server
It is a fairly odd behavior coming from an unknown part of the application. My setup: Django FreeTDS Unixodbc django-pyodbc-azure MS SQL The application will work for a seemingly random amount of time (usually 2-3 minutes), then will stop responding and so will the SQL Server. Other applications even with other accounts are unable to do any request to the database. The number of explicit requests on my side is 1 in the ready() of the django application to get some inital data. def ready(self): from django.conf import settings from app.models import SomeModel try: settings.SomeModel_ID = SomeModel.objects.filter(identifier=settings.SomeIdentifier)[0].pk except: settings.SomeModel_ID = SomeModel.objects.create(identifier=settings.SomeIdentifier).pk SQL Server Tracer will log some requests but nothing unusual (quite a lot of BatchStarted/BatchFinished). Wireshark with see an insane amount of packets moving between the application and the database (We are talking +250 for a simple SELECT). Here I took an example with some TCP but +95% for the packets are TDS. 5422 36.248815392 10.10.10.66 -> 10.10.10.103 TDS 183 TLS exchange 5423 36.249013989 10.10.10.103 -> 10.10.10.66 TDS 135 TLS exchange 5424 36.249427950 10.10.10.66 -> 10.10.10.103 TDS 135 TLS exchange 5425 36.250678349 10.10.10.103 -> 10.10.10.66 TCP 1514 [TCP segment of a reassembled PDU] 5426 36.250703683 10.10.10.103 -> 10.10.10.66 TDS … -
NoReverseMatch at /revision/login_user/ Reverse for 'module-add' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I am getting the following error in Django. NoReverseMatch at /revision/login_user/ Reverse for 'module-add' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []I am not really sure why i am getting this error. This is my views for logging in: (Traceback refers to here) def login_user(request): 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) modules = Module.objects.filter(user=request.user) return render(request, 'revision/index.html', {'modules': modules}) else: return render(request, 'revision/login.html', {'error_message': 'Your account has been disabled'}) else: return render(request, 'revision/login.html', {'error_message': 'Invalid login'}) return render(request, 'revision/login.html') Same with register: def register(request): form = UserForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) modules = Module.objects.filter(user=request.user) return render(request, 'revision/index.html', {'modules': modules}) context = { "form": form, } return render(request, 'revision/register.html', context) Both refers to the line of return render(request, 'revision/index.html', {'modules': modules}) How do i fix this issue? -
Convert ManyToMany into ForeignKey (django)
I have a ManyToMany field in my database that I want to convert to a ForeignKey relationship. The relationships are already one-to-many, so there will be no pigeonholing. The closest question I can find on stackoverflow is this more complicated situation in a different framework/language My simplified django models are shown below. The fields in question already exist in the database, and we just need to populate the DbLocation.pattern field. class DbPattern(models.Model): locations = models.ManyToMany(DbLocation) #trying to remove this ... class DbLocation(models.Model) pattern = models.ForeignKey(DbPattern) #and replace it with this ... My naive solution is a nested for-loop. It works, but looks like it will take days to handle several million records: patterns = DbPattern.objects.all() for p in patterns: locs = p.locations # there ary many locations for l in locs: l.pattern = p # each location has exactly 1 pattern. Is there an easy way to implement this in either Python/Django or PostreSQL that will run fast? I imagine there is a way to do this via queries. I only need to do it once. Thanks in advance for your help! -
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'manage.py'
I am facing a rather strange issue. I am trying to get my django app started using the python manage.py runserver. But I get a FileNotFoundError. I have checked multiple time. The file is in the directory from where I am running the python manage.py runserver command. Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\commands\runserver.py", line 58, in execute super(Command, self).execute(*args, **options) File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\commands\runserver.py", line 97, in handle self.run(**options) File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\commands\runserver.py", line 106, in run autoreload.main(self.inner_run, None, options) File "C:\New folder (2)\Anaconda\lib\site-packages\django\utils\autoreload.py", line 333, in main reloader(wrapped_main_func, args, kwargs) File "C:\New folder (2)\Anaconda\lib\site-packages\django\utils\autoreload.py", line 299, in python_reloader reloader_thread() File "C:\New folder (2)\Anaconda\lib\site-packages\django\utils\autoreload.py", line 275, in reloader_thread change = fn() File "C:\New folder (2)\Anaconda\lib\site-packages\django\utils\autoreload.py", line 205, in code_changed stat = os.stat(filename) FileNotFoundError: [WinError 2] The system cannot find the file specified: 'manage.py' Any help would be great. Thanks in advance -
Django postgres row-lock
I am trying to implement row level locking in my django project (postgres 9.5) for a model which handles API keys. I have read about select_for_update but it mentions that it throws TransactionManagementError when autocommit is set to True on postgres (select for update). So then I tried this: class APIKeyManager(models.Manager): ... def acquire_n_keys(self, retailer=None, n=1, calls_per=1, propagate=False, nowait=True, **kwargs): assert isinstance(n, int) or (isinstance(n, str) and n == 'max') transaction.set_autocommit(False) with transaction.atomic(): keys = self.get_queryset().select_for_update(nowait=nowait) \ .available_keys(retailer=retailer, num_calls=calls_per, **kwargs) exc = False num_keys = keys.count() if propagate: if num_keys is 0: exc = "No available keys!" elif isinstance(n, int) and (n > num_keys): exc = "Tried to acquire more keys (%d) than were available (%d)." % (n, num_keys) if exc: raise NoAvailableKeys(exc) n = num_keys if ((n == 'max') or (n > num_keys)) else n if num_keys > 0: key_pks = keys.values_list('pk', flat=True).all()[:n] keys = keys.filter(pk__in=key_pks).all() keys.update(in_use=True, last_started=timezone.now(), last_ended=None) transaction.commit() transaction.set_autocommit(True) return keys def release_key(self, **kwargs): assert all(arg in kwargs for arg in ['retailer', 'key', 'service_name']) or ('pk' in kwargs), \ "Must provide `retailer`, `key` and `service_name` args or `id` arg, got : %s" % json.dumps(kwargs) transaction.set_autocommit(False) with transaction.atomic(): pk = kwargs.pop('pk', None) if pk: key = self.get_queryset().select_for_update().filter(pk=pk) else: … -
Django admin editing inline objects is inactive in version 1.10
Editing Foreign Key objects via a "pencil" is inactive in Django version 1.10 and 1.11. In version 1.9 everything still works fine The pencil and cross are greyed out How to make inline editing active again? -
Passed parent ID to child form for child creation in Django app, I get 200 code but no record is created?
I followed some guidelines from This answer in order to pass Parent pk to the child creation page but I still can't get the desired results, my goal is to be able to add lines (CotizacionDetalle) records from a link in a Master/Detail like scenario (i.e.: Quotation creation) this link should take the current Master (parent) record (Cotizacion) and use it in the Detail (child) form creation process populating the relevant field in a transparent way for the user (a hidden field). My views.py: class CotizacionDetalleCreateView(CreateView): model = CotizacionDetalle form_class = CotizacionDetalleForm def form_valid(self, form): cotizaciondetalle = form.save(commit=False) cotizacion_id = form.data['cotizacion'] cotizacion = get_object_or_404(Cotizacion, id=cotizacion_id) cotizaciondetalle.cotizacion = cotizacion return super(CotizacionDetalleCreateView, self).form_valid(form) def get_context_data(self, **kwargs): context = super(CotizacionDetalleCreateView, self).get_context_data(**kwargs) context['c_id'] = self.kwargs['cotizacion_id'] return context def get_success_url(self): if 'slug' in self.kwargs: slug = self.kwargs['slug'] else: slug = self.object.cotizacion.slug return reverse('transporte_cotizacion_detail', kwargs={'slug': slug}) The forms.py file: class CotizacionForm(forms.ModelForm): class Meta: model = Cotizacion fecha_vence = forms.DateField(widget=DateWidget(usel10n=True, bootstrap_version=3)) fields = ['nombre', 'fecha_vence', 'itinerario'] class CotizacionDetalleForm(forms.ModelForm): class Meta: model = CotizacionDetalle fields = ['cotizacion', 'item', 'cantidad', 'nivel_de_precio'] def __init__(self, *args, **kwargs): super(CotizacionDetalleForm, self).__init__(*args, **kwargs) self.fields["cotizacion"] = forms.CharField(widget=forms.HiddenInput()) My template: cotizaciondetalle_form.html {% extends "base.html" %} {% load bootstrap3 %} {% block extlibs %}{% endblock %} {% … -
OperationalError at / unable to open database file in Django 1.8.6
I am getting the following error when I try to run a Django site in production: OperationalError at / unable to open database file The strangest part is that it worked for a few page reloads and even clicks on different navigation links. Then, it worked every other time or so. At the end, it stopped working all together. This behavior is very puzzling. Here is the relevant piece from settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I have done chmod 777 db.sqlite as well as chmod o+w . within the directory where db.sqlite3 is located. It did not help. How could I fix this? I am using a basic EC2 instance with Linux and Apache 2.4 -
Use a templatetags to find the location of an object
I've created a templatetags @register.filter def ipdb(element): import ipdb; ipdb.set_trace() return element So it is real nice, because I could use {{ element|ipdb }}. From there, I could query element. I would like to know where element is implemented. Could anyone have an idea how I could do such a thing? I mean if there is a line in a Django's template {{ total.perceptions }}, and I inserted below this line {{ total|ipdb }}, how could I find where total is implemented? find(element)? -
Rendering fields manually and custom css class
I am trying to manually render the form fields. I would like to add a bootstrap and custom css class to rendered html. How can I do this ? forms.py class OrderCreateForm(forms.ModelForm): # rabat = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect()) class Meta: model = Order fields = ['postal_code'] widgets = { 'postal_code': forms.RadioSelect(), } file.html <form action="." method="post" class="order-form"> <div class="fieldWrapper"> {{ form.postal_code }} </div> <p><input type="submit" value="Send"></p> {% csrf_token %} </form> {% endblock %} rendered html <div class="fieldWrapper"> <ul id="id_postal_code"> <li><label for="id_postal_code_0"><input type="radio" name="postal_code" value="Yes" required id="id_postal_code_0" />Yes</label></li> <li><label for="id_postal_code_1"><input type="radio" name="postal_code" value="No" required id="id_postal_code_1" />No</label></li> </ul> </div> How to solve a problem ? I would appreciate your help. -
Modify Activation Complete - Django-Registration-Redux
I am trying to modify the view/url users are sent to once they have successfully activated their account via the link they are sent in an email. Here Read The Docs it goes some way to explaining it but I must be missing a trick somewhere: Two views are provided: registration.backends.default.views.RegistrationView and registration.backends.default.views.ActivationView. These views subclass django-registration-redux‘s base RegistrationView and ActivationView, respectively, and implement the two-step registration/activation process. Upon successful registration – not activation – the default redirect is to the URL pattern named registration_complete; this can be overridden in subclasses by changing success_url or implementing get_success_url() Upon successful activation, the default redirect is to the URL pattern named registration_activation_complete; this can be overridden in subclasses by implementing get_success_url(). Imports in my apps Urls.py (I know I only need one, just trying both): from registration.backends.default.views import ActivationView from registration.backends.default.views import RegistrationView My class (I've tried with ActivationView as well): class MyRegistrationView(RegistrationView): def get_success_url(self,user): return reverse('profiles:step2', kwargs={'userid':request.user.id}) My modified URLs: url(r'^accounts/activate/complete/$', MyRegistrationView.as_view(), name='registration_activation_complete'), url(r'^accounts/', include('registration.backends.default.urls')), ... The reverse URL is good, I can access it via manually entering the URL but when I click the link in the email to activate, I get redirected to the register page BUT I am … -
How to save GeoJSON using GeoFeatureModelSerializer through POST - Django
I want to save GeoJSON from a HTTP POST request using the GeoFeatureModelSerializer serializer, however, the serializer.is_valid() method returns False so I can't even get to saving it. An example of the GeoJSON im trying to use is the following: { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "MultiLineString", "coordinates": [ [ [ -6.2511348724366, 53.340854644776 ], [ -6.2511348724366, 53.340854644776 ] ] ] }, "properties": { "start": "2017-04-14T22:57:21Z", "end": "2017-04-14T22:57:22Z", "created": "2017-04-14T22:57:54.037503Z", "owner_id": 1, "activity_type": "RUN" } } ] } I have a GeoFeatureModelSerializer subclass: class ActivitySerializer(GeoFeatureModelSerializer): class Meta: model = Activity geo_field = 'route' id_field = False fields = ('start', 'end', 'route', 'created', 'owner_id', 'activity_type') My APIView class has the following method for POST request serializer_class = ActivitySerializer def post(self, request, format=None): try: serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) else: return Response(status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST) The documentation doesn't mention a way to save data that is GeoJSON. https://github.com/djangonauts/django-rest-framework-gis/blob/master/README.rst The model for the Activity is the following: class Activity(models.Model): id = models.AutoField(primary_key=True) start = models.DateTimeField() end = models.DateTimeField() owner = models.ForeignKey( User, verbose_name="owner", on_delete=models.CASCADE, default=1 ) activity_type = models.CharField( max_length=100, verbose_name="activity_type" ) created = models.DateTimeField( auto_now_add=True ) route = models.MultiLineStringField(verbose_name="route", default=MultiLineString) -
Loading pickle files from another python file
I have a TFIDF vectorizer that I need to use later on to find the most relevant documents, so I saved it as pickle file. This is the code I used to pickle the file vectorizer = TfidfVectorizer() tfidf_matrix = vectorizer.fit_transform(my_text_data) import six.moves.cPickle as pickle with open('vectorizer.pk', 'wb') as fin: pickle.dump(vectorizer, fin) I am using this pickle file inside a django app to find the most relevant documents when a user enters a query. So in one of the codes that is called by the views.py file, I am loading that pickle file import six.moves.cPickle as pickle tfidf_vectorizer = pickle.load(open("vectorizer.pk", "rb" )) But I get the following error AttributeError: Can't get attribute 'preprocess_text' on <module '__main__' from 'manage.py'> When I simply import the preprocess_text function and read the pickle file in another window without intiating the django app it works fine, but on running it inside a django app causes this error. Any ideas on what should be done? Thanks in advance. -
Hinting in django model Meta - pycharm
Trying to build something similar I am wondering how pycharm (and other tools) know what members to hint in django's model meta: With this simple model: class MyModel(models.Model): class Meta: db_table = "bla" app_label ="blub" when I hit completion it completes all the options (like db_table). Looking at the code here: https://docs.djangoproject.com/es/1.11/_modules/django/db/models/options/ I could not find any generic hint on how to determine which members the Meta class might have. Is it just dark magic or do i oversee something? -
How to implement machine learing algorithms in a web applications?
I am working on a webapp whose backend is written in django,I am trying to provide news feed like feature to user(u can say like facebook). I think using machine learing algorithms results will be more efficient. Now coming to main question,i've no prior experience in machine learning and want to learn how can i implement machine learning algorithms in my webapplication? Any information will be helpful,Thankyou in advance. -
Django upload file
I have created a model Document a few weeks ago it was working, I don't remember what I did, but I'm now getting the following error whenever I try to save it in the django-admin page: expected string or buffer It points this line: super(Document, self).save(*args, **kwargs) class Document(models.Model): category = models.ForeignKey(DocumentCategory, related_name='%(class)s') name = models.CharField(max_length=64) description = models.CharField(max_length=64) datafile = models.FileField() date = models.DateField() is_inactive = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.id is None: self.date = timezone.now().date print(self.datafile.url) extension = os.path.splitext(self.datafile.name)[1][1:] time_stamp = timezone.now() self.datafile.name = self.name + '_' +\ self.category.category + '_' +\ str(time_stamp.year) +\ '_' + str(time_stamp.month) +\ '_' + str(time_stamp.day) +\ '_' + str(time_stamp.hour) +\ '_' + str(time_stamp.minute) +\ '_' + str(time_stamp.second) +\ '_' + str(time_stamp.microsecond) +\ '.' + extension super(Document, self).save(*args, **kwargs) Apr 24 13:19:06 intranet gunicorn[2085]: response = wrapped_callback(request, *callback_args, **callback_kwargs) Apr 24 13:19:06 intranet gunicorn[2085]: File "/py_venvs/microsoft_app_venv/lib/python3.4/site-packages/django/contrib/admin/options.py", line 544, in wrapper Apr 24 13:19:06 intranet gunicorn[2085]: return self.admin_site.admin_view(view)(*args, **kwargs) Apr 24 13:19:06 intranet gunicorn[2085]: File "/py_venvs/microsoft_app_venv/lib/python3.4/site-packages/django/utils/decorators.py", line 149, in _wrapped_view Apr 24 13:19:06 intranet gunicorn[2085]: response = view_func(request, *args, **kwargs) Apr 24 13:19:06 intranet gunicorn[2085]: File "/py_venvs/microsoft_app_venv/lib/python3.4/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func Apr 24 13:19:06 intranet gunicorn[2085]: response = view_func(request, *args, **kwargs) Apr … -
how can i save ModelForm data to database
I know i should probably not open another thread for this question because it has been asked and answered so many times here.Yes I've worked through the tutorials and browsed the web a lot - what I have is mix of what I'm finding here and at other sites but Im having a hard time saving form inputs in the database. some one should please come to my rescue i have been trying to get this done for 3 days now, its very frustrating. here are my codes models.py class QuestionBank(models.Model): First_Semester ='First_Semester' Second_Semester ='Second_Semester' Semesters = ((First_Semester, 'First_Semester'),(Second_Semester, 'Second_Semester')) level = models.ForeignKey(ClassLevel) CourseTitle = models.CharField(max_length=50, null=False) CourseCode = models.CharField(max_length=10, null=False ) CourseUnit = models.IntegerField() Semester = models.CharField(max_length=20, choices=Semesters, default="Select_Semester") Date = models.DateField() question_papers = models.FileField(upload_to = 'QuestionPapers') def __str__(self):`enter code here` return '%s %s %s %s %s %s %s' %(self.level, self.CourseTitle, self.CourseCode, self.CourseUnit, self.Semester, self.Date, self.question_papers ) forms.py class QuestionBankForm(forms.ModelForm): class Meta: model = QuestionBank fields = ('level', 'CourseTitle', 'CourseCode', 'CourseUnit', 'Semester', 'Date', 'question_papers' ) views.py def uploadQpapers(request): context = RequestContext(request) if request.method == 'POST': Qpapers = QuestionBankForm(data=request.POST) if Qpapers.is_valid(): Qpapers.save() return render_to_response("Qbank/uploadQpapers.html", {'Qpapers':Qpapers}, context) else: return HttpResponse('INVALID') i want to be able to upload past questions and save … -
Django named URL parameters no longer working after upgrade to 1.1x
I have an old Django app which uses the URL template tag this way: {% url 'smart_service.views.view_name' %} So far it worked greatly, but after the update to version 1.1 nothing works anymore and any use made that way returns NoReverseMatch. I can solve this problem by putting app_name = 'smart_service' into my urls.py file and by changing the url tag to this: {% url 'smart_service:view_name' %} This is a tedious task and very prone to errors, I'd like to avoid it unless strictly necessary. Is the first use-case been deprecated? If not, why isn't it working anymore? -
testing in django: what are differences between setUpTestData and setUpClass in TestCase class?
What are the differences between setUpTestData and setUpClass in the TestCase class? More specifically, what are the use cases for each? -
Get input from drop down into Python inside Django app
I've been stuck on this issue for a few weeks as I'm not very familiar with how to get the ajax set up. I'm working on a Django app which is basically one page that has a Dropdown menu. I would like to get whatever the user selects from the Dropdown menu and pass that data into my views.py so I can use that information to display a graph. Right now the graph part is working (I can pass in hard coded data into it and it will generate the graph) and my dropdown is working as well. However, I don't know how to get data from the drop down into my views.py. Here is how it looks. Display.html {% extends "RecordEvent/nav.html" %} <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> </head> {% block content %} <div class="row"> <div class="padded"> <div class="download-header"> <h3>Logs</h3> <div class="row inline download-header"> <div class="col-lg-6"> <div class="dropdown padding col-lg-6"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> <span id="dropdownTitle" class="">Measurable</span> <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> {% include 'RecordEvent/includes/EntryDropdown.html' %} </ul> </div> </div> </div> </div> </div> </div> <div class='padded'> <div class='col-sm-12' url-endpoint='{% url "api-data" %}'> <h1>Graph Data</h1> <canvas id="myChart" width="400" height="400"></canvas> </div> </div> <script> {% block jquery %} var endpoint … -
Django: Sum up Counts in one query
I have a list of elements that i would like to rank according to the count of related manytomany elements. I think aggregating the counts of those source elements is the right way, but i haven't found a solution yet. class Element(models.Model): Source1 = models.ManyToManyField(Source1) Source2 = models.ManyToManyField(Source2) Source3 = models.ManyToManyField(Source3) Ranked = (Link.objects.all().aggregate( Ranked=Sum(F('Source1') + F('Source2') + F('Source3'), output_field=IntegerField)['Ranked'] )) -
How to structure a website using given technologies?
Hello everyone and thank you for your time! I have a school project where I have to build a full responsive website in less than 2 months but the trick is that we have to use specific technologies. Front-End: HTML, CSS, Bootstrap, React.js Back-End: Django(Python) Even if I'm pretty familiar with HTML/CSS, others languages/frameworks are totally new to me. I have a hard time to understand how these tech are organized, which to implement first and how to deal with the backend. I won't be working alone on this project and I will basically do the front-end part but I'm a bit lost. I've done some research but I cannot find anything related to how these tech are organized. I know that, of course, we will implement HTML/CSS/Boostrap first but then, in which case do you use javascript, how do you generate pages etc...? In my project, we have to build a company website with a solid database where we can store specific articles that users will be allowed to comment etc. We also have to implement a user interface, an admin interface, a payment plugin etc... I just don't know how to proceed. Do I have to finish the … -
Can we use angular 2 with django(with out using django rest framework)?
Basically I am in a middle of a project, I am done with models and basic request. I wanted to use angular for front end but seems like integarting angular directly with django is a tough task. Can i use django directly if i return JsonResponse instead og=f HttpResponse or will it cause some trouble. -
Access specific object in a Django's class using ListView
In using a ListView in a Django's class, it is possible to access a specific object? Suppose I have three classes : The first class Perception(xwf_models.WorkflowEnabled, TimeStampedModel): loan = models.ForeignKey('loans.Loan') state = xwf_models.StateField(PerceptionWorkflow) start_date = models.DateField(_('Start date')) end_date = models.DateField(_('End date'), blank=True, null=True) current_balance = models.DecimalField(_('Current balance'), default=0, decimal_places=2, max_digits=11) operation_error = models.SmallIntegerField(_('Operation error'), default=0) notes = GenericRelation(Note) the second class PerceptionIndexView(StaffRestrictedMixin, FrontendListView): page_title = _('Perception') model = Perception template_name = 'loanwolf/perception/index.html' pjax_template_name = 'loanwolf/perception/index.pjax.html' row_actions_template_name = 'loanwolf/perception/list-actions.inc.html' url_namespace = 'perception' and the third class CustomerPerceptionIndexView(CustomerMixin, PerceptionIndexView): template_name = 'loanwolf/customers/perceptions.html' pjax_template_name = 'loanwolf/customers/perceptions.pjax.html' def get_context_data(self, **kwargs): context = super(CustomerPerceptionIndexView, self).get_context_data(**kwargs) filter_perceptions= (Perception.objects.filter(loan__request__customer__pk=self.customer.pk)) resultant = [r for r in context['results'] if r['object'] in filter_perceptions] context["resultant"] = resultant context["state"] = Perception.state #This has not solved my problem return context In the class Perception, I have already several perceptions instantiated. I would like to get access a specific instance of this class in CustomerPerceptionIndexView, but I am not able to do such thing.