Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django adding placeholders to django built in login forms
I'm using django built-in login forms and i want to add placeholders to username and password. My template: <div class="form-group"> <div class="col-md-12"> {{ form.username|add_class:'form-control' }} </div> </div> <div class="form-group"> <div class="col-md-12"> {{ form.password|add_class:'form-control' }} </div> </div> How can i do this? -
Creating bootstrap list using ajax in django
How to create a bootstrap list using AJAX view in django?? I have searched in all the websites and i did not get any answers. I am totally frustrated.. Someone please help me. Following is my view from django.views.generic import * from AssetHierarchy.models import * from django.shortcuts import render_to_response class TreeStructure(TemplateView): template_name = 'TreeStructure.html' def get_context_data(self, **kwargs): context = dict() organization = Organization.objects.all() orglocations = Orglocations.objects.all() locationprocessarea = Locationprocessarea.objects.all() processareaasset = Processareaasset.objects.all() processtaglink = Processareaassettaglink.objects.all() context["TreeStructure"] = [ { 'text': organizations.name, 'nodes': [ { 'text': orglocationss.name, 'nodes': [ { 'text': processarea.name, 'nodes': [ { 'text': processasset.name, 'nodes': [{ 'text': processareafilter.name, 'nodes': [{ 'text': taglink.name }for taglink in processtaglink.filter(areaassetid=processareafilter.id)] }for processareafilter in processareaasset.filter(parentassetid=processasset.id)] } for processasset in processareaasset.filter(processareaid=processarea.id).filter(parentassetid__isnull=True)] } for processarea in locationprocessarea.filter(locationid=orglocationss.id)] } for orglocationss in orglocations.filter(organizationid_id=organizations.id)] } for organizations in organization.filter(id=1)] return { "tree_view": context } class AjaxView(TemplateView): template_name = 'TreeStructure.html' def get_context_data(self, **kwargs): areaasset =Processareaasset.objects.all() taglink = Processareaassettaglink.objects.all() -
Dropzone Form not properly handled
I have a small django application: the user uploads a file, the file is modified on the server side and the modified file is sent back to the user as a download. In order to provide a nice drag-and-drop file upload form I use dropzone.js. The form contains other input elements, so I followed this howto. After the form is submitted, the django view returns a HttpResponse object: response = HttpResponse(f.read(), content_type="application/pdf") response['Content-Disposition'] = 'attachment; filename="%s"' % input_file My problem is: if I use the dropzone-based form, the response isn't shown, i.e., the browser does not show a download dialog. Here is the minimal example of my html file: <form method="post" class="dropzone" action="/mysite/" enctype="multipart/form-data" id="myForm"> {% csrf_token %} <select name="selectpdf" size="1"> // filled by django magic </select> <p><button type="submit">Do it!</button></p> </form> <script type="text/javascript"> Dropzone.options.myForm = { // Prevents Dropzone from uploading dropped files immediately autoProcessQueue : false, forceFallback : false, init : function() { myDropzone = this; this.element.querySelector("button[type=submit]").addEventListener("click", function(e) { // Make sure that the form isn't actually being sent. e.preventDefault(); e.stopPropagation(); myDropzone.processQueue(); }); } }; </script> When I use a regular HTML form (i.e., without the class="dropzone"), everything works perfectly. Also, if I activate dropzones fallback mode (which basically … -
Am I executing celery shared tasks correct?
Here is the way how I start celery periodic tasks. First I execute this command: celery worker -A my_project.celery And after that this command: celery -A my_project beat -l info -S django After executing these two commands on two different terminal tabs, my celery beat periodic tasks starts running. If I don't run one of the described commands, my periodic tasks do not run. My question is: is there any any way to start the celery with the single command, or even better with runserver command? -
Do I need to make a migration if I change null and blank values on a Model field?
I have the following model @python_2_unicode_compatible class Booking(models.Model): session = models.ForeignKey(verbose_name=_('Session'), to=Session, default=None, null=False, blank=False) quantity = models.PositiveIntegerField(verbose_name=_('Quantity'), default=1, null=False, blank=False) price = models.DecimalField(verbose_name=_('Price'), max_digits=10, decimal_places=2, default=None, null=False, blank=False) name = models.CharField(verbose_name=_('Name'), max_length=100, default=None, null=False, blank=False) email = models.EmailField(verbose_name=_('Email'), default=None, null=True, blank=True) phone_number = models.CharField(verbose_name=_('Phone Number'), max_length=30, default=None, null=True, blank=True) Say I need to change my email and phone_number fields. I want them to have null=False and blank=False. Do these alterations require a new migration? -
Django FloatField does render as input[type=number] even with localize=true
I am clueless about this. As far as documentation goes, django should render a FloatField as input[type="text"], when field.localize = True see https://docs.djangoproject.com/en/1.11/ref/forms/fields/#floatfield But in my case it is still rendered as input[type=number] - did I miss something? The main problem with that is, that I have localized number representation and with type=number I get issues with retrieving the value. Anyone can give me a hint, why django refuses to use type="text" when field.localize=true? Thank you very much -
Get million record from django with queryset is slow
I want to iterate all the objects of a table(Post) I am using below code: posts = Post.objects.all() for post in posts: process_post(post) But the problem I am having is Post table has 1 million records.This is not one time job.I am running it daily. for post in posts In above line, Query is called which fetches all the data from DB in one go. How can I improve its performance? Is there any way by which data is fetched in batches? -
Django How to display Form query results in a ListView
I've created a For where users will enter a date range, once submitted it then needs to return a list from my database of people all those whose birthdays are within that date range, I'm fairly new to Django and i've tried but do not understand how to pass my "start_date & end_date" as kwargs from my form to ListView. Views.py: class BirthdaysRangeFormView(FormView): template_name = 'snippets/date_selection_form.html' form_class = datefilterform def get_form_kwargs(self): kwargs = super(BirthdaysRangeFormView, self).get_form_kwargs() kwargs ['request'] = self.request return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = "Date Selection" context['header'] = "Please select date range" return context def form_valid(self, form): self.start_date = (form.cleaned_data['start_date'], People.next_birthday) self.end_date = (form.cleaned_data['end_date'], People.next_birthday) return self.redirect_to_results() def redirect_to_results(self): self.success_url = "dates:birthdays" return redirect( self.get_success_url(), ) class BirthdayCardListView(BirthdaysRangeFormView, ListView): template_name = 'unsubscribes/birthdays.html', context_object_name = "person" person = True # queryset = People.objects.order_by('next_birthday') def get_queryset(self): test = '' forms.py: class datefilterform(forms.Form): model = People start_date = forms.DateField( input_formats=['%d/%m/%Y'], widget=DateTimePicker( options={"format": "DD/MM/YYYY", "pickTime": False}) ) end_date = forms.DateField( input_formats=['%d/%m/%Y'], widget=DateTimePicker( options={"format": "DD/MM/YYYY", "pickTime": False}) ) People.next_birthday = start_date People.next_birthday = end_date def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(datefilterform, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'main_form' self.helper.form_class ='form-horizontal' self.helper.label_class = 'col-lg-3' self.helper.field_class = 'col-lg-8' self.helper.layout = … -
How to consume data in ModelViewSet - djangorestframework
I have a datepicker and angularjs cotroller in which I'm capturing date, and I'm trying to pass it into my ModelViewSet so I can filter on next_action_date field and display leads for selected date, but I'm not fully understand how can I code this in my rest view so I can display them correctly. I understand how to filter leads on next_action_date, for future dates like this: import datetime LeadContact.objects.filter(next_action_date__gte=datetime.date.today()) and to display past dates filter like this: LeadContact.objects.filter(next_action_date__lte=datetime.date.today()) This is my first time doing this so I'm in a dilemma how to approach this problem, should I filter in get_queryset or made a custom create - update method, so can anyone please help me to understand this or show me how to deal with this, thanks. My view: import datetime from rest_framework import viewsets, permissions, filters, status from rest_framework.response import Response from django.shortcuts import get_object_or_404 from cms.restapi.pagination import StandardResultsOffsetPagination from cms_sales.models import LeadContact from cms_sales import forms from cms_sales.restapi.permissions.lead_contact_permissions import LeadContactPermissions from cms_sales.restapi.serializers.lead_contact_serializer import LeadContactSerializer class LeadContactViewSet(viewsets.ModelViewSet): def get_queryset(self): queryset = LeadContact.objects.none() user = self.request.user if user.has_perm('cms_sales.can_view_full_lead_contact_list'): queryset = LeadContact.objects.all() elif user.has_perm('cms_sales.can_view_lead_contact'): queryset = LeadContact.objects.filter(account_handler=user) return queryset serializer_class = LeadContactSerializer filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter) filter_fields = ('account_handler',) ordering_fields … -
how to improve speed of django haystack search
I want to create a search engine in my django environment for the simple data structure: | id | comapany name | |:-----------|-----------------:| | 12345678 | company A's name | | 12345687 | peoples pizza a/s| | 87654321 | sub's for pugs | There will be about 800,000 companies and I only want to search by name. When the name is found the ID is returned in my django. I've tried various set ups with haystack, whoosh and such but I keep getting really slow search results as I raise from my test data set of ~500 to the 800,000. The search some times takes almost an hour. I'm using the Paas Heroku so I thought I would try an integrated paid service (searly's elasticsearch implementation). This helped, but as I arrive at about 80,000 companies it starts getting really slow again. Installed Apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', # Added. 'haystack', # Then your usual apps... ] More settings.py import os from urlparse import urlparse es = urlparse(os.environ.get('SEARCHBOX_URL') or 'http://127.0.0.1:9200/') port = es.port or 80 HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': es.scheme + '://' + es.hostname + ':' + str(port), 'INDEX_NAME': 'documents', }, if … -
TypeError: 'is_staff' is an invalid keyword argument for this function , when create superuser
python manage.py createsuperuser Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 168, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 149, in _create_user user = self.model(username=username, email=email, **extra_fields) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/base_user.py", line 68, in init super(AbstractBaseUser, self).init(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 555, in init raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) TypeError: 'is_staff' is an invalid keyword argument for this function -
attach img file in pdf weasyprint
me need help with attach img file in pdf we use WeasyPrint lib for generation pdf from html in html connect img file so <img src="1.png" alt=""> <img src="2.png" alt=""> <img src="3.png" alt=""> but instead images empty place -
How to get the value of appended elements
I have a form which involves entering a question. The form initially has 2 input slots for choices to that question, but clicking a button will append another input to add another choice. Problem is I can't get the value to these appended elements. Any idea how else I can do it? Here's my code: models class Question(models.Model): has_answered = models.ManyToManyField(User, through="Vote") question_text = models.CharField(max_length=80) date = models.DateTimeField(auto_now=True) total_votes = models.IntegerField(default=0) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=100) votes = models.IntegerField(default=0) percent = models.IntegerField(default=0) def __str__(self): return self.choice_text views def questions(request): question_form = QuestionForm(request.POST or None) choice_form = ChoiceForm(request.POST or None) if request.user.is_authenticated(): if question_form.is_valid(): question = question_form.save(commit=False) question.save() choices = request.POST.getlist('choice_text') for choice in choices: Choice.objects.create(choice_text=choice, question=question) else: print(question_form.errors) return render(request, 'questions.html', {'question_form': question_form, 'choice_form': choice_form}) template <form method="post" action="">{% csrf_token %} {{ question_form.question_text|placeholder:"Question" }} <br><br> <!--{{ choice_form.choice_text|placeholder:"Choice" }}--> <input class="choice" name="choice_text" placeholder="Choice" type="text" /> <input class="choice" name="choice_text" placeholder="Choice" type="text" /> <img src="{% static 'images/plus.png' %}" class="add_choice" /> <button class="submit" type="submit">Submit question</button> </form> js (adds another choice field) $(document).on('click', '.add_choice', function(){ $(this).after('<input type="text" class="choice" placeholder="Choice" name="choice_text" /><img src="/static/images/plus.png"' + " class='add_choice' />"); }); -
Django rest swagger, How to do POST api's?
I'm using django-rest-swagger(2.1.2), and used the basic scheme in the examples. from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='My great API', url='/a-different-path') I need complete details of each api including models details and form to fill out for post api. But when i click on POST api's i noticed that its missing post data adding part and all api's are missing model info. How can i fix this? I used django-rest-framework(3.6.2) django 1.9 -
Django/JS - Send file to users, as known as download functionality
I want to let users to download a specific file, by clicking on a button "Download". The button will be linked with many switchers, so I wrote a JS script that change the "href" tag to point to the correct static file. I tried to follow many stackoverflow questions and read documentation about Django staticfiles, media files but did not understand what I need to do on my case. Any help would be really appreciated, let me please introduce what I did and ask for your help/opinion. I want to let people download files that can be found in : "/home/user/xxxx/xxx/project/my_app/static/" Here is my function in views.py : def send_file(request,file_name): from django.contrib.staticfiles.storage import staticfiles_storage import os from wsgiref.util import FileWrapper import mimetypes filename = staticfiles_storage.url(file_name) download_name = file_name wrapper = FileWrapper(open(filename)) content_type = mimetypes.guess_type(filename)[0] response = HttpResponse(wrapper, content_type=content_type) response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = "attachment; filename=%s" % download_name return response I need the exact path to open the file, so what I have done is that I defined on my settings STATIC_URL = "/home/user/xxxx/xxx/project/my_app/static/" . I do not like this solution, because after it, if you check my source, you have the exact path of my project. If I defined STATIC_URL … -
Django Testing Models / testing dynamic objects
I'm new on testing on django. Due to coverage reports , I need to test models but couldn't do it. -
how to set django admin ordering field customely?
admin.py class MovieItemInline(AjaxSelectAdminTabularInline): model = MovieItem ordering = ['-date'] class MovielistAdmin(ModelAdminBase, AjaxSelectAdmin): inlines = (MovieItemInline, ) admin.site.register(Movielist, MovielistAdmin) models.py class MovieItem(Model): title = CharField(default="") view_number = IntegerField(default=0) price = IntegerField(default=0) date = IntegerField(default=0) class Movielist(Model): title = CharField(default="") display_order = CharField(default="date") MovieItemInline is MovielistAdmin's inline attribute, I wanna sort MovieItem, for example, if Movielist.display_order equals "date", then sort MovieItem by MovieItem.date. if Movielist.display_order equals "price", then sort MovieItem by MovieItem.price. if Movielist.display_order equals "view_number", then sort MovieItem by MovieItem.view_number. What should I do? Is django support? -
Django form: formatting data from an instance before render
Using Django 1.11, one of my models is an array stored within a django-jsonfield field. class MyModel(models.Model) id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) core = JSONField(blank=True, null=True, default=None) I am using a ModelForm in a couple of views to create and edit new instances. Within the ModelForm I'm borrowing the django.contrib.postgres.forms.SimpleArrayField to parse the input into the field. Adding a new model is fine, but in the edit version, the array gets pre-populated with what looks like the __str__ representation (eg an array of 1,2,3 becomes ['1','2','3']. I'm getting around this by parsing the array into initial= for each form but I'd rather do this in one place (DRY) rather than having to repeat it inside each view and form instance. Are there any hooks or methods (perhaps a custom widget?) that means I can do this just once in the form or somewhere else? Snippet of the current view with hacky approach using initial=: def edit_mymodel(id): current_instance = MyModel.objects.get(pk=id) if request.method == "GET": form = MyModelForm(instance=current_instance, initial={"core": ",".join(current_instance.core)} ) return render(request, 'network_manager/edit.html', {'form': form} ) -
How to connect a Django view with angular js Front end?
I'm fairly new to Django rest and angularjs. I'm trying to create a Django view which will have a function and this function has to be called via a button in angular js. Can anyone please help me out? Thanks -
How to include ejudge system to own web-site?
User should send the problems solution (.cpp and other) via my interface and get the result in my web-site. How to do it? I am doing web-site by using django framework. -
django parse Response header X-Auth
cursor.execute("SELECT DISTINCT User.name,Person.id,Person.firstName,Person.lastName,User.tokenHash from User JOIN Person ON User.personId = Parkloco.Person.id WHERE User.name = '%s' AND User.enabled = 1 " % username) fields = map(lambda x: x[0], cursor.description) result = [dict(zip(fields, row)) for row in cursor.fetchall()] Response['X-Auth'] = result.tokenHash return Response(result,status=status.HTTP_201_CREATED) How to Parse Response Header in django. -
Cache Control Header public for all dajngo media files
I am wondering if it's possible to put or set something in the settings.py to make all the media file's cache-control header to public -
modify unique_together bound form django
I'm trying to modify an existing row of my database, it's a from an intermediary table named "CharacterSkill" with an unique together constraint : models.py class CharacterSkill(models.Model): character = models.ForeignKey(Character, on_delete=models.CASCADE) level = models.IntegerField(default=0) skill = models.ForeignKey(Skill, on_delete=models.CASCADE) class Meta: unique_together = ("character","skill") I did a form to change the level but I'm unable to save the form, I have two errors messages from both fields "character" & "skill": Select a valid choice. That choice is not one of the available choices. My form : class SkillCreateForm(forms.ModelForm): class Meta: model = CharacterSkill fields = ('skill','level','character',) my view : def skill_update(request,skillpk,instancepk): form = SkillCreateForm(request.POST) user = User.objects.get (id = request.user.id) instance = Character.objects.get (id = instancepk) skill = CharacterSkill.objects.get(id = skillpk) data = {'character' : instance, 'skill' : skill.skill, 'level' : skill.level, } if form.is_valid(): form.save() return redirect('persomaker:skill_list', instance.id) else: form = SkillCreateForm(data) #form.fields['skill'].widget = HiddenInput() #form.fields['character'].widget = HiddenInput() return render(request, 'character/create_skill.html', {'instance':instance, 'skill':skill, 'form': form,}) -
I'm trying to install django=1.9 on ubuntu using python and I'm getting the following errors for admin login
django error displayed on terminal: Not Found: /favicon.ico [21/Apr/2017 07:33:24] "GET /favicon.ico HTTP/1.1" 404 1963 Not Found: /favicon.ico [21/Apr/2017 07:33:25] "GET /favicon.ico HTTP/1.1" 404 1963 [21/Apr/2017 07:34:23] "GET /admin/ HTTP/1.1" 302 0 Internal Server Error: /admin/login/ Traceback (most recent call last): File "/home/priya/.local/lib/python3.5/site-packages/django/template /utils.py", line 65, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/priya/.local/lib/python3.5/site- packages/django/template/backends/django.py", line 126, in get_package_libraries And this is the error message displayed on Browser: InvalidTemplateLibrary at /admin/login/ Invalid template library specified. ImportError raised when trying to load 'django.templatetags.future': cannot import name 'RemovedInDjango110Warning' Request Method: GET Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 1.11 I have installed django=1.9 version and it's showing 1.11 Exception Type: InvalidTemplateLibrary Exception Value: Invalid template library specified. ImportError raised when trying to load 'django.templatetags.future': cannot import name 'RemovedInDjango110Warning' Exception Location: /home/priya/.local/lib/python3.5/site- packages/django/template/backends/django.py in get_package_libraries, line 130 Python Executable: /usr/bin/python3 Python Version: 3.5.2 Python Path: ['/home/priya/Desktop/project/project', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-i386-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/priya/.local/lib/python3.5/site-packages', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages'] -
How to Encrypt pk from django url without using any package?
how to encrypt and decrypt pk from django url without using any package basically i have a url like example.com/update/1 where pk=1 i want to encrypt the pk like pk 1 = 345345435cgsfd2asdfaas