Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Password is not encrypted in django
When I create a new user, his password remains unencrypted in the database. Here is my models.py file: from django.contrib.auth.models import AbstractBaseUser from django.db import models from .managers import UserManager class UserProfile(AbstractBaseUser): phone = models.CharField(max_length=100, unique=True, db_index=True, primary_key=True) objects = UserManager() USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] class Meta: verbose_name = 'user' verbose_name_plural = 'users' def get_full_name(self): return self.phone def get_short_name(self): return self.phone serializers.py: class UserProfileSerializer(serializers.ModelSerializer): phone = serializers.CharField(required=True, allow_blank=False) password = serializers.CharField(required=True, allow_blank=False, write_only=True) class Meta: model = UserProfile fields = '__all__' extra_kwargs = {'password': {'write_only': True}} views.py: class UserProfileViewSet(ModelViewSet): serializer_class = UserProfileSerializer queryset = UserProfile.objects.all() def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(data=serializer.data, status=HTTP_200_OK) managers.py: from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, phone, password, **extra_fields): if not phone or not password: raise ValueError('Err!') user = self.model(phone=phone, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, phone, password, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(phone, password, **extra_fields) def create_superuser(self, phone, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(phone, password, **extra_fields) in settings.py i have wrote that: AUTH_USER_MODEL = 'users.UserProfile' Using print, I found out that no UserManager methods are used when creating a user. What am I doing wrong? -
How to override last() in django model manager
So I have some repeated logic in my django app that I would like to refactor move into the model layer, specifically in the last() method: I basically want to override last to make it similar to filter, so that I can run query like: Record.objects.last(build_id=1, name="test") and have it return the last record if more than one exist so it's like combining last and filter into one. class RecordManager(models.Manager): def last(self): ''' returns last record, logs multiple instances if more than one record exists ''' try: record_queryset = self.filter(*args, **kwargs) record_count = record_queryset.count() if record_count > 1: logger.debug("{} duplicates for record: {} found for this job. id's: {}".format(record_count, name, record_queryset)) return record_queryset().order_by('-id')[0] except IndexError: return None If I query Record.objects.last() I get this error: NameError: name 'args' is not defined I have never messed around with Django's ModelManager's so not sure what I'm doing wrong. -
Save the dynamically populated value on dropdown
I'm using wagtail CMS for Django, I want to add a dynamically populated value for a dropdown and save it on the Page model, this is my code: class ApiReferencePage(Page): domain = CharField(max_length=10, choices=MY_CHOICES) subdomain = CharField(max_length=10, choices=[('', '------')] I've got some frontend logic to populate dynamically the options for subdomain, but after I hit save I got: The page could not be created due to validation errors And in the subdomain field: Select a valid choice. [my value] is not one of the available choices. I can't use ForeignKey to populate subdomain because it depends from an external API service that we're using. I tried to use a custom field that inherits from CharField with no success, it looks it executes validate method only for the domain field. -
List of posts not displaying - django
I have created a post model and would like to view the posts in post_list. While creating the new post, it is redirecting to post_list but not displaying any post. Also, in my post_form I have rendered the fields manually by using django templates. I couldnt figure out where I have made the mistake. Can someone please help me out. Thanks models.py class Post(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE) slug = models.SlugField(unique=True, blank=True, default=uuid.uuid1) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) likes = models.IntegerField(default=0) title = models.CharField(max_length=100) project = models.CharField(max_length=100) s_desc = models.CharField(max_length=1000) outcome_type = models.CharField(max_length= 10) stage_initiation = models.BooleanField(blank=True, default = False) custom_tag = models.CharField(max_length = 50) pia = models.CharField(max_length = 3) action = models.CharField(max_length=200, blank=True) assigned_to = models.ForeignKey(User,blank=True,null=True, on_delete = models.DO_NOTHING, related_name="blog_assigned") def publish(self): self.published_date = timezone.now() self.save() def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title def count_posts_of(user): return Post.objects.filter(author=user).count() post_list.html <!DOCTYPE html> {% extends 'home.html' %} {% load staticfiles %} {% block content %} <div class="centerstage"> {% for post in post_list %} <div class="post"> <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ Post.title }}</a></h1> <h2>{{ Post.s_desc |truncatewords:150 }}</h2> <h3>{{ Post.o_desc |truncatewords:150 }}</h3> <div class="date"> <p>Published on: {{ Post.published_date|date:"D M Y"}}</p> </div> <a href="{% url 'post_detail' pk=post.pk %}"></a> </div> … -
Forbidden 403 : CSRF Validation failed error in Firefox, not in chrome
I have a webpage with more than 1 form with POST. I have included {% csrf_token %} in each of the forms. <form class="form-horizontal clearfix" role="form" id="Form1" method="post"> {% csrf_token %} In my view I have used bot ensure_csrf_cookie and csrf_protect decorators @ensure_csrf_cookie @csrf_protect @operation('monitor') def monitor(request, **kwargs): The first POST request fetches some details from the backend and displays it in the UI. After that, some data is requested from the user and then the second form is submitted. In firefox: When I first load the page and after the first post the csrftoken is X. For the second post request also, the csrftoken cookie is the same. But once the error is thrown, the csrf cookie changes to a different value. If I refresh the page after that, csrftoken remains the same and if I post the request again it succeeds. I have also verified that the form has the hidden value csrfmiddlewaretoken. This matches the cookie. I don't see any 404 for favicon when the page is loaded. This was there before. But I fixed that and chrome started working. In chrome: This is working. Any pointers on how to solve this? -
customize error message 'please fill out this form' in Django
I have written this function in Django to override the 'label suffix and form field error message. Within the same function, the lebel suffix is working (the colon is removed) but the error message did not replaced by with customized one. Here is the form class with the function: class User_accountModelForm(forms.ModelForm): # to remove colons from the labels: def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(User_accountModelForm, self).__init__(*args, **kwargs) # changing error messages: for field in self.fields.values(): field.error_messages = {'required':'The field {fieldname} is required'.format(fieldname=field.label)} class Meta: model = User_account fields = ['first_name', 'other fields'] any help or clue is appreciated -
Django Users, how can a user have permission to only edit the models they own (DRY)?
I am currently creating a lot of views and at each one of them only the User has permissions to access that view and create or edit the model. Depending on the view I either put a small permission IF statement in the get_context_data or get_object. While the following works I would like to make it more DRY since I have more than 20 views that need it: def get_context_data(self, **kwargs): context = super(SpaceCreate, self).get_context_data(**kwargs) house = House.objects.get(pk=self.kwargs['pk']) # CHECK IF USER HAS PERMISSION TO MAKE CHANGES TO THE MODEL if house.owner != self.request.user: raise PermissionDenied or in the get_object() , and with more permission checks: def get_object(self, *args, **kwargs): obj = super(SpaceManage, self).get_object() house = House.objects.get(pk=self.kwargs['pk']) space = Space.objects.get(pk=self.kwargs['space_pk']) if space.house.owner != self.request.user and house.pk != space.house.pk: raise PermissionDenied return space While I have read a lot on creating permissions ( https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication ), they seem to be applicable in cases where we want many users to have that permission instead of checking if the user has the permission to edit the models they have created. Another possibility (in my opinion) is the use of mixins, but I don't seem to understand how they work and how to implement them. … -
Parse and process CSV in Django
Apologies in advance since I'm new to Django (and I've also had to freshen up my Python skills). I'm trying to make a simple example of uploading a file through a form and then printing the rows in my terminal (as a test before doing some actual processing). My views.py contains the following: def upload_csv(request): if "GET" == request.method: return render(request, "portal/csvupload.html") csv_file = request.FILES["csv_file"] handle_files(csv_file) return HttpResponseRedirect(reverse("portal:csvupload")) def handle_files(csvfile): csv_reader = csv.reader(csvfile) for line in csv_reader: print(line) Now this returns an error message saying "expected str, bytes or os.PathLike object, not InMemoryUploadedFile", and I'm unsure what's wrong with the code based on the error message? From a Python perspective it looks fine I think, but perhaps it's something to do with the re-direct? Apperciate all answers -
Why Doesn't This Python/Django Unit Test with Mock Objects Work?
I'm having trouble understanding how to write a Python 3 unit test that uses mock objects to mock an instance method for a Django model. Here are my models and the test: # models.py class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, related_name='books') def retrieve_isbn(self): return 'abc123' # tests.py class TestModel(unittest.TestCase): @mock.patch('run.models.Book', autospec=True) @mock.patch('run.models.Author', autospec=True) def test_book_isbn(self, mock_author, mock_book): mock_author.name = 'Henry Miller' mock_book.title = 'Time of the Assassins' mock_book.author = mock_author mock_book.retrieve_isbn = MagicMock(return_value='foo123') # the next line doesn't work either #mock_book.retrieve_isbn.return_value = 'foo123' isbn = Book().retrieve_isbn() self.assertEqual(isbn, 'foo123') My test fails with this error: AssertionError: 'abc123' != 'foo123' As I understand it, when I create the mock_book object, any calls to instances of the Book class will be intercepted and replaced with the values I assign to the mock object's attributes. Isn't the line "mock_book.retrieve_isbn = MagicMock(return_value='foo123')" going to cause any calls to the Book class's retrieve_isbn method to return 'foo123' or have I not set up my test correctly? -
ImportError: Could not import settings... No module named settings?
I'm working with Django 1.4 and Python 2.7. I've encountered this issue before, but was able to work around it by adding the parent directory to sys.path using this code: import sys def rtrim(s, sep): return sep.join(s.split(sep)[0:-1]) sys.path.insert(0, rtrim(sys.path[0], '/')) from django.core.management import setup_environ import settings setup_environ(settings) Today, seemingly out of nowhere, it reared its ugly head once more. The directory structure is as follows (where 'Ingest' is the parent directory and 'ingest' is the child directory): Ingest -> settings.py Ingest -> ingest -> test.py (current working directory) Here are sys.path and part of the Traceback: ['/mnt/c/Users/Travis/Documents/GitHub/{redacted}/Ingest', '/mnt/c/Users/Travis/Documents/GitHub/{redacted}/Ingest/ingest', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 95, in __init__ raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e)) ImportError: Could not import settings 'Ingest.settings' (Is it on sys.path?): No module named settings As you can see, the parent directory is in sys.path. What could be causing this? -
Django: AttributeError
class EventDeleteView(generic.FormView): form_class = EventDeleteForm template_name = 'event/event_delete.html' def __init__(self, **kwargs): super().__init__(**kwargs) ---> self.event = Event.objects.get(pk=self.kwargs['pk']) def get_form_kwargs(self): kwargs = super().get_form_kwargs() ---> kwargs['pk'] = self.kwargs['pk'] What I do not understand is why self.kwargs['pk'] in the get_form_kwargs(self) method works and why it does not work in the constructor. I get this error: 'EventDeleteView' object has no attribute 'kwargs' -
Having Django slug before admin URL
I’m having trouble having a slug before the admin urls. I currently have a slug at the very beginning of all my urls. The slug regex works fine with all my other pages. For all my other views (views which aren’t the admin’s) I have the slug parameter within the defition of the view. Despite that I cannot figure out how to add this parameter to the admin view and thus get the error: index() got unexpected keyword argument slug How would I solve this? -
displaying a list of images from a dynamic root in django
Sorry if this is a repeated question but I have looked for an answer and cannot find it. So here we go. I have made a model called Strains. I wanted to incorporate photo uploading functionality to this model, so I created another model called Photo_save and inlined it inside of Strains (see the admin code below). The Photo_save model also allows me to upload multiple images, add a description for each image, and record the upload date for each image. I want all of this information to be displayed in strain-detail.html, but I cannot get it to work. Model.py code class Strain(models.Model): """; Model representing strains. """ strain_name = models.CharField(max_length=100, blank=False, null=True, default=None) strain_description = models.CharField(max_length=500, blank=True, null=True, default=None) data_of_generation = models.DateField(null=True, blank=True, default= None) strain_source = models.CharField(max_length=500, blank=True, null=True, default=None) strain_parent = models.ForeignKey('Strain', null=True, blank = True, on_delete= models.CASCADE, default= None) class Meta: ordering = ["strain_name"] def get_absolute_url(self): """ Returns the url to access a particular strain instance. """ return reverse('strain-detail', args=[str(self.id)]) def __str__(self): """ String for representing the Model object. """ return '{0}'.format(self.strain_name) class Photos_save(models.Model): import datetime def strain_directory_path(instance, filename): return 'strain_{0}/{1}'.format(instance.strain_name, filename) strain_name = models.ForeignKey(Strain, on_delete=models.CASCADE, default= None) upload_photo = models.FileField(upload_to= strain_directory_path, default= None) photo_description = … -
Django: Check password without User
In Django there is a check_password() method for Users. However, in my webpage unregistered users can upload something with a password. Later, they can delete it again (but the password is needed). How can I check the password? The check_password() method works only with the User object. -
Django-compressor. 404 for all compressed files in production
When DEBUG=True everything works. But when DEBUG=False i get 404 for every compressed file but they are still in CACHE folder. coompress command didn't help. What i find out: if i rename file and thy get it by link it still 404. What it can be? Spent 2 days for this issue.. There is my settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "page/static"), ] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) # scss precompilers COMPRESS_ENABLED = True COMPRESS_PRECOMPILERS = ( ('text/x-scss', 'django_libsass.SassCompiler'), ) -
NullBooleanField doesn't show None state after saving in the django admin
I'm trying to represent a simple NullBooleanField in the django. BOOL_CHOICES = [(True, 'Yes'), (False, 'No'), (None, "Unknown")] handicap_accessible = models.NullBooleanField(default=None, blank=True, null=True, choices=BOOL_CHOICES) in the django admin when i select the unknown radio button for None and save it, it clears the selection but still shows up null in the database. Not sure if this is a known bug with django NullBooleanSelect widget or not but i can't seem to find a solution to this issue. -
Is my web-app ready to face real-life people?
Good evening guys, I built a web-app with an angular frontend and a django backend (with a DRF API). It works. I'm satisfied with design and with the results it produces. It's already online and hosted by Heroku. How do I assess the capacity of my web-app to face real life people ? What are the further testing I should do to assess the code consistency ? Thanks -
(Django) Cannot update/add into manytomany field
So I currently in a project where I want the team leaders to update their groups and add/remove members but it doesn't work and idk why I tried doing it by the add/remove way as you can see in the code under. How can I fix this? Model class TeamGroup(models.Model): name = models.CharField(max_length=50) team = models.ForeignKey(Team) ingroup = models.ManyToManyField(TeamMembership, blank=True) Currently the code are this @login_required def teamsettings_members_updategroup(request, team_pk, group_pk): requested_team = get_object_or_404(Team, pk=team_pk) for member in requested_team.teammembership_set.all().order_by('-leader'): if member.user.pk == request.user.pk and member.leader: group = TeamGroup.objects.get(pk=group_pk) if request.method == 'POST': name = request.POST['name'] users = request.POST.getlist('users[]') group.name = name for user in users: for ingroup in group.ingroup.all(): if ingroup.pk != user: group.ingroup.remove(user) TeamMembership.objects.filter(pk=user).update(ingroup=False) group.ingroup.add(user) TeamMembership.objects.filter(pk=user).update(ingroup=True) group.save() return redirect('teamsettings_members', team_pk) feedback = FeedbackSupportForm() context = { 'feedback' : feedback, 'group' : group, 'requested_team': requested_team, } return render(request, 'team/update_group.html', context) return redirect('team', team_pk) -
Django model inheritance reverse_name issue
Let's start from the botton, this is what I want to achieve class ClassA(model.Models): pass class Class1(model.Models): fieldX = models.CharField() class Class2(Class1): fieldY = models.BooleanField() # all models are connected, and I prefere to have this situation # I want to call related ClassA from both Class1 and Class2 using the # same property c1 = Class1() c1.class_a c2 = Class2() c2.class_a # and, at the same time, call both Class1 and Class2 from ClassA a = ClassA() a.class_1 a.class_2 To solve this I am duplicating code (and I don't like it): class Class1(model.Models): fieldX = models.CharField() class Class2(model.Models): fieldY = models.BooleanField() fieldX = models.CharField() class ClassA(models.Models): class_1 = models.OneToOneField(Class1, reverse_name='class_a') class_1 = models.OneToOneField(Class2, reverse_name='class_a') The fields are much more than this dummy examples and modify them is quite annoying. How can I do that? I have lots of throubles with "reverse_name" field errors to achieve this, is there a workaroud? -
Trouble connecting MySQL to Heroku using Django
I have recently switched my Django database from SQLite to MySQL. I have Heroku's free MySQL database installed, called ClearDB and am using this documentation: https://devcenter.heroku.com/articles/cleardb. I can create/install the app and get the url for the database using the following commands: heroku addons:create cleardb:ignite heroku config | findstr CLEARDB_DATABASE_URL heroku config | set DATABASE_URL= # MySQL database url retrieved from above line After I do this, push everything to Heroku with my database change(which works locally) and open the app, I get the following traceback: Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /app/profiles/templates/base.html, error at line 0 2002 1 : 2 : <!DOCTYPE html> 3 : {% load staticfiles %} 4 : 5 : {% block styles %} 6 : {% endblock %} 7 : 8 : 9 : <style type="text/css"> 10 : Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection 216. self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in connect 194. self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/mysql/base.py" in get_new_connection 236. return Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/__init__.py" in Connect 86. return Connection(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/connections.py" in __init__ 204. super(Connection, self).__init__(*args, **kwargs2) The above exception ((2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")) was the direct cause of the following … -
Parameter missing from function when deploying to heroku but not locally
I am trying to deploy a django app to heroku. But when i enter git push heroku master I get the following error when it calls python manage.py collectstatic --noinput. Traceback remote: -----> $ python orphantracker/orphanapp/manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "orphantracker/orphanapp/manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate remote: app_config.import_models() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models remote: self.models_module = import_module(models_module_name) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 994, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 971, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 665, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 678, in exec_module remote: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed remote: File "/tmp/build_cac61d0e2017a75936388434ce352671/orphantracker/orphanapp/orphans/models.py", line 6, in <module> remote: from audit_log.models.fields import LastUserField, LastSessionKeyField remote: File "/app/.heroku/python/lib/python3.6/site-packages/audit_log/models/__init__.py", line 5, in <module> remote: class AuthStampedModel(Model): remote: File "/app/.heroku/python/lib/python3.6/site-packages/audit_log/models/__init__.py", line 10, in AuthStampedModel remote: created_by = CreatingUserField(verbose_name = _("created by"), related_name = "created_%(app_label)s_%(class)s_set") … -
how to create a sub URL in django url.py
I am trying to Create a sub url , But Unable to add Like I want to show like this localhost/products/addproducts my url.py is urlpatterns = [ url(r'^$', ProductListView.as_view(), name='list'), url(r'^(?P<slug>[\w-]+)/$', ProductDetailSlugView.as_view(), name='detail'), url(r'^addproducts$', addproducts, name='addproducts'), ] and main website url.py is urlpatterns = [ url(r'^$', home_page, name='home'), url(r'^about/$', about_page, name='about'), url(r'^contact/$', contact_page, name='contact'), url(r'^login/$', login_page, name='login'), url(r'^checkout/address/create/$', checkout_address_create_view, name='checkout_address_create'), url(r'^checkout/address/reuse/$', checkout_address_reuse_view, name='checkout_address_reuse'), url(r'^register/guest/$', guest_register_view, name='guest_register'), url(r'^logout/$', LogoutView.as_view(), name='logout'), url(r'^cart/', include("carts.urls", namespace='cart')), url(r'^register/$', register_page, name='register'), url(r'^bootstrap/$', TemplateView.as_view(template_name='bootstrap/example.html')), url(r'^products/', include("products.urls", namespace='products')), url(r'^search/', include("search.urls", namespace='search')), url(r'^admin/', admin.site.urls), ] -
Django to JS declared variable displaying in page source
I'm building a RESTful API that renders front-end using Django templating, but where the front-end is essentially built using JS/JQuery. Right now I'm just checking to see that the data has been sent properly, and I have a very simple template: {% extends 'base.html' %} {% block body %} Click <a href="{% url 'home_view' %}">here</a> to go to the home page <hr> <div id="keySelectForm"></div> <div id="dataDisplay"></div> {% endblock %} When the page loads I am just adding a simple drop-down box with the relevant data that has been passed to the front-end and a click-box that simply shows said data on the page. As such, I am declaring JS variables in a script at the bottom of the page as follows: {% block javascript %} {{ block.super }} <script id="dataDisplayScript" type="text/javascript"> $(document).ready(function() { var df_dict = {{ df_dict|safe }}; var names = {{ names|safe }}; // Build form var form = $('<form></form>'); var selection = $('<select name="keys" id="keySelectBox"></select>'); var button = $('<button id="test">Click me</button>'); form.append(selection) // Add selection options to main page Object.keys(df_dict).forEach(function(key) { selection.append($('<option value="' + key + '">' + key + '</option>')); }); form.append(button); $('#keySelectForm').append(form); // Pull data from select box and display only that part of the … -
beanstalk django http5xx error
hey I'm trying to deploy my first django app on aws beanstalk but I'm getting an : Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. I'm following this tutorial https://realpython.com/deploying-a-django-app-to-aws-elastic-beanstalk/ I use python 3.6 and django 1.11 I just create a blank django project part of log /var/log/httpd/error_log [Mon May 21 18:37:58.898238 2018] [:error] [pid 3353] [remote 172.31.30.216:17272] ModuleNotFoundError: No module named 'alpha_app.settings' [Mon May 21 18:38:13.914282 2018] [:error] [pid 3353] [remote 172.31.30.216:120] mod_wsgi (pid=3353): Target WSGI script '/opt/python/current/app/alpha_app/alpha_app/wsgi.py' cannot be loaded as Python module. [Mon May 21 18:38:13.914343 2018] [:error] [pid 3353] [remote 172.31.30.216:120] mod_wsgi (pid=3353): Exception occurred processing WSGI script '/opt/python/current/app/alpha_app/alpha_app/wsgi.py'. [Mon May 21 18:38:13.914484 2018] [:error] [pid 3353] [remote 172.31.30.216:120] Traceback (most recent call last): [Mon May 21 18:38:13.914527 2018] [:error] [pid 3353] [remote 172.31.30.216:120] File "/opt/python/current/app/alpha_app/alpha_app/wsgi.py", line 16, in [Mon May 21 18:38:13.914531 2018] [:error] [pid 3353] [remote 172.31.30.216:120] application = get_wsgi_application() [Mon May 21 18:38:13.914547 2018] [:error] … -
How to return a string in a Django DRF response without AttributeError?
this snippet is not working how I want: return Response({"Error": "build {} does not exist"}.format(build_name), status=status.HTTP_404_NOT_FOUND) error: AttributeError: 'dict' object has no attribute 'format' What am I doing wrong? I'm using Python 3 btw.