Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cant Access Django development server with 0.0.0.0:8000
I am trying to run my Django app on a windows system with python manage.py runserver 0.0.0.0:8000. But it doesnt runs in other systems. Following steps I have already followed: App runs in local system ALLOWED_HOSTS = ['*'] I have disabled firewall completely I open incomming and outgoing connection for port 8000. Tried with python manage.py runserver 192.xx.xx.xx:8000 Please suggest where am I missing. Additional Note: I already tried and run the similar app in an ubuntu server and it works perfectly fine. -
Error 101 sending email with mailgun on django heroku
My settings.py: EMAIL_HOST = "smtp.mailgun.org" MAIL_PORT = 587 EMAIL_HOST_USER = os.environ["MAILGUN_SMTP_LOGIN"] EMAIL_HOST_PASSWORD = os.environ["MAILGUN_SMTP_PASSWORD"] EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' My views.py: import re import os from django.http import HttpResponse from django.template import loader from django.contrib.auth.hashers import make_password import time import secrets from .models import User from .models import EmailConfirmation from django.core.mail import send_mail from threading import Thread import threading noReply = re.sub(".*@", "noreply@", os.environ["MAILGUN_SMTP_LOGIN"]) def threadingSendMail(subject, message, from_email, recipientList): send_mail( subject=subject, message=message, from_email=from_email, recipient_list=recipientList ) def wait(request): if request.method == "POST": password = request.POST["password"] email = request.POST["email"] if not re.match(r"[^@]+@[^@]+\.[^@]+", email): return HttpResponse("Email not valid") else: if User.objects.filter(email=email).exists(): return HttpResponse("Email already exists") else: theUser = User.objects.create(email=email, password=make_password(password), confirmed=False) hashKey = secrets.token_hex(16) EmailConfirmation.objects.create(email=theUser,emailHash=hashKey) verificationLink = request.get_host() + "/" + str(hashKey) threading.Thread(target=threadingSendMail, args=("Email conf", verificationLink,noReply,[email],)).start() return HttpResponse("pass") else: return HttpResponse("hello") My error in heroku logs: 2022-08-27T10:55:15.473726+00:00 app[web.1]: Exception in thread Thread-1 (threadingSendMail): 2022-08-27T10:55:15.473737+00:00 app[web.1]: Traceback (most recent call last): 2022-08-27T10:55:15.473738+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/threading.py", line 1016, in _bootstrap_inner 2022-08-27T10:55:15.473739+00:00 app[web.1]: self.run() 2022-08-27T10:55:15.473739+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/threading.py", line 953, in run 2022-08-27T10:55:15.473810+00:00 app[web.1]: self._target(*self._args, **self._kwargs) 2022-08-27T10:55:15.473820+00:00 app[web.1]: File "/app/djangocode/stocks/views.py", line 21, in threadingSendMail 2022-08-27T10:55:15.473912+00:00 app[web.1]: send_mail( 2022-08-27T10:55:15.473921+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/mail/__init__.py", line 87, in send_mail 2022-08-27T10:55:15.474010+00:00 app[web.1]: return mail.send() 2022-08-27T10:55:15.474018+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/mail/message.py", line 298, … -
djongo' isn't an available database backend or couldn't be imported. Check the above exception
enter image description here enter image description here enter image description here enter image description here enter image description here -
Django gettext <br> tag
Thank you for checking my question. I try to use gettext and serve my django website in another languages. I want to add a class to the br tag. As shown in ↓, an error does not occur if there is only a br tag, {% trans "I am a student. <br> I am a man."%} But as shown below, if you add a class, an error will occur. {% trans "I am a student. <br class="aaaa"> I am a man."%} Could you teach me is there any good solution? -
Drf serializer of childmodel for both nested ListAPIView and CreateAPIView
I have these models class myModel(models.Model): username = models.CharField(max_length=150, unique=True) o2=models.CharField(max_length=150, default='lllss') class myModel2(models.Model): owner=models.ForeignKey(myModel,on_delete=models.CASCADE) o2=models.CharField(max_length=150, default='lllss2') model2 has owner of myModel and these serializers class mySer(serializers.ModelSerializer): class Meta: model = my.myModel fields = ['username', 'o2'] class mySer2(serializers.ModelSerializer): class Meta: model = my.myModel2 fields = ['owner', 'o2'] depth=1 # to have nested in listviews note I have added depth=1to have nested in listviews so with from rest_framework import generics class myView(generics.CreateAPIView): queryset = my.myModel2.objects.all() serializer_class = my2.mySer2 class myView2(generics.ListAPIView): queryset = my.myModel2.objects.all() serializer_class = my2.mySer2 I can get nested info of owner, but in CreateAPIView there is no dropdown menu for owner in HTML form. better said nothing enables us to send owner. but when I delete depth=1 I have not that problem but I lose the nested views. I could have created 2 serializers but is there any way of doing this in a single serializer? -
return Invalid address; only example1@gmail.com could be parsed from "example1@gmail.com, example@gmail.com
any way around this i'm trying to send multiple mail through ajax in a textarea area i got this in return Invalid address; only example1@gmail.com could be parsed from "example1@gmail.com, example@gmail.com, this is my code below def post(self, request, *args, **kwargs): studentcourse = request.POST.get('studentcourse') from_email = request.user.email subject = Courses.objects.get(id=studentcourse) emails = request.POST.get('email') message = request.POST.get('message') notify_email = EmailMultiAlternatives(subject, message, from_email,[emails]) notify_email.send() return Invalid address; only example1@gmail.com could be parsed from "example1@gmail.com, example@gmail.com -
Django DRF login only superuser
I want to implement login with Django drf. I want only superuser (is_staff permission in my user model) to be able to log in. Until now I used rest_framework_simplejwt for generating a token for every user that trying to log in. How can I implement that only superuser will be able to log in? Views.py: calling the serializer class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer Serializer.py: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): user = CustomUser.objects.get(email=user.email) print(colored(user, "yellow")) token = super().get_token(user) # Add custom claims token['username'] = user.clinic_name token['email'] = user.email # ... return token In serializer.py when I'm trying to retrieve user user = CustomUser.objects.get(email=user.email) I get only the email filed back. I'm using email to retrieve user because email is a unique field. urls.py: urlpatterns = [ path('token/', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('register/', views.ClinicRegistration, name='auth_register'), path('users/', views.ClinicListView.as_view(), name='users_list'), path('users/<pk>/', views.ClinicDetailView.as_view(), name='get_user'), path('users/<pk>/update/', views.ClinicUpdate, name='update_user'), path('users/<pk>/delete/', views.ClinicDeleteView.as_view(), name='delete_user'), path('', views.getRoutes), path('test/', views.testEndPoint, name='test') ] In the frontend I'm using react I make an Axios.post request with the: username, password, and email fields. This is my CustomUserModel: class CustomUser(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(_('email address'), unique=True) clinic_name = models.CharField(max_length=150, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) fb_projectId … -
File import issue - python Django
I have a file in my management/commands folder and I am trying to import my models into the report.py folder. However, I get the following error. Traceback (most recent call last): File "c:\Users\Timmeh\source\Python\Django Projects\env\topxgym\members\management\commands\report.py", line 2, in <module> from members.models import ActiveMember ModuleNotFoundError: No module named 'members' I have a active.py file in that same folder with the same import and it works. However, the active.py is run from python manage.py active. The report.py I am just compiling/running it (not running it from python manage.py). That is the only difference. the file structure. -
How do I print the query that Python uses to call the database?
How do I print to the terminal the query used by a specific line of python code? see below notifications = user.get_notifications(max_id=max_id, types=types).order_by('-created')[:count] -
Nginx can't find bundles js file
I am trying this for a long time. I would really appreciate the help. In local, application is working, but in nginx, main.js resource is not found I have a django application with react on the save server served with webpacker and babel URL / will render frontend/index.html Index.html code: Nginx.conf file Settings.py In local, its working But in nginx server, its not project structure -
Errow while working with django, psycopg file shifting to mac (I WOULD ANSWER MYSELF, IT MAY HELP SOMEONE) [duplicate]
I recently shifted to MAC M2 MONTEREY & one project involved django & my dev env from older system isn't setup here. I got error while installing "psycopg" like this: Using cached psycopg2-2.8.5.tar.gz (380 kB) ERROR: Command errored out with exit status 1: command: /opt/homebrew/opt/python@3.9/bin/python3.9 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-install-9wiqe2nr/psycopg2_97efcf6747c249769acdc8430ba4238f/setup.py'"'"'; __file__='"'"'/private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-install-9wiqe2nr/psycopg2_97efcf6747c249769acdc8430ba4238f/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r cwd: /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-install-9wiqe2nr/psycopg2_97efcf6747c249769acdc8430ba4238f/ Complete output (23 lines): running egg_info creating /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info writing /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info/PKG-INFO writing dependency_links to /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info/dependency_links.txt writing top-level names to /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info/top_level.txt writing manifest file '/private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ============================================================================== Its beginning of the error, After that its tried to install each previous version of Psycopg ============================================================================== Searching out for solution, a few things helped me out so here's the answer from my side thinking it may help someone else … -
Apache + Python (Django): Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
I'm trying to host my Django Rest Framework project using Xampp & Apache on my Windows server but I'm getting the following error. Does anyone have an idea what causes it? I installed Python, mod_wsgi and all the requirements for my app. Full stacktrace below Current thread 0x00000e94 (most recent call first): <no Python frame> [Sat Aug 27 11:05:43.581446 2022] [mpm_winnt:notice] [pid 2484:tid 332] AH00428: Parent: child process 5104 exited with status 1 -- Restarting. [Sat Aug 27 11:05:43.741583 2022] [mpm_winnt:notice] [pid 2484:tid 332] AH00455: Apache/2.4.53 (Win64) PHP/8.1.6 mod_wsgi/4.9.3 Python/3.10 configured -- resuming normal operations [Sat Aug 27 11:05:43.741583 2022] [mpm_winnt:notice] [pid 2484:tid 332] AH00456: Apache Lounge VS16 Server built: Mar 16 2022 11:26:15 [Sat Aug 27 11:05:43.741583 2022] [core:notice] [pid 2484:tid 332] AH00094: Command line: 'C:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache' [Sat Aug 27 11:05:43.757121 2022] [mpm_winnt:notice] [pid 2484:tid 332] AH00418: Parent: Created child process 2976 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\xampp\\apache\\bin\\httpd.exe' sys.base_prefix = 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310' sys.base_exec_prefix = 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310' sys.platlibdir = 'lib' sys.executable = 'C:\\xampp\\apache\\bin\\httpd.exe' sys.prefix = 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310' sys.exec_prefix = 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310' sys.path = [ 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', '.\\DLLs', '.\\lib', … -
Django replace text in template
In my project i can filter products with queryset. How can i change a h1 element to the filter name? I tried to change with javascript, but when i filtered the products the page reloaded and the text didn't change models.py TYPE = ( (0, "monitor"), (1, "pc"), (2, "phone"), ) class Product(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) image = models.ImageField(upload_to='images/') description = models.TextField() price = models.CharField(max_length=12, unique=True) type = models.IntegerField(choices=TYPE, default=0) def __str__(self): return self.name views.py class ProductList(generic.ListView): template_name = 'products.html' def get_queryset(self): queryset = Product.objects.all() type_query = self.request.GET.get("type", None) if type_query == 'monitor': queryset = Product.objects.filter(type=0) elif type_query == 'pc': queryset = Product.objects.filter(type=1) elif type_query == 'phone': queryset = Product.objects.filter(type=2) elif type_query == 'all': queryset = Product.objects.all() return queryset products.html <form onsubmit="return setTypeText()" id="type-form"> <input type="radio" id="all-radio" name="type" value="all"> <input type="radio" id="monitor-radio" name="type" value="monitor"> <input type="radio" id="pc-radio" name="type" value="pc"> <input type="radio" id="phone-radio" name="type" value="phone"> <input type="submit" value="Filter"> </form> <h1 id="type-text">All product</h1> #<---I need to change this I need to change the h1 to the input value Javascript function setTypeText(){ var elements = document.getElementsByName('type'); var type_name; for(i = 0; i < elements.length; i++) { if(elements[i].checked) type_name = elements[i].value; } document.getElementById("type-text").innerHTML = type_name; return true; } When … -
Show only users that don't yet exist in the through table
Inside of the __init__ method of a form ProjectUserCreateForm(forms.ModelForm) to add Users to a Project (Project model has a users = models.ManyToManyField(...)) I have self.fields['users'].queryset = User.objects.filter(company=self.request.user.company) This way I'm able to show only the users to be added to the Project that belong to the company of the user requesting the page. This form can be found in path('<int:pk>/users/create/', views.ProjectUserCreateView.as_view(), name='project-user-create'), where the <int:pk> is the PK of the Project, and ProjectUserCreateView is a CBV CreateView. How can I show only the users that belong to the company of the logged in user (this part already works) AND that don't yet exist in the through table (the table based on the ManyToManyField)? -
Django messages not displaying message
I'm trying to use django messages to notify user if form was submitted successfully or not. But nothing pops up when I submit the form no matter what. I've gone through the views.py code and template and I don't seem to anything wrong. I've even tried changing the default messages backend storage to session yet nothing. MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' views.py: from django.shortcuts import render, HttpResponse, HttpResponseRedirect, redirect from django.contrib import messages from .forms import MyUserCreationForm import bcrypt def register(request): if request.method == "POST": # Populate form using submitted data form = MyUserCreationForm(request.POST) if form.is_valid(): # Clone form model user = form.save(commit=False) password = user.password # Validate password length if len(password) > 25: messages.error( request, "PASSWORD MUST BE LESS THAN OR EQUAL TO 25 CHARACTER LENGTH") # Hash user password bytes = password.encode('utf-8') salt = bcrypt.gensalt() hash = bcrypt.hashpw(bytes, salt) # Save modified form to database user.password = hash user.save() messages.success(request, "ACCOUNT CREATED SUCCESSFULLY!") messages.add_message(request, messages.INFO, 'Thanks for reaching out! We will be in contact soon!', extra_tags='ex-tag') return redirect('register') # Create empty form form = MyUserCreationForm() return render(request, 'register.html', {'form': form}) templates/register.html: {% extends "layout.html" %} {% block title %} Testing Registration {% endblock %} {% load static %} {% load … -
How to connect two django projects on two different servers
Problem: I am having a website which has various apps (Accounts, Community, Company, Payments, Main_project_app). What I want is to set up a google type similar architecture where the userbase is on one server and other apps such as Gmail, drive, etc. serve the specific services on different servers based on the user authentication from the main Google userbase server i.e. Accounts app which have information about the user such as username, email, password, etc must remain on one server and using the REST API's or something we connect accounts app with another server to take the user from sign-in page to dashboard and serve them other services by using all other apps. I am a newbie so please if I have done some mistakes to explain or something do correct me. -
Django Template – Mark only certain HTML tags as safe
I have the following use case: a user should be able to enter in HTML input and it should be displayed as such. However, it can only contain <br>, <italic>, <strong>, <ul> or <li> tags. I know about the safe filter, but that way it would allow every HTML input and be prone to XSS. Any idea how I can solve this? Thanks! -
Social Authentication from drf_social_oauth2 : error with django.urls.exceptions.NoReverseMatch: 'social' is not a registered namespace
I'm developing an new application with an Angular and Django Rest Framework stack. In my API, I use drf_social_oauth2 for a Social Authentication. The token exchanges are successful. Tokens and users are created on the database. However, the authentication for others views are in failure. I use this type of authentication_classes in my others views : from rest_framework import authentication from drf_social_oauth2.authentication import SocialAuthentication class UsersListApiView(APIView): authentication_classes = [authentication.TokenAuthentication, SocialAuthentication] My URLs are : path('auth/login/', obtain_auth_token, name='login'), path('auth/', include('dj_rest_auth.urls')), path('auth/registration/', include('dj_rest_auth.registration.urls')), re_path(r'^auth/', include('drf_social_oauth2.urls', namespace='drf')), This is a part of my settings.py file : AUTHENTICATION_BACKENDS = [ # Google OAuth2 'social_core.backends.google.GoogleOAuth2', # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', # drf_social_oauth2 'drf_social_oauth2.backends.DjangoOAuth2', # DJango 'django.contrib.auth.backends.ModelBackend', ] # Facebook configuration SOCIAL_AUTH_FACEBOOK_KEY = '' SOCIAL_AUTH_FACEBOOK_SECRET = '' # Define SOCIAL_AUTH_FACEBOOK_SCOPE to get extra permissions from Facebook. # Email is not sent by default, to get it, you must request the email permission. SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email' } # Google configuration SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "" # Define SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE to get extra permissions from Google. SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS':'rest_framework.schemas.coreapi.AutoSchema', 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'drf_social_oauth2.authentication.SocialAuthentication', 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } SITE_ID = 2 … -
How do I sync my ecommerce django website with my Facebook page to automatically display products
I have developed a ecommerce website using Django, I want to link it with my Facebook business page. I searched but couldn't find any good answer -
What is the correct field it should be applied
I cannot figure out what kind of field shoud I use in my serializer class if in the model it is a ForeignKey class DotPrivateSerializer(serializers.ModelSerializer): tag = serializers.________________Field( queryset=TagPrivate.objects.filter(user=serializers.CurrentUserDefault()) ) models.py class DotPrivate(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) name = models.CharField(max_length=255) description = models.TextField(max_length=350, blank=True) lon = models.CharField(max_length=20) lat = models.CharField(max_length=20) rating = models.FloatField(validators=[MinValueValidator(0.0), MaxValueValidator(5.0)]) tag = models.ForeignKey('TagPrivate', on_delete=models.PROTECT) -
Can't install mysqlclient error metadata-generation-failed
I am trying to install mysqlclient, but it throws me an error, what should I do, please help. pip install mysqlclient Defaulting to user installation because normal site-packages is not writeable Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-9itgdei2/mysqlclient_8d860bd4cbc249d9aecc553fe594f5c2/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-9itgdei2/mysqlclient_8d860bd4cbc249d9aecc553fe594f5c2/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-9itgdei2/mysqlclient_8d860bd4cbc249d9aecc553fe594f5c2/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. -
django-markdown: How to disable loading image when render article briefing
I am a beginer of web development and I have had some python exprience while this is my first try on django (Django==3.2) . I have managed to store markdown article by using Markdown==3.3.7, the everything looks like: # models.py class ArticlePost(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) title = models.CharField(max_length=64) body = models.TextField() # views.py def article_create(request): if request.method == "POST": article_post_form = ArticlePostForm(data=request.POST) if article_post_form.is_valid(): new = article_post_form.save(commit=False) new.author = User.objects.get(id=1) new.body = markdown.markdown( new.body, extensions=[ 'markdown.extensions.extra', ]) new.save() return redirect("article:article_list") # else: # Shell test: >>> print(article.body) <p><a href="https://img.com/"><img alt="test.png" src="https://xxxx" /></a></p> >>> type(article.body) <class 'str'> at first it looks like: so I use CSS display:none, the img doesn't render just as expecting But I happened to find that display:none doesn't prevent browser to load image: a practical way is when calling article_create() "sed" out img tag and dump a copy which is only for the usage of rendering the brief but to me, I prefer some way that I can remain current article.body content, then add something in html or css, so that I can make the brief brief(cuz it render without loading img). thx in advance! -
How to set Django settings from within a function?
Is there a way to set django settings from within a function? Essentially, I want to create logic blocks that set various django settings (perhaps more than one at a time). An quick example of this: def set_log_settings(env): if env == 'prod': set_settings({'LOG_LEVEL': 'INFO', 'LOG__HANDLER': 'prodhandler'} else: set_settings({'LOG_LEVEL': 'DEBUG', 'LOG__HANDLER': 'devhandler'} I would call this instead of having in my settings.py: if env == 'prod': LOG_LEVEL='INFO' LOG__HANDLER='prodhandler' else: LOG_LEVEL='DEBUG' LOG__HANDLER'='devhandler' Note: I want to call this from within the settings.py file, not from the actual loaded app code, it's more a question of grouping settings-related logic, rather than a question of when that logic runs. This would allow me to not have a giant settings file where all logic is sitting virtually un-organized at the global level. -
POST request with ajax not working after installing django hosts
Hello I am just getting acquainted with django hosts which I am trying to set up on an ecommerce website I am building. So basically I will have the main website - www.shop.com And I want to have a subdomain - sell.shop.com - which will be where sellers can register and access their dashboard. Previously I set the seller website on www.shop.com/sell which is wrong in my opinion. When the seller would register, I was handling the form validation using AJAX. And everything was working properly. Once I installed django hosts and reconfigured the application, I noticed that the AJAX POST request is no longer getting detected. And so, no data is being stored in the DB nor is the validation on the form working. settings.py ALLOWED_HOSTS = ['127.0.0.1', 'www.shop.com', '.shop.com',] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third Party 'django_hosts', 'corsheaders', # Custom 'pages', 'users', 'vendors', ] MIDDLEWARE = [ 'django_hosts.middleware.HostsRequestMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_hosts.middleware.HostsResponseMiddleware' ] ROOT_URLCONF = 'sns.urls' ROOT_HOSTCONF = 'sns.hosts' DEFAULT_HOST= 'www' PARENT_HOST = 'surfnshop.mu' HOST_PORT = '8009' CORS_ALLOWED_ORIGINS = [ "http://surfnshop.mu:8009", "http://sell.surfnshop.mu:8009" ] CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', … -
Django admin command equivalent for gin golang
I want to write a script a to migrate data from one table to another using gin golang. The dataset is quite big so I can't create an API endpoint and do it as it will get timed out. I am looking an equivalent of django admin commands for golang that can help me to connect to the database easily and perform these task.