Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-admin startproject
I am new to django and I tried to create a project with django-admin startproject command. The tutorial I was referring to had no errors while going through this command but I get the following error. The tutorial and I are not doing it in any virtual environment. Though this error comes, the files and folder is created in the directory I am working in, how should I solve this error? Traceback (most recent call last): File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in run_module_as_main return run_code(code, main_globals, None, File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\username\AppData\Local\Programs\Python\Python39\Scripts\django-admin.exe_main.py", line 7, in <module> File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\startproject.py", line 21, in handle super().handle("project", project_name, target, **options) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\templates.py", line 225, in handle run_formatters([top_dir]) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\utils.py", line 165, in run_formatters subprocess.run( File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 501, in run with Popen(*popenargs, **kwargs) as process: File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 947, in init self._execute_child(args, executable, preexec_fn, close_fds, File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1416, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, PermissionError: [WinError 5] Access is denied -
Django Admin doesn't recognise blank=True in model
When I try to edit a user (using a custom UserChangeForm) in the Django admin panel, validation insists that fields I have set blank=True in the model are required. I don't know where to begin solving this; I had the same issue with the CustomUserCreationForm but reverted to using the default which works as expected (asks for username, password1 & password2, creates the user with blank display_name, bio and profile_picture fields). models.py: from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): display_name = models.CharField(max_length=30, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_picture = models.ImageField(upload_to='images/', blank=True, null=True) def save(self, *args, **kwargs): if not self.display_name: self.display_name = self.username super().save(*args, **kwargs) def __str__(self): return self.username forms.py: from django import forms from django.contrib.auth.forms import UserChangeForm from .models import CustomUser class CustomUserChangeForm(UserChangeForm): display_name = forms.CharField(label="display_name") bio = forms.CharField(widget=forms.Textarea) profile_picture = forms.ImageField(label="profile_picture") class Meta(): model = CustomUser fields = ("username", "email", "display_name", "bio", "profile_picture") admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): form = CustomUserChangeForm fieldsets = ( (None, {'fields': ('username', 'password', 'email', 'display_name', 'bio', 'profile_picture')} ), ) model = CustomUser list_display = ["username", "email",] admin.site.register(CustomUser, CustomUserAdmin) -
'NoneType' object has no attribute 'strip' - CS50W Wiki
I'm getting this error while trying to create a search function in Django. This is where I'm having trouble: If the query does not match the name of an encyclopedia entry, the user should instead be taken to a search results page that displays a list of all encyclopedia entries that have the query as a substring. For example, if the search query were ytho, then Python should appear in the search results. This is the view: def search(request): if request.method == 'POST': search_title = request.POST['q'] content = converter(search_title) if search_title is not None: return render(request, "encyclopedia/entry.html", { "entry": content, "entryTitle": search_title }) else: entries = util.list_entries() search_pages = [] for entry in entries: if search_title in entries: search_pages.append(entry) return render(request, "encyclopedia/search.html",{ "entries": search_pages }) And the HTML: <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> Traceback: Traceback (most recent call last): File "C:\Users\anshi.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\anshi.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\Py Projects\CS50 attempt 00\wiki\encyclopedia\views.py", line 70, in search content = converter(search_title) File "D:\Python\Py Projects\CS50 attempt 00\wiki\encyclopedia\views.py", line 19, in converter html = Markdowner.convert(content) File "C:\Users\anshi.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\markdown\core.py", line 248, in convert … -
Adding widgets to django form does not update the forms
So I have a login form for which I am trying to edit the css attributes. However I cannot seem to find the correct solution. Below is my views.py, forms.py and html snippet accordingly. def index(request): context = {} if request.method == 'POST': form = LoginForm(data=request.POST) context['form'] = form logging.debug(form.is_valid()) logging.debug(form.cleaned_data) logging.debug(form.errors) if form.is_valid(): logging.debug("form valid") username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') if authenticate(username, password): logging.debug("logged IN") messages.success(request, f' welcome {username} !!') return redirect('loggedIn') else: logging.debug("wrong!") messages.info(request, f'Password or Username is wrong. Please try again.') form = AuthenticationForm() return render(request, "index_logged_out.html", {"form": form}) class LoginForm(forms.ModelForm): class Meta: model = WebsiteRegistrant fields = ['username', 'password',] widgets = { 'username': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Username' }), 'password': PasswordInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Password' }) } <form method="POST"> {% csrf_token %} <center> <div class="form-group" style = "margin-bottom: 10px; width: 300px"> {{ form.password }} </div> <div class="form-group" style = "margin-bottom: 10px; width: 300px"> {{ form.password }} </div> <button class="btn btn-primary btn-block fa-lg gradient-custom-2 mb-3" type="submit" style="width: 300px;">Login</button> </center> </form> Any idea what I am doing wrong or what I could fix in order to add the class name and attributes as I have defined in the form widget? Thanks -
How to add data to Django's database by the click of a button using JS and AJAX
I'm trying to add data that I rendered on a page from an API endpoint, to my database when I click "Add to my records" button, as can be seen in the image below, and I'm only trying to store "Date and Country" into the database (my model table has only date and country) enter image description here I've seen many resources talking about how JS and AJAX are useful in this case but I'm lost with logic of it all. Is there any way someone could explain how it's supposed to be done. models.py from django.db import models class CountryData(models.Model): country = models.CharField(max_length=100) date = models.DateTimeField() def __str__(self): return self.country views.py def all_countries(request): first_response = requests.get("https://api.covid19api.com/summary").json() results = len(first_response["Countries"]) my_new_list = [] data_list = [] for i in range(0, results): my_new_list.append(first_response["Countries"][i]) # print(my_new_list) if request.method == "POST": if request.POST.get("country") and request.POST.get("date"): added_record = CountryData() added_record.country = request.POST.get("country") # 2022-12-19T08:53:48.179Z added_record.date = datetime.datetime.strptime( request.POST.get("date"), "%Y-%m-%dT%I:%M:%S.%fZ" ) added_record.save() return render(request, "allcountries.html") else: return render(request, "allcountries.html", ) context = {"my_new_list": my_new_list} return render(request, "allcountries.html", context) urls.py from django.urls import path, include from .views import home, all_countries urlpatterns = [ path("", home, name="home"), path("allcountries", all_countries, name="all_countries") ] allcountries.html {% extends '_base.html' %} {% … -
Upload file to database with file link
I am working on a project whereby the user has to upload a document. I have successfully been able to upload a file to the database and serve the user the uploaded file. I however want to upload files to the database using the file link rather than just selecting file from your device. models.py class Books(models.Model): title = models.CharField(max_length=500, default="") author = models.CharField(max_length=500, default="") publication = models.CharField(max_length=500, default="") edition = models.IntegerField(default="") is_available = models.BooleanField() book = models.FileField( default="", upload_to="books", validators=[validate_book_extension], verbose_name="books", ) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default="") class Meta: verbose_name_plural = "Books" def __str__(self): return self.title views.py def books(request): genres_names = Genre.objects.all() if request.method == "POST": form = BookFile(request.POST, request.FILES) files = request.FILES.getlist("book") genres_name = request.POST.get("genres") try: if form.is_valid(): new_old_genre, created = Genre.objects.get_or_create( genres=genres_name.lower() ) genre = Genre.objects.filter(genres=genres_name) if files: for f in files: names = str(f) name = names.strip(".pdf") Books.objects.create( genre=new_old_genre, book_title=name, book=f ) return redirect(index) except IntegrityError: messages.error(request, "value exist in database") return redirect(books) else: form = BookFile() return render(request, "books.html", {"form": form, "genres_names": genres_names}) forms.py class BookInfo(forms.ModelForm): class Meta: model = Genre fields = [ "genres", ] widgets = {"genres": forms.TextInput(attrs={"list": "genres"})} class BookFile(BookInfo): book = forms.FileField(widget=forms.ClearableFileInput(attrs={"multiple": True})) class Meta(BookInfo.Meta): fields = BookInfo.Meta.fields + [ "book", … -
cannot import name 'FieldDoesNotExist'
I am trying to run command: python3 manage.py runserver 0:80 and I get the below error Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib64/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 423, in check databases=databases, File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 416, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.6/site-packages/django/utils/functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 602, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.6/site-packages/django/utils/functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 595, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib64/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "/home/rc/qrd/qos-dashboard/config/urls.py", line 4, in from rest_framework_swagger.views import get_swagger_view File "/usr/local/lib/python3.6/site-packages/rest_framework_swagger/views.py", line 3, in from … -
Setup logging of Celery in Django correctly - how?
Setting up celery on our production server seems to be more complicated than it should be - and the problem is logging. Our setup is like this: Server is Ubuntu 20.04.5 LTS We run Django 3.2.8 in it's own user and group named "django" The Celery process also has it's own user and group named "celery". Celery is set up as a service and logs to /var/log/celery In celery.py we have set djangoConf pointing to the main settings.py On startup Celery tries to touch a django-logfile and - missing the permissions to do so - returns an error: Dec 16 10:57:27 h2989788 celery[128418]: Usage: celery [OPTIONS] COMMAND [ARGS]... Dec 16 10:57:27 h2989788 celery[128418]: Try 'celery --help' for help. Dec 16 10:57:27 h2989788 celery[128418]: Error: Invalid value for '-A' / '--app': Dec 16 10:57:27 h2989788 celery[128418]: Unable to load celery application. Dec 16 10:57:27 h2989788 celery[128418]: While trying to load the module theApp the following error occurred: Dec 16 10:57:27 h2989788 celery[128418]: Traceback (most recent call last): Dec 16 10:57:27 h2989788 celery[128418]: File "/usr/lib/python3.8/logging/config.py", line 563, in configure Dec 16 10:57:27 h2989788 celery[128418]: handler = self.configure_handler(handlers[name]) Dec 16 10:57:27 h2989788 celery[128418]: File "/usr/lib/python3.8/logging/config.py", line 744, in configure_handler Dec 16 10:57:27 h2989788 … -
Unable to install libapache2-mod-wsgi-py3
I am having some issues with wsgi and getting my django api up and running using apache. I think the issue is the mod_wsgi.so. I have already installed libapache2-mod-wsgi, but my venv is configured using python 3.6. Based on my research I think I need libapache2-mod-wsgi-py3. Trying to install with sudo yum install libapache2-mod-wsgi-py3 returns Loaded plugins: extras_suggestions, langpacks, priorities, update-motd amzn2-core | 3.7 kB 00:00:00 No package libapache2-mod-wsgi-py3 available. Error: Nothing to do Error log shows: Traceback (most recent call last): [Tue Dec 20 19:02:24.660246 2022] [:error] [pid 13266] File ".../project/project/wsgi.py", line 13, in <module> [Tue Dec 20 19:02:24.660275 2022] [:error] [pid 13266] from django.core.wsgi import get_wsgi_application [Tue Dec 20 19:02:24.660283 2022] [:error] [pid 13266] File ".../lib/python3.6/site-packages/django/__init__.py", line 1, in <module> [Tue Dec 20 19:02:24.660295 2022] [:error] [pid 13266] from django.utils.version import get_version [Tue Dec 20 19:02:24.660302 2022] [:error] [pid 13266] File ".../lib/python3.6/site-packages/django/utils/version.py", line 7, in <module> [Tue Dec 20 19:02:24.660313 2022] [:error] [pid 13266] from django.utils.regex_helper import _lazy_re_compile [Tue Dec 20 19:02:24.660319 2022] [:error] [pid 13266] File ".../lib/python3.6/site-packages/django/utils/regex_helper.py", line 10, in <module> [Tue Dec 20 19:02:24.660330 2022] [:error] [pid 13266] from django.utils.functional import SimpleLazyObject [Tue Dec 20 19:02:24.660336 2022] [:error] [pid 13266] File ".../lib/python3.6/site-packages/django/utils/functional.py", line 362, in <module> … -
Seeing a 500 internal server error with mod_wsgi, apache and django but nothing in the log file. Gunicorn runs without issue
We released some new code that depends on django-tree-queries and are now seeing an internal server error with mod_wsgi. There is nothing in the apache logs and nothing in the django logs. Normally when we have django erors we do see a stack trace in the logs and get an email. Here is our apache config: <VirtualHost IP_ADDR:443> ServerName our.url ErrorLog ${APACHE_LOG_DIR}/dev-ssl-error.log CustomLog ${APACHE_LOG_DIR}/dev-ssl-access.log combined LogLevel debug Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" SSLEngine on <Directory /var/www/django/app/config> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess apps-dev processes=2 threads=15 display-name=%{GROUP} WSGIProcessGroup apps-dev WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /var/www/django/app/config/wsgi.py RewriteEngine On RewriteCond %{REQUEST_METHOD} ^(OPTIONS|TRACE) RewriteRule .* - [F] </VirtualHost> Here is our wsgi.py file: activate_file = "/var/www/django/app/venv/bin/activate_this.py" exec(open(activate_file).read(), {"__file__": activate_file}) import os # noqa: E402 import sys # noqa: E402 from pathlib import Path # noqa: E402 from django.core.wsgi import get_wsgi_application # noqa: E402 ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent # This allows easy placement of apps within the interior # our_app directory. sys.path.append(str(ROOT_DIR / "our_app")) sys.path.append(str(ROOT_DIR)) # Explicitly set the settings module for this wsgi app os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.apps_dev" # Enable dot env file reading by default for this environment os.environ["DJANGO_READ_DOT_ENV_FILE"] = "True" # This application object is used by any WSGI server configured to … -
My django form is never valid. Why is this happening?
I have django application where I want user to be able to upload videos. My view looks like this: class CreateVideo(View): def post(self, request): videos = models.Video.objects.all().order_by('-created_on') form = forms.VideoUploadForm(request.POST) if form.is_valid(): print('form is valid') video = form.save(commit=False) video.save() print('video uploaded') else: print('form not valid') context = { 'video_list': videos, 'form': form, } return redirect('index') def get(self, request): videos = models.Video.objects.all().order_by('-created_on') form = forms.VideoUploadForm() context = { 'video_list': videos, 'form': form, } return render(request, 'videos/upload_video.html', context) My form: class VideoUploadForm(forms.ModelForm): class Meta: model = Video fields = ['title', 'description', 'file'] and model: class Video(models.Model): video_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True ) title = models.CharField(max_length=50, null=True) description = models.CharField(max_length=500, null=True) file = models.FileField(null=True) created_on = models.DateTimeField(default=timezone.now, null=True) at = models.ForeignKey(at, on_delete=models.CASCADE, null=True) and my template: <div> <form method="post"> {% csrf_token %} {{ form | crispy }} <button>Submit!</button> </form> </div> When I click submit button, I get: form not valid in terminal. I want form to be created, but form is just never valid. Where is the problem? -
How can I add a dyno for my deployed app in Heroku?
I deployed the app for Heroku successfully but when I check status with 'heroku ps' command I receive information that I have no dynos on the app. The app is created in Django. I tried to add a dyno for my app by browser on my account but there is not any option to do that. Is there a possibility that Procfile causes that issue? My Procfile (file without extension) command: web: gunicorn mywebsite.wsgi --log-file - I tried a lot of solutions from the internet and stackoverflow but my problem is still not solved. I would be grateful for any help. -
I don't know where to look
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I don't know where to look -
Django Sub Filter Brings Same Datas with Main Filter
I am making very simple business directory. I wanna display a list of firms that belong to a particular city and district, and belong to a certain category. But district filter and city filter brings same datas. How can i fix this? I filtered to district but again brings main city datas. Where is my fault? models.py class City(models.Model): city = models.CharField(max_length=50) slug = models.SlugField() def __str__(self): return str(self.city) class District(models.Model): district = models.CharField(max_length=50) slug = models.SlugField() city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return str(self.district) class FirmaCategory(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() class Meta: verbose_name_plural = 'Firma Kategorileri' def __str__(self): return str(self.title) class Firma(models.Model): category = models.ForeignKey(FirmaCategory, related_name="Firma", on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField() adres = tinymce_models.HTMLField() tel = tinymce_models.HTMLField() website = tinymce_models.HTMLField() email = tinymce_models.HTMLField() intro = tinymce_models.HTMLField() body = tinymce_models.HTMLField() city = models.ForeignKey(City,related_name="FirmaCategory" ,on_delete=models.CASCADE) district = models.ForeignKey(District,related_name="FirmaCategory", on_delete=models.CASCADE) #url = models.CharField(max_length=255) date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Firmalar' def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('firma-frontpage') views.py def firmaana(request): firmalar = Firma.objects.all() context = { 'firmalar': firmalar } return render(request, 'firma/firma-frontpage.html', context) def firmadetail(request, slug): firmax = Firma.objects.get(slug=slug) context = { 'firmax': firmax, } return render(request, 'firma/firma-detail.html', context) def firmacategory(request, slug): firmacategory = FirmaCategory.objects.get(slug=slug) context … -
Can't download working dxf file generated by ezdxf from django server
Generated dxf file (ezdxf) from django server using below code: bio = io.StringIO() document.write(bio) # save to memory stream length = bio.tell() bio.seek(0) # rewind the stream response = HttpResponse( bio.getvalue(), # use the stream's contents content_type="image/x-dxf", ) response["Content-Disposition"] = 'attachment; filename = {0}'.format(cab.split(' ')[1] + ".dxf") response["Content-Encoding"] = "UTF-8" response['Content-Length'] = length return response is missing the last few lines, including the EOF line. Compared to a dxf file obtained simply by document.save() What needs to be added to the code so that the downloaded dxf file is identical to the saved dxf file? -
WebSocket django channels doesn't work with postman
Django Channels Throw error with postman while working well with Html. I'm following Django Socket Tutorial "here's the error showing in Django". WebSocket HANDSHAKING /ws/chat/roomName/ [127.0.0.1:56504] WebSocket REJECT /ws/chat/roomName/ [127.0.0.1:56504] WebSocket DISCONNECT /ws/chat/roomName/ [127.0.0.1:56504] "Error showing in postman when connecting to ws://127.0.0.1:8000/ws/chat/roomName/" Sec-WebSocket-Version: 13 Sec-WebSocket-Key: fSSuMD2QozIrgywqTX38/A== Connection: Upgrade Upgrade: websocket Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits Host: 127.0.0.1:8000 My Code asgi.py django_asgi_app = get_asgi_application() import digital_signage.playlist_management.routing application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(digital_signage.playlist_management.routing.websocket_urlpatterns)) ), } ) consumer.py class ChatConsumer(WebsocketConsumer): def connect(self): print("self", self) self.accept() -
Switching from LDAP to AD LDAPS using Python Django
Converting authentication from LDAP to AD LDAPS Python + Django ============== Following Django Docs: https://django-auth-ldap.readthedocs.io/en/latest/authentication.html OLD: AUTH_LDAP_SERVER_URI = "ldap://ldap-example.test.com" NEW: AUTH_LDAP_SERVER_URI = "ldaps://ad.example.com" ============== I have worked with the AD administrator to set these values correctly. I changed the values themselves for obvious privacy reasons. AUTH_LDAP_BIND_DN = "cn=ex-test,cn=user,dc=test,dc=ad" AUTH_LDAP_BIND_PASSWORD = "{PASSWORD}" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=sites,dc=test,dc=ad",ldap.SCOPE_SUBTREE,"(uid=%(user)s)") AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS: 0} AUTH_LDAP_USER_DN_TEMPLATE = "cn=%(user)s,ou=sites,dc=test,dc=ad" AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_GROUP_SEARCH = LDAPSearch("cn=priv-ex,ou=due,ou=ldap,ou=shared,dc=test,dc=ad", ldap.SCOPE_SUBTREE) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='cn') AUTH_LDAP_USER_ATTR_MAP = { "first_name": "usersName", "last_name": "usersLastName", "email": "usersEmail" } AUTH_LDAP_REQUIRE_GROUP = "cn=DUE-MAIN,ou=DUE,ou=Applications,ou=Sharing,o=LDAP" ============== Problem It will not work for login. I do not know what I am doing wrong as I am following the docs precisely. Questions Q1: Is there anyway I can test the connection from a terminal or command line? Q2: I have seen the django-pyad package recommened with a settings.py that looks like # settings.py AUTHENTICATION_BACKENDS = [ 'django_pyad.backend.ADBackend', ] # AD configuration AD_LDAP_SERVER = "ad.example.com" AD_NT4_DOMAIN = "example" AD_SEARCH_DN = "OU=Users,DC=ad,DC=example,DC=com" Should I scrap what I did for the previous LDAP tree and go this route instead? Or can I re-use the previous LDAP connection code but change the values for AD like I am doing now? -
How to store data typed by user into input using Django
Im kinda new to django and i got stuck I want to get user input, and after that i want to display value which depend on it For example in djanog i have if statment which checking input from user, for exaple car model. So, when user type Ibiza i want to display "Seat", user type E92 i want to dispaly "BMW" etc I want to display car brands in list which can be cleard or dissapear after user close tab and re-open. Which solution is the best? Database in django? Cookies? Local storage in javascript? -
Mod_wsgi server will not start up
I am moving a currently working Django project to a new Red Hat server and upon moving the project, it's virtual env, and installing pip packages I started up the server how I always have and it worked fine. Going back to it a week later I enter in the web address of the django site and it times out. The mod_wsgi error log reads. [Tue Dec 20 17:55:49.282343 2022] [core:warn] [pid 831143:tid 139775964862784] AH00098: pid file /tmp/mod_wsgi-localhost:8080:21056/httpd.pid overwritten -- Unclean shutdown of previous Apache run? [Tue Dec 20 17:55:49.283800 2022] [mpm_event:notice] [pid 831143:tid 139775964862784] AH00489: Apache/2.4.37 (Red Hat Enterprise Linux) mod_wsgi/4.9.4 Python/3.6 configured -- resuming normal operations [Tue Dec 20 17:55:49.283823 2022] [core:notice] [pid 831143:tid 139775964862784] AH00094: Command line: 'httpd (mod_wsgi-express) -f /tmp/mod_wsgi-localhost:8080:21056/httpd.conf -D MOD_WSGI_KEEP_ALIVE -D MOD_WSGI_MPM_ENABLE_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_WORKER_MODULE -D MOD_WSGI_MPM_EXISTS_PREFORK_MODULE -D FOREGROUND' I can't figure out what this error indicates is happening. httpd.pid overwritten -- Unclean shutdown of previous Apache run? I've even restarted the apache server that runs on this server and it has done nothing. -
Getting data from another Foreign key - DRF
The relations of tables are shown in the picture. I have a main Table named Product. Two tables ProductImage , OrderedProduct have a Foreign key set to it. Now, I want to retrieve the image from OrderedProduct. How should I write the code for Serialization for it? Thanks Models.py Visualization This is my model.py file: class Product(models.Model): name = models.CharField(max_length=50) description = models.TextField() def __str__(self) -> str: return self.name class ProductImage(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='product_images') image = models.ImageField(upload_to="images/", null=True, blank=True) class OrderedProduct(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='ordered_products') quantity = models.IntegerField() Serializers.py class OrderedProductSerializer(serializers.ModelSerializer): product_name = serializers.CharField(source='product.name') product_price = serializers.FloatField(source='product.price') # product_img = >>> what should I do here? <<< class Meta: model = OrderedProduct fields = ('user', 'product', 'quantity', 'delivered', 'product_name', 'product_price', 'product_img') I've read the documentation, asked in some programming groups but couldn't find any good solution. I am expecting someone to give a reference that leads to the solution. -
How to upload an image to django from an html input file
I am developing a web service on django with frontend on react. I ran into a problem that I can't upload an image to django. Below is my component code where I'm trying to download it: export function ProviderRegistration(){ const[logoField, setLogoField] = useState() const token = useSelector((state) => state.user.token) const [cookie, setCookie] = useCookies(['auth']) const confirm = () => { axios.post(`/providers/?username=${cookie.auth.login}`, { photo : logoField }, { "headers" : { "Authorization" : "token " + token }}) .then(res => console.log(res)) .catch(err => console.log(err)) } return( <div className="registration-provider-container"> <div className="registration-title">Provider registration</div> <input type="file" className="registration-logo-add" onChange={(e) => setLogoField(e.target.value)}/> <button className="registration-confirm" onClick={() => confirm()}>Confirm</button> </div> )} And the endpoint processing this request class Providers(viewsets.ModelViewSet): filterset_class = ProvidersFilter queryset = Provider.objects.all() permission_classes = [IsAuthenticatedOrReadOnly, IsProviderPermission, IsOneToOneProviderPermission] def get_serializer_class(self): if self.action == 'list': return GetProviderSerializer else: return PutProviderSerializer def create(self, request): username = request.GET.get('username', '') user = User.objects.get(username=username).pk request.data.update({'user' : user}) print(request.data) return super().create(request) When I try to upload an image, django returns the following error: "The submitted data was not a file. Check the encoding type on the form." And I haven't found a way to correctly upload an image to django using Ajax. I also output what my browser sends to the server: … -
Using Model.objects.filter in Form prevents me from updating Model
I have a form setup like this where I use the values from TestModel to create a select field in a form. However if I want to update the TestModel to add a new column, Django gives me a psycopg2.errors.UndefinedColumn saying the new column is not found on the table and the stack trace points back to this form ModelChoiceField. Its not until I comment out this select that I am able to make the migration to the database. So my question is there a better way to setup this ModelChoiceField where I don't have to comment it out to update the underlying model on the database? I'm using Django 4.0 and python 3.8 for reference. class TestModelChoiceField(forms.ModelChoiceField): """ Overwriting model choice field attribute to use a different __str__ representation than the default model """ def label_from_instance(self, obj): return obj.test_field class TestForm(forms.Form): first_select = TestModelChoiceField( queryset=TestModel.objects.filter(model_attribute__isnull=False), initial=TestModel.objects.filter(model_attribute__isnull=False) .filter(test_field="Yes") .first() .team_id, label="Field One:", ) -
Creating a simple multiple users app in Django
So I've created 3 different users: admins, developers, and project managers. When I use the individual signup forms for each of these users and log out, it works, but then I when try to use the login form, it seems to me that it's acting like the signup form. Because when I input the same user details as the one I just created into the login form, it throws up the built-in error message, 'A user with that user name already exists' I'm not sure how to proceed from here. Here's what I have so far. models.py class CustomUser(AbstractUser): ACCOUNT_TYPE_CHOICES = ( ('admin', 'Admin'), ('developer', 'Developer'), ('project_manager', 'Project Manager') ) account_type = models.CharField(max_length=20, choices=ACCOUNT_TYPE_CHOICES) login and signupviews class LoginView(View): def get(self, request): # Render the login form form = LoginForm() return render(request, 'users/login.html', {'form': form}) def post(self, request): # Get the form data from the request form = LoginForm(request.POST) # Validate the form data if form.is_valid(): # Get the username and password from the form username = form.cleaned_data['username'] password = form.cleaned_data['password'] # Authenticate the user user = authenticate(request, username=username, password=password) # If the user is authenticated, log them in and redirect to the homepage if user is not None: login(request, … -
How to show print diagloue box in browser in Django?
I am trying to get the print dialogue box in my Django app. Currently its downloading in my local computer. But when I am serving in apache server, its not working. my views.py def download(request,lothash): lot=lotnumber.objects.get(lot_hash=lothash) postdata = request.POST array = postdata.get("array", None).split(",") template=lot.template_type f = open(f"/home/username/public_html/nitin2/media/{template.template_file}", "r") txt=(f.read()) df=pd.read_excel("/home/username/public_html/nitin2/media/"+str(lot.file)) df = df.reset_index() n=1 k=0 for index, row in df.iterrows(): if n>len(array)+1: break if str(n) in array: txt = txt.replace("(As Provided by Bank)", str(row['RGN_A'])) txt = txt.replace("(Customer Name)", str(row['Applicant Name'])) txt = txt.replace("(Customer Address)", str(str(row['Address1']) + " " + str(row['Address2']) + " " + str(row['Address3']))) txt = txt.replace("(Product)", str(row['Product'])) txt = txt.replace("(LAN)", str(row['LAN'])) txt = txt.replace("(Notice Amount)", str(row['Notice Amount'])) # save FPDF() class into a # variable pdf pdf = FPDF() # Add a page pdf.add_page() # set style and size of font # that you want in the pdf pdf.set_font("Arial", size = 12) # insert the texts in pdf newtxt=splitlinesoftext(txt) for x in newtxt: pdf.multi_cell(0, 5, txt = x, align = 'L',border=0) downloads_path = str(Path('/home/username/public_html/nitin2/media/') / "Downloads/nitin").replace('\\','/') if not os.path.isdir(f"{downloads_path}/{str(row['Applicant Name'])}"): os.makedirs(f"{downloads_path}/{str(row['Applicant Name'])}") pdf.output(f"{downloads_path}/{str(row['Applicant Name'])}/document.pdf", 'I') #pdf.output(f'document.pdf', 'D') template=lot.template_type f = open(f"/home/username/public_html/nitin2/media/{template.template_file}", "r") txt=(f.read()) k=k+1 n=n+1 return JsonResponse({'context': "done"}) I want now to show download dialogue box. Currently if … -
Need help about redirecting views in Django
I a beginner in learning Django and have met with an issue that need everyone help. I'm working on a web application for reading novels. I met with an issue that is related to views redirecting in Django. It's about how I can open the chapter page that I clicked on and read it perfectly normal but when I want to return to the novel index page by clicking on the link, I'm met with a NoReverseMatch error. I'll post my code below: This is what I configured in the urls.py: Then I created and configured the urls.py like this: And this is my views.py: The part that I've met with issue is an Html page for viewing chapter: What I have in mind is that by clicking on the url, I'll be redirected to the novel index page. But what happened is that I'm met with the NoReveseMatch error because the part that should have the slug that point to the index page is blank so I can't redirect to it. Anyone have an idea of what I did wrong ? Any helps or suggestions are appreciated