Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid block tag on line 49: 'ifequal', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
<tbody style="border-color:white"> {% for i in data %} <tr> <td>{{forloop.counter}}</td> <td>{{i.que.question}}</td> <td>{{i.que.answer}}</td> <td>{{i.your_ans}}</td> {% ifequal i.que.answer i.your_ans %} <td><i class="fa fa-check-circle fa-3x" aria-hidden="true"></i></td> {% else %} <td><i class="fa fa-times-circle fa-3x" style="color:red" aria-hidden="true"> <!---icon---> </i></td> {% endifequal %} </tr> {% endfor %} </tbody> // This code is about online quiz website. I got the error when I click the submit exam button. this is line no.49 {% ifequal i.que.answer i.your_ans %} -
Cannot query "ahmed": Must be "User" instance
when i pass a user comes this err Cannot query "ahmed": Must be "User" instance. my code is def user_add_post(sender, instance, *args, **kwargs): post = instance profile = Profile.objects.all() users = Profile.objects.filter(following=post.author.user) for u in users: user = Profile.objects.filter(following=u) sender = post.author.user text_preview = post.title[:50] notify = Notifications(post=post, sender= sender, user = user, text_preview=text_preview, notifications_type=1 ) notify.save() and the problem in user = Profile.objects.filter(following=u) and if i change it to user = Profile.objects.filter(following=u.user) Cannot assign "<QuerySet []>": "Notifications.user" must be a "User" instance. this is the models of the notifications app class Notifications(models.Model): NOTIFICATIONS_TYPES = ((1,'Post'), (2, 'Comment'), (3, 'Follow')) post = models.ForeignKey('post.Post', on_delete=models.CASCADE, related_name='noti_post', blank=True, null=True) sender= models.ForeignKey(User, on_delete=models.CASCADE, related_name='noti_from_user') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='noti_to_user') notifications_type = models.IntegerField(choices=NOTIFICATIONS_TYPES) text_preview = models.CharField(max_length=50, blank=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) and this is my profile models class Profile(models.Model): user = models.OneToOneField(User, verbose_name='user', on_delete=models.CASCADE) following = models.ManyToManyField(User, related_name='following', blank=True) avatar = models.ImageField(default='default.jpg', upload_to='profile_images') bio = models.TextField(default='this is your bio you can edit it if you want.', blank=True) -
How to move my main content when hover sidebar is active?
:root { font-size: 16px; --text-primary: #b6b6b6; --text-secondary: #ececec; --bg-primary: #23232e; --bg-secondary: #141418; --transition-speed: 600ms; } body { overflow-x: hidden; color: black; background-color: rgb(81, 146, 225); margin: 0; padding: 0; } body::-webkit-scrollbar { width: 0.5rem; } body::-webkit-scrollbar-track { background: #00ff8c; } body::-webkit-scrollbar-thumb { background: #ff0000; } .main { top: 0; margin-left: 5rem; margin-top: 5rem; padding: 1rem; } .topbar { display: block; position: fixed; z-index: 3; background-color: var(--bg-primary); } .navbar { display: block; position: fixed; z-index: 3; background-color: var(--bg-primary); transition: 200ms ease; } /*small screen*/ @media only screen and (max-width:600px) { .navbar { bottom: 0; width: 100vw; height: 5rem; } .topbar { top: 0; width: 100%; height: 5rem; } .main { margin-top: 5rem; margin-left: 0; margin-right: 0; margin-bottom: 5rem; } } /*mid size screens*/ @media only screen and (min-width:600px) { .navbar { top: 0; width: 5rem; height: 100vh; } .topbar { top: 0; width: 100%; height: 5rem; } .navbar:hover { width: 16rem; } } /*large screens todo*/ <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="style.css" /> </head> <body> <nav class="topbar" style="padding-left: 0px;padding-top: 0px;padding-right: 0px;padding-bottom: 0px;"> <!--i would have my menu in here....--> </nav> <nav class="navbar" style="padding-left: 0px;padding-top: 0px;padding-right: 0px;padding-bottom: 0px;"> <!--i would have my menu in here....--> </nav> <div id="content" name="main_content" … -
django channels test code AsyncConsumer.__call__() missing 1 required positional argument: 'send'
Channels Test I was writing the test code while looking at the documentation. But this error occurs. Traceback (most recent call last): File "C:\Users\Home\Desktop\exchange-rate\venv\lib\site-packages\asgiref\testing.py", line 74, in receive_output return await self.output_queue.get() File "C:\Users\Home\AppData\Local\Programs\Python\Python310\lib\asyncio\queues.py", line 159, in get await getter asyncio.exceptions.CancelledError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Home\Desktop\exchange-rate\venv\lib\site-packages\asgiref\testing.py", line 73, in receive_output async with async_timeout(timeout): File "C:\Users\Home\Desktop\exchange-rate\venv\lib\site-packages\asgiref\timeout.py", line 65, in aexit self._do_exit(exc_type) File "C:\Users\Home\Desktop\exchange-rate\venv\lib\site-packages\asgiref\timeout.py", line 102, in _do_exit raise asyncio.TimeoutError asyncio.exceptions.TimeoutError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Home\Desktop\exchange-rate\venv\lib\site-packages\asgiref\sync.py", line 213, in __call__ return call_result.result() File "C:\Users\Home\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\_base.py", line 439, in result return self.__get_result() File "C:\Users\Home\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\_base.py", line 391, in __get_result raise self._exception File "C:\Users\Home\Desktop\exchange-rate\venv\lib\site-packages\asgiref\sync.py", line 279, in main_wrap result = await self.awaitable(*args, **kwargs) File "C:\Users\Home\Desktop\exchange-rate\backend\exchange_rate\channel\tests.py", line 15, in test_connect response = await communicator.get_response() File "C:\Users\Home\Desktop\exchange-rate\venv\lib\site-packages\channels\testing\http.py", line 42, in get_response response_start = await self.receive_output(timeout) File "C:\Users\Home\Desktop\exchange-rate\venv\lib\site-packages\asgiref\testing.py", line 78, in receive_output self.future.result() File "C:\Users\Home\Desktop\exchange-rate\venv\lib\site-packages\asgiref\compatibility.py", line 34, in new_application return await instance(receive, send) TypeError: AsyncConsumer.__call__() missing 1 required positional argument: 'send' It is used well in runserver and deployment environment. Only the test code throws the error. I was writing the test code while looking at the documentation. … -
How to merge two querysets in Django
setting = Subject.objects.filter.annotate( A_setting=Count('id', filter=Q(type='A', id__in=workers.filter(worker=1).values('id')), distinct=True) * Value(50), B_setting=Count('id', filter=Q(type='B', id__in=workers.filter(worker=1).values('id')), distinct=True) * Value(30), C_setting=Count('id', filter=(~Q(type='A') & ~Q(type='B') & Q(id__in=workers.filter(worker=1).values('id')))) * Value(10)) \ .values('setting__user_id', 'A_setting', 'B_setting', 'C_setting') Result: <QuerySet [{'setting__user_id': 4, 'A_setting': 50.0, 'B_setting': 120, 'C_setting': 10.0}, {'setting__user_id': 34, 'A_setting': 0.0, 'B_setting': 0, 'C_setting': 0.0}, {'setting__user_id': 33, 'A_setting': 0.0, 'B_setting': 150, 'C_setting': 0.0}, {'setting__user_id': 30, 'A_setting': 0.0, 'B_setting': 150, 'C_setting': 0.0}, {'setting__user_id': 74, 'A_setting': 50.0, 'B_setting': 120, 'C_setting': 10.0}]> uploader=Feedback.objects.values('uploader_id').distinct().values('uploader_id') Result: <QuerySet [{'uploader_id': 25}, {'uploader_id': 20}, {'uploader_id': 74}, {'uploader_id': 34}, {'uploader_id': 93}, {'uploader_id': 88}, {'uploader_id': 73}, {'uploader_id': 89}, {'uploader_id': 30}, {'uploader_id': 33}, {'uploader_id': 85}, {'uploader_id': 4}, {'uploader_id': 46}]> "setting" outputs only users who satisfy the conditions. But I need a list of all users. The "uploader" is a queryset containing all users. First, the entire list of users is printed, and if the user's id is included in the "setting", the setting value is output. The final result I want to achieve is as follows. <QuerySet [['25', '0', '0', '0'], ['20', '0', '0', '0'], ['74', '50', '120', '10'], ['34', '0', '0', '0'], ['93', '0', '0', '0'], ['88', '0', '0', '0'], ['73', '0', '0', '0'], ['89', '0', '0', '0'], ['30', '0', '150', '0'], ['33', '0', '150', '0'], ['35', '0', '0', … -
I am getting an error "ModelForm has no model class specified."
[This is my forms.py. I googled the error and found solutions like change META into Meta, models into model, which were not userful for me.[ Blockquote ]1 -
("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'asgi'
My settings.py file: """ Django settings for myproject project. Generated by 'django-admin startproject' using Django 2.2.13. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'af^zgg5*t&h)3dghcvd#9o1@st9b(bgh@5a32%m%!g38u(tl!f' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat', 'channels', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # WSGI_APPLICATION = 'myproject.wsgi.application' ASGI_APPLICATION = 'asgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE … -
How does django db index work with minus?
What does this index with minus (-text) mean in Django? migrations.AddIndex( model_name='comment', index=models.Index(fields=['-text'], name='xxx'), ) -
How to create time dynamic models in django?
I'm trying to build a school management system in django. It has every year which has 3 terms or semesters which each runs for a period of 4months i.e 2022/2023 - 1st semester, 2nd semester and 3rd semester. Each semester is dynamic and moves to the next semester after 4months but if it's 3rd semester, it automatically adjust the year by adding a year and starts from 1st semester ie 2023/2024 then after completing 3 semesters moves to 2024/2025 while recounting from 1st semester(3 × 4months = a year) Also each student is connected to each semester because they have courses registered and their results for each semester. The system automatically upgrades the students of every class/level after 3rd semester so they start a new level from 1st semester each year. I.e 100level moves to 200level while 200level students move to 300level after each year My issue is how to develop the logic to write my models efficiently and connect each other i.e Year - semesters - course registered for each semester - results - user/student. Also how do I create a timer function of 4months for each semester and a year for the year? How do I make this … -
Why does my django allauth verification email send from 'example.com' after the domain and display name have been changed?
I'm using Django allauth to send verification emails when users register for an account. However, the emails continue to send from 'example.com' and to include the default message (also from example.com). So far I have: changed the domain and display names in the 'Sites' section of Django admin added the site ID number in settings set the 'DEFAULT_FROM' email in settings added my own email_confirmation_subject.txt and email_confirmation_message.txt under templates/account/email When performing the registration procedure locally, the validation emails send to the terminal from the desired email address; however, the message in the body of the email remains the generic allauth message. When registering over the deployed site, at Heroku, however, the validation emails continue to show as being sent from 'example.com', both in the subject and the body of the email. -
Django suspicious file operation
I have made a django package with templates and a static file that I installed in a different django project. When I run the function that calls the installed package it gives me this error: SuspiciousFileOperation at /test/render The joined path (/static/images/logo.png) is located outside of the base path component (/mnt/c/Users/user/Work/project/env/lib/python3.8/site-packages/django/contrib/admin/static) Request Method: GET Request URL: http://localhost:8000/test/render Django Version: 4.0.4 Exception Type: SuspiciousFileOperation Exception Value: The joined path (/static/images/logo.png) is located outside of the base path component (/mnt/c/Users/user/Work/project/env/lib/python3.8/site-packages/django/contrib/admin/static) I tried several different approaches to this issue, but none have worked out for me. I tried collectstatic but nada. I have added my package to the installed_apps so that the staticfiles.finders can serve the static but still nothing. Here are my static settings: STATIC_URL = 'static/' STATIC_ROOT = 'static/' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder' ] Has someone else encountered this issue or have any advice for this problem? Thanks in advance. -
How can i upload Default Image for all new user when the registration form is submitted
is there anyway I can Upload Image for all new user in their profile. I created a user registration page so when a user submitted the form the new profile will be created automatically using Django Signals the problem I'm facing now is: when a new user is created and redirected the user to home page, when a user click on the Profile page the profile page throws an error like this: ValueError at /profile/15/ The 'profile_image' attribute has no file associated with it. and it highlighted this html code in the page: <img class="card-img-top" src="{{profile.profile_image.url}}" alt="Card image cap"> is there anyway I can upload image for all new user in their profile just to avoid the error message in the template. Just like How I make automatic profile for all new user. my model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(upload_to='avatar', blank=True, null=True) stories = RichTextField(blank=True, null=True) twitter = models.URLField(max_length=300, blank=True, null=True) website = models.URLField(max_length=300,blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) location = models.CharField(max_length=80, blank=True, null=True) slug = models.SlugField(unique=True, max_length=200) def save(self, *args, **kwargs): self.slug = slugify(self.user) super(Profile, self).save(*args, **kwargs) def __str__(self): return str(self.user) signals.py file: from django.conf import settings from django.db.models.signals import post_save from django.dispatch import … -
Django Image not showing admin for extended User
I am trying to extend the build in User to allow a user to add an image to their profile, however have no option to save an image in the admin for my page. The other extended fields are showing. I am not sure why this is.. model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.TextField(default='', blank='') last_name = models.TextField(default='', blank='') def save(self, *args, **kwargs): super().save(*args, **kwargs) def user_image_upload_handler(instance, filename): fpath = pathlib.Path(filename) new_fname = str(uuid.uuid1()) # uuid1 -> uuid + timestamps return f"request/{new_fname}{fpath.suffix}" class ProfilePicture(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_image_upload_handler, blank=True) admin.py from django.contrib import admin from django.contrib.auth.models import User from .models import Profile, ProfilePicture class ProfileAdmin(admin.ModelAdmin): model = [Profile] list_display = ['id'] class ProfilePictureAdmin(admin.ModelAdmin): model = [ProfilePicture] extra = 10 class UserAdmin(admin.ModelAdmin): model = ProfileAdmin model = ProfilePictureAdmin admin.site.unregister(User) admin.site.register(User, UserAdmin) -
Gunicorn Multiple Workers behind nginx
I am running my Django app with Gunicorn on Docker and there are 5 workers on gunicorn gunicorn -w=5. On my dev environment I can see the 5 workers replying at the same time since gunicorn is directly serving the app, although when I go to my productive environment (the django app is behind a nginx server) I see only one thread of responses. How can I enable the equivalent of the gunicorn workers on nginx so that I can have the 5 workers "working" there? -
Django aws ebs deployment
I am trying to deploy my django project on aws ebs but its health is showing as severe and the url shows 502 bad gateway error. I am using git action for the deployment. on: push: branches: [ branchname ] jobs: build: runs-on: ubuntu-latest steps: - name: Git clone on our repository uses: actions/checkout@v2 - name: Create zip deployment package run: zip -r ${{ env.DEPLOY_PACKAGE_NAME }} ./ -x *.git* - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID_KK }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY_KK }} aws-region: ${{ env.AWS_REGION_NAME }} - name: Copy our deployment package to S3 bucket run: aws s3 cp ${{ env.DEPLOY_PACKAGE_NAME }} s3://${{ env.EB_PACKAGE_S3_BUCKET_NAME }}/ - name: Print nice message on success finish run: echo "CI Pipeline part finished successfuly" deploy: runs-on: ubuntu-latest needs: [build] steps: - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID_KK }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY_KK }} aws-region: ${{ env.AWS_REGION_NAME }} - name: Create new EBL Application version run: | aws elasticbeanstalk create-application-version \ --application-name ${{ env.EB_APPLICATION_NAME }} \ --source-bundle S3Bucket="${{ env.EB_PACKAGE_S3_BUCKET_NAME }}",S3Key="${{ env.DEPLOY_PACKAGE_NAME }}" \ --version-label "${{ github.sha }}" - name: Deploy new app run: aws elasticbeanstalk update-environment --environment-name ${{ env.EB_ENVIRONMENT_NAME }} --version-label "${{ github.sha }}" - name: Print nice message … -
Having A problem while running python manage.py runserver for my Django Project
I'm setting up a django project and was trying to do some basic configurations involving staticfiles While trying to run python manage.py runserver , I ran into a Type Error File "/home/muyiwa/anaconda3/lib/python3.9/posixpath.py", linenter code heree 375, in abspath path = os.fspath(path) TypeError: expected str, bytes or os.PathLike object, not function -
Cannot Append new list data to a dict in a for loop
I have a list of IPs being returned from a POST in listip. I want to iterate over the list of IPs and store data in a dictionary so i can render it on a webpage. But the dictionary is overriding the values for the last IP only. How can i solve this ? Currently there are 3 IPs in the listip but dict is only storing the last passed IPs data. def healthcheckresults(request): if not listip: return render(request, "home/homepage.html",) for ip in range(len(listip)): conn = manager.connect( host= listip[ip], port='22', username='XXX', password = 'XXX', timeout=10 ) result = conn.get_ospf_neighbor_information() hostnameresult = conn.get_software_information() hostname = hostnameresult.xpath('//software-information/host-name/text()') ospfneighboraddress = result.xpath('//ospf-neighbor/neighbor-address/text()') ospfneighborinterface = result.xpath('//ospf-neighbor/interface-name/text()') ospfneighborstate= result.xpath('//ospf-neighbor/ospf-neighbor-state/text()') ospfneighborID = result.xpath('//ospf-neighbor/neighbor-id/text()') ##METHOD1 ospfdictkey = {"hostname":[],"ospfneighboraddress":[],"ospfneighborinterface":[],"ospfneighborstate":[],"ospfneighborID":[]} ospfmetalist = [hostname,ospfneighboraddress,ospfneighborinterface,ospfneighborstate,ospfneighborID] for key, value in zip(ospfdictkey, ospfmetalist): ospfdictkey[key].append(value) ##METHOD2 ospfdict={"hostname":hostname,"ospfneighboraddress":ospfneighboraddress,"ospfneighborinterface":ospfneighborinterface, "ospfneighborstate":ospfneighborstate,"ospfneighborID":ospfneighborID } context = {'LUnique': zip(ospfneighboraddress, ospfneighborinterface, ospfneighborstate,ospfneighborID)} conn.close_session() listip.clear() return render(request, "healthcheck/healthcheckresults.html",{ "ospfneighboraddress":ospfneighboraddress, "ospfneighborinterface":ospfneighborinterface, "ospfneighborstate":ospfneighborstate, "ospfneighborID":ospfneighborID, "context":context, "hostname":hostname, "listip":listip, "ospfdict":ospfdict, "ospfdictkey":ospfdictkey, }) Both mentioned methods are returning the same data when i check the data in the dictionary. {'hostname': ['R3-ISP'], 'ospfneighboraddress': ['192.168.5.34', '192.168.5.5', '192.168.5.10'], 'ospfneighborinterface': ['ae10.0', 'ae2.0', 'ae3.0'], 'ospfneighborstate': ['Full', 'Full', 'Full'], 'ospfneighborID': ['172.0.0.6', '172.0.0.2', '172.0.0.4']} {'hostname': [['R3-ISP']], 'ospfneighboraddress': [['192.168.5.34', '192.168.5.5', '192.168.5.10']], 'ospfneighborinterface': [['ae10.0', 'ae2.0', 'ae3.0']], 'ospfneighborstate': … -
'function' object has no attribute 'listings'
I am trying to create an e-commerce site (CS50 Project 2) that allows the user to add and remove listing items to their watchlist. When trying to add a listing, which is a model, to the watchlist model I am receiving this error: 'function' object has no attribute 'listings' which corresponds to this line of code in my views.py: new_watchlist_listing = watchlist.listings.add(listings). The user is able to add the listing item to their watchlist through a Django form with a Boolean Field, and I need help making that field true after the user has added the listing to their watchlist (I want the checkbox that the user sees to be marked so that they can potentially remove the listing from their watchlist). views.py def listing(request, id): #gets listing listing = Listings.objects.get(id=id) watchlist_form = WatchListForm() #checks if request method is post for all the forms if request.method == "POST": watchlist_form = WatchListForm(request.POST) #checks if watchlist form is valid if watchlist_form.is_valid(): new_watchlist_listing = watchlist.listings.add(listings) WatchList.add_to_watchlist = True return render(request, "auctions/listing.html",{ "auction_listing": listing, "watchlistForm": watchlist_form }) else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "watchlistForm": watchlist_form }) return render(request, "auctions/listing.html",{ "auction_listing": listing, "watchlistForm": watchlist_form }) models.py class Listings(models.Model): CATEGORY = [ ("Miscellaneous", "Miscellaneous"), ("Movies and … -
Django. How make a handler that opens this link on the server side
I do not know how to properly put the question to find useful articles on google. So here is my problem. I have a hard coded button in my template <a type="button" href="https://api.telegram.org/bot******:*****-*****/sendMessage?chat_id=-******&text=test" class="btn btn-dark w-100 p-3" style="margin-bottom: 16px;">Button 1</a> When you click the link opens and the message after "text= " is sent to messenger. There are two problems with this. The Api token is visible in the inspector. After opening it, the user leaves the site I want to make a handler that opens this link on the server side and redirects the user to the "Successfully Sent" page. What is the easiest way to make it? -
post request in django-react project through mobile
whenever I send data from react to django on same machine it is successful, but when I open that website in mobile , I can not , why? -
How can I best run a daily script that updates my Django App with content from external URLs in Digital Ocean App Platform?
I have a Django Web App set up on the Digital Ocean App Platform. I want to update my Django App daily with content from external URLs. Unfortunately, cron jobs are not available in the App Platform. Specifically, I want to fetch images from external URLs, attempt to download the images, and update it in my Django App if the download was successful. -
Why is it that non-programmers (like my family) can't understand me? [closed]
I understand that such questions are not asked here, but there is professional programmers who have a lot of experience, I hope for a positive response from the community, I am 14 years old, I am not from a very developed country that is far from such concepts as programming, I really like programming, so I started doing it for 3 years and during this time I have gained experience in web full stack programming, but my family does not understand my success, and says that I play for a computer, or fox social networks. How can I explain to them that I'm not wasting my time? -
How to set "verbose_name_plural" variable in metaclass of ModelAdminForm, instead of setting it directly in model's metaclass?
My every single model has metaclass that defines string representation for admin panel, I perform that by setting verbose_name_plural variable: class MyModel(models.Model): ... class Meta: ... verbose_name_plural = "My Representation" I'm sure that this is a very bad approach to set variables directly in model metaclass that are used only inside admin panel. So, I've tried to replace verbose_name_plural into the admin forms metaclasses: class MyModelAdminForm(forms.ModelForm): class Meta: verbose_name_plural = "My Representation" model = MyModel fields = "__all__" class MyModelAdmin(admin.ModelAdmin): form = MyModelAdminForm admin.site.register(MyModel, MyModelAdmin) And this gives no result. How can I perform that, thanks ? -
New django project migrations not reflected in database
I'm attempting to set up a new django project. I am using Adminer for my database GUI and docker for my containers. I have added a model, Notification.py and have created migrations for setting it up on the database. I am able to make this migration within the Docker container without error. On Adminer though, I do not see the Notification table I am creating. I'm including my docker setup here as well, just in case that is the culprit. I also attempted to run the SQL directly in Adminer: root@65787223f662:/mos-nss# python manage.py sqlmigrate main 0001 BEGIN; -- -- Create model Notification -- CREATE TABLE "main_notification" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "sender_id" integer NOT NULL, "receiver_id" integer NOT NULL, "notification_group_id" integer NOT NULL, "notification_type" varchar(255) NOT NULL, "date_created" datetime NOT NULL, "is_deleted" bool NOT NULL); COMMIT; ... which results in an error when I copy and paste the auto-generated query and run it: Error in query (7): ERROR: syntax error at or near "AUTOINCREMENT" LINE 1: ..._notification" ("id" integer NOT NULL PRIMARY KEY AUTOINCREM... Trace from my terminal while making migrations: root@65787223f662:/mos-nss# ./manage.py makemigrations main Migrations for 'main': main/migrations/0001_initial.py - Create model Notification root@65787223f662:/mos-nss# python manage.py migrate main … -
Repeat functions 500 per day
Hi i want to make program.how can i repeat a function 500 times per day? please answer me with an example.I have used time module and loop command.This is my example: import schedule import time def job(t): print "I'm working...", t return schedule.every().day.at("01:00").do(job,'It is 01:00') while True: schedule.run_pending() time.sleep(60)