Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Identify the Timer for uploading the data sheet ( excel ) in python
I have the excel sheet of 10 k records. If I upload the excel data it will take around 58 secs to complete the method. In my web application is it possible to say the this file upload will be completed in 58 secs in user notification ? whether we are able to identify the seconds/minutes based on records(excel file) in python / Django / celery / RabbitMQ process > -
Django3 Background Tasks not working with Apache2 + mod_wsgi
use django-background-tasks to run some heavy tasks in the background in my Django application. On my local machine everything works fine. However, if I deploy my application in production with Apache and mod_wsgi, the scheduled tasks are not executed. Instead, if I run the command python manage.py process_tasks Executing the above command will cause the Apache server to stop working and must be restarted. In the apache error file I found: [Sat Aug 14 04:53:43.420851 2021] [wsgi:warn] [pid 5573] self.sig_manager = SignalMana ger() [Sat Aug 14 04:53:43.420855 2021] [wsgi:warn] [pid 5573] File "/home/ubuntu/.virtualenvs /dj/lib/python3.9/site-packages/background_task/utils.py", line 20, in init [Sat Aug 14 04:53:43.420859 2021] [wsgi:warn] [pid 5573] signal.signal(signal.SIGTSTP, self.exit_gracefully) [Sat Aug 14 04:53:43.420874 2021] [wsgi:warn] [pid 5573] mod_wsgi (pid=5573): Callback reg istration for signal 10 ignored. [Sat Aug 14 04:53:43.420963 2021] [wsgi:warn] [pid 5573] File "/home/ubuntu/web_myboot/d jango_boot/core/wsgi.py", line 18, in [Sat Aug 14 04:53:43.420971 2021] [wsgi:warn] [pid 5573] management.call_command('proc ess_tasks') [Sat Aug 14 04:53:43.420977 2021] [wsgi:warn] [pid 5573] File "/home/ubuntu/.virtualenvs /dj/lib/python3.9/site-packages/django/core/management/init.py", line 181, in call_com mand [Sat Aug 14 04:53:43.420981 2021] [wsgi:warn] [pid 5573] return command.execute(*args, **defaults) [Sat Aug 14 04:53:43.420985 2021] [wsgi:warn] [pid 5573] File "/home/ubuntu/.virtualenvs /dj/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute [Sat Aug 14 04:53:43.420989 2021] [wsgi:warn] [pid 5573] output … -
problem with updating date in django-rest
I've tried to make a form that contains date-to-published. by default, when we register a new form, automatically adds a date of now! when I try to update it using postman, it seems nothing to be changed at all ! models.py class Student(models.Model): first_name = models.CharField(max_length=100, default=None,blank=True) last_name = models.CharField(max_length=100,default=None,blank=True) edu_code = models.CharField(max_length=100,default=None) national_code= models.CharField(max_length=100,default=None) date_to_published = jmodels.jDateField(blank=True,auto_now_add=True) phone_number = models.CharField(max_length=30,blank=True) student_sign = models.ImageField(upload_to = image_saving,blank=True) admin_fname = models.CharField(max_length=100) admin_lname = models.CharField(max_length=100) item = models.CharField(max_length=100,blank=True) img1 = models.ImageField(upload_to= image_saving, blank=True) img2 = models.ImageField(upload_to= image_saving, blank=True) img3 = models.ImageField(upload_to= image_saving, blank=True) def __str__(self): return f'{self.first_name} {self.last_name}' def __unicode__(self): return f'{self.first_name} {self.last_name}' serlializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ['id','first_name','last_name','edu_code','national_code','student_sign','date_to_published','phone_number','admin_fname', 'admin_lname','item','img1','img2','img3'] read_only_fields = ['admin_fname','admin_lname'] def create(self, validated_data): request = self.context.get("request") return Student.objects.create(**validated_data,admin_fname=request.user.first_name,admin_lname=request.user.last_name) def update(self, instance, validated_data): instance.date_to_published = validated_data.get('date_to_published', instance.date_to_published) instance.save() return instance views.py class StudentViewSet(viewsets.ModelViewSet): authentication_classes = [TokenAuthentication] #permission_classes = [IsAdminUser] queryset = Student.objects.all().order_by('-id') serializer_class = StudentSerializer filter_backends = [filters.SearchFilter] search_fields = ['edu_code','national_code',] enter image description here this is my new date to change an old date but I get the old date as Response. me request method is PUT -
Original exception text was: 'RelatedManager' object has no attribute 'type'. - Django Rest
models.py class Sequence(models.Model): category_id = models.ForeignKey(SequenceCategory, on_delete=models.CASCADE) description = models.TextField() code = models.CharField(max_length=50) total_divisions = models.IntegerField() status = models.BooleanField(default=True) def __str__(self): return self.code class SequenceValue(models.Model): TYPE_CHOICES =( ('N', 'Numeric'), ('A', 'Alphabet') ) sequence_id = models.ForeignKey(Sequence, on_delete=models.CASCADE, blank=True, null=True, related_name='Sequence_details') type = models.CharField(max_length=100, choices=TYPE_CHOICES) value = models.CharField(max_length=50) starting_value = models.CharField(max_length=50, null=True, blank=True) increment_value = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.value serializers.py class SequenceValueSerializer(serializers.ModelSerializer): class Meta: model = SequenceValue # fields = '__all__' exclude = ['sequence_id'] class SequenceSerializer(serializers.ModelSerializer): Sequence_details = SequenceValueSerializer() class Meta: model = Sequence fields = '__all__' def create(self, validate_data): Sequence_details_data = validate_data.pop('Sequence_details') sequence_id = Sequence.objects.create(**validate_data) SequenceValue.objects.create(sequence_id=sequence_id, **Sequence_details_data) return sequence_id views.py class SequenceCreate(ListCreateAPIView): queryset = Sequence.objects.all() serializer_class = SequenceSerializer Why do I get the error? When I refer n number of articles I got a solution that put many=True something like this. Sequence_details = SequenceValueSerializer(many=True) But when I make changes on that then I can't get the Sequence details fields. How can I fix this issue. Can you give a solution please? Actual error- Got AttributeError when attempting to get a value for field type on serializer SequenceValueSerializer. The serializer field might be named incorrectly and not match any attribute or key on the RelatedManager instance. Original exception text … -
Certain pages on Heroku return server error 500
good day, I was hoping my first post would be something helpful to other but here we go with a question instead. I'm fairly new to python/django and i'm working on an ecommerce project. My deployed site worked flawlessly, but all of a sudden I started getting server error 500 when trying to access login/register/admin pages. To my untrained eye it seems it's only affecting pages connected with allauth. When I turned on debug on my heroku app it returns "DoesNotExist" / "Site matching query does not exist". Only thing I fiddled with before it stopped working is "sites" in admin panel where I deleted "example.com" and put my site name as it was needed for email sending templates". Could it be that changing site name in admin panel made it this way, and if so, how can I revert the changes now that I can't access my admin panel? any help is greatly appreciated nsum -
FreeBSD: How to run UWSGI with python37 instead of python38
I am running a website on a FreeBSD 13.0 machine. The website is running in a python37 virtual environment with Django. I installed uwsgi on the operating system (not in the virtual environment) so that I can make the website auto-start when the system starts and run it in emperor mode. I have previously set this up successfully before but I ran into some issues when python38 was released. When I install uWSGI 2.0.19.1, it pulls python38 along with it, and when I run uwsgi, it runs with python version 3.8. I confirmed that both versions of python are installed, but uwsgi prefers to use python38. My question is, how can I specify to uwsgi which python version to use? I want to make uwsgi run with python37 instead of py38. I know that an alternative could be to install a different version of uwsgi but how would I go about installing a different version? Only the latest version appears with 'pkg.' -
is there any way to solve this error need some good insights
my error is :- groups.Groups.members: (fields.E303) Reverse query name for 'groups.Groups.members' clashes with field name 'auth.User.groups'. HINT: Rename field 'auth.User.groups', or add/change a related_name argument to the definition for field 'groups.Groups.members'. from django.db import models from django.utils.text import slugify import misaka from django.urls import reverse from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class Groups(models.Model): name = models.CharField(max_length=264) slug = models.SlugField(allow_unicode=True,unique = True) description = models.TextField(blank = True,default = '') description_html = models.TextField() members = models.ManyToManyField(User,through = 'GroupMember') def __str__(self): return self.name def save(self,*args,**Kwargs): self.slug = self.slugify(self.name) self.description_html = self.misaka(self.description) super().save(*args,**Kwargs) def get_absolute_url(self): return reverse('groups:single',Kwargs={'slug':self.slug}) class Meta(): ordering = ['name'] class GroupMember(models.Model): group = models.ForeignKey(Groups,related_name='membership',on_delete = models.CASCADE) user = models.ForeignKey(User,related_name = 'user_group',on_delete = models.CASCADE) def __str__(self): return self.user.username class Meta(): unique_together=['group','user'] -
How to copy files from host to docker named volume
I started a Django app with docker with bind host to handle user uploads but now I want to migrate to named volumes but I already have files in my host, so I was wonderings how can I copy the files from the host to the volume, this is my docker-compose for my web container: version: '3' services: db: restart: always image: "postgres:13.2-alpine" container_name: db ports: - "5432:5432" env_file: - ./.env.dev volumes: - ./pgdata:/var/lib/postgresql/data web: container_name: web restart: always build: context: . dockerfile: ./docker/development/Dockerfile environment: DEBUG: 'true' DJANGO_SETTINGS_MODULE: myapp.app_settings.development command: sh ./docker/development/runserver.sh ports: - "8000:8000" env_file: - ./.env.dev volumes: - .:/app # Enable code reload - django-static:/app/run/static - django-media:/app/run/media depends_on: - db volumes: django-static: django-media: And this is my Dockerfile: FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY ./requirements.txt /app/ RUN pip install --no-cache-dir -r requirements.txt # COPY . /app ADD . /app RUN apt-get clean && apt-get update && apt install -y netcat COPY ./docker/development/entrypoint.sh /docker-entrypoint.sh RUN chmod +x /docker-entrypoint.sh ENTRYPOINT ["/docker-entrypoint.sh"] There is a way to copy my uploads from host: /home/art/myapp/run/media and /home/art/myapp/run/static to volumes django-static and django-media ? Also, How I can backup the files from the volume? -
Using Django StreamingHttpResponse in template
How can one use the streamed data using Django's StreamingHttpResponse in a template? This is so trivial, yet I found 0 info about this online. views.py : import VideoCamera def Gen(feed): while True: something = feed.do_something() yield (something) def Use(request): return StreamingHttpResponse(Gen(VideoCamera()), content_type='text') urls.py : urlpatterns = [ path('use_feed_data/', views.Use, name='use_feed_data'), ] in template : {% url 'use_feed_data' %} The result in the template is the path "/use_feed_data/" instead of the streamed data, yet in localhost:8000/use_feed_data/ I'm able to see all the streamed data. How can I access that streamed data in the main template? -
Django profile picture: The 'ImageField' attribute has no file associated with it
thank you for taking your time! This is my problem, I'm working on a little project about a blog with Django. When I upload a profile picture, everything works fine, but when I don't, the "The 'ImageField' attribute has no file associated with it." error prompts. The thing is that I uploaded a default pic in the static dir and created and if to manage that. If the user doesn't have a photo, just show the image from the static dir. Here are the HTML and model files. <div class="ui items"> <div class="item"> {% if post.author.profile.image.url %} <div class="ui small image"> <img src="{{ post.author.profile.image.url }}"> </div> {% else %} <div class="ui small image"> <img src="{% static 'static/ProyectoBlog/images/default-profile-pic.png' %}"> </div> {% endif %} <div class="content"> <a class="header">{{ post.author.first_name }} {{ post.author.last_name }}</a> <div class="meta"> <span>About</span> </div> <div class="description"> <p>{{ post.author.profile.bio }}</p> </div> <div class="extra"> <a href="{{ post.author.profile.fb_url }}"> <i class="big facebook icon"></i> </a> <a href="{{ post.author.profile.tw_url }}"> <i class="big twitter icon"></i> </a> <a href="{{ post.author.profile.ig_url }}"> <i class="big instagram icon"></i> </a> </div> </div> </div> </div> class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField(max_length=500) image = models.ImageField(upload_to="bios", blank=True, null=True, default='static/ProyectoBlog/images/default-profile-pic.png') fb_url = models.CharField(max_length=255, null=True, blank=True) tw_url = models.CharField(max_length=255, null=True, blank=True) … -
New Graphene-Django installation gives ImportError for schema.schema path in settings.py when accessing /graphql/
Important part of the traceback Exception Type: ImportError at /graphql Exception Value: Could not import 'website.schema.schema' for Graphene setting 'SCHEMA'. ModuleNotFoundError: No module named 'motophoto.website'. This is a brand new Graphene-Django install with barely any work. I followed the tutorial on the website and have done everything correct, checked and double checked. Have been looking at other SO answers with no luck. Made sure the recommended versions are installed. Checked for misspellings and tried different paths Restarted the Django server many times Project Structure Relevant Source Code I don't really want to upload the entire project, but comment if you need a look at a specific file other than what's provided. -
Templates First element of a List /Django
I have two models of connected to each other. post and comment. I want show last message date on post. My model perfectly works but i can not show on the template. I tried "first" tag but the first tag only shows the date of the first post. I add few image for your better understanding They are left blank because there are no messages in the blank sections yet. Views: def forums(request,forumname): forum = Category.objects.get(categoryName=forumname) post2 = UserPosts.objects.all().filter(category=forum.id).order_by('- created_at').filter(category=forum.id) post_message = UserMessages.objects.all().order_by('-created_at') post3 = UserMessages.objects.all().order_by('-created_at') context = { 'categoryName':forumname, 'categoryDescription':forum.Categorydescription, 'posts': post2, "post_message":post_message, "post3":post3 } return render(request, "_forums.html",context) HTML <div class="col "> <div class="col mb-2 text-muted"> {% for x in post_message %} {% if x.post_id == post.id %} answered {{x.created_at| naturaltime }} {% endif %} {% endfor %} </div> </div> -
How can I validate a dependent dropdown list?
I'm trying to make a dependent selection form (choose a game race, then choose a related subrace) following this tutorial:https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html However, their fix for the validation step isnt working for me for some reason. Suposeddly, I should overwrite the queryset with the adequate set of correct subraces before it validates the user choice, that way it doesnt see an empty queryset when looking for valid selections. I do that, and when I print the queryset it shows me the correct list <QuerySet [<Subrace: Forest>, <Subrace: high>]>. I have chosen the forest subrace, but it tells me "Select a valid choice. 2 is not one of the available choices." even though 2 is the id of the forest subrace, which is in the queryset. These are the models class Character(models.Model): raceKey = models.ForeignKey(Race, on_delete=models.CASCADE) subraceKey = models.ForeignKey(Subrace, on_delete=models.CASCADE) class Race(models.Model): name = models.CharField(max_length=30) # string def __str__(self): return self.name class Subrace(models.Model): raceKey = models.ForeignKey(Race, on_delete=models.CASCADE) name = models.CharField(max_length=30) # string def __str__(self): return self.name and these are the widget, field and form: class CharacterForm(forms.ModelForm): subraceKey = forms.ChoiceField( label="Subraza", ) # height = LengthField(label="Altura (en pies/pulgadas)") class Meta: model = Character fields = ( "raceKey", "subraceKey", ) def __init__(self, *args, **kwargs): super().__init__(*args, … -
Django API: URL query with filter equals null
I want to use a third-party Django API via HTTP. First I discovered existing API calls via /api/v1/schema/. There is: /api/v1/classification/. It has a propterty parent: - name: parent required: false in: query description: parent schema: type: string For some items it is null. I want to find those. What is the correct syntax? /api/v1/classification/?parent=null /api/v1/classification/?parent=<null> /api/v1/classification/?parent= /api/v1/classification/?parent="null" All give me: Select a valid choice. That choice is not one of the available choices. -
Can't change variables in a nested for loop. Even when inside a parent for loop iterating a global variable [duplicate]
def decodeMorse(morse_code): # ToDo: Accept dots, dashes and spaces, return human-readable message morse_word_list = morse_code.split(' ') decoded_message = [] for count, morseword in enumerate(morse_word_list): morseword = morseword.split(' ') for count, letter in enumerate(morseword): if letter == '': letter = ' ' else: letter = MORSE_CODE[letter] print(morseword) For some reason the "print(morseword)" still prints as the original in the loop without all the letters being changed. LOG ['....', '.', '-.--'] ['', '.---', '..-', '-..', '.'] -
python migrate.py command fails in django
I am trying to setup my environment using VS code, and I have noticed that when i run the python manage.py migrate command I get the following errors. Its strange because the project is new one, from the research I did I noticed that some people were getting the error because they changed some files etc, in my case I have not changed any file. its a new clean project. All I have done is removed the default sqllite database and replaced this with a SQL server database configuration. I noticed that 2 tables gets created, that is django_content_type and django_migrations then the process fails, is it possible to get some kind of verbose logs to see what the issue is ? The error details that I have are below. (env) PS C:\Users\User\Documents\django\feature\django\deployment_reporting\reporting_project> python manage.py makemigrations No changes detected (env) PS C:\Users\User\Documents\django\feature\django\deployment_reporting\reporting_project> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "C:\Users\User\Documents\django\feature\django\deployment_reporting\reporting_project\manage.py", line 22, in <module> main() File "C:\Users\User\Documents\django\feature\django\deployment_reporting\reporting_project\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\User\Documents\django\feature\django\deployment_reporting\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\User\Documents\django\feature\django\deployment_reporting\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\Documents\django\feature\django\deployment_reporting\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File … -
Reducing size of Django JSON object through mapping
I have User and Post models, that broadly look like the following: class User(models.Model): # a bunch of fields class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # a bunch of fields When I query for some posts and then serialize them to JSON, if there are multiple posts from the same user, which usually happens, all the user's data ends up being repeated, as seen in the following very simplified example. [ { "user":{ ... }, ... }, { "user":{ ... }, ... }, { "user":{ ... }, ... }, { "user":{ ... }, ... } ] Is there any way to automatically create a dictionary, that will store separately all users, and have the posts reference that dictionary? It could, basically, look like this: { "users": [ { ... }, { ... } ], "posts":[ { "user": 0, ... }, { "user": 1, ... }, { "user": 1, ... }, { "user": 0, ... } ] } Where user would be the index of the user in the other -
Permission for object that share the same attribute
I am trying to create a permission that extend the "get_queryset" method to several Class based views. Let's say I have a two models, one call guestcard and one call notebook, they both share the same attribute which is properties so I would like to create a permission that apply to both of them. For example : class IsPropertyMember(object): def get_queryset(self): return Notebook.objects.filter(properties=self.request.user) Where notebook would be replace by a general object so I can use it in model which share the same attribute. I have some idea, maybe using getattr ? But I fail to see the logic in order to implement it. -
AttributeError: 'dict' object has no attribute 'headers'
Please help how to solve this problem. :( Views def chatbot_process(request): #INITIALIZATION CHATBOT lemmatizer = WordNetLemmatizer() intents = json.loads(open('chatbot/intents.json').read()) words = pickle.load(open('words.pkl', 'rb')) classes = pickle.load(open('classes.pkl', 'rb')) model = load_model('chatbotmodel.h5') # FUNCTION DEFINITION def clean_up_sentence(sentence): sentence_words = nltk.word_tokenize(sentence) sentence_words = [lemmatizer.lemmatize(word) for word in sentence_words] return sentence_words def bag_of_words(sentence): sentence_words = clean_up_sentence(sentence) bag = [0] * len(words) for w in sentence_words: for i, word in enumerate(words): if word == w: bag[i] = 1 return np.array(bag) def predict_class(sentence): bow = bag_of_words(sentence) res = model.predict(np.array([bow]))[0] ERROR_THRESHOLD = 0.25 results = [[i,r]for i, r in enumerate(res) if r > ERROR_THRESHOLD] results.sort(key = lambda x: x[1], reverse = True) return_list = [] for r in results: return_list.append({'intent': classes[r[0]], 'probability': str(r[1])}) return return_list def get_response(intents_list, intents_json): tag = intents_list[0]['intent'] list_of_intents = intents_json['intents'] for i in list_of_intents: if i ['tag'] == tag: result = random.choice(i['responses']) break return result # TAKING OF INPUT MESSAGES message = request.POST.get("input_text") ints = predict_class(str(message)) response = get_response(ints, intents) response2 = str(response) print("MESSAGE: ", ints) print("REPONSE: ", response2) context = { 'message': message, 'response': response } return context # return render(request, "chatbot/chatbot.html", context) # return HttpResponse(response) def chatbot(request): return render(request, "chatbot/chatbot.html") HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta … -
using filter with django tables 2
So I am trying to add filter to django tables 2 using django filter and I can see the filters but it does not apply to table. What do I do from this point? Is it something with url or do I have to do something with function on TestView? views.py from django.shortcuts import render from django.views.generic import TemplateView from django_tables2 import SingleTableView import django_tables2 as tables from .models import Test from .tables import TestTable from .filters import TestFilter class TestView(LoginRequiredMixin, tables.SingleTableView): model = Test template_name = "/test_info.html" filterset_class = TestFilter def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = TestFilter(self.request.GET, queryset=self.get_queryset()) return context filters.py import django_filters from django_filters import DateFilter, CharFilter from .models import * class TestFilter(django_filters.FilterSet): class Meta: model = Test fields = { 'name': ['icontains'], } test_info.html {% extends "base.html" %} {% load render_table from django_tables2 %} {% load bootstrap4 %} {% block head_title %} Vendor Info {% endblock %} {% block header %}{% endblock %} {% block content %} <div class="container-fluid w-75 p-3"> <div class="card card-body"> <form method="get" class="form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' button_type='submit'%} <!-- <button class="btn btn-primary" type="submit">Search</button> --> </form> </div> <div class="row justify-content-sm-center table-responsive mt-4"> {% render_table table %} </div> </div> … -
Summernote editor not show any content on django admin page
I'm using summernote package in my django project. However, the editor is not showing any content. The body = TextField() is completely blank (the whole space is white) in the admin page as shown in the attached file. admin.py class postAdmin(SummernoteModelAdmin): summernote_fields = '__all__' admin.site.register(post, postAdmin) settings.py X_FRAME_OPTIONS = "SAMEORIGIN" models.py class post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) slug = models.SlugField() title = models.CharField(max_length=50) body = models.TextField() ... serializers.py class post_serializer(serializers.ModelSerializer): class Meta: model = post fields = '__all__' lookup_field = 'slug' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('summernote/',include('django_summernote.urls')), ... ] I saw similar question online but none of the approaches I saw worked for me. How do I make the textfield in the screenshot editatble? I'm not using bootstrap or css because I'm creating an api that will be consumed by a frontend react app. -
how to connect DJANGO app to AWS RDS connected to a bastion via SSH
Is there a way to connect Django to a private RDS connected to a bastion via SSH? My current AWS infrastructure has a EC2 Bastion in a public subnet and two private subnets where postgres RDS DB reside. DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "aaaa", "USER": "bbbb", "PASSWORD": "cccc", "HOST": "xxx.zzz.us-east-z.rds.amazonaws.com", "PORT": 5432, } } using the terminal i can ssh into the bastion and check the connection with RDS, OK. Now i want to connect Django settings above to RDS so: i connected my RDS to https://dbeaver.com/ software (result say: connected!) On Django side now when I edited the settings.py above with the AWS RDS credentials started django python manage.py runserver i receive the following error. django.db.utils.OperationalError: could not translate host name "xxx.zzz.us-east-z.rds.amazonaws.com" to address: nodename nor servname provided, or not known. Is there something that i am missing on the approach? -
To insert elements into the javascript input box
I am a student studying JavaScript. I want to put the checkValue value in the strong tag into the input box, but I don't know how to write JavaScript to get it into the input box. Do I need to find cart_table of div? Or should I find a strong tag? <script> $().ready(function() { $("#optionSelect").change(function() { var checkValue = $("#optionSelect").val(); var checkText = $("#optionSelect option:selected").text(); var product = $("#productname").text(); var price = parseInt($("#price").text()); var test = parseInt($(this).find(':selected').data('price')); var hapgae = price + test if (checkValue != "no") { var whtml = " <div class=\"cart_table\">\n" + " <hr style='width: 300px; margin-bottom: 30px;'>" + " <p style='font-size: 17px;'>" + product + "</p>" + " <p style='font-size: 13px; margin-top: -10px; class=\"check\" margin-bottom: 20px;'>" + checkText + "</p>" + " <strong class=\"value_code2\">" + checkValue + "</strong>\n" + " <input name=\"value_code\" id=\"value_code\" class=\"value_code\">" + Strong tags and input tags refer to this part. " <strong class=\"value_code2\">" + checkValue + "</strong>\n" + " <input name=\"value_code\" id=\"value_code\" class=\"value_code\">" + -
django += 1 increments by 2 instead of 1
models.py class ModFile(models.Model): mod = models.ForeignKey(Mod, on_delete=models.CASCADE) title = models.CharField(max_length=128) downloads = models.IntegerField(default=0) file = models.FileField(upload_to='mods/') views.py class downloadMod(APIView): def get(self, request, id): file = models.ModFile.objects.get(id=id) file.downloads += 1 file.save() return FileResponse(file.file) In views.py, the get() function retrieves the model by its id and should increment file.downloads by 1 but for some reason it increments by 2, what am I doing wrong? -
Adding new instances of model to database Django
I'm very new to Python and programming at all. I'v encountered quite weird problem. While creating and adding certain amount of new instances to database it generates some amount of additional instances. For example I'm passing parameter of 10 new instances to view function but it creates 10 plus 70 additional. Two examples of view function please find below. def generate_students(request): class CountForm(forms.Form): count = forms.IntegerField(min_value=1, max_value=100) form = CountForm(request.GET) if form.is_valid(): count = form.cleaned_data['count'] studentList = [] for _ in range(count): studentList.append(Student(first_name=f.first_name(), last_name=f.last_name(), age=random.randint(18, 100))) Student.objects.bulk_create(studentList) output = [ f"{student.id} {student.first_name} {student.last_name} {student.age};<br/>" for student in studentList] else: return HttpResponse(str(form.errors)) return HttpResponse(output) def generate_students(request): class CountForm(forms.Form): count = forms.IntegerField(min_value=1, max_value=100) form = CountForm(request.GET) if form.is_valid(): count = form.cleaned_data['count'] studentList = [ Student.objects.create(first_name=f.first_name(), last_name=f.last_name(), age=random.randint(18, 100)) for _ in range(count)] output = [ f"{student.id} {student.first_name} {student.last_name} {student.age};<br/>" for student in studentList] else: return HttpResponse(str(form.errors)) return HttpResponse(output) def generate_students(request): class CountForm(forms.Form): count = forms.IntegerField(min_value=1, max_value=100) form = CountForm(request.GET) if form.is_valid(): count = form.cleaned_data['count'] studentList = [] for _ in range(count): studentList.append(Student(first_name=f.first_name(), last_name=f.last_name(), age=random.randint(18, 100))) Student.objects.bulk_create(studentList) output = [ f"{student.id} {student.first_name} {student.last_name} {student.age};<br/>" for student in studentList] else: return HttpResponse(str(form.errors)) return HttpResponse(output) def generate_students(request): class CountForm(forms.Form): count = forms.IntegerField(min_value=1, max_value=100) form = …