Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
After submit, dropdown list is empty. Form doesn't work the second session
I made a modelform that link to a column in my model. Everything run smooth after I submit the form. However my Stocks dropdown(choicefield) is empty when I want to add more the second time. Is it related to the way I render? or perhaps an html problem? forms: class My_Folio(forms.ModelForm): symbol = forms.ChoiceField(choices=coin_choices) class Meta: model = my_data widgets = {'event_date': forms.DateInput(attrs={'class':'datepicker'})} fields = ['symbol','buy_price','quantity','event_date'] -
Error during template rendering in django with specific image that displays on other pages
I've been trying to get a Django instance my predecessor here at work left me up and running, and I ran into a strange error with the templates that I can't seem to comprehend. Using the new {% static '/core/images/image_name.gif' %} format to display images works just fine in a header bar for all of the pages - with one specific exception. When I click on that page that causes the error, though, I get told that there's a problem in the base template, which all of the other pages that work just fine also extend. It implies that there's a problem with a specific image which displays just fine on all the other pages, and I can't understand why. {% load static %} is performed in every template. Error during template rendering In template C:\path_to_project\core\templates\core\base.html, error at line 20 401 Client Error: for url: https://bitbucketdev.it.contoso.com/rest/api/1.0/projects?start=0&limit=1000 10 <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script> 11 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> 12 <link rel="stylesheet" type="text/css" href="{% static 'core/css/style.css' %}"> 13 </head> 14 <body> 15 <div class="container-fluid"> 16 <nav class="navbar navbar-expand-sm bg-dark navbar-dark"> 17 <!-- Brand/logo --> 18 <a class="navbar-brand" href="https://www.contoso.com/us/en/home.html"> 19 {% load static %} 20 <img src="{% static '/core/images/contosotransparent.gif' %}" alt="Contoso Technologies" style="width:120px;"> 21 </a> 22 23 <!-- … -
Gunicorn is timeout and no logs in error files
I am running django application serving with nginx and gunicorn in supervisor,I am getting gunicorn timeout errors in gunicorn error logs but don't know what causing the errors. 2018-10-01 20:20:19 [20529] [CRITICAL] WORKER TIMEOUT (pid:20646) 2018-10-01 20:20:19 [23948] [INFO] Booting worker with pid: 23948 Is there a way we can configure gunicorn to write logs entry before the gunicorn process is timeout and killed ? -
Django: Redirect to Detail View after Creation
I'd like to redirect to a detail view after I successfully submitted a form and created the object. My view.py class ObjectCreateView(CreateView): model = Object form_class = ObjectCreateForm template_name = 'frontend/base/object_create.html' def get(self, request, *args, **kwargs): form = ForecastConfigurationCreateForm() form.fields['status'] = ModelChoiceField(queryset=ObjectStatus.get_object_status_list(self)) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): self.fcc_form = form.save(commit=True) messages.add_message(self.request, messages.INFO, 'Good job!') return render_to_response(reverse(viewname='object_detail', kwargs={'uuid': self.fcc_form.uuid})) else: messages.add_message(self.request, messages.ERROR, 'Error!') return render(request, self.template_name, {'form': form}) The error message is: TemplateDoesNotExist at /object_create/ /object_detail/3a3d6279-1531-45d4-9ba9-b691886facf4/ And the URL that's calling is: http://test.com:8000/object_create/?next=/object_detail/a5b2a693-6f90-4b98-b9a2-fc2fe6a90995/ what I want it to be is http://test.com:8000/object_detail/a5b2a693-6f90-4b98-b9a2-fc2fe6a90995/ Thanks! -
Django-compressor & S3 Boto: UncompressableFileError because can't find static files in S3
I'm getting an UncompressableFileError for Django-compressor when in production using S3 & Boto. Here are the docs from Django-compressor for Remote Storages which I've copied. The Error 'https://<prod-bucket>.s3.amazonaws.com/css/project.css' isn't accessible via COMPRESS_URL ('https://s3.amazonaws.com/<prod-bucket>/static/') and can't be compressed To be clear the issue seems to be that Compressor is looking in the wrong place for my static files. This is not where they are. https://<prod-bucket>.s3.amazonaws.com/css/project.css They are here: https://s3.amazonaws.com/<prod-bucket>/static/ My Code Production settings COMPRESS_ENABLED = True STATICFILES_STORAGE = '<myproject>.storage.CachedS3Boto3Storage' COMPRESS_STORAGE = STATICFILES_STORAGE COMPRESS_URL = STATIC_URL COMPRESS_FILTERS = { 'css': ['compressor.filters.css_default.CssAbsoluteFilter'], 'js': ['compressor.filters.jsmin.JSMinFilter'] } CachedS3BotoStorage from django.core.files.storage import get_storage_class from storages.backends.s3boto3 import S3Boto3Storage class CachedS3Boto3Storage(S3Boto3Storage): """ S3 storage backend that saves the files locally, too. """ def __init__(self, *args, **kwargs): super(CachedS3Boto3Storage, self).__init__(*args, **kwargs) self.local_storage = get_storage_class( "compressor.storage.CompressorFileStorage")() def save(self, name, content): self.local_storage._save(name, content) super(CachedS3Boto3Storage, self).save(name, self.local_storage._open(name)) return name What is recommended The docs show you'll end up with something like this - STATIC_ROOT = '/path/to/staticfiles' COMPRESS_ROOT = STATIC_ROOT STATICFILES_STORAGE = 'mysite.storage.CachedS3BotoStorage' COMPRESS_STORAGE = STATICFILES_STORAGE STATIC_URL = 'https://compressor-test.s3.amazonaws.com/' COMPRESS_URL = STATIC_URL ** What I can confirm ** My COMPRESS_ROOT & STATIC_ROOT are the same : '/app/staticfiles' STATICFILES_STORAGE is pointing at <myproject>.storage.CachedS3BotoStorage STATIC_URL is 'https://s3.amazonaws.com/<my_prod-bucket>/static/' COMPRESS_URL == STATIC_URL Ideas? Any ideas why compressor isn't … -
Add a button into django admin change list view page
I am trying to follow the below tutorials to rewrite the the view from the admin page. How can I add a button into django admin change list view page However, above tutorials does not work for me> here is the problem I have not wtih Django 2.0 I have following button in admin page {% block object-tools-items %} <li><a class="historylink" href="evilUrl/">{% trans "Start" %}</a></li> {{ block.super }} admin.py page has following code; class DeviceAdmin(admin.ModelAdmin): def get_urls(self): urls = super(DeviceAdmin, self).get_urls() my_urls = patterns('', url(r'^my_view/$', self.my_view, name="custom_view") ) return my_urls + urls def my_view(self, request): return HttpResponse('Success! Thank you for your message.') I am seeing following error in the cdoe \pages\admin.py", line 105, in get_urls url(r'^my_view/$', self.my_view, name="custom_view") TypeError: 'module' object is not callable -
Ways for Using Django with reactjs
Hi i search internet for finding solution for using Django and Reactjs together but i can't find a solution in offical webpages of this projects Can we use Django with Reactjs without using API ? Can anyone suggest me a book for this ? Thanks -
In DRF how can I extract a field of request.body/data as an unadultered string without it being interpreted as a dict/list?
I'm offering front-end clients the option of storing their own data in a file for a particular endpoint. Some clients want to store json, and this is conflicting with all the DRF machinery when request.body is parsed. I've marked two PLACEHOLDER comments for lines I'll refer to afterwards: class FooDetail(APIView): def patch(self, request): # PLACEHOLDER1 obj = self.get_object() serializer = self.serializer_class(obj, data=request.data, partial=True) # PLACEHOLDER2 if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) At PLACEHOLDER1, request.body is a bytestring. At PLACEHOLDER2, request.data is a python dict (and if front_end_data was json, it has been parsed as python data types at that stage too). I need to extract the exact value of front_end_data without any adulteration. front_end_data is not gauranteed to be valid json (or even invalid json). My attempts to parse request.body tend to parse front_end_data as json. Is there some way to limit parsing the body as json to one single level deep so that it doesn't parse the value of front_end_data? Even when I do hack the data conversion (by making the bad assumption that the front_end_data is json and valid) and save it in a file, when I attempt to re-insert it back in the … -
Adding M2M on post_save
I have an object that has a m2m relation, and I would like to populate it after saving. The problem is that the signal is triggered, but the command add doesn't work. I did try the same steps using python shell, and it worked fine. class Event(models.Model): name = models.CharField(max_lenght=40) location = models.ManyToManyField('Location') class Location(models.Model): address = models.CharField(max_lenght=60) @receiver(post_save, sender=Event) def populate_location(sender, instance, **kwargs): instance.locations.add(*Locations.objects.all()) Any hint? -
Is there a way to extract just the decimal value from django-money MoneyField without currency value?
I want to extract just the decimal value from the MoneyField value. Right now the value of the field renders as something like US$1.00, but this isn't ideal when just the decimal value is required for use. I get an error message like ["'US$1.00' value must be a decimal number."] -
AWS WSGIPath refers to a file that does not exist
I have been going through every thread on here and have tried all the ways I can think of. I am following the AWS deploy django tutorial and keep getting this error ERROR Your WSGIPath refers to a file that does not exist. I have used eb config to edit the file to the same path thats in django.config which is endjango/wsgi but nothing I have tried has worked. Also tried wrapping it in quotes and that did not work either. Heres my file django.config option_settings: "aws:elasticbeanstalk:container:python": WSGIPath: ebdjango/wsgi.py Config.yml branch-defaults: default: environment: django-env group_suffix: null global: application_name: django-tutorial branch: null default_ec2_keyname: aws-eb default_platform: python-3.6 default_region: us-east-1 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: null workspace_type: Application -
Django migration set default for arrayField
Migration Script: # -- coding: utf-8 -- from future import unicode_literals from django.db import models, migrations from django.contrib.postgres.fields import ArrayField class Migration(migrations.Migration): dependencies = [('adminmgr', '0001_initial'), ('adminmgr', '0003_private_pop'), ('adminmgr', '0005_add_partner_models'), ('adminmgr', '0061_pop_related_failover_pop'), ('adminmgr', '0136_common_name_length_256'), ] operations = [ migrations.AddField( model_name='pop', name='pop_category', field=ArrayField(ArrayField(models.CharField(max_length=256, blank=True),default=['CLASSIC'], preserve_default=True), ), ] (ENV) wuser@mpop-base:/opt/wapp/mgmt-apps$ python manage.py makemigrations running mgmt in debug mode /opt/wapp/ENV/local/lib/python2.7/site-packages/redis_sessions_fork/utils.py:13: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9. from django.utils.importlib import import_module Traceback (most recent call last): File "manage.py", line 14, in execute_from_command_line(sys.argv) File "/opt/wapp/ENV/local/lib/python2.7/site-packages/django/core/management/init.py", line 338, in execute_from_command_line utility.execute() File "/opt/wapp/ENV/local/lib/python2.7/site-packages/django/core/management/init.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/wapp/ENV/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/opt/wapp/ENV/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/opt/wapp/ENV/local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 63, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/opt/wapp/ENV/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 47, in init self.build_graph() File "/opt/wapp/ENV/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 174, in build_graph self.load_disk() File "/opt/wapp/ENV/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 100, in load_disk migration_module = import_module("%s.%s" % (module_name, migration_name)) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/code/mgmt-apps/adminmgr/migrations/0165_add_pop_category_pop.py", line 23 ] ^ SyntaxError: invalid syntax -
Grouping in django admin
models.py from django.db import models from collections import Counter from django.db.models import Count from itertools import groupby Gender = ( ('Male', 'MALE'), ('Female', 'FEMALE'), ) Diseases = ( ('Cholera', 'CHOLERA'), ('HIV', 'HIV'), ('Malaria', 'MALARIA'), ('Typhoid', 'TYPHOID'), ('Measles', 'MEASLES'), ) class MyModel(models.Model): Gender = models.CharField(max_length=16, choices=Gender, default='MALE') Diseases = models.CharField(max_length=16, choices=Diseases, default='MALARIA') vote = models.IntegerField(default=0) def __str__(self): r=0 return u'%s %s' % (self.Gender, self.Diseases) Now this returns this in the admin django panel Male Measles Male Measles Male Cholera Female Cholera Female Typhoid Female Typhoid But I want to group it so it looks something like this: Male malaria 2 Male Measles 2 Female Typhoid 3 in this admin panel instead of listing all of it like it does now -
alternative to range function in django template. TemplateSyntaxError: Could not parse the remainder
In template, I try to use: {% for i in range(object.punctuation) %} <i class="material-icons">star</i> {% endfor %} Where object.punctuation is an integer with the rating that the object has. Visually this punctuation needs to be represented with stars. But I get: Could not parse the remainder: '(object.punctuation)' from 'range(object.punctuation)' As cited in: https://jbmoelker.github.io/jinja-compat-tests/functions/range/#stop looks like range function in jinja has problems with django integration. Is there an alternative to accomplish what I'm trying to do? -
Django model to field
want to use a model to another models field in django. Is the following possible? class Foo(models.Model): name = models.CharField(max_length=100) class Bar(models.Model): students_name = #class foo fields fathers_name = #class foo fields Thanks in advance. -
Changing the path for virtualenv in Visual Studio code to run different Django projects
I have different Django projects and have been trying to open one up successfully. I deleted some of the .virtualenvs folders that were no longer valid for django runserver. However, now I have been trying to run the visual Studio code debugger and it seems like it's still searching for the old, invalid .virtualenvs path. (Something on the lines of C:\users\<userId>\.virtualenvs\old-project-1abc when I need it to debug a different project that's here: C:\users\<userId>\.virtualenvs\new-venv-1abc Note I am using pipenv to do the install, not sure if that matters or not. I am able to run the Django app locally, just not via Visual Studio code. -
Prefilling a Django Select form with AJAX
So what I have going on here is, I select a date from a datepicker (#id_date in the AJAX portion below), this goes back and queries our DB for a list of jobs from that day, renders a new django select form with those jobs as choices, and sends an HTML version of that back to our JS. What's currently happening is, after this is all done, our dropdown gets populated with the first job in that list when you click it, but no other options are presented / the dropdown itself doesn't appear to work. However, if I just print the exact same thing to console (data.form), and paste the resulting HTML in an HTML file, it renders a dropdown with all the values and works perfectly fine. I'd appreciate any insight / directions as to why this isn't functioning correctly. forms.py class OrderForm(forms.Form): def __init__(self, job_list, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.fields['order'] = forms.ChoiceField(choices=job_list, widget=forms.Select( attrs={})) order = forms.CharField(widget=forms.Select( attrs={}), label='Order #') views.py @login_required def date(request): if request.is_ajax(): day = request.GET.get('date').replace('-', '') jobdf = get_jobs(day) choices = tuple( (m, m + ' - ' + jobdf[jobdf['Inv_Num'] == m]['Customer'].iloc[0].title()) for m in jobdf['Inv_Num']) form = OrderForm(job_list=choices).as_p() data = {'form': … -
Why the ValueError Exception is raised?
models.py class Post(models.Model): message = models.CharField(max_length=2000) topic = models.ForeignKey(Topic, related_name="posts", null=True, blank=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) like = models.IntegerField(default=0) views = models.IntegerField(default=0) class ReplyPost(models.Model): reply = models.CharField(max_length=2000) post = models.ForeignKey(Post, related_name="reply", null=True, blank=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) views.py def reply_post(request,pk): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': form = ReplyPostForm(request.POST) if form.is_valid(): replypost = form.save(commit=False) replypost.reply = form.cleaned_data.get('reply') replypost.post = post replypost.created_by = request.user replypost.save() return redirect("post", post.id) else: form = ReplyPostForm() args = { 'form': form, 'post':post } return render(request, 'home/replypost.html', args) urls.py urlpatterns = [ #..... url(r'^home/questions/(?P<pk>\d+)/reply/$', views.reply_post, name="replypost"), url(r'^home/questions/(?P<pk>\d+)/$', views.post, name="post"), ] forms.py class ReplyPostForm(ModelForm): reply = forms.CharField(widget=forms.Textarea) class Meta: model = ReplyPost fields = ('reply',) ValueError. The view WebBoard.views.reply_post didn't return an HttpResponse object. It returned None instead. I can't not understand what is wrong with the code..Please update me if the code above is not sufficient to understand. -
How to pass `Chk` parameter to dotpay payments gateway in Django (Saleor)
I'm having having difficulties integrating dotpay payment gateway in saleor. I'm not sure how am I suppose to pass Chk parameter to dotpay. Saleor is using django-payments for that: https://github.com/mirumee/django-payments/blob/master/payments/dotpay/forms.py Dotpay docs: https://ssl.dotpay.pl/s2/login/cloudfs1/magellan_media/common_file/dotpay_technical_manual_for_payments_implementation.pdf -
Pip not installing the last Django-extra-views version (0.12.0)
I'm Using Django 2.1.1 with Python 3.6. While using the following pip command: pip install django-extra-views It installs the v.0.11.0 and I don't have the 'Factory' changes, so I can't use InlineFormSetFactory, and InlineFormSet does not work and gives the following exception: Setting MediaInline.extra at the class level is now deprecated. Set MediaInline.factory_kwargs instead. I tried uninstalling that version and then installing using the following command: pip install -e git://github.com/AndrewIngram/django-extra-views.git#egg=django-extra-views But doing this Django does not detect the 'import extra-views', so I tried to delete the -e from the command, but it stills installing the 0.11.0 without the changes I need. I've seen on the changelog that they made the version 0.12.0 with the corresponding solution, but I don't know any way using pip or git to install this version. I also tried asking on the app's Github 4 days ago but I haven't got any response for now and I need to solve this ASAP. Maybe I'm missing something so, if anyone could please help me installing the lastest version I would appreciate it. -
What is the way to ignore/skip some issues from python bandit security issues report?
I've got a bunch of django_mark_safe errors ``` Issue: [B703:django_mark_safe] Potential XSS on mark_safe function. Severity: Medium Confidence: High Location: ... More Info: https://bandit.readthedocs.io/en/latest/plugins/b703_django_mark_safe.html 54 return mark_safe(f'{title}') Issue: [B308:blacklist] Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed. Severity: Medium Confidence: High Location: ... More Info: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b308-mark-safe 54 return mark_safe(f'{title}') ``` And I'm curious if there is a way to skip or ignore such lines? I understand that using mark_safe could be dangerous, but what if I want to take the risk? For example this method is the only way to display custom link in Django admin, so I don't know any other option how to do it without mark_safe -
Ajax request django rest framework
I've got a problem. Every time I have to clear caches and cookies first and then the AJAX request can be requested successfully. Otherwise I will get 403 response from the server, which is Django RESTful framework. This is what I request $.ajax({ url: url_add, type : 'PATCH', dataType: 'json', data: { 'followup_customer': note, }, statusCode: { 200: function() { window.location.reload(); } }, }); -
Client side validation for credit card form
I am trying to integrate credit card form where i would use credentials filled in the inputs to send to paypal api with post method and get response back. I was trying to write client side validation,and facing problem is writing validation for expire date where i need a format of month/year(00/0000) and month should be 2 digit and year should be 4 digits. right now my form is accepting any kind length of digits if they are written with "/" ex: 23456/12456 and giving error only if its in character completely. So,i am kind of confused how to write such validation!! Till now i'm using regex to validate simple all-integer of all-character input fields. Dont know complex form validation like above. So, how can i use ajax or jquery validation to force user to write in required format ? html <form action="/payment" method="post"> {% csrf_token %} <div class="col-md-4 col-sm-6 col-xs-6 input_mb"> <label>Name on Card</label> <input id="id_card_name" class="form-control" name="fields[]" type="text" placeholder="Full name as display on card"> </div> <div class="col-md-4 col-sm-6 col-xs-6 input_mb"> <label>Credit Card Number</label> <input id="id_card_number" class="form-control" name="fields[]" type="text" placeholder="Enter Card Number"> </div> <div class="col-md-4 col-sm-6 col-xs-6 input_mb"> <label>Expiry</label> <input id="id_card_expiry" class="form-control" name="fields[]" type="text" placeholder="Ex: 06/2023"> </div> <div class="col-md-4 … -
Querying Sql Server function in Django
I am successfully able to query a legacy database table in Django by leveraging the Meta settings of a model table... but how do I use the results of a SQL Server function? Is there a way to bring the results of a SQL Server function into a Django model? -
URL error missing 1 required positional argument: 'offset' when trying to access from browser
I am trying to follow this tutorials: https://djangobook.com/django-views-dynamic-content/ URL page is like below urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello/$', hello), url(r'^time/$', current_datetime), url(r'^time/plus/(\d{1,2})/$', hours_ahead), ] And the associate view is like below: def hours_ahead(request, offset): try: offset = int(offset) except ValueError: raise Http404() dt = datetime.datetime.now() + datetime.timedelta(hours=offset) html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt) return HttpResponse(html) however when i try to access any URL like below it gives me error. http://127.0.0.1:8000/time/plus/5/ I am seeing following error. I am not passing the offset from browser URL to view. In the console it shows following error: response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: hours_ahead() missing 1 required positional argument: 'offset' [01/Oct/2018 13:29:12] "GET /time/plus/3/ HTTP/1.1" 500 62628