Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Server as a Windows Service
I have a batch File that runs Django Server and it works perfect. c:\Python27\python.exe manage.py runserver 8003 and that I am using a 3rd Party app NSSM https://nssm.cc/ Which run my Batch file as a Windows Service. the point is the Service does not start the Server. How can I run the server using this service; the service will open the cmd and execute the command. Should I use another 3rd party app or is there any command that I can add to my batch file and update it the serive -
Recompile django app after chages
After installing pinax-user-account app I have two directories, mysite and mysiteenv. Once I change the urls.py in the mysiteenv I cannot see the changes applied. I guess I need to recompile the app as the main urls.py in mysite respond well after changes. -
Django EC2 remote debug connection refused
I am trying to add remote interpreter to debug my Django project remotely in Pycharm. I thought I set up all necessary things. I also open the port 8000 on my EC2 instance. So, when I clicked the debug button on Pycharm connection is establishing however when I open a browser and type http://my-site-env.elasticbeanstalk.com:8000/ I am getting ERR_CONNECTION_REFUSED. I think it is somehow related with port but I am sure I opened it. Pycharm is successfully connecting when I clicked the debug button Open ports on my instance -
how to print the result of a bash script on a webpage using django rest framework
i'm new to django (DRF), i want to print the result of a script "myscript.sh" using a view and a template. I tried the following but it doesn't work : In myapp/views.py : class TestView(TemplateView): template_name = 'index.html' def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) proc = subprocess.Popen("./myscript.sh", shell=True, stdout=subprocess.PIPE) line = proc.stdout.readline() while line: yield line line = proc.stdout.readline() In myapp/templates/index.html: <html> <head> <title> Lines </title> </head> <body> <p> {{ line }} </p> </body> </html> -
django ORM : query of three models
Hi I wondering if someone can help me with this problem as I am new to django. I have the following models class Article(models.Model): articleid = models.CharField(primary_key=True,max_length=20) author = models.CharField(max_length=300) title = models.CharField(max_length=500) # Each article can only have one ArticleTone class ArticleTone(models.Model): label = ( ('sad', 'Sad'), ('happy', 'Happy'),) articleid = models.ForeignKey(Article, on_delete=models.CASCADE, db_column="article") tone = CharField(max_length=10,choices=label,blank=False, null=False) class Meta: ordering = ('tone',) # Each article will have 5 keywords class ArticleKeywords(models.Model): articleid = models.ForeignKey(Article, on_delete=models.CASCADE, db_column="article") keywords = models.CharField(max_length=100,blank=False, null=False) I am able to get the top 20 entities using this query. ArticleKeywords.objects.values('articleid').annotate(result=Count('keywords')).order_by('-result')[:20] and able to get articles that are sad or happy using something like this ArticleTone.objects.filter(name= 'sad'); But how do I put the pieces together to get all the articles that contain the top 20 sad or happy articles. Any help is appreciated -
Django: registration, login, and logout
New to django, I see quite some tutorials and I'm confused: is there a built-in something in django that I should use for registration, login and logout? do I need to code my self or is it already available as third party stuff to install? I need guidance on the best practice and fastest, most reliable way. -
Django Datetimepicker change icons
Django-boostrap3-datetimepicker use "Glypicon". Does anyone know it is possible change to Font awesome ? Can you help me ? -
when installing virtualenv what's the point of adding --no-site-packages
I usually just go virtualenv myfolder but I see some people using --no-site-packages at the end, what's the point of this? -
Django Queryset Iterator for Ordered queryset
I want to use queryset iterator for iterating over a large dataset. Django provides iterator() for this, but that will hit database for each iteration. I found following code for iteration in chunks - def queryset_iterator(queryset, chunksize=1000): ''''' Iterate over a Django Queryset ordered by the primary key This method loads a maximum of chunksize (default: 1000) rows in it's memory at the same time while django normally would load all rows in it's memory. Using the iterator() method only causes it to not preload all the classes. Note that the implementation of the iterator does not support ordered query sets. ''' pk = 0 last_pk = queryset.order_by('-pk').values_list('pk', flat=True).first() if last_pk is not None: queryset = queryset.order_by('pk') while pk < last_pk: for row in queryset.filter(pk__gt=pk)[:chunksize]: pk = row.pk yield row gc.collect() This works for unordered queryset. Is there any solution/workaround to do this on an ordered queryset? -
Django unittest POST form with image
I am doing a Django Unittesting on Django REST ViewSets. In one endpoint it can receive fields and image. Here is models.py class CarData(AbstractSoftModelController): front_photo = models.ImageField(upload_to=RandomFileName('upload/cars'), blank=True, verbose_name=_('Front photo')) brand = models.CharField(max_length=255, db_index=True, verbose_name=_('Brand')) model = models.CharField(max_length=255, db_index=True, verbose_name=_('Model')) color = models.CharField(max_length=255, blank=True, db_index=True, verbose_name=_('Color')) viewsets.py class CarDataViewSet(viewsets.ModelViewSet): serializer_class = CarDataSerializer permission_classes = (IsAuthenticated,) filter_class = CarDataFilter queryset = CarData.objects.filter(license_plate__alive=True, license_plate__isnull=False) serializers.py class CarDataSerializer(ModelControllerSerializer): class Meta: model = CarData exclude = EXCLUDE_COMMON_FIELDS extra_kwargs = { } And I want to test POST to this endpoint with image. class CarDataViewSetTestCase(APITestCase): def setUp(self): mommy.make(User, _quantity=1, username='sivabudh') mommy.make(CarData, _quantity=3, brand='Ferrari', color='black') mommy.make(LicensePlate, _quantity=3) self.client.force_login((User.objects.get(username='sivabudh'))) def test_create(self): file_path = str(settings.ROOT_DIR.path('static_files/images/logo-eneos.png')) with open(file_path, "r", encoding='utf-8', errors='ignore') as fp: data = { 'brand': 'Ferrari', 'model': 'LaFerrari Aperta', 'color': 'Red', 'license_plate': LicensePlate.objects.first().id, 'front_photo': fp } response = self.client.post( reverse('api:car-list'), data, content_type='application/x-www-form-urlencoded' ) import pdb; pdb.set_trace() assert 200 == response.status_code And the error is: (Pdb) response.data ["{'brand': ['This field is required.'], 'model': ['This field is required.'], 'license_plate': ['This field is required.']}"] My attempts: Then I change the header a bit content_type='multipart/form-data' I got {'detail': 'Multipart form parse error - Invalid boundary in multipart: None'} Where am I wrong? -
Best practice to rebind js widget after ajax/replacement?
I have a django website with some custom js/widgets i wrote myself. To give an idea of the js code: $(document).ready(function() { $(".input_group_text_clear button").on("click", function (e) { data_action = $(this).attr('data-action'); data_target = $(this).attr('data-target'); $.each(data_target.split(':'), function(i, target) { $("#" + target).val("").trigger("change"); }); e.preventDefault(); }); }); Now this works very well since i only need to glue this js code to a django widget, tie it to the form and the code is included with the template. The issue is that often i post forms using ajax and upon failure the rendered form including error/blocks is returned via a json api. I then "replace" the form element with the one containing the errors. Issue is that i need to rebind the controls; otherwise the control won't work as planned obviously. What i usually do is to extract the "bind" code in a global function and invoke that from the ajax/done handler but i don't really like it because you need to assume what controls are in the form, my question is if there are best practices for such element replacement combined with binding js functions? Help is greatly appreciated, Paul -
django forms how to show error/warning when part of form is hidden
all, I have a django form separated to 4 parts as attached below, and part2,3,and 4 are hidden as an requirement. There are "requried" field in the hidden part. I want to show warning/error message as an pop-up alert when click on "Submit". But if I understand correctly, as django form will validate the required fields in the hidden part, and the "Submit" can not be triggered. And because these parts are hidden, the django warning info can not be displayed as well. I am wondering how can I trigger warning to notify user to click the hidden parts. Thanks, Zhihong -
MultiValueDictKeyError at /viewname when using <select>
I'm using Django 1.11.2, I get this error MultiValueDictKeyError at /addOne whenever i use html select to post data. The form works fine when I replace select with an input type=number. The key 'ino' doesn't appear in post data when using select. Image of error page html- <form action="{% url 'addOne' %}" method="POST" name="addItem"> {% csrf_token %} <div class="form-group"> <label for="ino">Select Invoice Number</label> <select class="form-control" id="ino" name="ino" size="2" required> {% for vendor in vendors %} <option value="{{vendor.ino}}">{{vendor.ino}}</option> {% endfor %} </select> </div> ... </form> view- def addOne(request): if(request.method == 'POST'): ino = request.POST['ino'] ides = request.POST['ides'] ihsn = request.POST['ihsn'] iqty = request.POST['iqty'] iunit = request.POST['iunit'] irate = request.POST['irate'] itotal = request.POST['itotal'] idisc = request.POST['idisc'] itaxable = request.POST['itaxable'] icgstr = request.POST['icgstr'] icgsta = request.POST['icgsta'] isgstr = request.POST['isgstr'] isgsta = request.POST['isgsta'] iigstr = request.POST['iigstr'] iigsta = request.POST['iigsta'] invoice = Invoice(ino=ino, ides=ides, ihsn=ihsn, iqty=iqty, iunit=iunit, irate=irate, itotal=itotal, idisc=idisc, itaxable=itaxable, icgstr=icgstr, icgsta=icgsta, isgstr=isgstr, isgsta=isgsta, iigstr=iigstr, iigsta=iigsta) invoice.save() return redirect('/') else: vendors = Vendor.objects.all().order_by('ino') return render(request, 'addOne.html', {'vendors':vendors}) -
Django staticfiles static tempalate helper equivalent in view (Python code)
I have a Django app which uses ManifestStaticFilesStorage, in production static assets are served via a CDN and references to them in templates are correctly set, e.g. Template: {% load staticfiles %} <script type="text/javascript" src="{% static 'some.js' %}"></script> Rendered HTML: <script type="text/javascript" src="https://example.com/some.abc123.js"></script> Is it possible to get the fully-qualified URL to a static asset in a view? I would like to have a view that redirects to a static asset on my CDN. Something like: import django.http HttpResponseRedirect def my_lovely_view(request): static_asset_url = static('some.js') # does this fn exist? # static_asset_url == 'https://example.com/some.abc123.js' return HttpResponseRedirect(static_asset_url) -
Calling a secured (authentication required) REST from django
I need to call a REST service from django where authentication (username + password) is required . I can get the password from request.user.password but it is not there in clean-text format but pbkdf2_sha256$36000$rOpm97qpHsy4$NFKCCfMmve1Z6c1U/grizJ6TyQck3bE/Fe+Gy3Gi+c8= (which is good from security point of view) However as far as I know a secured REST service needs the clean-text password to perform the authentication so I cannot call it. I wouldn't be a big fan of storing the password when the user logs in. How can a secured REST service be called from Django? -
python - Django + Materializecss
Everytime i'm trying to alter a manytomanyfield from an instance using django-forms, fields are always unchecked on the view but checked on the database. Is there something wrong with materializecss? forms.py class CustomForm(forms.ModelForm): class Meta: model = Custom fields = ['single_meta', 'many_to_many_meta', 'hard_meta'] views.py custom_form = CustomForm(instance=custom_instance) return render(request, "custom.html", {"form": custom_form}) custom.html <div class="row"> <div class="input-field col s3"> {{ custom_form.many_to_many_meta }} <label for="{{custom_form.many_to_many_meta.id_for_label }}"> ManyToManyField! </label> </div> </div> -
Django: Aggregation using Trunc on AWARE datetime field fails to count correctly
Considering this model: class MyModel(models.Manager): timestamp_unaware = models.DateTimeField(auto_now_add=True) timestamp_aware = models.DateTimeField(default=timezone.now) And these instances: MyModel.objects.create() --> pretending now is 2017-06-22 T 10:00:00 MyModel.objects.create() --> pretending now is 2017-06-22 T 11:00:00 I'm trying to create timeseries (count per day) for a graph using Trunc. But the query gives different result depending on the timestamp format. I've tried both sqlite3 and postgres with no change in result. # 1) this works as expected; timestamp was generated by auto_now_add MyModel.objects\ .annotate(day=TruncDay('timestamp_unaware ', output_field=DateField()))\ .values('day')\ .annotate(count=Count('id')) --> <QuerySet [{'day': datetime.date(2017, 6, 22), 'count': 2}]> # 2) this does not count correctly; timestamp was generated using the timezone.now MyModel.objects\ .annotate(day=TruncDay('timestamp_aware ', output_field=DateField()))\ .values('day')\ .annotate(count=Count('id')) --> <QuerySet [{'day': datetime.date(2017, 6, 22), 'count': 1}, {'day': datetime.date(2017, 6, 22), 'count': 1}]> Notice the Count-aggregation does not combine the two to give 'count': 2 So, how can I get the desired result 1) with the correct count using the aware timestamp field? It will work using the extra() modifier like so: queryset\ .extra({'day' : "date(timestamp_aware )"})\ .values('day')\ .annotate(count=Count('id')) --> <QuerySet [{'count': 2, 'day': datetime.date(2017, 6, 22)}]> but it is deprecated, so looking for another way out. -
Django form to change order results are presented
Can a Django Form be used to change the order in which results are presented? I'm trying to allow a user to change item results in a shop based on the price: high to low etc. Can this be done with forms? Currently using Django-Haystack for faceting based on brands. -
Display special character in Django HTML templates
I wonder how to display special character in Django template In models.py i have chessman=models.CharField contain for example '&#9821;', what suits https://en.wiktionary.org/wiki/%E2%99%9D, but in html templates does not replace to symbol. It is problem in encoding on website or .py files or database? Or i have to change type? -
ValueError: Attempted relative import beyond toplevel package DRF
I have the following structure suitsandtables media suitsandtables __init__.py settings.py urls.py wsgi.py venue __init__.py models.py views.py whateverelse.py __init__.py the first suitsandtables has the init.py strictly for the relative import I have in the urls.py file. In the urls.py file I need access to stuff in the views.py folder. SOOOO I did a relative import from ..venue import views which worked but then I get this lame error which given the fact I made the top level suitsandtables a package makes no sense to me. Maybe I'm stupid, maybe the planets are aligned in the wrong way, but its broken homes and I don't know how to fix it. How do we make this right? This nonsense is holding up my whole project. -
I am trying to create a django query that returns the posts that are of post_type "mobiles"
class Entry(models.Model): title = models.CharField(max_length=200) post_type = models.CharField(max_length=50, default="others") author = models.CharField(max_length=30, default = "") body = models.TextField() slug = models.SlugField(max_length = 200, unique = True) publish = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now_add=True) objects = EntryQuerySet.as_manager() def __str__(self): return self.title class Meta: verbose_name = "Blog Entry" verbose_name_plural = "Blog Entries" ordering = ["-created"] The above code is my models.py class MobilesIndex(generic.ListView): queryset = models.Entry.objects.get(post_type="Mobile") template_name = "index.html" paginate_by = 5 def Mobiles(request): context = locals() template = "Mobiles.html" return render(request,template,context) The above code is view.py how do i write the query that has only the posts that are of post_type="Mobile" -
Can not sign up using social sign in
I'm getting an error when I try to use social sign-up/sign-in on Facebook. I'm using Authomatic and my site uses the django framework. I have previously been successful in doing this with Facebook on websites I've worked on. the only difference I can pick up is that now I'm using version 2.9 of Graph API. The error message I get reads: URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs. -
yielding chunked pdf by using StreamingHttpResponse
The view that returns StreamingHttpResponse() doesn't clear its buffer before it yields new iteration and as a result it keeps appending last iteration to a merged buffer. If I print out two different pdfs it returns merged pdf file like: "PDF1, PDF1, PDF2" . Is someone see a bug in the code I wrote ? It shouldn't have printed out three pdf pags but only two "PDF1, PDF2" def _chunk_pdf(contexts_templates, context_instance): merger = PdfFileMerger() for context, template_name in contexts_templates: parser = get_parser(template_name) input = render_to_string(template_name, context, context_instance) outstream = StringIO.StringIO() outstream.write(parser.parse(input)) reader = PdfFileReader(outstream) merger.append(reader) output = StringIO.StringIO() merger.write(output) output = output.getvalue() yield output def multiple_contexts_and_templates_to_pdf_download(contexts_templates, context_instance=None, filename=None): """ Render multiple templates with multiple contexts into a single download """ context_instance = context_instance or Context() outputStream = StringIO.StringIO() response = StreamingHttpResponse( _chunk_pdf(contexts_templates, context_instance), content_type="application/pdf" ) response['Content-Disposition'] = u'attachment; filename=%s' % (filename or u'document.pdf') return response -
Django makemigraions can't work
Something wrong with Django makemigrations, the code like below: class User(AbstractBaseUser, PermissionsMixin): nickname = models.CharField(max_length=30, blank=True, verbose_name=u'') is_staff = models.BooleanField(default=False, verbose_name=u'') is_active = models.BooleanField(default=True, verbose_name=u'') objects = UserManager() When i run python manage.py makemigrations , the field is_staff doesn't show in migration file. I don't know why this field disappear. But i change the name to is_aa, it shows right. -
Django - Import variable from django admin.py file
Is it possible to import variable from django admin.py file? I tried: from .admin import * but I get: "AttributeError: module 'django.contrib.admin' has no attribute 'new_value'" This is place when I am trying to put this variable: @kronos.register('*/{} * * * *'.format(admin.new_value)) and part of my admin.py: new_value = config.CRON_MIN @receiver(config_updated) def constance_updated(sender, key, old_value, new_value, **kwargs): call_command('installtasks') I am trying to find a solution to modify my cron jobs (I use Kronos and django constance packages). This is link to my another (related) question: Django call_command