Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How pass queryset to djangofilter
in my django app i would pass a queryset where retrieve groups of the current user as filter. Now I did this code and it works as aspected. But in the searchbox in html i do not have filter class DatiBoeView(LoginRequiredMixin,SingleTableMixin,FilterView): queryset = DatiBoe.objects.all() model = queryset table_class = DatiBoeTable template_name = 'sito_boe/boefilt.html' filterset_class = filtroTableS form_class = DatiBoeForm paginate_by = 10 def get_queryset(self): #print(self.request.user) # print(self.request.user.groups.all()) itemset_queryset = Boe.objects.filter(id__in=self.request.user.groups.all()) queryset = DatiBoe.objects.filter(boa_id__in=itemset_queryset) return queryset If i don't put queryset = DatiBoe.objects.all() at start i receive error. How can pass my queryset from get_queryset function to filterset_class? -
Docker pull Django image and run container
So, I have followed this tutorial by Docker to create a Django image. It completely works on my local machine by just running a docker-compose up command from the root directory of my project. But, after pushing the image to docker hub https://hub.docker.com/repository/docker/vivanks/firsttry I am pulling the image to another machine and then running: docker run -p 8020:8020 vivanks/firsttry But it's not getting started and showing this error: EXITED(0) Can anyone help me on how to pull this image and run it? -
How to return a huge generated ZIP file in Django?
I would like to return a really big generated ZIP file in Django. The ZIP would include from 1000 to 5000 PDF files. These PDF files are stored on Amazon S3. I am using Heroku, and it has a 30 second timeout. So I can't get all the files and send a response in time. What I tried is generating the ZIP file, in the backend, where I don't have this timeout limit. But Heroku has a 1GB Memory limit. So i can't do that either. This is the code I used to perform this task: from zipfile import ZipFile def make_incoming_zip_file(): zip_obj = ZipFileIncomingInvoices.objects.get(zip_file="") invoices = get_invoices(year, quarter) with ZipFile("invoices.zip", "w") as zf: for idx, invoice in enumerate(invoices): file_path = "work_folder/incoming_invoice.pdf" with open(file_path , "wb") as f: f.write(invoice.invoice_file.read()) zf.write(filename=file_path , arcname=f"{idx+1} {invoice}.pdf") zip_obj.zip_file = File(open("invoices.zip", "rb")) zip_obj.save() What would be the best way to achieve this task? Thank you -
How to use the autocreated Django models.py from Database
I have a problem, I have a database with the following tables: Images(recipeID,image_url) Recipe(recipeID,recipe_title) Preperation(recipeID,preparation) Ingredients(ingredientID,recipeID,amount,unit,unit2,ingredient) I auto-created a models.py file with Django from the database with the following command: python manage.py inspectdb > models.py. In this file, he created all the models and three "strange" models: AllRecipesIngredient, AllRecipesRecipe, and AllRecipesRecipeIngredients. Now I want to know what they are and how I can use the recipes from one model or class like recipes.objects.all(), at the moment it would just give me the title or the preparation. I think the "strange" models he created are a part of what I need but I found no working solution so I hope you can help me. Here is the code: from django.db import models class Images(models.Model): rezept = models.ForeignKey('Rezepte', models.DO_NOTHING, db_column='Rezept_ID', blank=True, null=True) # Field name made lowercase. image_url = models.CharField(db_column='Image_URL', blank=True, null=True,max_length=1000) # Field name made lowercase. class Meta: managed = False db_table = 'Images' class Rezepte(models.Model): rezept_id = models.AutoField(db_column='Rezept_ID', primary_key=True, blank=True) # Field name made lowercase. rezept_title = models.CharField(db_column='Rezept_Title', blank=True, null=True,max_length=1000) # Field name made lowercase. class Meta: managed = False db_table = 'Rezepte' class Zubereitungen(models.Model): zubereitungs = models.OneToOneField(Rezepte, models.DO_NOTHING, db_column='Zubereitungs_ID', primary_key=True, blank=True) # Field name made lowercase. zubereitung = models.TextField(db_column='Zubereitung', … -
Can't access health check
I am currently working on a web app using Django. I used this app.yaml and it is deployed successfully on google app engine. However, I couldn't access /_hc, because Django checks whether the url is in url patterns and it just responds with 'Page not found'. How do I fix this? runtime: python37 entrypoint: bash -c 'gunicorn -b :$PORT projectservice.wsgi' liveness_check: path: "/_hc" check_interval_sec: 30 timeout_sec: 4 failure_threshold: 2 success_threshold: 2 handlers: # This configures Google App Engine to serve the files in the app's # static directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to the main app. # It is required when static routes are defined, but can be omitted # (along with the entire handlers section) when there are no static # files defined. - url: /.* script: auto # [END django_app] -
How to check if `MultiSelectField` is empty or not in Django?
In my model I have a field department which is a MultiSelectField and I give the blank=True to that field for some reasons. Now I want to check if user fills the field or not. I have tried to get data from request.POST and gave it a condition using len() function like this if len(field) == 0: but I got an error. Everything works just fine until I added teacher_year = request.POST['teacher_year'] models.py class CustomUser(AbstractUser): teacher_department = MultiSelectField(choices=department_choice, blank=True) forms.py class TeacherRegisterForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ['teacher_year', ...] views.py def teacherRegisterView(request): form = TeacherRegisterForm() template_name = "attendance/login-register/teacher_register.html" if request.method == "POST": form = TeacherRegisterForm(request.POST) teacher_year = request.POST['teacher_year'] if len(teacher_year) == 0: messages.warning(request, "Just a remind! You didn't select deparment!") return redirect('teacher_register') elif form.is_valid(): form.save() messages.success(request, "Your account was created! You can log in now.") return redirect('/') return render(request, template_name, {'form': form}) the error I got django.utils.datastructures.MultiValueDictKeyError: 'teacher_year' -
displaying data from django model in template with celery
I am working on a django project. In the project, I am scraping some data from a website and storing the results into a django model. I want to now display this data in a django template as and when it is saved in the model. this is my code so far mainapp/views.py from django.shortcuts import render from .tasks import get_website from .models import Articles def index(request): if request.method == 'POST': website = request.POST.get('website') title = request.POST['title'] author = request.POST['author'] publish_date = request.POST['publish_date'] get_website.delay(website, title, author, publish_date) return render(request, 'output.html') return render(request, 'index.html') def output(request): return render(request, 'output.html') in the index page, I have a form which when submitted starts the scraping process through the celery task get_website(). mainapp/tasks.py @shared_task def get_website(website, title, author, publish_date): ... return save_function(article_list) @shared_task(serializer='json') def save_function(article_list): print('saving extracted data') new_count = 0 for article in article_list: try: new_article = Articles( Title = article['Title'], Link = article['Link'], Website = article['Website'], Author = article['Author'], Publish_date = article['Publish_date'], ) new_count += 1 new_article.save() except Exception as e: print(e) break return print('finished') All of the scraped data is stored in a list article_list and is passed to save_function() to save the data into the django model Articles. I want … -
Multi file upload in django
I want to upload multiple files through a form field. I tried many solutions including here on stackoverflow and medium.com This is my latest approach to tackle the problem. I have bank_statement field in my form for which I have to accept multi file upload option. I tried to override the POST method in order for bank_statement field to take multiple file upload using the multi_upload function in views.py as shown below. However, it still shows one upload button for the field when I open the page. What am I doing wrong and how do I fix it? models.py class Customer(models.Model): id=models.AutoField(primary_key=True, default=None) customerReg=models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) status=models.CharField(max_length=254, choices=Status_Choices, default='Incomplete') first_name=models.CharField(max_length=200, blank=False, default=None) last_name=models.CharField(max_length=200, blank=False, default=None) personal_photo=models.FileField(upload_to=content_file_name, default=None, blank=True) bank_statement=models.FileField(upload_to=content_file_name, default=None, null=True, blank=True) forms.py class RegForm(ModelForm): class Meta: model=Customer fields=['status','customerReg','first_name', 'last_name','personal_photo','bank_statement'] #readonly_fields=['status'] widgets={ 'status':forms.TextInput(attrs={'readonly':'readonly'}), 'bank_statement':ClearableFileInput(attrs={'multiple':True}), view.py def multi_form(request): #view for multi-form page form=RegForm() if request.method=='POST': form=RegForm(request.POST, request.FILES) if form.is_valid(): reg=form.save(commit=False) reg.customerReg=request.user reg.save() messages.success(request, "Your Response has been recorded") context={'form':form} return render(request, 'customer/success.html', context) else : return render(request, 'customer/index.html', {'form': form}) else: context = {'form': form} return render(request, 'customer/index.html', context) def multi_upload(request): if request.method == "POST": form=RegForm(request.POST, request.FILES) files=request.FILES.getlist('bank_statement') if form.is_valid(): for f in files: file_instance=Customer(bank_statement=f) file_instance.save() else: form=RegForm() return render(request, … -
Add additional information to request
I have an e-commerce website I'm working on, and I'd like it to be able to do something like this: class Shop(ListView): # Set the model as Product, the rest is handled by Django model = Product # Name of HTML File to show template_name = 'store/shop.html' # What to refer to in the HTML file (injection) context_object_name = 'products' # If the request.method is POST (a filter request) def post(self, request, *args, **kwargs): # Function from utils.py min_price, max_price, products = filter_shop(request) print(min_price, max_price) # Function from utils.py data = cartData(self.request) # Assigning keys to keys in context which can then be referenced in the html # Pass is in the completed query as a option, plus cartitems for the cart context_dict = {'products': products, 'cartitems': data['cartItems'], 'min_price': min_price, 'max_price': max_price, 'categories': category_choices()} return render(request, 'store/shop.html', context_dict) def get(self, request, *args, **kwargs): category = self.kwargs['category'] if category == 'custom': return super().get(request, *args, **kwargs) elif category == 'men': context_dict = {'men-coats': 'on'} request = request + context_dict return self.post(request, *args, **kwargs) What's happening is that the get request looks for something in the URL, and then needs to run the request as if it is a post request, I just … -
Django: How do I query posts for showing to users?
EXAMPLE to elaborate my problem -> I am a user named arthor and i have created many posts. when i go to the link https:example.com/posts/arthor then i want to see all my posts that i have created. similarly if another user name julia goes to https:example.com/posts/julia then she should see her posts that she created but if she goes to https:example.com/posts/arthor then she should see the arthor i.e my posts only. ISSUE i am facing -> i have created somewhat correct views but in the get_queryset i have postlist which takes myposts and filter them. In the filter at the place of uploaded_by i have given self.request.user.profile which gives the current user not the user of the link that i being entered in the url. such as if url https:example.com/posts/arthor is triggered then i want uploaded_by=arthor urls.py urlpatterns = [ path("posts/<str:username>", views.UserPostList.as_view(), name="posts"), ] models.py class MyPost(models.Model): pic = models.ImageField( upload_to="users/post_images/%y/%m/%d", null=True ) subject = models.CharField(max_length=200) message = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now=True) uploaded_by = models.ForeignKey(to=Profile, on_delete=CASCADE, null=True) def __str__(self): return "%s" % self.subject views.py class UserPostList(LoginRequiredMixin, SelectRelatedMixin, generic.ListView): login_url = "accounts:signin" raise_exception = False model = models.MyPost select_related = ('uploaded_by',) context_object_name = 'myposts' template_name = 'posts/user_post_list.html' def get_queryset(self): si … -
How to send multiple model from a classbased view in django
I made a booklist where cover image can be uploaded inside Booklist class. For more image I added another class called Bookcover. Now in Views.py how can I send both Booklist and Bookcover's by using BookListView models.py file is below from django.db import models from django.utils import timezone class Booklist(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length = 100) cover = models.ImageField(null=True, blank=True, default='default-book.jpg') description = models.TextField() date_posted = models.DateTimeField(default=timezone.now) price = models.DecimalField(decimal_places=3, max_digits=100) def __str__(self): return self.title class Bookcover(models.Model): post = models.ForeignKey(Booklist, default=None, on_delete=models.CASCADE) covers = models.ImageField(upload_to = 'images/') def __str__(self): return self.post.title here is views.py file from django.shortcuts import render from django.views.generic import ListView from .models import Booklist, Bookcover def home(request): return render(request, template_name='home/index.html') class BookListView(ListView): model = Booklist template_name = 'home/index.html' context_object_name = 'books' ordering = ['-date_posted'] -
Scrapy spider not working on Django after implementing WebSockets with Channels (cannot call it from an async context)
I'm opening a new question as I'm having an issue with Scrapy and Channels in a Django application. The reason why I'm using channels is because I want to retrieve in real-time the crawl statuses from Scrapyd API, without having to use setIntervals all the time, as this is supposed to become a SaaS service which could potentially be used by many users. I've implemented channels correctly, if I run: python manage.py runserver I can correctly see that the system is now using ASGI: System check identified no issues (0 silenced). September 01, 2020 - 15:12:33 Django version 3.0.7, using settings 'seotoolkit.settings' Starting ASGI/Channels version 2.4.0 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Also, the client and server connect correctly via the WebSocket: WebSocket HANDSHAKING /crawler/22/ [127.0.0.1:50264] connected {'type': 'websocket.connect'} WebSocket CONNECT /crawler/22/ [127.0.0.1:50264] So far so good, the problem comes when I run scrapy via the Scrapyd-API 2020-09-01 15:31:25 [scrapy.core.scraper] ERROR: Error processing {'url': 'https://www.example.com'} raceback (most recent call last): File "/Users/Andrea/anaconda3/envs/DjangoScrape/lib/python3.6/site-packages/twisted/internet/defer.py", line 654, in _runCallbacks current.result = callback(current.result, *args, **kw) File "/Users/Andrea/anaconda3/envs/DjangoScrape/lib/python3.6/site-packages/scrapy/utils/defer.py", line 157, in f return deferred_from_coro(coro_f(*coro_args, **coro_kwargs)) File "/private/var/folders/qz/ytk7wml54zd6rssxygt512hc0000gn/T/crawler-1597767314-spxv81dy.egg/webspider/pipelines.py", line 67, in process_item File "/Users/Andrea/anaconda3/envs/DjangoScrape/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File … -
Nested ManytoMany field not in the Response
I am trying to write a nested serializer which would add serialize 2 models in the same view. Serialization seems to work fine since changes get reflected in the database but I am not able to get the many-to-many related field data in the response. I have been trying to figure out what the issue might be but still no progress. Here is my code: Model class User(AbstractBaseUser): AccountName = models.ManyToManyField(Account, through='User_Account', through_fields=('user', 'acc'), related_name='AccountData', blank=True) EmailId = models.EmailField(max_length=128, blank=False, null=False) USERNAME_FIELD = 'EmailId' REQUIRED_FIELDS = ['AccountName'] class Account(models.Model): AccountName = models.TextField(max_length=100, blank=False, null=False) Serializer class AccountCreationSerializer(ModelSerializer): class Meta: model = Account fields = ["AccountName"] class SignUpSerializer1(ModelSerializer): AccountData = AccountCreationSerializer(read_only=True, many=True) class Meta: model = User fields = ['EmailId', 'AccountData', 'password'] extra_kwargs = {'password': {'write_only': True, 'required': True}} def validate(self, attrs): attrs = super(SignUpSerializer1, self).validate(attrs=attrs) attrs.update({"AccountData": self.initial_data.get("AccountData")}) return attrs def create(self, validated_data): AccountName_data = validated_data.pop('AccountData') acc = Account.objects.create(AccountName=AccountName_data) userAcc = User.objects.create_user(**validated_data) if acc: userAcc.AccountName.add(acc) print("added") return userAcc View class SignUpView(APIView): serializer_class1 = SignUpSerializer1 def post(self, request, *args, **kwargs): if request.data['CreateAccount']: serializer = self.serializer_class1(data=request.data) is_valid_serializer = serializer.is_valid(raise_exception=True) if is_valid_serializer: with transaction.atomic(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: raise Exception("Bad error") Request1 "EmailId" : "xyz@gmail.com", "AccountData":{"AccountName":"TestAcc1"}, "CreateAccount": true, "password" … -
Django Rest Multiple Image Upload to React-Native
It is been three days and I couldn't manage to upload images. Looked over every possible post on the internet and couldn't find a solution. I would be appreciated if someone helps me. I am really stuck. I got errors for the many to many relationship fields below and Couldn't able to upload any images. KeyError: 'dopings' and 'photos' Here is my models def upload_location(instance, filename): return '/images/%s-%s' % (str(datetime.now()),instance.file) class Picture(models.Model): file = models.ImageField(upload_to=upload_location) slug = models.SlugField(max_length=50, blank=True) def __str__(self): return self.file.name def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) def delete(self, *args, **kwargs): self.file.delete(True) super(Picture, self).delete(*args, **kwargs) class Dopings(models.Model): name = models.CharField(verbose_name="Doping Name",max_length=225) def __str__(self): return self.name class ListingDopings(models.Model): doping = models.ForeignKey(Dopings,on_delete=models.SET_NULL, verbose_name="Doping", null=True, blank=True) expire_date = models.DateField() class Listings(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='listing_user', null=True, blank=True) categoryName = models.ForeignKey(GameCategories,on_delete=models.SET_NULL, verbose_name="Category Name", null=True, blank=True) currency = models.ForeignKey(Currency,on_delete=models.SET_NULL, verbose_name="Currency", null=True, blank=True) price = models.IntegerField(default=0) date = models.DateField(auto_now=True) title = models.CharField(verbose_name="Title",max_length=225, null=True,blank=True) description = models.TextField(null=True,blank=True) slug = models.SlugField(max_length=555, blank=True) photos = models.ManyToManyField(Picture,blank=True) isActive = models.BooleanField(default=False) dopings = models.ManyToManyField(ListingDopings, blank=True) def __str__(self): return self.title My Serializers class ListingSerializer(serializers.ModelSerializer): photos = PictureSerializer(many=True, required=False, allow_null=True) dopings = DopingSerializer(many=True, required=False, allow_null=True) class Meta: model = Listings fields = ( 'id', 'categoryName', 'currency', … -
Export postgres table to yaml file
I am working in django and trying to figure out how to export a table i have in my database to a yaml file, but cant find the solution to it..probably some simple change.. Right now i have a written a bash to export my customer table to a CSV file that works fine: export_customer.sh echo "Enter the directory path to save the file" read path_to_save file_name="myFile.csv" psql --dbname=mydb --host=localhost --username=mydb -c "COPY ( select name, id from customers ) to stdout DELIMITER ',' CSV HEADER" > "${path_to_save}/${file_name}" My customer table look something like this: id name ------------------- 1 xxxxx 2 yyyyy Does anyone now how to export this into a yaml file instead? -
Django 3.x accesing media files using JavaScript
i am writing a simple gallery where image onclick expands it. I am trying to implement it using JavaScript. Every image is been uploaded from django admin panel to specified media folder. Anyway, there is trouble accesing the image's src as JS have no understanding where are these images stored because django serve it on localhost:8080/media/ url. What should i do? Or are there any options after using manage.py collectstatic command? -
How to get queryset affected by filters in django admin
I am trying to get query set after applying all filters which selected by user (query set displayed in admin display list) at django 1.9 i am using super(MyAdminClassNAme, self).get_queryset(request) but it always return myModel.objects.all() when i need it with all filters applied automatically not manually -
Is it safe to use builtin django login system on production
I am developing a website which is expected to get more than 1000 visitors everyday and I am using built-in authentication system of django. I want to know - is it safe and secure enough? Also, what precautions should I take or what can I do to improve its security. Or should I use third party or other apps available out there? -
Django Limit subquery
I wrote the following code: away_fixtures = Fixture.objects.filter(Q(away=home) | Q(home=away)).order_by('-date')[:3] tips = tips.filter(prediction__fixture__in=away_fixtures) When executing the following error occurs (I use MariaDB 10.4, which does not support LIMIT in subqueries): django.db.utils.NotSupportedError: (1235, "This version of MariaDB doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'") When executing the following code: away_fixtures = Fixture.objects.filter(Q(away=home) | Q(home=away)).order_by('-date') tips = tips.filter(prediction__fixture__in=away_fixtures) But this returns the 'tips' for all the 'away_fixtures' and I only want the for the last 3 fixtures (so limiting it to 3 fixtures). How can I achieve this without switching database engines? -
How to write pure unittest in Django?
so my question is, how to write pure unit tests with Django? For exmaple I have this model: class Topic(models.Model): title = models.CharField(max_length=255, validators=[MinLengthValidator(5)]) created_at = models.DateTimeField(auto_now_add=True) This serializer: class TopicSerializer(serializers.ModelSerializer): class Meta: model = Topic fields = ('id', 'title', 'created_at') and I wrote these tests: class TopicModelTest(TestCase): def test_create_topic(self): topic = Topic(title='Topic title') self.assertEqual(topic.title, 'Topic title') def test_too_short_title(self): topic = Topic(title='W'*4) with self.assertRaises(ValidationError): topic.save() topic.full_clean() class TopicSerializerTest(TestCase): def setUp(self) -> None: mocked = datetime.datetime(2020, 1, 1, 0, 0, 0, tzinfo=pytz.utc) self.topic_attr = {'title': 'What is the weather like?'} self.topic_serialized = {'id': 1, 'title': 'What is the weather like?', 'created_at': '2020-01-01T00:00:00Z'} with mock.patch('django.utils.timezone.now', mock.Mock(return_value=mocked)): self.topic = Topic.objects.create(**self.topic_attr) self.serializer = TopicSerializer(instance=self.topic) def test_contains_expected_fields(self): data = self.serializer.data self.assertCountEqual(data.keys(), ['id', 'title', 'created_at']) def test_serialized_data(self): self.assertEqual(self.serializer.data, self.topic_serialized) Everything works, but this is not unit tests. This is integration tests, because database is used. So my question is, how can I write unit tests? I ask about this, because many companies want to write simple project with unit test (TDD) for junior, but I don't know how can I write isolated unit tests without DB -
Why does my django website look different when I deploy it on heroku as compared to localhost?
This is my website when I use it on localhost: This is the same website when I deploy it on heroku. I didn't change the css files at all. Still why are the positions and sizes getting changed? -
cant display images in emails in django after sending emails
in my project, I've added a newsletter feed. But when when the email is sent its doesnt not display the images from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string def send_multiple_email(name, receiver): subject = 'Welcome' sender = 'host' #passing in the context vairables text_template = render_to_string('newsletter/email-subscribe.txt',{"name": name}) html_template = render_to_string('newsletter/new.html',{"name": name}) message = EmailMultiAlternatives(subject,text_template,sender, [receiver]) message.attach_alternative(html_template, "text/html") message.send() -
Assert correct scrolling position with selenium in python
I am running a django app and in that scope I have a page with a navigation bar and when I click on my contact-tab this automatically scrolls down to my contact-section. I am trying to test this behaviour with selenium but I can't seem to figure out how I can test the actual position of the page. Or, in other words, I want to verify that the page actually scrolled down to the contact-section. Right now I am doing this: def test_verify_position( self, browser, live_server ): """""" browser.get(live_server.url) contact_section = browser.find_element_by_id("contact").click() assert ???? I think I somehow have to get the current scroll location-coordinates. I know I can get the location of an element using .location. But the relative position of an element is always the same no matter the scroll-position. I tried this to debug: def test_verify_position( self, browser, live_server ): """""" browser.get(live_server.url) e = browser.find_element_by_xpath( "/html/body/section[4]/div/div[1]/h2/strong") location = e.location print(location) browser.find_element_by_css_selector(".nav-contact").click() e = browser.find_element_by_xpath("/html/body/section[4]/div/div[1]/h2/strong") location = e.location print(location) This prints the same coordinates for before and after the scroll. I also searched the official doc https://www.selenium.dev/documentation/en/webdriver/web_element/ but couldn't find a better solution or any solution for that matter. Anyone knows how to do this? Help is very … -
Malfunction of django nginx server [closed]
I don't know why 3 game objects are created for every four minutes instead of one. It didn't happen on localserver. After hosting the website it creates 3 objects for every 4 minutes. This creates a very big problem. I can't figure out what is the problem. Here is the source code. Here is the website link. Please help me to solve this problem. -
How can I make a practical DD-MM form input?
I'm creating an application in Django and in the registration I'd like users to enter the day and month they were born, so that their birthday can be hailed on the site. I can't really think of a practical way to do this, I'm having trouble converting the jQuery datepicker to MM-DD format and the other method I have made (that works decently) is impractical and throws an error: Here's what I have done, which I want to change: <script> const daysInMonth = (month, year) => { return new Date(year, month, 0).getDate(); } $('#birthday_year').change(function(){ verifyDate(daysInMonth) $('#birthday_month').change(function(){ daysInMonth = daysInMonth($('#birthday_month').val(), $('#birthday_year').val()) verifyDate(daysInMonth); $('#birthday_day').change(function(){ verifyDate(daysInMonth); }) }) }) const verifyDate = () => { if($('#birthday_day').val() > daysInMonth){ $('#birthday_day').val('Select an option'); } } </script> I won't show the form code, but it takes 3 inputs - Year of birth; month of birth and day of birth. The actual issue is that I cannot efficiently moderate the day people enter, basically I can't check whether a day is in the month they enter. E.g. someone could enter febuary 31st as their birthday. I'm open to suggestions on a better way to do this, thanks in advance.