Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Finding the decorator name using django middleware
I had created a decorator to check if a person has session as follows: (comments added for brevity) def session_enabled(func=None, prefix='calling: '): # some preprocessing def session_enabled_wrapper(*args, **kwargs): # check for session in request obj # execute the function and get result onto a variable say result # some API profiling logic return result return session_enabled_wrapper I have used this on some views as follows: @session_enabled @csrf_exempt def view_function(request): # some processing My goal was to check if any function are being accessed without this decorator in place on the logs. So i wrote a middleware as follows: class SessionEnabledMiddleware(object): ''' class that represents middleware called during requests ''' def process_view(self, request, view_func, view_args, view_kwargs): ''' called during the request cycle :param request: request param :param view_func: view function object :param view_args: args passed to view function :param view_kwargs: kwargs passed to view function :return: None ''' print('############# Inside session enabled middleware ###################') if not view_func.__name__ == 'session_enabled_wrapper': print('Function Not session enabled', request.path) else: print('function is session enabled', request.path) I added the above middleware to tuple of MIDDLEWARE_CLASSES in settings.py file. I was happy as this worked, but the happiness was short lived as my APIs started to crash with … -
Foreign Key Error to Itself on Django
So I am trying to create an inline set similar to this image (http://oi48.tinypic.com/4gm5w2.jpg) so I can add multiple prices for different sizes for a product. I can't get it to even display the area in the django admin. On top of that by doing so I get the error: <class 'apps.main.admin.PriceInline'>: (admin.E202) 'main.Apparel_Price' has no ForeignKey to 'main.Apparel_Price'. models.py: @python_2_unicode_compatible class Apparel_Product(models.Model): product_name = models.CharField(_("Name"), max_length=255) default='media/None/no-img.jpg') product_gender_type = models.CharField(max_length=256, choices=[('male', 'Male'), ('female', 'Female'), ('unisex', 'Unisex')]) product_brand = models.CharField(_("Brand"),max_length=25) product_sizes = models.CharField(_("Sizes"),max_length=25) product_colors = models.CharField(_("Colors"),max_length=25) product_price = models.CharField(_("Price"),max_length=10) product_description = models.CharField(_("Description"),max_length=500) product_shipping_options = models.CharField(_("Shipping Options"),max_length=250) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = _("Apparel Product") verbose_name_plural = _("Apparel Products") def __str__(self): return self.album_name @python_2_unicode_compatible class Apparel_Picture(models.Model): master_apparel_product = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE) product_caption = models.CharField(_("Caption"), max_length=255) product_photo = models.ImageField(_("Picture"), upload_to='media/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = _("Picture") verbose_name_plural = _("Pictures") def __str__(self): return self.photo_caption @python_2_unicode_compatible class Apparel_Price(models.Model): # master_apparel_product = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE) master_apparel_product = models.OneToOneField(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE) product_price = models.CharField(_("Price"), max_length=255) product_size = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = _("Price") verbose_name_plural = _("Prices") def __str__(self): return self.product_price admin.py: from django.contrib import admin … -
custom_ids in batch notification API
I want to use batch notification for communicating between devices. here is the documentation that could help https://batch.com/doc/api/transactional.html I'm using Transactional API part and my code is on Django my question is there is a part of the post request body ,recipients, which is required. I can't understand how should I get custom_ids from. -
Files getting renamed while using file upload in django
I am using file upload control in my Django application (Code is mentioned below). I know Django uses two FILE_UPLOAD_HANDLERS to process file upload request. Memory based: If the file size is smaller than 2.5mb than it uses MemoryFileUploadHandler and saves the files in memory. Disk based: If the file size is larger than 2.5mb then it uses TemporaryFileUploadHandler and saves the files on disk. I am strictly using 2nd approach by removing MemoryFileUploadHandler from request token. What I have observed is that files are getting renamed before getting saved in the /tmp folder. sample_01.pdf --> /tmp/tmpqj9jb13w.upload.pdf sample_02.pdf --> /tmp/tmph1u_6x4r.upload.pdf sample_03.pdf --> /tmp/tmp8p5uoh4g.upload.pdf sample_04.pdf --> /tmp/tmpuwis6ar0.upload.pdf sample_05.pdf --> /tmp/tmpq24bk6tm.upload.pdf Because of this it is getting very difficult to identify the files. Is there any way to keep the name of the files as it is. <div class="custom-file"> <input type="file" class="custom-file-input" id="fileupload" name="fileupload" multiple> <label class="custom-file-label" for="fileupload">Choose files</label> </div> if request.method == 'POST': files_list = request.FILES.getlist('fileupload') -
when using filter in django MultipleObjectsReturned error occur
i am new to django. i see the documentation the model.filter function able to return multiple objects but when using it the following error occur get() returned more than one Jobs -- it returned 2! my code bellow return Jobs.objects.filter(Government=self.Government) -
Django Render template with new dict data
I am currently trying to make a website that shows a summary of git user profiles. Everything works except the data updating live. All of the ajax side of the code works, I am able to make a post request to the server and receive which username the client wants to show. I am having issue actually making the data show on the site. def index(request): if request.method == 'POST': #Get post data from request unparsed = request.body.decode('utf-8') parsed = loads(unparsed) #Parse the json and get the username print(parsed['gitusername']) username = getUserInfo(parsed['gitusername']) #Ask the api to return json of user info print(username) return render(request, "ui/index.html", username) #Re render the template with the new dict data return render(request, "ui/index.html",getUserInfo("jarmahent")) #initially load the website with this dict data -
Limit ajax autocomplete results
How do you limit the number of search result given that the data is not local. I know local data can be easily limited as shown below. source: function(request, response) { var results = $.ui.autocomplete.filter(myarray, request.term); response(results.slice(0, 10));` This is not working quite well when I get my data externally. Below is my code. $(function() { $("#search").autocomplete({ source: function(request, response) { request = "/accounts/ajax/search/"; }, minLength: 2, select: function(event, ui ){ window.open(ui.item.url,'_self')}, open: function(event, ui) { $('.ui-autocomplete').append("<li><a class = \" text-primary\" href='javascript:document.getElementById(\"search_form\").submit();'> See All Result </a></li>"); }, }); }); -
How to Pull info from another model within a DetailsView template (without ForeignKey)?
I am trying to pull data from two models within a DetailsView template (in Django). There is of course a primary model (eg. Articles) associated with the view, which is easy to access. However, I want to access data from a model (eg. Terms). I do not want to use ForeignKey because I will be using many 'Terms' in each 'Article,' and since ForeignKey will allow me to link to only row in the Terms model, I will have to set-up mutiple ForeignKey fields, which can get messy fast. I was thinking that this could be accomplished using get_context_data or templatetags, but haven't have had any luck yet. Any thoughts? Thanks for your assistance, in advance. -
Django Version 1.8.3 SQL Server v13 is not supported
I'm new to this stuff so I apologize if this is in the wrong place. I've inherited a Debian 7.14 system that has Django version 1.8.3 and Python version 2.7.6. It has a connection to SQL Server. We've just upgraded to SQL Server 2016 and are now getting the error Exception Type: NotImplementedError Exception Value: Sql Server v13 is not supported. How can I upgrade to a newer version of Django for this connection to work again? What version will work with SQL Server 2016? I'm thinking it would be a good idea to upgrade Debian version as well while I'm at it, but I'm unsure whether that will break this further. Any insight or suggestions is greatly appreciated, I've done a ton of research and I'm out of places to turn. -
Return invalid Django form and errors to AJAX
I am working on a django website where I've used crispy-forms to render and AJAX to submit a form to the server. I am stuck trying to return a response with the form contents and errors to the AJAX code in order to display the errors in a div (or above the invalid field) Code forms.py: class SubscriptionForm(forms.ModelForm): class Meta: model = Sub fields = "__all__" def __init__(self, *args, **kwargs): super(SubscriptionForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.template_pack = 'bootstrap3' self.helper.form_tag = True self.helper.form_id = 'sub-form-1' self.helper.form_class = 'form-inline' self.helper.form_action = 'landing:subscribe' self.helper.field_template = 'bootstrap3/inline_field.html' self.helper.layout = Layout( Div(Div(css_class='sub-form-notifications-content'), css_class='sub-form-notifications'), InlineField('name', id='subName'), InlineField('email', id='subEmail'), FormActions(Submit('sub-form', 'Notify me'), ), ) def clean_email(self): """ Validate that the supplied email address is unique for the site. """ if Sub.objects.filter(email__iexact=self.cleaned_data['email']): raise forms.ValidationError( _("This email address is already in use. Please supply a different email address.")) return self.cleaned_data['email'] form html: <form class="form-inline" id="sub-form-1" method="post"> <input type='hidden' name='csrfmiddlewaretoken' value='tdiucOssKfKHaF7k9FwTbgr6hbi1TwIsJyaozhTHFTKeGlphtzUbYcqf4Qtcetre'/> <!-- success/error messages should come HERE --> <div class="sub-form-notifications"> <div class="sub-form-notifications-content"> </div> </div> <div id="div_id_name" class="form-group"> <label for="subName" class="sr-only requiredField">Name</label> <input type="text" name="name" maxlength="30" required placeholder="Name" class="textinput textInput form-control" id="subName"/> </div> <div id="div_id_email" class="form-group"><label for="subEmail" class="sr-only requiredField">Email address</label> <input type="email" name="email" maxlength="60" required placeholder="Email address" class="emailinput form-control" id="subEmail"/> … -
django searching with blank instead of underscore
models.py class ImageModel(models.Model): name = models.ForeignKey(WorkModel, on_delete= models.CASCADE) image1 = models.ImageField(upload_to = 'static/images',null=True) image2 = models.ImageField(upload_to = 'static/images',null=True) image3 = models.ImageField(upload_to = 'static/images',null=True) thumbnail = ThumbnailerImageField(upload_to='static/thumbnails/', verbose_name='thumbnail', blank=True) views.py class WorkListView(generic.ListView): model = models.ImageModel template_name = 'work_list.html' context_object_name = 'image_list' html {% for image in image_list %} <tr> <td>{{ image.name }}</td> <td> <img src="{{ image.thumbnail.avatar.url }}" alt="why?"> </td> </tr> {% endfor %} when i run it i get image not found it seems to be searching for an image with blanks instead of underscore how do i fix this -
How to add comment to a particular model in django?
I have to add comment to model class Question, class Question(models.Model): My comment must be from user sides. Do help me with both codes for django and html-interface. -
Django-rest-framework with django OAuth 2.0 giving authentication error
I have integrated django-rest-framework with django-oauth-toolkit. And it is giving me {"detail": "Authentication credentials were not provided."} with un authenticated apis. Here's my settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } views.py from rest_framework.views import APIView from rest_framework.response import Response class SignUpView(APIView): """ Signup for the user. """ def get(self, request): return Response({'result': True, 'message': 'User registered successfully.'}) urls.py from django.urls import path from myapp.views import SignUpView urlpatterns = [ path('signup/', SignUpView.as_view()), ] -
Pagination in Django not working as expected
I wanted a pagination for all the courses available and that was easy to achieve. But now I'm stuck because I wanted pagination for faculties also, that will show specific courses of the accessed faculty. I have 4 models: faculties, departments, studies and courses. The pagination will show for faculties as well, but problem is that if I try to go to the second page, it will redirect me to the second page of all courses list. Or, if I change page on all courses and then try to access a faculty, no course will show at all in the faculty. This is working: <div id="crs"> <h3>All courses</h3> <ul> {% for course in courses %} <li><a href={{ course.slug }}>{{ course.name }}</a></li> {% endfor %} </ul> <div class="pagination"> <span class="step-links"> {% if courses.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ courses.previous_page_number }}">{{ courses.previous_page_number }}</a> {% endif %} <span class="current"> Page {{ courses.number }} of {{ courses.paginator.num_pages }} </span> {% if courses.has_next %} <a href="?page={{ courses.next_page_number }}">{{ courses.next_page_number }}</a> <a href="?page={{ courses.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </div> This is not working: <div id="fac_{{ faculty.pk }}_tab" style="display:none;"> <h3> {{ faculty.name }} Courses</h3> <ul> {% for department in faculty.department_set.all %} {% for … -
Dynamic page using Django(1.8) and Python 3.5
I am making a Dynamic Websites which updates Cryptocurrency rates every 1 minute using Django 1.8 and Python 3.5 Question Is it possible to make a function using Django and python that calls itself after every 1 minute or make another function that calls the other function after every 1 minute ,since that function will update values of cryptocurrencies and also change values shown on the website to the user? -
MultiValueDictKeyError when submitting ModelFormSet
When trying to submit my ModelFormSet I am getting a MultiValueDictKeyError. The error message is not very descriptive so I'm not sure why the error is being thrown. Here is the view: def admin_tools(request): ElectionFormSet = modelformset_factory(Election, exclude=('Complete',), formset=BaseElectionFormSet, extra=0) if request.method == 'POST': if 'new_election' in request.POST: new_election = NewElectionForm(request.POST) if new_election.is_valid(): election = new_election.save(commit=False) election.save() messages.add_message(request, messages.SUCCESS, 'Election created') return redirect(reverse('elections:home')) elif 'edit_elections' in request.POST: formset = ElectionFormSet(request.POST) if formset.is_valid(): formset.save() messages.add_message(request, messages.SUCCESS, 'Election settings saved') return redirect(reverse('elections:home')) else: new_election_form = NewElectionForm() formset = ElectionFormSet() return render(request, 'admin/admin_tools.html',{ 'new_election': new_election_form, 'formset': formset, }) Here is the relevant section of the template: <div class="card-body"> <h4>Toggle election settings:</h4> <form method="post" action=""> {{ formset.management_form }} {% for form in formset %} {% csrf_token %} <div class='card'> <div class='card-body w-75 mx-auto'> <div class='row'> <div class='col-6 text-center'> <p>Name<br>{{form.Name}}</p> </div> <div class='col-6 text-center'> <p>Videos<br>{{form.FlipGrid}}</p> </div> </div> <div class='row'> <div class='col-12 text-center'> <p>Description<br>{{form.Description}}</p> </div> </div> <div class='row'> <div class='col-6 text-center'> <p>Allow registration: {{form.CandidateReg}}</p> </div> <div class='col-6 text-center'> <p>Allow voting: {{form.VotingOpen}}</p> </div> </div> </div> </div> {% endfor %} <div class='text-center'> <br><button type="submit" class='btn btn-outline-dark' name='edit_elections'>Save</button> </div> </form> </div> The error is raise MultiValueDictKeyError(repr(key)) django.utils.datastructures.MultiValueDictKeyError: "'form-0-id'" and it was flagged on the line: if formset.is_valid(): of the … -
Adding redirect for Django admin detail view
I'm trying to set up a redirect so that when Django CMS users are accessing a detail view for one of the admin models, they get redirected to the listing view. I was able to successfully override the detail view within the admin.py file: class MyAdmin(MyModelAdmin): change_form_template = u"admin/myadmin/change_form_content.html" within the template, I'm creating a redirect back to the list view: {% block content %} <meta http-equiv="REFRESH" content="0;url=/myadmin/"> {% endblock %} This works fine, but it's messy. How can I move the redirect to the admin.py file instead? -
django category and subcategory selection on admin page
I'm having three tables, Category, Subcategory, Products. While inserting new product, there are two select boxes 1)1st select is for Category (its working) 2) 2nd is for Subcategory, which should be relevant to the 1st select. Needs to fetch the data from subcategory table. Subcategory table has category id as a foreign key. I am a beginner, please somebody help. -
Django: Accessing user-uploaded files in view
I have the following question: I have a listview that lists a number of user uploaded PDF files. I am creating a method that Zips them all in a .zip file and emails them (when a button is clicked). I have the following question: I am currently working locally on test data, but on our production setup the User Uploaded files are kept on a seperate S3 storage server. (As I understand is common). Since these files are on a different server however, do I need to write code in my view to download them first? Lets say for example that this is the model of an PDF file class ResumeItemFile(models.Model): item = models.ForeignKey(ResumeItem, related_name='attachment_files') file = models.FileField( max_length=255, upload_to=RandomizedFilePath('resume_attachments'), verbose_name=_('Attachment')) name = models.CharField(max_length=255, verbose_name=_('Naam'), blank=True) Since the file field links to a different S3 server, would a ResumeItemFile.file call result in a .get request that I need to handle, or does Django do this stuff automatically in the background? -
Methods for rendering only a block in a django base template
I am in dire need of some direction, I need no code unless its an example. I have been struggling with this: My base.html page has 3 div elements in the top that will cycle alert messages and rotate every 10 seconds or so. Easy enough, however I want this ticker to remain site wide. I'm using Django as my back end and have yet to integrate react or riotjs. I attempted AJAX however I would have to do so much to make my site function as everything BUT the ticker would be an AJAX call which doesn't feel right. Plus I lose back button and SEO. Attached is an image of what the site looks like for these tickers. I can add code if anyone thinks it will help however i just need the basic method to decide where to move on. I cannot think of anything for the life of me, THANK YOU! This is the top of the site that I am working on, as you can see the 3 alert divs -
Loaded image on canvas disappears when user draws on it
I am working with Django framework and I want to load on a canvas an image and then draw over it. With the following code I successfully load the image: <form method="post" enctype="multipart/form-data"> <input TYPE="button" onClick="myReload();" VALUE="Refresh"> <script> function myReload() { location.reload(); } </script> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p> {% endif %} <canvas id="canvas" width="768" height="576" style="border:1px solid #d3d3d3"></canvas> {% if name_of_file %} <img id="image" style="display: none;" src="/static/{{ name_of_file }}"> {% endif %} I am trying to draw a polygon over the loaded image. When I press the 'Draw' button I can draw on the canvas but the image I uploaded disappears. <button onclick="drawPolygon()" name="plaque">Draw</button> function drawPolygon() { var img = new Image; img.onload= function() { document.getElementById("canvas").style.cursor="crosshair"; var canvas=document.getElementById("canvas"); var context=canvas.getContext("2d"); var cw=canvas.width; var ch=canvas.height; function reOffset(){ var BB=canvas.getBoundingClientRect(); offsetX=BB.left; offsetY=BB.top; } var offsetX,offsetY; reOffset(); window.onscroll=function(e){ reOffset(); } context.lineWidth=2; context.strokeStyle='blue'; var coordinates = []; var isDone=false; $('#done').click(function(){ isDone=true; }); $("#canvas").mousedown(function(e){handleMouseDown(e);}); function handleMouseDown(e){ if(isDone || coordinates.length>10){return;} // tell the browser we're handling this event e.preventDefault(); e.stopPropagation(); mouseX=parseInt(e.clientX-offsetX); mouseY=parseInt(e.clientY-offsetY); coordinates.push({x:mouseX,y:mouseY}); var stringY = document.getElementById('yA1').value; document.getElementById('yA1').value = stringY + ' ' +parseInt(e.clientY-offsetY); var stringX = document.getElementById('xA1').value; … -
Splitting Django views in multiple views with import in a separate file
I am trying to split my very very long view.py file I am following tutorials that I found but I may miss something. I will make my example generic to fit to other that may have the same issue. Let say that I have a view.py in following way : import xx from yy import xx from yy import xx from yy class name1(view): class name2(view): class name3(view): class name4(view): Now what I did is to create a view file with inside: View -> __init__.py -> views_import.py -> view1.py -> view2.py -> view3.py in __init__.py : from .views_import import * from .view1 import * from .view2 import * from .view3 import * However I get an error message that NameError: name 'generic' is not defined. When from django.views import generic is in my views_import.py Could you help ? -
Django ContentType Name of CamelCase models
I am playing with generic foreign key, and i wanted to filter the available models with limit_choices_to. class Foo(models.Model): name = models.CharField(max_length=300) class FooBar(models.Model): name = models.CharField(max_length=300) class Treatment(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to={'model': 'foo'}) # !! object_id = models.CharField(max_length=300, null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') So it works with the class Foo, in lower case, but for FooBar i tried foo_bar, fooBar, foo bar and none of these works... How am i suppose to spell it ?? I can see its separated by spaces in the drop down menu of the content type form. -
Django Crud for a Model, Need to Copy for Big no of Models, Need DRY Concept
I have crud for model but i need to copy this for big no of models.. I Need Your Recommendations to minimize the copy past. Thanks And kindly dont recomment django admin, i want to use my own theme. I hvae model as: class Board(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) description = models.CharField(max_length=100, null=True, blank=True) And ModelForm as: class BoardForm(forms.ModelForm): class Meta: model = Board fields = [ 'name', 'description', ] I have Django Url Patterns as shown below: url(r'^board/$', board_crud, name='board_crud'), url(r'^board/(?P<pk>\d+)$', board_crud, name='board_update'), And i Have View: def board_crud(request, pk=None): objects = Board.objects.filter() if pk is not None: object = get_object_or_404(Board, pk=pk) form = BoardForm(request.POST or None, instance=object) if form.is_valid(): form.save() form = BoardForm() return redirect('board_crud') return render(request, "crud/boards.html", {'form': form, 'object_list': objects}) else: if request.method == 'GET': form = BoardForm() else: form = BoardForm(request.POST) if form.is_valid(): instance.save() form = BoardForm() messages.success(request, 'Record Added Successfully') return render(request, "crud/boards.html", {'form': form, 'object_list': objects}) And Template with form Maker and Table: {% for field in form %} <section class="col col-6"> <label class="label">{{ field.label_tag }}</label> <label class="input"> {{ field }} </label> </section> {% endfor %} <table id="tbl" class="table table-bordered table-striped"> <thead> <tr> <th>Board Name</th> <th>Description</th> </tr> </thead> <tbody> {% for … -
Overriding Django Admin Detail View
How can I override the existing admin detail view for a model in Django? I understand how to make changes to the listing view, but I'm not entirely sure how to make changes to the detail views. Ideally I want create an override so that instead of accessing a form, the user is redirected back to the listing view. class MyAdmin(MyModelAdmin): change_list_template = u"admin/post_manager/content/change_list_content.html"