Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get data of last 6 months by using date field - django
I have a model as below, class Visits(models.Model): visit_date = models.DateField(blank=False, null=False) fees = models.DecimalField(null=False, blank=False, max_digits=10, decimal_places=2) I want to get data for last six months (including current month) total fees month wise Example: { July : 750, June : 800, May : 500, April : 200, March: 450, Febraury: 310 } How to get done this by having date field.? -
Python, JSignature, and ReportLab
I'm looking to write a signature to PDF. I'm using JSignature and Reportlab. My code works successfully for writing the data to a file and the database. I just cannot figure out how to write the signature to the canvas. Has anyone passed the signature into the canvas successfully? Thank you in advance. Here's a look at my code: pdf.py import io from django.core.files.base import ContentFile from reportlab.lib.units import inch from reportlab.pdfgen import canvas from reportlab.lib.utils import ImageReader def create_pdf(parent): # create a file-like buffer to receive PDF data buffer = io.BytesIO() # create the pdf object, using the buffer as its "file" p = canvas.Canvas(buffer) # create text textobject = p.beginText() # start text at top left of page textobject.setTextOrigin(inch, 11*inch) # set font and size textobject.setFont("Helvetica-Bold", 18) textobject.textLine("My Document") textobject.textLine("") # write page 1 textobject.setFont("Helvetica", 12) p_name = f'Name: {participant.first_name} {participant.middle_initial} {participant.last_name}' textobject.textLine(p_name) sig = f'Signature:' textobject.textLine(sig) ----insert signature here---- # write created text to canvas p.drawText(textobject) # close the pdf canvas p.showPage() p.save() buffer.seek(0) # get content of buffer pdf_data = buffer.getvalue() # save to django File object file_data = ContentFile(pdf_data) # name the file file_data.name = f'{participant.last_name}.pdf' # participant.pdf = file_data participant.save() Model: class Participant(models.Model): first_name … -
Django - object has no attribute 'object' when injecting POST form data
Goal I'm trying to inject the "Send BCC" Job Site email addresses/objects into the form as the initial default value. The difficulty seems to be how it's interpreting super().get_context_data(**kwargs) and the view somehow is missing the object() it's looking for. I can't seem to figure out what's wrong, despite checking for duplicate names, defining self.object inside of post and get. GitHub: https://github.com/varlenthegray/wcadmin/blob/dev/communication/views.py#L21 Referenced the following StackOverflows in attempts to find the solution: 'CheckoutView' object has no attribute 'object' Django: object has no attribute 'object' Django Test: type object has no attribute 'objects' Django: AttributeError: "Object has no attribute" Error Environment: Request Method: POST Request URL: http://localhost:3003/email/compose_email Django Version: 4.0.6 Python Version: 3.8.10 Installed Applications: ['customer', 'equipment', 'service', 'supplier', 'users', 'qb', 'communication', 'main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'dateutil', 'widget_tweaks', 'intuitlib', 'quickbooks', 'rest_framework', 'rest_framework_datatables', 'markdownify'] Installed 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'] Traceback (most recent call last): File "/home/wcadev/public_html/lib/python/Django-4.0.6-py3.8.egg/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/wcadev/public_html/lib/python/Django-4.0.6-py3.8.egg/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/wcadev/public_html/lib/python/Django-4.0.6-py3.8.egg/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "/home/wcadev/public_html/lib/python/Django-4.0.6-py3.8.egg/django/contrib/auth/mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) File "/home/wcadev/public_html/lib/python/Django-4.0.6-py3.8.egg/django/views/generic/base.py", line 119, in dispatch return handler(request, *args, **kwargs) … -
Django&Echart Uncaught SyntaxError: missing ) after argument list
I'm learning to use echart to draw in Django's template, I'm trying to pass my database data to the template via the view function and then store the data into an array for drawing via a for loop, but I'm finding that my time field can't be stored into the array via a for loop because it loses the quotes error mycode var seris_data = []; var xAxis_data = []; {% for data in activity_detail %} seris_data.push({{ data.heart_rate }}) xAxis_data.push({{ data.timestamp }}) {% endfor %} -
Docker not showing the port number for running container
Hi I am running a web app in Docker but I do not have the container port showing on docker ps -a ➜ pansible git:(master) ✗ docker container ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ead78f0f8a8c ask_webapp "sh /usr/src/app/sp_…" 20 seconds ago Restarting (0) 2 seconds ago ask_dashboard_web 4e9ef2611f7f sp_ask_dashboard_celery_worker "sh /usr/src/app/sp_…" 20 seconds ago Exited (0) 18 seconds ago pansible_celery_worker_1 ec72e473ef8d sp_ask_dashboard_celery_flower "sh /usr/src/app/sp_…" 20 seconds ago Exited (0) 18 seconds ago pansible_flower_1 31fc39e60a34 sp_ask_dashboard_celery_beat "sh /usr/src/app/sp_…" 20 seconds ago Exited (0) 18 seconds ago pansible_celery_beat_1 69c87984ebfc postgres:14.0-alpine "docker-entrypoint.s…" 21 seconds ago Up 19 seconds 5432/tcp pansible_db_1 f536a781e2ed redis:6-alpine "docker-entrypoint.s…" 21 seconds ago Up 19 seconds 6379/tcp pansible_redis_1 f92d2f110227 ask_webapp "sh /usr/src/app/sp_…" 5 minutes ago Exited (0) 5 minutes ago pansible_web_run_be8a8e63e09d I am looking for the ask_webbapp and I don't see the port. In docker-compose.yml I specified port 8000 version: '3.3' services: db: image: postgres:14.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_PASSWORD=postgres networks: - djangonetwork redis: image: redis:6-alpine web: container_name: ask_dashboard_web build: context: . dockerfile: ./sp_dashboard/DockerfileBuild image: ask_webapp restart: always command: > sh -c "python sp_dashboard/manage.py runserver 0.0.0.0:8000" volumes: - .:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev networks: - djangonetwork environment: - lh3_salt=jasdjfst - lh3_scheme=https - POSTGRES_PASSWORD=postgres … -
Urlpattern regular expression not working
So i'm trying to make url like so re_path(r'^product_list/(?P<category_slug>[\w-]+)/(?:(?P<filters>[\w~@=]+)?)$', views.ProductListView.as_view(), name='filtered_product_list'), and at this point it works with things like: /product_list/sdasdadsad231/bruh=1~3~10@nobruh=1~4 bruh=1~3~10@nobruh=1~4 - those are filters but later i want to implement search by word functionality so i want it recognize things like /product_list/sdasdadsad231/?filters=bruh-1~3~10&nobruh-1~4&search_for=athing /product_list/sdasdadsad231/?filters=bruh-1~3~10&nobruh-1~4 /product_list/sdasdadsad231/?search_for=athing /product_list/sdasdadsad231/ so in different situations it will get filters and/or search_for or nothing at all -
How to fix "django.core.exceptions.FieldError: Unknown field(s) (username) specified"
I have an app that uses a custom User model called MyUser, a custom User manager, and a custom UserCreationForm. I'm trying to add the rest of the fields from the MyUser model to the UserCreationForm, but I keep getting the error: django.core.exceptions.FieldError: Unknown field(s) (username) specified for MyUser. What is the proper way to set a custom UserCreationForm? Why am I getting this error? Here's my code. Models.py from django.db import models from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin import uuid class UserManager(BaseUserManager): def create_user(self, fname, lname, email, phone, password=None): if not email: raise ValueError('You must enter an email address') user = self.model( fname=fname, lname=lname, email=self.normalize_email(email), password=password, is_superuser=False ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): user=self.create_user(self, fname, lname, email, phone, password) user.staff=True user.save(using=self._db) return user def create_superuser(self, email, password): user=self.create_user(self, fname, lname, email, phone, password) user.staff=True user.admin=True user.is_superuser=True user.save(using=self._db) return user class MyUser(AbstractBaseUser, PermissionsMixin): fname=models.CharField(max_length=100) lname=models.CharField(max_length=100) email=models.EmailField(max_length=200, unique=True) phone=models.CharField(max_length=15) password=models.CharField(max_length=200) user_id=models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4) is_active=models.BooleanField(default=True) staff=models.BooleanField(default=False) admin=models.BooleanField(default=False) USERNAME_FIELD='email' required_fields=['fname', 'lname', 'email', 'password'] @property def is_staff(self): #is the user staff? return self.staff @property def is_admin(self): #is the user an admin? return self.admin objects = UserManager() Forms.py from django import forms from django.forms import ModelForm from django.contrib.auth.forms import … -
Django - How can I "upgrate" user type?
I have two models, Buyer and Merchant with the default user type after the account creation being Buyer. # Abstract User class User(AbstractUser): is_buyer = models.BooleanField(default=False) is_merchant = models.BooleanField(default=False) date_created = models.DateTimeField(default=timezone.now) # Buyer class Buyer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) pin = models.CharField(max_length=6, blank=True) items = models.ManyToManyField(Product, blank=True) # items = models.ManyToManyField(Product, blank=True) def __str__(self): return f'{self.user.username}' # Merchant class Merchant(models.Model): # items user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) pgp = models.CharField(max_length=150, blank=True) # image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username}' And I have a become-a-merchant.html template in which I would like to make the Buyer be able to become a Merchant after checking a checkbox and pressing a button. {% extends 'base.html' %} {% block content %} <input type="checkbox" name="checkbox" value="check"> <label for="checkbox">Become a merchant.</label> <br><br> <button type="submit">Upgrade</button> {% endblock %} I don't know what to type of view to use or how to do a form that upgrades my user type. -
CSS and JAVASCRIPT files don't work in my django project
I did not really try much because I am a beginner, but I searched and did not find a solution to my problem. I did everything as required, I created the static file and called it in the "template/base.html" but only the HTML files worked and static files including CSS and JAVASCRIPT did not work -
Django Rest Framework Serializer - How to return value of data in response?
I am using dj-rest-auth and docs say I can serialize extra fields with the RegisterSerializer My serializer: from dj_rest_auth.registration.serializers import RegisterSerializer class CustomRegistrationSerializer(RegisterSerializer): user_id = serializers.SerializerMethodField('get_user_id') def get_user_id(self, obj): o = obj['username'] user_id = User.objects.get(username=o).id print(user_id) return Response(user_id) My settings: REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'users.serializers.CustomRegistrationSerializer' } I am able to print the id in my console, but in the api response, it's only returning the token and not the id Appreciate any help! Don't know what I am doing wrong. -
ERROR: Could not install requirements.txt packages due to an OSError?
I am getting errors please tell me what is wrong with this, I am not able to find a solution anywhere! I am working on one project but when other members try with install -r rquirements.txt they get this error! please tell what should be the action to handle or remove this error? -
django-'str' object has no attribute 'ppoi'
i install django-versatileImageField package and it's working very well but when i want change model or add new model in admin it show this error 'str' object has no attribute 'ppoi'. 'str' object has no attribute 'ppoi' -
hwo to fetch upper data and then delete in one action in Django?
I just want to fetch the upper data only and then delete it in one action. I tried this code: `def Data(request): data = Plan.objects.get(id = 1) data.delete() context = {'data':data} return render(request,'data.html',context)` But didn't work. see Database column -
Django with sockets io for Texas hold'm poker game
is it possible to create a poker game with django back end and socket io (front end using vanilla javascript) if no what is the best alternative -
Using custom fonts in TinyMCE API for editor in django admin
I am trying to use TinyMCE API in Django admin for blog post editing. It is working flawlessly. However, now I want to add custom fonts to my editor. As per tinymce documentation for adding custom fonts i have followed all steps but still cannot figure out what is wrong. Step-1: Add fonts as per menu option admin/base.html: font_formats:"Andale Mono=andale mono,times; ........ ; Montserrat = Montserrat , sans-serif",` Step-2: Import fonts in tinymce admin/base.html: {% extends "admin/base.html" %} {% load static %} {% block footer %} tinymce.init({ .... content_css: "{% static "TinyMCE/style.css" %}", content_style:"@importurl('https://fonts.googleapis.com/css2family=Montserrat:ital,wght@0,400;0,600;1,400&display=swap');", .... {% endblock %} TinyMCE/style.css @import url('https://fonts.googleapis.com/css2family=Montserrat:ital,wght@0,400;0,600;1,400&display=swap'); snapshot: the custom font is added in the dropdown menu 'Monstserrat' Step3: Import the font on the page admin/base.html {% block extrahead %} <style> @import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,600;1,400&display=swap'); * {font-family : 'Montserrat', sans-serif;} </style> {% endblock %} snapshot: the custom font changes in dropdown from fallback font to 'Monstserrat' Step4: Import the font on any published pages I am using tailwind in my project and my default font is Monstserrat which is perfectly working over the site style.css @import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,600;1,400&display=swap'); body{ font-family: Montserrat, sans-serif; } Problem: Although i see the custom font 'Montserrat' in the dropdown on tincymce editor but when … -
Reach django user from javascript template
I'm following Corey Shafer's django guide and I have run into some problems he doesn't cover. I'm trying to make profiles that are visible to everyone but only editable by the user itself. In my views.py I have a boolean "editable", and this part is working. However, I can't get that boolean to my js file... Code below. const button = document.getElementById("button"); button.addEventListener("click", () => { const form = document.getElementById("form"); var bool = {{ user.profile.editable }}; if(form.style.display == "none" && bool){ form.style.display = "block"; }else{ form.style.display = "none"; } }); When I inspect it in the browser it gives me a syntaxError because I'm using '{'. And here is the code from my views.py: @login_required def profile(request, username): user = User.objects.get(username=username) Profile.objects.get_or_create(user=request.user) editable = False if request.method == "POST": user_form = UserUpdateForm(request.POST, instance=request.user) profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, f"Profile successfully updated!") return redirect("profile") else: user_form = UserUpdateForm(instance=request.user) profile_form = ProfileUpdateForm(instance=request.user.profile) context = { "user_form": user_form, "profile_form": profile_form } if request.user == user: editable = True return render(request, "users/profile.html", context) Any help would be much appreciated. Thanks in advance! -
Django & AJAX file upload
When using POST request with AJAX in Django 4.0.1 I can't reach the file from the backend using request.FILES. The form used is pretty simple so I can't spot any typos etc. HTML: <form id="snipForm" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="multiFiles" name="files[]" multiple="multiple"/> <button id="upload">Upload</button> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> JavaScript: (sorry for quite a long code sample but I can't shrink it more) $(document).ready(function (e) { $('#upload').on('click', function (event) { //Prevent page from reloading event.preventDefault() var form_data = new FormData(); // check if there is any file selected var ins = document.getElementById('multiFiles').files.length; if(ins == 0) { $('#msg').html('<span style="color:red">Select at least one file</span>'); return; } // add all files for (var x = 0; x < ins; x++) { form_data.append("files[]", document.getElementById('multiFiles').files[x]); } // obtain CSFR token csrf_token = $('input[name="csrfmiddlewaretoken"]').val(); // set the headers headers = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest', 'X-CSRFToken': csrf_token}; $.ajax({ type: 'POST', url: '/docs/', // point to server-side URL dataType: "json", ContentType: "application/x-www-form-urlencoded", cache: false, processData: false, headers: headers, data: form_data, success: function (response) { // display success response console.log("successssssssssssss") }, error: function (response) { console.log("NOPEEEEEE") } }); }); }); views.py: from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def generate(request): is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if request.method == 'POST' and is_ajax: files … -
Search with Django (for Tags)
I'm doing a 3-part search. (1st username 2.caption 3.tag) only the 3rdtag search doesn't work. (The error I get when I add the tag -Related Field got invalid lookup: icontains) I also tried using the Tag model, but it didn't work, can you help? enter code here myviews.py @login_required(login_url="login") def UserSearch(request): query = request.GET.get("q") context = {} specailAd= Ad.objects.order_by('-dateAd') ads = list(Ad.objects.all()) oneAd = random.choice(ads) post_items = Post.objects.all().order_by('-posted') if query: post_items = post_items.filter(caption__icontains = query) if query: post_items = post_items.filter(tags__icontains = query) if query: users = User.objects.filter(Q(username__icontains=query)) #Pagination paginator = Paginator(users, 6) page_number = request.GET.get('page') users_paginator = paginator.get_page(page_number) context = { 'users': users_paginator, 'post_items':post_items, 'specailAd':specailAd, 'oneAd':oneAd, } template = loader.get_template('direct/search_user.html') mymodels.py class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content = models.ManyToManyField(PostFileContent, related_name='contents') caption = models.TextField(max_length=1500, verbose_name='Caption') posted = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag, related_name='tags') user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField( User, related_name='like', default=None, blank=True) like_count = models.BigIntegerField(default='0') def get_absolute_url(self): return reverse('postdetails', args=[str(self.id)]) def __str__(self): return str(self.id) class Tag(models.Model): title = models.CharField(max_length=75, verbose_name='Tag') slug = models.SlugField(null=False, unique=True) class Meta: verbose_name='Tag' verbose_name_plural = 'Tags' def get_absolute_url(self): return reverse('tags', args=[self.slug]) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) -
why i am getting no reverse match error after adding the url in home.html file?
I am getting the error after adding the URL in the home.html file. I migrated before running the program. I used commands to migrate. i.e., python manage.py migrate. 2. python manage.py makemigrations app_name. Django version I am using is 4.0.6. Thank you Settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR=os.path.join(BASE_DIR,"templates") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-d4@4fwcpkk$6a8ylqjmyhp-9%22t^aizetygwkxzw9s_wu5$&2' # 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', 'g6app', ] 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 = 'g6.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], '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', ], }, }, ] urls.py from django.contrib import admin from django.urls import path from g6app.views import V1,V2 urlpatterns = [ path('admin/', admin.site.urls), path("",V1.as_view(),name="v11"), path("index/<int:pk>",V2.as_view(),name="index_detail1"), ] admin.py from django.contrib import admin from . models import T1 # Register your models here. admin.site.register(T1) models.py from django.db import models from django.urls … -
Sending email verfications works locally but doesnt work on heroku in my django app
i am using an email verfication using links once the user register an email is sent to the user to activate their account this works fine in my local app when i run it but after i deployed the app to heroku even tho i set the config vars to be the same as my enviroment vars i still get this error (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError t19-20020a05622a181300b0031e9b5ead3asm2297749qtc.76 - gsmtp', 'samdjangoemail@gmail.com') this error indicates that for some reason heroku cant access the gmail even tho i set an app password for it and this is my settings for heroku DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_FROM_USER') EMAIL_FROM_USER = os.environ.get('EMAIL_FROM_USER') EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = os.environ.get('EMAIL_FROM_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') EMAIL_USE_SSL = True EMAIL_PORT = 465 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' CRISPY_TEMPLATE_PACK = 'bootstrap5' # heruko settings cwd = os.getcwd() if cwd == '/app' or cwd[:4] =='/tmp': import dj_database_url DATABASES = { 'default' : dj_database_url.config(default='postgres://localhost') } # honor the 'X-Forward-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARD_PROTO', 'https') DEBUG = False #static asset configuration BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = 'staticfiles' STATICFILES_DIR = (os.path.join(BASE_DIR, 'static')) … -
I have uploaded a django project on ngnix server. I want the api requests to go to subdomain.example.com but it's going to 0.0.0.0:8083 instead
Nginx setup: server { listen [::]:8005 ssl; # managed by Certbot listen 8005 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/qatekinternal.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/qatekinternal.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot server_name subdoamin.example.com; location /static { alias /home/example/jrms_server/static; } location /media { alias /home/example/jrms_server/media; add_header Access-Control-Allow-Origin *; } location / { proxy_pass http://0.0.0.0:8083; proxy_http_version 1.1; } } Gunicorn config file: command = '/home/example/jrms_prod_env/bin/gunicon' pythonpath = '/home/qatekadmin/jrms_server' bind = ['0.0.0.0:8083'] workers = 9 Limit_request_line = 8190 Project settings.py file: https://gist.github.com/salmanc2/e0a00d27945a2a93863c0822ab0a91b1 Project api.js file: https://gist.github.com/salmanc2/dabd163b091478bd3567518224e8e1a8 I have used the address "https://subdomain.example.com:8005"; for my APIs but after uploading to server they are calling at 0.0.0.0:8083 instead. -
BeautifulSoup4 Scraping doesn't work when I try to deploy
In my Django system I use django-bs4 for scraping. It works well on my local host but when I deploy it on Pythonanywhere.com it beautifulsoup doesn't working. On Pythonanywhere it returns None when I try to scrape some HTML. It works on local but why it doesn't work on Pythonanywhere? -
module not found when using include in django
I'm trying to use include in my app following the tutorial here - https://www.w3schools.com/django/django_views.php it seems that when I run the server using this configuration- urlpatterns = [path('members/', include('mimi.urls')), path('admin/', admin.site.urls),] I get ModuleNotFoundError: No module named 'mimi'. I've attached a screenshot of my Pycharm project folder as it is now. I don't understand what I'm doing wrong. It seems to fail to recognize anything outside the web_questions folder, but I can't find a way to give it the absolute path. I'm running the server using this command line - py web_questions/manage.py runserver Help! Karin. -
How can I replace part of url in redirecting?
I have some problems in redirecting urls in my Django app. This is my urls.py: urlpatterns = [ path('Stu_SignUp/step1/', views.new_student, name='new_student'), path('Stu_SignUp/step2/', views.comPnew_student, name='comPnew_student')] Now I want to change part of url from /step1/ to /step2/. These are my views.py app: def new_student(request): if request.method == "POST": Person.objects.create(p_fName=request.POST['fName'], p_lName=request.POST['lName'], p_SSN=request.POST['SSN'], p_birthDate=request.POST['birthdate'], p_phoneNum=request.POST['phoneNum']) return redirect('Stu_SignUp/step2/') else: return render(request, 'signUp_student.html', context={'person': Person}) def comPnew_student(request): if request.method == "POST": if request.method['password'] == request.method['conf_Pass']: update_person = Person.objects.get(Person_ID=Person.objects.last().id) update_person.p_Email = request.POST['email'] update_person.p_Password = request.POST['password'] return redirect('Stu_SignUp/step2/') else: return render(request, 'signUp_student2.html', context={'person': Person}) Html Template is signUp_student.html and signUp_student2.html: Page Number 1: <form action="{% url 'new_student' %}" method="post"> {% csrf_token %} <label for="firstName">First Name<br> <input type="text" name="fName"> </label><br> <label for="lastName">Last Name<br> <input type="text" name="lName"> </label><br> <label for="firstName">SSN Code<br> <input type="text" name="SSN"> </label><br> <label for="birthdate">Birthdate <br> <input type="date" name='birthdate'> </label><br> <label for="phoneNumber">Phone Number<br> <input type="text" name='phoneNum'> </label> <br><br> <button type="submit">Sign up</button> </form> Page Number 2: <form action="{% url 'comPnew_student' %}" method="post"> {% csrf_token %} <label for="Email">Email<br> <input type="text" name="email"> </label><br> <label for="password">Password<br> <input type="text" name="password"> </label><br> <label for="confPassword">Confirm Password<br> <input type="text" name="conf_Pass"> </label><br> <br><br> <button type="submit">Sign up</button> </form> I'll appreciate your help. -
when I try to search I get this error : Related Field got invalid lookup: tag
views.py def home(request): WAllPAPER_PER_PAGE = 15 WALL = Wallpaper.objects.all() from django.core.paginator import EmptyPage, Paginator from django.db.models import Q qd = request.GET.copy() qd.pop('page', None) querystring = qd.urlencode() #link formatting for ordering ordering =request.GET.get('ordering', "") #link formatting for sorting search = request.GET.get('search', "") if search: wallpapers = Wallpaper.objects.filter(Q(name__icontains=search) | Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search)).distinct().order_by('-pk') WALL = None else: wallpapers = Wallpaper.objects.all().order_by('-pk') if ordering: wallpapers = wallpapers.order_by(ordering) page = request.GET.get('page', 1) wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE) try: wallpapers = wallpaper_paginator.page(page) except EmptyPage: wallpapers = wallpaper_paginator.page(wallpaper_paginator.num_pages) except: wallpapers = wallpaper_paginator.page(WAllPAPER_PER_PAGE) context = {'querystring': querystring, "wallpapers": wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator, 'WALL': WALL} return render(request, "Wallpaper/Home.html", context) models.py class Tags(models.Model): tag = models.CharField(max_length=100) def __str__(self): return self.tag class Category(models.Model): category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Wallpaper(models.Model): name = models.CharField(max_length=100, null=True) size = models.CharField(max_length=50, null=True) pub_date = models.DateField('date published', null=True) resolution = models.CharField(max_length=100, null=True) category = models.ManyToManyField(Category) tags = TaggableManager() Device_Choices = [ ('PC', 'pc'), ('mobile', 'mobile') ] Devices = models.CharField(max_length=20,choices=Device_Choices, default= 'PC') image = models.ImageField(upload_to='Wallpaper/Images/', default="") def __str__(self): return self.name error File "C:\Users\Atharva thaware\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\q uery.py", line 1339, in build_filter raise FieldError('Related Field got invalid lookup: {}'.format(lookups[0])) django.core.exceptions.FieldError: Related Field got invalid lookup: tag