Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle FileNotFound error when using img tag using mark_safe in django admin
I am importing images into AWS S3 using django-storages. However, if Django admin does not have the corresponding image in S3, Admin would like to issue a FileNotFoundError to correct the S3BotoStorage object or fix the underlying problem to handle the error. admin/hospital.py class HospitalAdmin(OrderedInlineModelAdminMixin, IdFieldIncludedModelAdmin): list_display = ("name", "tags_comma_separated", "created_at") list_display_links = ("name",) list_filter = [TagFilter] fieldsets = ( (None, {"fields": ("user",)}), ( None, { "fields": ( "logo_image", "logo_image_width", "logo_image_height", "logo_image_preview", "name", "description", "address", "longitude", "latitude", "near_station_name", "phone_number", "sms_phone_number", ) }, ), ( None, { "fields": ( "created_at", "updated_at", ) }, ), ) readonly_fields = [ "logo_image_width", "logo_image_height", "logo_image_preview", "created_at", "updated_at", ] ... # FileNotFound Error occurs in the lower part @display(description="preview log image") def logo_image_preview(self, obj): return mark_safe( '<img src="{url}" width="{width}" height="{height}" />'.format( url=obj.logo_image.url, width=obj.logo_image.width, height=obj.logo_image.height, ) ) I added a try/except statement to the error part to generate a correct error, but it doesn't seem to solve the fundamental problem try: return mark_safe( '<img src="{url}" width="{width}" height="{height}" />'.format( url=obj.logo_image.url, width=obj.logo_image.width, height=obj.logo_image.height, ) ) except FileNotFoundError as e: return str(e) -
Django NoReverseMatch Error while testing: 'testapp' is not a registered namespace
Hii i try to test my url easily with TestCase and reverse, but i get NoReverseMatch error. urls.py from django.urls import path from . import views app_name = "testapp" urlpatterns = [ path("", views.index, name="index"), ] tests.py from django.test import TestCase from django.urls import reverse class BasicTests(TestCase): def test_index(self): response = self.client.get( reverse('testapp:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "Hello World") And the error: ERROR: test_index (mysite.tests.BasicTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "django\myvenv\lib\site-packages\django\urls\base.py", line 71, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'testapp' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "django\mysite\mysite\tests.py", line 7, in test_index reverse('testapp:index')) File "django\myvenv\lib\site-packages\django\urls\base.py", line 82, in reverse raise NoReverseMatch("%s is not a registered namespace" % key) django.urls.exceptions.NoReverseMatch: 'testapp' is not a registered namespace What am I missing here? -
Django PasswordResetView does not work for inactive users
I have a simple django app where users can create and login to their accounts. When a user is registering for a new account, the user object is created and saved in the database with the is_active flag set to false. Once the user clicks the confirmation email, the user object has its is_active flag set to true. I have built out a password reset flow using Django's views: PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, and PasswordResetCompleteView. Everything works as expected unless I am trying to reset the password for an account which has not yet been activated (is_active == False), in which case, the reset password email is never sent to the user. The edge case I am considering here is for a user who created an account, and never clicked the registration link which expires after 72 hours, and thus have a user account which exists but is not active. Then the user wants to get a new registration link, and to do so I require a user to enter their username and password (so that no malicious actors can spam a random users email inbox with new registration link emails). If the user has since forgotten their password, they are … -
Displaying Countdown in Django Loop not working properly when clicked
Hi I have the following Countdown in Javascript, which is inside a Django for loop and it is showing more than once. In my current situation when I click on any of the countdown start button only the first one works. I want to be able to click on any of them and each on of them work separetly when clicked not simultaneously. here is the Script: <button id="myBtn" onclick="myFunction()" type="button" class="btn btn-warning"> <i class="fa-solid fa-play" style="margin-right:2px"></i> <span id="demo" class="countdown-live" style="text-align:center;"></span> </button> <script type="text/javascript"> var countDownDate = new Date(Date.now() + 45000).getTime(); var x = setInterval(function() { var now = new Date().getTime(); var distance = countDownDate - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); document.getElementById("demo").innerHTML = minutes + " : " + seconds + " "; if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = 'Done'; } }, 1000); </script> My question: How to click on any of the countdown buttons inside the django … -
How to show all the tags related to a publication in a list of publications filtered by a tag in Django?
Consider following models: # models.py from django.db import models class Tag(models.Model): name = models.CharField() number_of_publications = models.PositiveIntegerField() class Publication(models.Model): text = models.TextField() tags = models.ManyToManyField(Tag) # urls.py from .views import publications_tagged urlpatterns = [ path('/questions/tagged/<str:name>', publications_tagged) ] # views.py from .models import Tag, Publication from django.shortcuts import get_object_or_404, render def publications_tagged(request, name): tag = get_object_or_404(Tag.objects.prefetch_related('tags_set'), name=name) return render(request, 'myapp/tagged_questions.html', {'tag': tag}) Ok, so when we'd go to a template and make a for-loop that will create a representation of every publication and show appropriate tags of it, Django would make a database call for every publication to fetch all the tags the publication has, meaning: Iteration x of tag.tags_set -> check what tags match with publication X. Of course, we can just not show tags and everything will work like magic (utilizing prefetch_related), but that's not what we want :) How could we do something similar in Django? What we want is some kind of optimized way to achieve such a result, because stackoverflow renders 15 items really fast, which makes me think they do not do it the monkey way that Django does by default. This is what html might look like P.S. My problem doesn't quite sound like … -
How can I prevent row duplicates in Django when no field is unique?
Upon saving an object, is there a simple way to prevent duplication when the combination of all the fields together have the same data? The unique=True parameter doesn't seem to help here, because individually any of the data could be duplicated, but never all of them at the same time. If statement with several and conditions does not seem to me like a smart way so I'm looking for a better approach. Does Django provide it? All I could find was related to one field or other being duplicated. Ex.: if Model.objects.filter(field_A=source_A).exists() == True and Model.objects.filter(field_B=source_B).exists() == True and Model.objects.filter(field_C=source_C).exists() == True: continue else: *save object* -
Django rest framework write / update nested serializer
How to write and update nested serializer in drf. I have two models. Just an example below. Class Account (AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True Class USerProfile(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) address_line_1 = models.CharField(max_length=100) address_line_2 = models.CharField(max_length=100) phone = models.IntegerField(null=True) already have an AccountSerilaizer for Registration view class AccountSerializer(ModelSerializer): confirm_password = CharField(write_only=True) class Meta: model = Account fields = ["first_name", "last_name", "email", "password", "confirm_password"] extra_kwargs = { "password": {"write_only": True}, } def validate_email(self, value): qs = Account.objects.filter(email__iexact=value) if qs.exists(): raise ValidationError("Email already exists") return value def validate(self, attrs): if attrs.get("first_name") == "" or attrs.get("last_name") == "": raise ValidationError("Names cannot be blank") return attrs def validate_password(self, data): if len(data) < 8: raise ValidationError( "Password should be atleast 8 digits or characters or letters" ) return data def validate(self, data): if data["password"] != data.pop("confirm_password"): raise ValidationError({"error": "Passwords donot match"}) return data def create(self, validated_data): user = Account.objects.create_user(**validated_data) return user def update(self, instance, validated_data): instance.first_name = validated_data.get("first_name", instance.first_name) instance.last_name = validated_data.get("last_name", instance.last_name) instance.email = validated_data.get("email", instance.email) instance.save() return instance So UserProfile is FK to Account, how to update/write UserProfile and how to get request.user inside serializer during create/update method and I'm using JWT Authentication. There is a third … -
STL viewer on web browser?
I developing a Django application that can upload STL. How to view the STL on a web browser? Does anyone know of anything that may be able to help? -
Django rest_framework : count objects and return value to serializer
i need to count all supporters in model and return value to serializer models.py class Supporters(models.Model): name = models.CharField(max_length=255) img = models.ImageField(upload_to="Supporters", blank=True, null=True) serializers.py class SupportersSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() supporters_count = serializers.SerializerMethodField() class Meta: model = Supporters fields = ("id", "name", "img", "supporters_count") def get_supporters_count(self, obj): return obj.supporters_count.count() views.py class SupportersViwe(generics.RetrieveAPIView): queryset = Supporters.objects.all() def get(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = SupportersSerializer(queryset, many=True) return Response(serializer.data) -
My function to check for ajax on a page is not working
I am making a django project where there is a search/filter dropdown for a form. I am using select2 and ajax. It isn't working, and when I try to debug with print statements, it seems that the is_ajax(request) function is not returning true. I know the is_ajax() function was deprecated in JQuery, which is why I defined it myself. However, mine doesn't seem to work either. Here is the portion my view that filters objects: @login_required def job_application_create(request): form = JobApplicationForm() if is_ajax(request): print('TESTING TESTING TESTING TESTING TESTING TESTING TESTING TESTING ') term = request.GET.get('term') companies = Company.objects.filter(name__icontains=term) response_content = list(companies.values()) return JsonResponse(response_content, safe=False) and here is the is_ajax(request) definition: def is_ajax(request): return request.headers.get('x-requested-with') == 'XMLHttpRequest' I also tried this function: def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' Here is the JS in the page that has my form: <script> $(document).ready(function () { $('#id_company').select2({ ajax: { url: "{% url 'homepage' %}", dataType: 'json', processResults: function (data) { return { results: $.map(data, function (item) { return {id: item.id, text: item.name}; }) }; } }, minimumInputLength: 1 }); }); </script> -
Making a functional contact form using django
I'm created a website for a friend. I have created a contact form which he would like people to use and the messages will directly be sent to his own personal email address. I can't seem to get it working. I'm currently testing using my own outlook account and eventually would like to be using his Gmail account. please see my code below. Any input would be greatly appreciated. I did end up getting it working using mailtrap, but as far as im aware i would need to pay to redirect to an email address of my choosing? Settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_HOST_USER = 'email@email.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 Contact.html {% extends 'portfolio/main.html' %} {% block content %} {% load crispy_forms_tags %} <!--Section heading--> <h2 class="h1-responsive font-weight-bold text-center my-4"> Contact vstheworld </h2> <!--Section description--> <p class="text-center w-responsive mx-auto mb-5"> Do you have any questions? Please do not hesitate to contact us directly. Our team will come back to you within a matter of hours to help you. </p> <!-- Wrapper container --> <div class="container py-4"> <form method="POST"> {% csrf_token %} {{form|crispy}} <div class="d-grid"> <br> <button class="btn btn-dark btn-lg" id="form-submit" type="submit"> Submit </button> … -
How to query database and display on charts.js in django
Hi I am trying to display all marketplace as label and the quantity of infringements in those marketplace as data on a pie chart. Please help. dashboard.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- semantic UI --> <link rel="stylesheet" type='text/css' href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.14/semantic.min.css"> <!--Chart js--> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" integrity="sha256-Uv9BNBucvCPipKQ2NS9wYpJmi8DTOEfTA/nH2aoJALw=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" integrity="sha256-aa0xaJgmK/X74WM224KMQeNQC2xYKwlAt08oZqjeF0E=" crossorigin="anonymous" /> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> {% block title %}Dashboard{% endblock title %} {% block scripts%} <script> $(document).ready(function(){ const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'pie', data: { labels: [{% for infringement in qs %}'{{infringement.marketplace}}',{% endfor %}], datasets: [{ label: '% Breakdown', data: [{% for infringement in qs %}{{infringement.id}},{% endfor %}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); }); </script> {% endblock scripts%} {% block content %} <canvas id="myChart" width="200" … -
How to add Javascript file into html Django
I want to use Javascript file in my Django project. But somehow I can't figure out how to import it into my html file. I tried to add it same way as I did my css file but it doesn't work. On load it shows always the same error : "Uncaught ReferenceError: fun1 is not defined at onload". Project structure: Js file, coding.js: function fun1(){ alert("It works!") } Html file, index.html: <script src="{% static '/js/coding.js' %}"></script> and as I mentioned, the css file, the line above, works just fine: <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/> Adding type: text/javascript doesn't fix it. -
Google Cloud Run for Django, Cloud Build fails for psycop2-binary
I have been successfully using Google Build for continuous integration with Google Cloud Run for the Django Application. However recently psycop2-binary started giving errors as below Step #0 - "Buildpack": ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 202.7/202.7 kB 28.3 MB/s eta 0:00:00 Step #0 - "Buildpack": Collecting google-cloud-build==3.9.0 Step #0 - "Buildpack": Downloading google_cloud_build-3.9.0-py2.py3-none-any.whl (88 kB) Step #0 - "Buildpack": ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 88.2/88.2 kB 13.0 MB/s eta 0:00:00 Step #0 - "Buildpack": Collecting psycopg2-binary==2.9.3 Step #0 - "Buildpack": Downloading psycopg2-binary-2.9.3.tar.gz (380 kB) Step #0 - "Buildpack": ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 380.6/380.6 kB 39.3 MB/s eta 0:00:00 Step #0 - "Buildpack": Preparing metadata (setup.py): started Step #0 - "Buildpack": Preparing metadata (setup.py): finished with status 'error' Step #0 - "Buildpack": error: subprocess-exited-with-error Step #0 - "Buildpack": Step #0 - "Buildpack": × python setup.py egg_info did not run successfully. Step #0 - "Buildpack": │ exit code: 1 Step #0 - "Buildpack": ╰─> [25 lines of output] Step #0 - "Buildpack": /layers/google.python.runtime/python/lib/python3.11/site-packages/setuptools/config/setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. Step #0 - "Buildpack": warnings.warn(msg, warning_class) Step #0 - "Buildpack": running egg_info Step #0 - "Buildpack": creating /tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info Step #0 - "Buildpack": writing /tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info/PKG-INFO Step #0 - "Buildpack": writing dependency_links to /tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info/dependency_links.txt Step #0 - "Buildpack": writing top-level names to /tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info/top_level.txt … -
SMTPServerDisconnected at /account/signup/ using django-allauth on Google Cloud Run and Workspace smtp-relay
I've attempted the various recommended config options and my SMTP relay works perfectly locally, but fails when deployed in my Google Cloud Run service with the following error: SMTPServerDisconnected at /account/signup/ Connection unexpectedly closed ... File "/usr/local/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 67, in open self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile) File "/usr/local/lib/python3.9/smtplib.py", line 764, in starttls self.ehlo_or_helo_if_needed() File "/usr/local/lib/python3.9/smtplib.py", line 607, in ehlo_or_helo_if_needed (code, resp) = self.helo() File "/usr/local/lib/python3.9/smtplib.py", line 436, in helo (code, msg) = self.getreply() File "/usr/local/lib/python3.9/smtplib.py", line 400, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") The relevant settings for my SMTP config from settings.py: EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_HOST_USER = env('EMAIL_HOST_USER', default=None) # according to the traceback the credential env variables are pulling through correctly EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD', default=None) EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER I am building from a Dockerfile, so as an additional attempt to fix, I added EXPOSE 587/tcp, which seems to have no impact. This doc from Google seems to suggest there is nothing blocking it, although it doesn't explicitly refer to the Cloud Run service. Less secure apps is also enabled and I am using a generated app password from the email host account. Unsure if there are any settings I am missing to account for my setup … -
Django admin panel add custom view that not depends on any model
I'm trying to add a custom view in Django admin panel under the localhost:8000/admin/my_view and getting "Page not found 404" response. Why don't django admin panel see url to my custom page? Here is my admin.py file: from django.contrib import admin from django.template.response import TemplateResponse from .models import * class MyAdminSite(admin.AdminSite): site_header = 'BeautyShop' site_title = site_header def get_urls(self): from django.urls import path urls = super().get_urls() urls += [ path('my_view/', self.admin_view(self.my_view)) ] return urls def my_view(self, request): data = {"MyName": "MyName"} return TemplateResponse(request, "my_view.html", context=data) def get_app_list(self, request): apps = [{'name': 'Additional options', 'models': [ {'name': 'Update dictionaries', 'perms': {'change': True}, 'admin_url': 'my_view/' } ] }] return apps + super().get_app_list(request) admin_site = MyAdminSite() # Register your models here. admin_site.register(Product) admin_site.register(Review) admin_site.register(Order) admin_site.register(OrderItem) admin_site.register(ShippingAddress) and urls.py from base.admin import admin_site from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin_site.urls), path('', TemplateView.as_view(template_name='index.html')), path('api/products/', include('base.urls.product_urls')), path('api/users/', include('base.urls.user_urls')), path('api/orders/', include('base.urls.order_urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In settings.py I added os.path.join(BASE_DIR, 'backend/templates/') to the TEMPLATES -
How to combine methods with each other?
I try to combine some methods with eatch other for outputting some values. So the individual methods are working. But when I combine them there is no output. So I have this two methods: def total_fruit_per_sort(self): #self.extractingText.extract_text_from_image(filename) number_found = re.findall(self.total_amount_fruit_regex( ), self.extractingText.text_factuur_verdi[0]) fruit_dict = {} for n, f in number_found: fruit_dict[f] = fruit_dict.get(f, 0) + int(n) return str({value: key for value, key in fruit_dict.items()}).replace("{", "").replace("}", "") and: def verdi_total_fruit_cost_regex(self): fruit_list = self.fruit_list(format_="(?:{})".format) return self.regex_fruit_cost(f"(?:{fruit_list})") and the method that combines them: def show_extracted_data_from_file(self, file_content): self.extractingText.extract_text_from_image(file_content) regexes = [ self.verdi_total_fruit_cost_regex(), self.total_fruit_per_sort() ] matches = [self.findallfruit(regex) for regex in regexes] return "\n".join(" \t ".join(items) for items in zip(*matches)) this is the fruit_list: def fruit_list(self, format_=re.escape): """ Return a string with all the fruit words, escaped or formatted for use in a regex """ return "|".join(format_(word) for word in self.extractingText.list_fruit) and the list of fruit: self.list_fruit = ['Appels', 'Ananas', 'Peen Waspeen', 'Tomaten Cherry', 'Sinaasappels', 'Watermeloenen', 'Rettich', 'Peren', 'Peen', 'Mandarijnen', 'Meloenen', 'Grapefruit', 'Rettich'] findallfruit: def findallfruit(self, regex): return re.findall(regex, self.extractingText.text_factuur_verdi[0]) and one example string for extracting the data: "[' \n\na)\n\n \n\nFactuur\nVerdi Import Schoolfruit\nFactuur nr. : 71201 Koopliedenweg 33\nDeb. nr. : 108636 2991 LN BARENDRECHT\nYour VAT nr. : NL851703884B01 Nederland\nFactuur datum : 10-12-21\nAantal Omschrijving Prijs Bedrag\nOrder … -
create customer for a user in django
My website can create users via the google sign-in option. My Django model is for multi-type users like customers, merchants, etc. A customer-type user has cart functionality along with miscellaneous. To perform these functionalities, users must have customer instance. For this I have to create customers for the users who are logged in via google. What are the possible ways to accomplish this? -
how to access list of all url names in django?
how can I access to all url names in django? for site setting I need to list all url names. but I can`t find this item dynamic in django. I was try to list all urls with code but that`s not work. Because I cal that function in model file and in choices part and that returns a empty list. -
process 2 forms from 2 html files in Django
Sorry for my bad english I've got "topics.html" file, that extends "base.html". In "base" I've got search form. In "topics" I've got any checkboxes. How can I connect 2 forms in 1 request? Base: <form id="form_1" action="{% url 'topics' %}"><input type="search" id="search" name="search" placeholder="Search"></form> Topics: <form id="form_1" action="{% url 'topics' %}"> <div class="typess"> <h1 class="vk">Categories:</h1> {% for typee, name in types.items %} <label> <input type="checkbox" style="display:none" value="{{ typee }}" name="category" {% if typee in categories %} checked {% endif %}> <span class="typee" title="{{ name }}"><i class="{{ typee }}"></i>{{ name }}</span> </label> {% endfor %} </div> </form> It should connect in "topics" function: def topics(request): info = [] categoriess = request.GET.getlist('category') typess = request.GET.getlist('type') search = request.GET.get('search') if categoriess: ... But when I run code, it's not see the checkboxes -
Is there a way to enable secure websockets on Django?
I can't use secure websockets on Django with the sll enabled. I use the sslserver package for Django to allow HTTPS on the development server. My goal is to make a secure chat. Here is the configuration : INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sslserver', 'accounts', 'chat', ] #WSGI_APPLICATION = 'sendapp.wsgi.application' ASGI_APPLICATION = 'sendapp.asgi.application' # LEARN CHANNELS CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" }, } Concerning the asgi file : os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sendapp.settings') application = ProtocolTypeRouter({ 'https': get_asgi_application(), 'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns)) }) I start the Django server this way : python .\manage.py runsslserver --certificate .\sendapp\certif.crt --key .\sendapp\code.key 0.0.0.0:8000 I understand that to use secure websockets, you have to use a Daphne server. So I tried to run it in its basic configuration in the root of manage.py : daphne sendapp.asgi:application but i have this error code in the shell : 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. Does anyone have a solution to this error message ? -
"save() got an unexpected keyword argument 'commit'" error in functional view
I got this error in my functional view: save() got an unexpected keyword argument 'commit' I'm try to save one object in database. 'debtors' is Many to Many field in models.py. forms.py class ExpenseForm(forms.ModelForm): class Meta: model = Expense fields = ('amount', 'text', 'debtors', 'date', 'time',) widgets = { 'date': AdminDateWidget(), 'time': AdminTimeWidget(), 'debtors': forms.CheckboxSelectMultiple(), } views.py def expenseformview(request, pk): if request.method == 'POST': form = Expense.objects.create( expenser = request.user, amount = request.POST.get('amount'), text = request.POST.get('text'), date = request.POST.get('date'), time = request.POST.get('time'), ) form.debtors.add(request.POST.get('debtors')) formcoseshare = form.save(commit=False) formcoseshare.save() form.save_m2m() return redirect('expense_detail', pk=pk, expenseid=form.id) else: form = ExpenseForm() return render(request, 'financials/expense_form.html', {'form': form}) How can to solve this problem? -
How to use django for dapp project?
I'm trying to build an auction app with solidity and React but I need some server to handle data and internal logic and I don't know what tool to use for the backend for these reasons: when just using react and solidity it's not fast. when using Django and web3py, I can't transfer money with Metamask. I've heard about Next.js and Node.js as the backend but I cant decide. I would appreciate any help. -
Register view in Django with edited UserCreationForm not working
I am using Django to build an app for a school project. My authentication attempt using Django's auth and Usercreationform (but modifying it to include email) doesn't seem to work. I already tested my login/logout views using my admin user and that is working pretty fine, but I can't seem to save new users in my application. I had to modify the user creation form to include email because in the future I'm suppossed to filter what kind of emails people register in the app with (only institutional emails are intended to work on this app, but I haven't implemented it yet), but everytime I submit my user register form it says the form is invalid in debugging. I created a form in forms.py from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class CustomUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] in my views.py I imported the form and set it to debug which fields are failing when the form is not valid from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from .forms import CustomUserForm def register_view(request): form = CustomUserForm(request.POST) if form.is_valid(): user_obj = form.save() form.save() return redirect('/login') else: print("FORM IS INVALID.") for field in … -
How to submit the Individual Fieldset in a Form
I have a form and inside it there are 4 fieldset, what I am trying to do is that when a user click on the "Next" button in the first fieldset, the button should work as both a submit button and a next button, or it should first submit the fieldset and then move to another fieldset. I am using Bootstrap-5 and Django My code and too long so I found a similar one on the net, and it is as follows:- You can find it here here and here the code:- HTML: <!-- MultiStep Form --> <div class="container-fluid" id="grad1"> <div class="row justify-content-center mt-0"> <div class="col-11 col-sm-9 col-md-7 col-lg-6 text-center p-0 mt-3 mb-2"> <div class="card px-0 pt-4 pb-0 mt-3 mb-3"> <h2><strong>Sign Up Your User Account</strong></h2> <p>Fill all form field to go to next step</p> <div class="row"> <div class="col-md-12 mx-0"> <form id="msform"> <!-- progressbar --> <ul id="progressbar"> <li class="active" id="account"><strong>Account</strong></li> <li id="personal"><strong>Personal</strong></li> <li id="payment"><strong>Payment</strong></li> <li id="confirm"><strong>Finish</strong></li> </ul> <!-- fieldsets --> <fieldset> <div class="form-card"> <h2 class="fs-title">Account Information</h2> <input type="email" name="email" placeholder="Email Id"/> <input type="text" name="uname" placeholder="UserName"/> <input type="password" name="pwd" placeholder="Password"/> <input type="password" name="cpwd" placeholder="Confirm Password"/> </div> <input type="button" name="next" class="next action-button" value="Next Step"/> </fieldset> <fieldset> <div class="form-card"> <h2 class="fs-title">Personal Information</h2> <input type="text" …