Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Como autocompletar campos (lat, long) en un modelo con la api geocode?
Tengo un dilema, quiero autocompletar los campos (latitud y longitud) con la peticion a la api geocode cuando genero un post a un modelo con los datos de que se suministran manualmente (ciudad y direccion). este es mi modelo class Comprador(models.Model): usuario = models.ForeignKey(User, on_delete=models.CASCADE) nombre = models.CharField(verbose_name="Nombre", max_length=50) apellido = models.CharField(verbose_name="Apellido", max_length=50) direccion = models.CharField(verbose_name="Dirección", max_length=50) ciudad = models.CharField(verbose_name="Ciudad", max_length=50) longitud = models.DecimalField(verbose_name="Longitud", max_digits=20, decimal_places=2, null=True, blank=True, default=0.00) latitud = models.DecimalField(verbose_name="Latitud", max_digits=20, decimal_places=2, null=True, blank=True, default=0.00) mi view: def post(self, request): serializer = CompradorSerializer(data=request.data, many=True) address = request.data[0]["direccion"] city = request.data[0]["ciudad"] api_response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address='+address.replace(" ","+"),city+'&key=AIzaSyDlmeg0VOQzbGnYDlYaRapYCG6w_DmnB54') api_response_dict = api_response.json() if api_response_dict['status'] == 'OK': latitud = api_response_dict['results'][0]['geometry']['location']['lat'] longitud = api_response_dict['results'][0]['geometry']['location']['lng'] print(latitud, longitud) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return HttpResponse('OK') como lat y long pueden ir vacios quiero que con direccion y ciudad y la peticion de geocode en el post me autocomplete estos campos. Agradeceria su colaboracion. Gracias!! -
NameError: name '*field*__range' is not defined
I'm attempting to filter a QuerySet within a certain date range with the __range lookup field. However, the following error is being raised: NameError: name 'posted__range' is not defined. Upon checking the model instance in the QuerySet, it in fact does have a value assigned to the posted field. I cannot debug it any further so it leaves me puzzled as to why that NameError is being raised in this context? class TestTopicListMainPage__002(TestCase): '''Verify that a topic and associated information is displayed on the main page once the topic is created''' @classmethod def setUpTestData(cls): user = User.objects.create_user("TestUser") python_tag = Tag.objects.create(name="Python") js_tag = Tag.objects.create(name="JavaScript") content = { 'heading': "Test Title", 'text': "Mock text content", 'posted': datetime.datetime.now() } cls.topic = Topic(**content) cls.topic.author = user cls.topic.save() cls.topic.tags.add(python_tag, js_tag) def test_topics_main_page_rendered_topics(self): print(self.topic.posted) response = self.client.get( reverse("topics:listing") ) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "topics/listing.html") self.assertContains(response, "Test Title") self.assertContains(response, "Python") self.assertContain(response, "JavaScript") self.assertContains(response, "TestUser") > \topics\views.py(63)get() -> if topics: (Pdb) topics <QuerySet [<Topic: Test Title>]> (Pdb) topics.count() 1 (Pdb) topics[0].posted datetime.date(2021, 3, 15) (Pdb) n > topics\views.py(64)get() -> topics = topics.filter(posted__range(previous_days, now)) (Pdb) n NameError: name 'posted__range' is not defined class AbstractListingView(TemplateView): template_name = "topics/listing.html" def get_context_data(self): context = super().get_context_data() context['topics'] = Topic.objects.all() return context class TopicsMainPage(AbstractListingView): template_name … -
How to build a backend for an iOS app with swift 5
I want to build an ios app but i am not sure how to build the backend of the app. Do i have to build an api? I have some experience in django and I have seen some people use the Django rest framework. But i am still not sure on how to do this. If some of you know how to build a backend for an ios app please let me know what I need to learn in order to do so. Also, if possible, are there any good resources that are useful for doing this? -
django update view not showing date input (previous) values
when I go to the update page, all previous values are shown except date inputs (deadline and reminder). how can I fix it? At first I didnt use TaskCreationForm for TaskUpdateView considering django will handle it automatically, but then the date inputs became normal text inputs and therefore no datepicker would appear when clicking on the textbox. I thought it was for the widgets that I had used so I decided to use TaskCreationForm for both creation and update. models.py class Task(models.Model): deadline_date = models.DateTimeField(verbose_name='Deadline') status = models.BooleanField(verbose_name='Task Status', default=False) reminder = models.DateTimeField(verbose_name='reminder') class Meta: verbose_name_plural = 'Tasks' ordering = ('-deadline_date',) db_table = 'task' forms.py class DateInput(forms.DateInput): input_type = 'datetime-local' class TaskCreationForm(forms.ModelForm): class Meta: model = Task fields = ('title', 'deadline_date', 'description', 'reminder') labels = { 'reminder': 'remind me' } widgets = { 'deadline_date': DateInput(), 'reminder': DateInput(), 'description': forms.Textarea(attrs={'cols': 80, 'rows': 5}) } views.py class TaskCreateView(CreateView): model = Task form_class = TaskCreationForm template_name = 'mysite/add_task.html' success_url = reverse_lazy('mysite:home') def post(self, request, *args, **kwargs): task_form = TaskCreationForm(request.POST) if task_form.is_valid(): cd = task_form.cleaned_data current_user = request.user task = Task(title=cd['title'], description=cd['description'], user=current_user, deadline_date=cd['deadline_date'], reminder=cd['reminder'] ) task.save() return redirect('mysite:home') class TaskUpdateView(UpdateView): model = Task form_class = TaskCreationForm # fields = ('title', 'deadline_date', 'reminder', 'status', … -
bulk add object for many to many fields for existing objects
Models here. class Book(models.Model): title = models.CharField(max_length=100) author = models.ManyToManyField(null=true, blank=true) class Author(models.CustomUser): # some fields And some instance. Book1: {author: 1, author:2} Book2: {author: 2, author:3} I want to add author 4 to all books. Books.objects.bulk_update(????) , expect the result below: Book1: {author: 1, author:2, author:4} Book2: {author: 2, author:3, author:4} ... ... ... Book100: {author: ****, author:4} -
How to handle error function in python / django
I am new in python and django, right now I am trying to develop face recognition api and I get error, here is the error log: https://gist.github.com/wahyu-handayani/9d8338741ee50697332f7ed63f9769e2 when that error happens, the server will off so I just want to throw or return something in postman, so that the server will still on. So far I have been doing try and except try: # some codes cv2.imshow('Frame', image) # here is the code that makes the error happens except Exception as e: return JsonResponse({"Error": str(e)}) but still.. it does't go to Exception block. How to do the right way for try and except in a function ? -
Empty Queryset upon requesting TemplateView
I'm creating a page where if no model instances have been created, placeholder text is inserted into the page to give the user that no topics exist. If model instances do exist, they are rendered in a manner similar to the Stack Overflow main page. Upon testing (and debugging) the view, an empty QuerySet is returned instead of returning a QuerySet with the one model instance created in the TestCase. What is missing for the QuerySet to not populate with the instance. I'm familiarizing myself with CBVs, thus the reason I'm using a TemplateView > \topics\views.py(49)get() -> context = self.get_context_data() (Pdb) n > \topics\views.py(50)get() -> if not query: (Pdb) context {'view': <topics.views.TopicsMainPage object at 0x000001BE71677A48>, 'topics': <QuerySet []>, 'login_form': <UserLoginForm bound=False, valid=Unknown, fields=(username;password)>, 'search_form': <SearchForm bound=False, valid=Unknown, fields=(search)>} tests.py class TestTopicListMainPage__002(TestCase): '''Verify that a topic and associated information is displayed on the main page once the topic is created''' @classmethod def setUpTestData(cls): user = User.objects.create_user("TestUser") python_tag = Tag.objects.create(name="Python") js_tag = Tag.objects.create(name="JavaScript") content = { 'heading': "Test Title", 'text': "Mock text content" } cls.topic = Topic(**content) cls.topic.author = user cls.topic.save() cls.topic.tags.add(python_tag, js_tag) def test_topics_main_page_rendered_topics(self): response = self.client.get( reverse("topics:listing") ) self.assertequal(response.status_code, 200) self.assertTemplateUsed("topics/listing.html") self.assertContains(response, "Test Title") self.assertContains(response, "Python") self.assertContain(response, "JavaScript") self.assertContains("TestUser") views.py … -
Can't run Celery task in Django - I either get "AppRegistryNotReady: Apps aren't loaded yet" or "RuntimeError: populate() isn't reentrant"
I'm trying to setup a task with Celery in Django to run every day at 23:00. app = Celery('App.tasks', broker='redis://localhost') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "App.settings") django.setup() <== PROBLEM @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task( crontab(hour=23), calc_average_rating.s(), ) @app.task def calc_average_rating(final_content_id): The problem is that in this function, I have Rating = apps.get_model(app_label='App', model_name='Rating'), and If I don't call django.setup() then I get django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.. However, If I call django.setup(), the tasks are running fine but I can't do manage.py runserver as I get RuntimeError: populate() isn't reentrant. Any solutions? -
How to delete all migration files in Django app
I'm trying to delete all migration files in my Django app using a single command. Here's the structure of my repository: |-- core | |-- migrations | |-- __init__.py | |-- 0001_initial.py | |-- 0002_add_column1.py | |-- 0003_add_column1.py | |-- users |-- migrations |-- __init__.py |-- 0001_initial.py |-- 0002_add_column2.py My goal is to delete all files besides __init__.py so the repo looks like this: |-- core | |-- migrations | |-- __init__.py | |-- users |-- migrations |-- __init__.py I've tried the following command but no luck: find . -path "*/migrations/*.py" -not -name "__init__.py" -delete -
django singup & log in on index page doesnt work
This is my first time to extend User with AbstractBaseUser. However, I have a problem when I try to signup/login from the index page. Before I implement login I was able to signup without a problem and redirected to the dashboard, as well a message will show up that I'm signup. Now I can't signup neither login. I'm not sure what could be the problem. I will appreciated any help to solve this. Thank you. forms: class ProfileForm(ModelForm): class Meta: model = Profile exclude = ('user',) class SignUpForm(UserCreationForm): class Meta: model = User fields = ('username','full_name','email','password1','password2',) labels = { 'email' : 'Email address', } view: def index(request): # SIGN UP form = SignUpForm() login_form = AuthenticationForm() if request.method == "POST": if request.POST.get('submit') == 'sign_in': form = SignUpForm(request.POST) if form.is_valid(): form.save(); messages.success(request, "Successfully registered.") return redirect("dashboard") elif request.POST.get('submit') == 'sign_up': # LOGIN login_form = AuthenticationForm(data = request.POST) if login_form.is_valid(): email = login_form.cleaned_data.get('email') password = login_form.cleaned_data.get('password') user = authenticate(email=email, password=password) if user is not None: login(request, user) messages.success(request, "Successfully logged in.") return redirect('dashboard') return render(request, 'index.html', context={'form':form,'login_form':login_form}) _header.html: <div class="logout"> {% if user.is_authenticated %} <!-- LOGGED IN --> <!-- MENU --> <div class="profile-menu-dropdown hide"> <a href = "">Profile</a> <a href = "">Edit … -
Django: AND filter on related objects
Imagine: class Player(model.Model): name = models.CharField() class Game(model.Model): name = models.CharField() class Match(model.Model): game = models.ForeignKey(Game, related_name='matches') class Score(model.Model): match = models.ForeignKey(Match, related_name='scores') player = models.ForeignKey(Player, related_name='scores') I'd like a query that returns all Match objects that contain a list of players. I'm really quite stuck. Say I have a list of Player objects (a QuerySet or a list of PKs, is fine), I can get all the matches ANY player played in as follows: Match.objects.filter(scores__player__in=players) But a list of matches that ALL players played in is eluding me. I'm wondering if there is a canonical approach to this, it is a simple AND query on related set of objects. I want matches where player[1] is in scores AND player[2] is in scores etc. Ultimately I want a list of games but I think that is easy from a list of matches: Game.objects.filter(matches__in=matches) I have considered ArrayAgg but it's both Postgresql specific and I've not found a syntax for filtering on membership. I have looked at Subquery but also not found a syntax that helps me here yet. There are also performance issues. Ideas I'm toying with are: Annotate a Match query with an ArrayAgg of Player objects that are … -
PGAdmin4 virtual host not working with Apache2 + WSGI
I have a problem. I'm creating a server where I will host a Django project and also PGAdmin4. I configured PGAdmin to run through apache2 and WSGI with a Python 3.8 virtual environment. It was working perfectly before I set up the Django project. at the ip/pgadmin. As soon as i manage to host the Django on the virtual host. The pgadmin started not to work. When trying to enter the "ip/pgadmin" while the django webserver is not at the root at the WSGIScriptAlias i receive this page. Not Found The requested URL was not found on this server. Apache/2.4.41 (Ubuntu) Server at 192.168.0.10 Port 80 and the following log error. The pgadmin4 is installed withing the same virtualenv that runs the django project but as they are daemons thats not a problem. So i do not see why is searching under "/var/www/acas_webserver/pgadmin/" [Tue Mar 16 00:54:22.633470 2021] [core:info] [pid 26119:tid 140348751849216] [client 192.168.0.5:63072] AH00128: File does not exist: /var/www/acas_webserver/pgadmin/ But when i place the django project at the root of the WSGIScriptAlias i reacieve this page but no log info to know what happened. Not Found The requested resource was not found on this server. I'm trying to get … -
Creating database cursor for SQL Server 2000 in Django throws ProgrammingError: SYSDATETIME Is Not A Recognized Function Name
I have to hook a modern Django application up to a very old version of SQL Server 2000. I don't need to be creating/inserting/selecting records; I just need to pass XML to a stored procedure. I've created an entry in the settings.py file for the SQL Server instance I must connect to. I'm getting weird behavior in the interactive shell when I try to create a cursor. Weirdly, the first time I create the cursor, Django throws an error. The second time, the cursor creates successfully and I can execute my stored procedure. django.db import connections cursor = connections['sqlServer2000'].cursor() File "/Users/qotsa42/lib/python3.8/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/Users/qotsa42/lib/python3.8/site-packages/django/db/backends/base/base.py", line 196, in connect self.init_connection_state() File "/Users/qotsa42/lib/python3.8/site-packages/sql_server/pyodbc/base.py", line 362, in init_connection_state val = cursor.execute('SELECT SYSDATETIME()').fetchone()[0] File "/Users/qotsa42/lib/python3.8/site-packages/sql_server/pyodbc/base.py", line 546, in execute return self.cursor.execute(sql, params) pyodbc.ProgrammingError: ('42000', "[42000] [FreeTDS][SQL Server]'SYSDATETIME' is not a recognized function name. (195) (SQLExecDirectW)") Weirdly, when I try to create the cursor again, it works and i have no issues. >>> from django.db import connections >>> cursor = connections['sqlServer2000'].cursor() File "/Users/qotsa42/lib/python3.8/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/Users/qotsa42/lib/python3.8/site-packages/django/db/backends/base/base.py", line 196, in connect self.init_connection_state() File "/Users/qotsa42/lib/python3.8/site-packages/sql_server/pyodbc/base.py", line 362, in init_connection_state val = cursor.execute('SELECT SYSDATETIME()').fetchone()[0] File "/Users/qotsa42/lib/python3.8/site-packages/sql_server/pyodbc/base.py", line 546, in execute … -
Accessing BASE_DIR in utils.py
I want to access an Excel file in my static folder from my myapp/utils.py. I'm getting an error when trying to bring in BASE_DIR from settings.py AttributeError: module 'django.conf.global_settings' has no attribute 'BASE_DIR' utils.py from django.conf import settings wb = openpyxl.load_workbook(os.path.join(settings.BASE_DIR, '/static/myfile.xlsx'), data_only=True) -
Why is pytest fails to assert the following django serializer?
I am using pytest and it has failed in two serializers that are not behaving as expected. This is my code for the models.py file: from django.db import models from django.contrib.auth.models import User import django.utils.timezone class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="client") birthDate = models.DateField(default=django.utils.timezone.now) phone_number = models.CharField(max_length=30) address = models.CharField(max_length=300) def __str__(self): return self.user.username class Contract(models.Model): client = models.ForeignKey( Client, on_delete=models.CASCADE, related_name="contracts", related_query_name="client", ) experation_date = models.DateField(default=django.utils.timezone.now) tacit_renewal = models.DateField(default=django.utils.timezone.now) I have tested the models and they are working as I expect them to. Now, I created three serializers, only the first one 'User', worked as I expected. The two others kept failing, the code is in test_serializers.py file: from rest_framework import serializers from .models import Contract, Client from .models import User as UserModel class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserModel fields = ("username", "email", "first_name", "last_name") # Used in a Customer domain class ClientSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer(many=True) def to_representation(self, instance): representation = super().to_representation(instance) return { "id": instance.id, "username": instance.user.username, "email": instance.user.email, "first_name": instance.user.first_name, "last_name": instance.user.last_name, "birthDate": instance.birthDate, "phone_number": instance.phone_number, "address": instance.address, } class Meta: model = Client fields = ( "id", "user", "birthDate", "phone_number", "address", ) class ContractSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Contract fields = ("id", "url", "client", … -
Style errorlist in all Django forms?
This answer shows styling the Django errorlist for one form by passing it in the constructor, as described in the Django documentation. How can I style all forms in Django with the DivErrorList style given in that answer? -
Optimize a Django queryset to check if nested attribute is true and preserve order?
I have two models in Django, Course, which can have zero or more Classes. A class is basically a course but with a string start_date and a boolean honors field. I want to query for all courses that have at least one honors class, how would I do that? Second question is given a Course, I want to: query all other courses that have the same string subject field query all other courses that have the same string teacher field unique courses only (no duplicates) Courses with at least one honors Class The caveat is that I need to maintain priority so that all courses with a matching subject are earlier in the returned JSON than the course with a matching field. -
Problems to send email using Django EmailBackend
I don´t know what is wrong in my code. I´m trying to use send_mail using django.core.mail.backends.smtp.EmailBackend but is not working. The security level of my gmail account is unlocked and the message in python looks like sent the email message. But the email didn´t arrive in my email account. Bellow are the codes that I´m using. settings.py # Email configuration EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '<my_email>@gmail.com' EMAIL_HOST_PASSWORD = '<my_password>' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False views.py In the top of file ... # send email from django.core.mail import send_mail ... In the request page def contact_us(request): if request.method == 'POST': form = ContactFormEN(request.POST) if form.is_valid(): sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message']) send_mail('New Message from site', message, sender_email, ['<my_email>@gmail.com'], fail_silently=False) return render(request, 'contact_us.html') After run the code the console shows the follow message Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: New Message from site From: <from_email>@gmail.com To: <my_email>@gmail.com Date: Mon, 15 Mar 2021 23:01:50 -0000 Message-ID: <161584931042.10464.14254641113919007176@my_machine_name> Name has sent you a new message: Test message ------------------------------------------------------------------------------- -
Django model filtering from multiple tables without direct relation
Hey I have two tables "Book" and "Author" and they don't have a direct relation between each other but I need all the Book records whos author_id is in a list of ids from the table Author which is filtered according to the LIKE operator. The following SQL statement is exactly what I want to achieve with the django filtering options but it doesn't seem to work. I read a lot about select_related and prefetch_related but they don't seem to solve my problem because those tables don't have a foreign key to each other: SELECT * FROM Book b WHERE b.author_id IN (SELECT id FROM Author WHERE country LIKE "%er%") // this will give back a list of ids -
Error deploying to Elastic Beanstalk: chown /var/app/staging/bin/python: no such file or directory
I am trying to deploy my app to Elastic Beanstalk however the CLI keeps returning the following error when I run 'eb deploy'. I am puzzled because my app is running fine locally. What does the error mean and how can I resolve it? I have been trying to find answers for hours with no luck .. error 2021/03/15 22:49:08.925837 [INFO] Executing instruction: StageApplication 2021/03/15 22:49:09.877646 [INFO] extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ 2021/03/15 22:49:09.877695 [INFO] Running command /bin/sh -c /usr/bin/unzip -q -o /opt/elasticbeanstalk/deployment/app_source_bundle -d /var/app/staging/ 2021/03/15 22:49:18.870026 [INFO] finished extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ successfully 2021/03/15 22:49:18.872859 [ERROR] An error occurred during execution of command [app-deploy] - [StageApplication]. Stop running the command. Error: chown /var/app/staging/bin/python: no such file or directory -
Makemigrations: ValueError: <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model
I struggle with migrations. I have created a model fine, with a model named 'RecipeIngredient', run migration and all is good. I decide to rename it to 'Ingredient', and change the only two places in models.py where it is mentioned: class Recipe(models.Model): created_by = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True, default=1) fooditems = models.ManyToManyField(Fooditem, through='Ingredient', through_fields=('recipe', 'foodit'), ) recipe_name = models.CharField(max_length=50, default='Calories') class Ingredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) foodit = models.ForeignKey(Fooditem, on_delete=models.CASCADE) q_set = models.DecimalField(max_digits=5, decimal_places=1, default=1) When i makemigrations, I have the error: ValueError: <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x000001B1FDE8B550> contains a lazy reference to Fityfeed.recipeingredient, but app 'Fityfeed' doesn't provide model 'recipeingredient'. I would like to understand the logic in migrations: I can see that in the old migrations there is still a 'RecipeIngredient' of course , am I supposed to change /delete old migrations? That creates all sort of problems. Or maybe the cause is somewhere else, where could the old name be present in the project? Thanks a lot for your help D -
NoReverseMatch at / error when implementing a comment option
I'm trying to implement a comment option for a django social media app and I get the NoReverseMatch at / error. NoReverseMatch at / Reverse for 'post-detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['post/int:pk/$'] I have read What is a NoReverseMatch error, and how do I fix it? and I understand that it seems like it can't find the url for post_detail.html. I have looked up a lot of similar issues but I can't find anything helpful to my case. I am following this tutorial : https://towardsdatascience.com/build-a-social-media-website-with-django-feed-app-backend-part-4-d82facfa7b3 I have tried to change the way I declare my url in urls.py but nothing seems to work so far. I am including the relevent python and html files , edited for length. urls.py from django.conf.urls import url, include from myapp import views as core_views from django.contrib.auth.views import LoginView, LogoutView from django.contrib import admin urlpatterns = [ url(r'^$', core_views.PostListView.as_view(), name ='home'), url(r'^post/<int:pk>/$', core_views.post_detail, name='post-detail'] views.py ... @login_required def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) user = request.user is_liked = Like.objects.filter(user=user, post=post) if request.method == 'POST': form = NewCommentForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.post = post data.username = user data.save() return redirect('post-detail', pk=pk) else: form = NewCommentForm() return render(request, 'feed/post_detail.html',{'post':post, 'is_liked':is_liked, … -
How to deploy a Django project generated by Cookie cutter to Elastic Beanstalk?
So I'm following a book named Django Crash Course by the Greenfelds. Here's the starter template they used. https://github.com/feldroy/django-crash-starter So this project template generates a Django version of 3.1.1 with Python 3.8. I tried to use Amazon Linux and Amazon Linux 2 on generating an environment on Elastic Beanstalk, both had 502 Bad gateway error. I have no idea how to fix since I'm still learning. I'm curious how can I use this template for production ready to Elastic Beanstalk. Thanks! -
Django forms & document.getElementById javascript - doesn't find id?
I have an app with a draggable marker on a map which populates the latitude and longitude. Beforehand, I was using a normal form where each input has an ID, this meant I could use document.getElementById('someformID').value to get the coordinates of the marker and input them into the form. However, when using Django forms, each form element doesn't have an ID in the HTML, so instead I added it the forms.py file as an attribute. It now doesn't grab the coordinates however. In the below code, I'm looking to get latcentre1 and longcentre1 from the Javascript forms.py class SafezoneForm(forms.ModelForm): class Meta: model = Safezone name = forms.CharField(widget=forms.TextInput (attrs={'id': 'name'})) useremail = forms.CharField(widget=forms.TextInput (attrs={'id': 'useremail'})) latitudecentre = forms.CharField(widget=forms.TextInput (attrs={'id': 'latcentre1'})) longitudecentre = forms.CharField(widget=forms.TextInput (attrs={'id': 'longcentre1'})) fields = ['useremail', 'name', 'longitudecentre', 'latitudecentre'] labels = { "name": "Name of safezone", "useremail": "Alert Email", "latitudecentre": "Latitude", "longitudecentre": "Longitude", } From reference in HTML file <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input class="btn btn-primary" type="submit" name="Submit"> </form> Javascript in the HTML file marker.on('dragend', function() { var lngLat = marker.getLngLat(); var latforform = lngLat.lat; var lonforform = lngLat.lng; document.getElementById('latcentre1').value = lngLat.lat; document.getElementById('longcentre1').value = lngLat.lng; Thanks! -
Can I use annotate to create a Charfield in django?
I'm working with a dataset of objects called Account that needs to go through an annotate in order to make some calculations. I have a list of ranges [[0, 1], [2, 4], [5, 49], [50, 99]] that represent different ranges of employees. I want to make an annotate that analizes if an object account belongs to a certain range and if it does, create a dynamic field called "range_name" and store the range as a string. For some reason, when i want to do this I get this: django.core.exceptions.FieldError: Cannot resolve keyword '[0, 1]' into field. Choices are: annual_revenue, avg_deal_size, cltv, employees, velocity Here is my models.py: class Account(models.Model): name = models.CharField(max_length=200, null=True, blank=True) employees = models.PositiveIntegerField( db_index=True, blank=True, null=True, ) annual_revenue = models.BigIntegerField( db_index=True, null=True, blank=True ) avg_deal_size = models.PositiveIntegerField( db_index=True, null=True, blank=True ) cltv = models.BigIntegerField(db_index=True, null=True, blank=True) velocity = models.PositiveIntegerField( db_index=True, null=True, blank=True ) Here's the code from my views.py where I try the annotate(): accounts = Account.objects.all() employees_ranges = [[0, 1], [2, 4], [5, 49], [50, 99]] for employee_range in employees_ranges: #here i turn the range into a string ranges_as_string = ', '.join([str(number) for number in employee_range]) ranges_as_string = '['+ranges_as_string+']' accounts_with_range_field = accounts.filter(employees__range=var).annotate( range_name=Case( When( Q(employees__gt=var[0]) …