Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make sense build a app and dashboard with Python/Django?
I am starting with Django/Python, and I would like do create a poll application between users. This app will have specific rules that will be hard to manage with django-admin, so I would like to know if make sense to use Django to develop de website/app and build a dashboard too. Thank you -
How can I paginate by a common value with Django and REST Framework?
Background: Hi, folks. I have a model, Transplant, which describes which plant species were transplanted at a given time. Here are my models, boiled down to a simple form: class Species(models.Model): name = models.TextField() class Transplant(models.Model): datetime = models.DateTimeField() species = models.ManyToManyField(Species, related_query_name='transplants') Problem: I'd like to serve results from my API paginated by the date component of my DateTimeField, and showing the date and a list of distinct species. There are an arbitrary number of transplants per day, and transplants are done on arbitrary days. Given the following transplants: [ { 'datetime': '2019-07-01 10:00:00', 'species': ['Lettuce', 'Kale'] }, { 'datetime': '2019-07-01 12:00:00', 'species': ['Basil', 'Kale', 'Chard'] }, { 'datetime': '2019-07-01 15:00:00', 'species': ['Lettuce'] }, { 'datetime': '2019-07-02 11:00:00', 'species': ['Spinach'] }, { 'datetime': '2019-07-02 16:15:00', 'species': ['Lettuce'] }, { 'datetime': '2019-07-05 09:00:00', 'species': ['Lettuce', 'Kale'] }, { 'datetime': '2019-07-05 12:00:00', 'species': ['Arugula', 'Spinach'] }, ] I'd like these results (if page_size = 2): # page 1 [ { 'date': '2019-07-01', 'species': ['Lettuce', 'Kale', 'Basil', 'Chard'] }, { 'date': '2019-07-02', 'species': ['Spinach', 'Lettuce'] }, ] # page 2 [ { 'date': '2019-07-05', 'species': ['Lettuce', 'Kale', 'Arugula', 'Spinach'] }, ] What I've Tried: What I'm doing now is querying for distinct … -
"This field is required." DRF
Began to deal with DRF. I want to authenticate users with jwt token. But nothing happens. I’ve come across the problem that when creating a user, I get: {"user": {"email": ["This field is required."], "Username": ["This field is required."], "Password": ["This field is required."]}}. Although all the fields are filled. models class UserManager(BaseUserManager): def create_user(self, username, email, password=None): if username is None: raise TypeError('Users must have a username.') if email is None: raise TypeError('Users must have an email address.') user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(db_index=True, max_length=255, unique=True) email = models.EmailField(db_index=True, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) bio = RichTextUploadingField(_('bio'), blank=True) city = models.CharField(_('city'), max_length=100, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() @property def token(self): return self._generate_jwt_token() def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') serializers class RegistrationSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=128, min_length=8, write_only=True ) token = serializers.CharField(max_length=255, read_only=True) class Meta: model = User fields = ['email', 'username', 'password', 'token'] def create(self, validated_data): return User.objects.create_user(**validated_data) view class RegistrationAPIView(APIView): permission_classes = (AllowAny,) renderer_classes = (UserJSONRenderer,) serializer_class … -
Django and Ajax refreshing a div
I am very new to JS/Ajax and a relative novice to Django. I am testing to see how I can get information back and forth from an Ajax call to my view, and back to Ajax to replace a header string as a simple test. I can receive information back to my view (h1, which is "AJAX TEST"). What I can't seem to get is the h2text to change to "HEADER CHANGED". Any help is appreciated as I don't know if it's my Django return function or my Ajax function. Here is my ajax_test.html: <div class="content"> <div class="center"> <h1 id="h1">AJAX TEST</h1> <div> <button id="btn">PRESS ME</button> </div> </div> <div id="update_div"> {% include "ProdPlat/ajax_test_div.html" %} </div> </div> <script type="text/javascript" src="{% static 'ProdPlat\js\ajax_test.js' %}"></script> {% endblock %} My ajax_test_div.html (which I'm trying to refresh): <div class="content"> <div class="center"> <h2 id="h2">{{h2text.h2text}}</h2> </div> </div> My views_test.py: def test_ajax(request): logger.debug('\n\ntest_ajax FUNCTION:') # return HttpResponse('test_ajax') logger.debug('referer = {}'.format(request.META.get('HTTP_REFERER'))) h2text = {'h2text': "INITIAL HEADER"} if request.method == 'POST': logger.debug('POST request') text = request.POST.get('text') logger.debug('text = {}'.format(text)) h2text = "HEADER CHANGED" dict = { 'h2text': h2text, } # return JsonResponse(dict) # return render(request, 'ProdPlat/ajax_test_div.html', {'h2text': h2text}) return render_to_response('ProdPlat/ajax_test_div.html', dict) return render(request, 'ProdPlat/ajax_test.html', {'h2text': h2text}) And finally my Ajax call: … -
Problem with Array javascript with django print [
I am working in django 1.11 and want to export data to javascript, right now works!. But i have problem the array in moment print isn't array because print char to char I want to have something like that: Color_rgb = [ 160.73776956820626, 192.43254103235958, 58.88702020483803] when i write: Color_rgb[0]; my output be: 160.73776956820626 views.py def vista(request): Color_RGB = [] semana_max = Resultados_Alumnos.objects.all().aggregate(Max('noSemana')) Resultados_RGB= [] for Color in Resultados_Alumnos.objects.raw('Select * from test_app_alumno_competencia_evaluacion_estado where idMapasxalumnos_id = 25 and noSemana = %s',[semana_max["noSemana__max"]]): R = Color.bajo * 0 G = Color.medio * 1 B = Color.alto * 2 RGB = R + G + B Incertidumbre = (-Color.bajo * ln(Color.bajo) - Color.medio * ln(Color.medio) - Color.alto * ln(Color.alto)) / -ln(1.0/3) B = Incertidumbre * 60 if RGB >= 1: R = int((2 - RGB) * 255) G = 255 else: G = int((1 - RGB) * 255) R = 255 R = R - Incertidumbre * R *.25 G = G - Incertidumbre * G *.25 Resultados_RGB = [R, G , B] Color_RGB.append(Resultados_RGB) context = { 'color': Color_RGB } return render(request, 'resultados_app/resultados.html', context ) html <script> var rgb = [] '{% for k in color %}' rgb.push('{{ k }}'); '{% endfor %}' </script> my … -
Why is the format parameter for a HyperlinkedIdentityField page set to "api" when I have explicitly defined it as html in serializers.py
I'm trying to use a HyperlinkedIdentityField to display a link for a field within a serializer. The link is correct on the except for the suffix of ?format=api when it should be ?format=html. I'm using a DefaultRouter for myapplication/urls.py, this might be the cause of my problems, but I don't what to do in order to solve the problem class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') And in the browser, the JSON format of a model previously created is displayed as: { "url": "http://127.0.0.1:8000/snippets/1/?format=api", "id": 1, "highlight": "http://127.0.0.1:8000/snippets/1/highlight/?format=api", "owner": "admin", } When the link is clicked, the user is linked to a 404 error, however, if the link is manually updated to http://127.0.0.1:8000/snippets/1/?format=html everything is displayed as expected -
neomodel doesn't save nodes in database
I have a neomodel model: class User(StructuredNode): id = UniqueIdProperty() username = StringProperty(unique_index=True) email = StringProperty(unique_index=True) password = StringProperty() def save(self, *args, **kwargs): self.password = make_password(self.password) return super(User, self).save(*args, **kwargs) When I save a new instance of such model in the console, I get a new User instance successfully, but when I retrieve all User objects from model, I get an empty resultset: (AttractoraVenv) MacBook-Pro-de-Hugo:AttractoraBackend hugovillalobos$ python manage.py shell Python 3.7.1 (default, Dec 14 2018, 13:28:58) [Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from users.models import User >>> user = User(username='admin', email='admin@admin.com', password='secret').save() >>> user <User: {'id': '0d3b0aa56499414d8fb205ea1279662e', 'username': 'admin', 'email': 'admin@admin.com', 'password': 'pbkdf2_sha2 56$150000$vTdAnqAvXnOM$0hPMc1KiMpLvHbVO4C77OXUa9dmKzt9lMxIg8Ig+za8='}> >>> User.nodes.all() [] I don't know what I am missing. -
How can i use more different forms in the same Django template?
In my project, i have a template where i'm trying to put two forms for different use cases. I've never come across this problem before, so i don't really know where to go from here to use two forms in the same page. At first i thought of creating another view to handle each form, but i think that this solution would create problems with the rendering of my templates, other than not being sustainable if i should have this problem again with another template. After making some research, i found a solution but it works for class based views, but i'd like to avoid that since my view is already a function based view, and i would have to make a lot of changes in my code. Would it be possible to solve this problem with a function based view? Every advice is appreciated First field class FirstForm(forms.ModelForm): firstfield = forms.CharField() secondfield = forms.CharField() class Meta: model = MyModel fields = ("firstfield", "secondfield") def save(self, commit=True): send = super(FirstForm, self).save(commit=False) if commit: send.save() return send** Second Form class SecondForm(forms.ModelForm): firstfield = forms.FloatField() secondfield = forms.Floatfield() thirdfield = forms.CharField() class Meta: model = MyModelTwo fields = ("firstfield", "secondfield", "thirdfield") def … -
Apply Autocomplete=off to Django password reset confirm form
I am using Django 2.2 with Python 3.7 Following a security audit, I have been asked to ensure all security-related fields on forms in our application render with the autocomplete="off" attribute. Whether or not this is a valid and useful security measure is out of scope... unfortunately. So far, I have accomplished this by extending the form in question. For example, with the PasswordResetForm (where the user enters the email associated with the account): class NoAutocompletePasswordResetForm(PasswordResetForm): def __init__(self, *args, **kwargs): super(PasswordResetForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs.update({'autocomplete': 'off'}) And then instructing the relevant auth view to use it like so (in urls.py): url(r'^accounts/password_reset/?$', auth_views.PasswordResetView.as_view(form_class=forms.NoAutocompletePasswordResetForm)), This worked fine up until the Password Reset Confirm View, which uses the SetPasswordForm. The first attempt there went something like this: url(r'^accounts/reset/(?P<uidb64>[0-9A-Za-z]+)/(?P<token>[0-9A-Za-z\-]+)/$', auth_views.PasswordResetConfirmView.as_view(form_class=forms.NoAutocompleteSetPasswordForm)), class NoAutocompleteSetPasswordForm(SetPasswordForm): def __init__(self, *args, **kwargs): super(SetPasswordForm, self).__init__(*args, **kwargs) self.fields['new_password1'].widget.attrs.update({'autocomplete': 'off'}) self.fields['new_password2'].widget.attrs.update({'autocomplete': 'off'}) However this just yields a TypeError, on the super() line, with the detail that __init__() got an unexpected keyword argument 'user', despite the presence of a named user argument to the init of that form, as seen in the Django source. But for funsies, I tried passing the user as a positional arg instead, like so: class NoAutocompleteSetPasswordForm(SetPasswordForm): def __init__(self, *args, **kwargs): … -
How To Save Table Data on Form Post (Django)
I have a table nested within a form where each HTML element is populated by iterating throughout various records stored in a local database. The user may make changes to one or more elements. On POST I want to submit and save the data for the edited table row only, as the table will include many rows. I will reference what record to be updated by the attribute id which is stored within a hidden div. For readability, I have only included one example of the HTML elements within the table. More than anything, I am looking for guidance on how to best implement my solution. For example, how can I specify a particular row to be saved? Will this solution require jQuery or AJAX? views.py def update_table(request): id = request.POST.get('id') obj = Opportunity.objects.get(id=id) account_manager_id = request.POST.get('account_manager') form_class = CreateOpportunityForm if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): try: obj.accountManager = account_manager_id obj.save() except Opportunity.DoesNotExist: obj = None context = { } return render(request, 'website/opportunity_dashboard.html', context) template.html <form action="{% url 'update_table' %}" method="post" name="opportunityTable"> {% csrf_token %} <div class="table-container"> <table id="opportunityTable"> <thead> <tr> <th>Account Manager</th> </tr> </thead> <tfoot> <tr> <th>Account Manager</th> </tr> </tfoot> {% for object, opportunity, account_manager, presales_engineer, … -
Having trouble over-riding style on bootstrap components
I cannot get my custom css to override any of the components of Bootstrap4 in Django project. I am very new to front-end development and hope that I can ask this question clearly. note: This is an html sheet in a Django project. My custom css sheet is linked properly as I can use it successfully on other components (non-bootstrap) of the page. The only way I have been able to override any of my bootstrap components is by including the style as an html attribute as seen in the example below where I made the background of the first row blue. I have been working on solving this issue for a couple of days now and the only things I seem to find is to make sure your custom style sheet is loaded after the Bootstrap style sheet. I have my home.css sheet loading after the bootstrap css, but I am not sure if the way Django loads these is interfering with the order. Any help or suggestions on trouble-shooting this would be greatly appreciated. Thank you. {% load staticfiles %} <head> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato&display=swap" > <link rel="stylesheet" … -
How to initialize the database with your test data for each module? Pytest-django
For each application in the project, you need to write tests. Also for each application you first need to upload your test data, which, after passing all the module tests, must be deleted. I found several solutions, but none of them seems to me optimal First: in file conftest.py in each app I override method django_db_setup , but in this case, the data is not deleted after passing the tests in the module, and become available for other applications. In theory, with the help of yield you can delete all the data after passing the tests. def django_db_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): call_command('loaddata', './apps/accounts/fixtures/accounts.json') call_command('loaddata', './apps/activation/fixtures/activation.json') call_command('loaddata', './apps/questionnaire/fixtures/questionnaire.json') yield delete_test_data``` Second: ``` @pytest.fixture(autouse=True) def setup(self, db): call_command('loaddata', './apps/accounts/fixtures/accounts.json') call_command('loaddata', './apps/activation/fixtures/activation.json') call_command('loaddata', './apps/questionnaire/fixtures/questionnaire.json')``` In this case, the data will be loaded exactly as many times as there will be tests in the module, which also seems to be not quite correct. -
Form onsubmit which places an ajax call does not return before the form goes to its action. However works on mac but not PC
I am building an application in Django that creates rubrics to grades assignments. Each rubric item is editable and on submission of the form, the page is checking if a rubric item has been edited and if it has editing it in the database. Then once all those have been updated, it will submit the checked checkboxes as the grade. So the form action is to submit the grade, and in the jquery I have an event listener checking for when the submit button is clicked that will make an ajax call to update the rubric entries. The rubric entries arent being edited before the form goes to its action. Like its going to the form action too quickly the jquery doesnt have time to finish. I've tried doing event.preventDefault to prefent the form from going to the action and then submiting the form after the loop that edits all the rubric entries which should give it time to finish. I've also tried calling this function in an onsubmit instead of an onclick because I heard that the onsubmit executes before the form action does. But here's the thing. The code works perfectly on my mac, but does not work … -
How to integrate opencv code in django framework
I am making openCV base face recognition project... now I want to ( face recognition) project deploy to django framework import numpy as np import cv2 import pickle face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml') eye_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_eye.xml') smile_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_smile.xml') recognizer = cv2.face.LBPHFaceRecognizer_create() recognizer.read("./recognizers/face-trainner.yml") -
Django Dynamic Search with Multiple Values
I am creating a site that a user can search for multiple ingredients and look up recipes with those ingredients. There will be a single search bar with 2 buttons, 'Add' and 'Search'. the Add button will add the ingredients to a list, and search will redirect them to a page of results. As users add ingredients I have them being updated in a list below the search bar and saving the values in a javascript array, this works good and I can see the array being updated when I print to console. My error comes when I hit the Search button. I am sending the Javascript array back to the server through AJAX. The request come back successfully and I can get the data back and convert it to a python list. However, I cannot render a new view. It doesn't give me errors, it just stays on the home page after pressing submit. I believe I have to send a JsonResponse back to frontend, but when I do that I lose the reference to the array that I need to render the next page. Is there a way I can save the array that I am given through … -
Using a modal to select quatities
I'm trying to implement a system to sell books, first I implemented a way to look into my database for the data of my books, for example if I look for "Algebra" I get: 0: Object { id: 1, titulo: "Algebra", coleccion: "AM" } 1: Object { id: 3, titulo: "Algebra II", coleccion: "AM" } with that I would like to use a modal to have something like. Algebra [ ] Algebra II [ ] [Ok] [Cancel] And then I can use as: Algebra [ 3 ] Algebra II [ ] [Ok] [Cancel] But I don't know how can I do this. This is the code of my django template. {% extends 'base.html' %} {% block content %} <form method="GET" action="{% url 'libros:buscar' %}" id="buscador-libros"> <div> <input type="text" , name="titulo" /> <input type="submit" value="Buscar" /> </div> </form> <script type="text/javascript"> $(document).ready(function() { $("#buscador-libros").submit(function(e) { e.preventDefault(); $.ajax({ url: $(this).attr("action"), type: $(this).attr("method"), data: $(this).serialize(), success: function(json) { console.log("perro"); console.log(json); } }); }); }); </script> <!-- The Modal --> <div id="selector-cantidades" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close">&times;</span> <form> **titulo**:<br /> <input type="number" name="Cantidad" /><br /> </form> </div> {% endblock content %} Any ideas on how to do it? -
What is a good way to store visits and clicks in a django app
I have a website built in Django in which I need to save clicks to specific ads and also page visits to be shown in a dashboard. Right now they’re being saved in the database itself but it is growing too much every day and I’m afraid it will impact on performance. What alternative do I have to store this simple user tracking data and retrieve it? -
How can I integrate a list in place of static values in charts.js/javascript with a list that is dynamically loaded from django backend?
I want to dynamically load database datas to fill a chart. I am using django as backend and chart.js for visualization. "images": [{ "zoomLevel": 5, "scale": 0.5, "title": "Brussels", "latitude": 50.8371, "longitude": 4.3676 }, { "zoomLevel": 5, "scale": 0.5, "title": "Copenhagen", "latitude": 55.6763, "longitude": 12.5681 }, { "zoomLevel": 5, "scale": 0.5, "title": "Paris", "latitude": 48.8567, "longitude": 2.3510 }] This above code is my javascript default code. I want to pass the above values dynamically from django backend as mentioned below: for item in Listings.objects.all()[:5]: images.append( { "zoomLevel": 5, "scale": 0.5, "title": item.neighbourhood, "latitude": item.latitude, "longitude": item.longitude } ) Here, Listings is a model and neighbourhood, latitude and longitude are its fields. I am passing only 5 values here so it makes a list named images containing 5 dictionary elements. return render(request, template_name, {"context": images} Now, I pass it to javascript as context. {% autoescape off %} <script type="text/javascript"> var arr_images = {{ context }}; </script>{% endautoescape %} Then, in the html, I loaded the context in a variable named arr_images. "images": arr_images Now, in javascript, I want to load the whole list as a part of code, just like the code in the top but due to some reason, only … -
Field required when using two forms in Django
I have a template in my Django project where i'm using the same form two times. The form is the same, but each of them has a different use case for the user. The problem when using two forms is that if i try to use the first one, the data will NOT be sent to the database, as i will get this error This field is required.. That's because if i compile one form, the second one, being not compiled, will throw the error. Is there any way to solve this? <h3> First form </h3> <form method="post" novalidate> {% csrf_token %} {% include 'main/includes/bs4_form.html' with form=form %} <button type="submit" class="btn btn-danger style="background-color: red;">SUBMIT</button> </form> <h3> Second form </h3> <form method="post" novalidate> {% csrf_token %} {% include 'main/includes/bs4_form.html' with form=form %} <button type="submit" class="btn btn-danger style="background-color: red;">SUBMIT</button> </form> -
'CommentForm' object has no attribute 'cleaned_data'
I tried this if form.is_valid() and request.user.is_authenticated():, it shows me that, bool obj is not callable. then i tried without parentheses then it shows error that, 'CommentForm' object has no attribute cleaned_data. please help me out, it would be appreciated. def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) if instance.publish > timezone.now().date() or instance.draft: if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote_plus(instance.content) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid() and request.user.is_authenticated(): c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type= content_type, object_id = obj_id, content = content_data, parent = parent_obj, ) return HttpResponseRedirect(new_comment.content_object.get_absolute_url()) comments = instance.comments context = { "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "comment_form":form, } return render(request, "post_detail.html", context) -
Getting a circular import error in django urls
I'm getting the following circular import error in the project level urls.py file: ImproperlyConfigured: The included URLconf 'pres_value.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. To be clear, pres_value is the project level and present is the app level. So apparently the error is occurring in the project level urls file. The app has been registered in the settings.py file. Any help on what's wrong here is appreciated. Project level pres_value/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('present/', include('present.urls')), ] App level present/urls.py: from django.urls import path from .views import HomePageView, PresentValueView, AboutPageView, ResultView urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('about/', AboutPageView.as_view(), name='about'), path('pv/', PresentValueView.as_view(), name='present_value'), path('result/', ResultView.as_view(), name='result'), ] -
Django: collectstatic fails locally after configuring django-storages for AWS S3
I'm trying to configure my webapp, so when deployed to Heroku it will acept files (audio, video) and stores them in Amazon S3 Bucket. I've made the necessary changes in settings.py but now I cannot use python manage.py collectstatic. I'm also hopping my configurations lets my app recieve and store files in AWS S3. I get this error: File "D:\virtual_envs\universidad_elim\lib\site-packages\botocore\handlers.py", line 219, in validate_bucket_name if VALID_BUCKET.search(bucket) is None: TypeError: expected string or bytes-like object .env: In my env file, I've: AWS_STORAGE_BUCKET_NAME = 'universidad-elim-test-videos' AWS_S3_REGION_NAME = 'us-west-1' # Tell django-storages the domain to use to refer to static files. AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_ACCESS_KEY_ID = 'XXXX' AWS_SECRET_ACCESS_KEY = 'XYXYX' Apparently it's something related to botocore library. setttings.py: The app works correctly (renders index.html and contents). The problem is when trying to collecstatic files. """ Django settings for el_comercio_app project. Generated by 'django-admin startproject' using Django 2.2.1. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from decouple import config from dj_database_url import parse as dburl # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS … -
Invalid literal for int() with base 10 : "some string", but the field in question is a foreign key to a charfield
I keep getting the invalid literal error for an int() with base 10. The field in question is a foreign key to a class that only has one attribute and that attribute is a CharField, so I don't understand why I keep getting this error. If I try to query the the Progress class it works fine, but when I search for a value for progress within the Tasks class I get the error. I have already tried clearing my my migrations and re-migrating, it had no effect. class Program(models.Model): name = models.CharField(max_length=30) class Tasks(models.Model): program = models.ForeignKey(Program, max_length=30, on_delete=models.CASCADE) Shell >>> from app.models import * >>> a = Program.objects.filter(name="GM") >>> print(a) <QuerySet [<Program: GM>]> >>> a = Tasks.objects.filter(program="GM") ValueError: invalid literal for int() with base 10: 'GM' I should be able to grab this object and manipulate it, I am certain that there is an object with program set to "GM". -
mutex on different instances of django model
I'm creating a django-docker project where each user has their own docker container running an agent that manages their blockchain wallet. The problem I'm running into is that sometimes the server needs to start a container to manage user connections, and the user starts their docker container on login as well. If the server and the user both logout at the same time, it may try to delete a container twice. likewise if the user and the server start a docker container at the same time, we would have two copies of the same docker container running. I've used a couple semaphores and a lock to solve the problem on paper, but I'm wondering if I create two agent objects using: agent_obj_1 = agent.objects.get(wallet_name=request.session["wallet"]) agent_obj_2 = agent.objects.get(wallet_name=request.session["wallet"]) agent_obj_1.start() agent_obj_2.start() where each agent has a lock and semaphore local variable, and I lock the mutex on agent_obj_1, can I still lock agent_obj_2 because they are different instances? or can I not lock agent_obj_2 because it is only a different referance pointing to the same object in memory as agent_obj_1? ie. do agent_obj_1 and agent_obj_2 share a lock instance variable defined in the __init__() method? here is the relevant part of my … -
How to Save Table Row On Change (Django/Ajax)
I have a table which is populated by iterating over various records in a local database. Nested within the table data are divs which hold different HTML objects such as textboxes and dropdown menus which are subject to user input. Upon a change to one or more of these elements in a particular row, I would like to update the database record with the data in the table row. Do I need individual AJAX payloads for each HTML element for which I want to save data? Or am I able to assign an ID to the table to reference in my AJAX? If so, then how would I specify which row needs to be updated since rows are dependent upon the iteration which creates them? template.html <table class="table is-fullwidth is-striped is-bordered"> <thead> <tr> <th>Header 1</th> <th>Header 2</th> <th>Header 4</th> <th>Header 5</th> </tr> </thead> <tfoot> <tr> <th>Header 1</th> <th>Header 2</th> <th>Header 3</th> <th>Header 4</th> <th>Header 5</th> </tr> </tfoot> {% for object, opportunity, account_manager, presales_engineer, inside_solution, time in object_zip %} <tbody> <tr> <th> {{ object.opportunityId }} </th> <td> <div class="select"> <select name="status" id="cw_status"> <option value="{{ opportunity.status.id }}">{{ opportunity.status.name }}</option> <option value="Lost">Lost</option> </select> </div> </td> <td> <div class="select"> <select name="account_manager" id="account_manager"> <option value="{{ …