Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not Found The requested resource was not found on this server - Django-Cpanel
I'm trying to deploy the Django project.I don't know the problem is with the WHM&cpanel or my code I configured the python app from Cpanel passenger_wsgi.py import os import sys from selenium.wsgi import application urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('bulk.urls')) ] views.py from django.shortcuts import render def ime_bot(request): return render(request, 'Ibot.html') settings.py INSTALLED_APPS = [ 'bulk.apps.BulkConfig' ] TEMPLATES = [ {'DIRS': ['bulk/templates'],} ] bulk/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.ime_bot, name='bot_here'), ] Also I'm able to acces url.com/admin in the wierd html content I'm done with makemigrations,migrate,createsuper user and settings.py here is my error.log App 1193039 output: /opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses App 1193039 output: import sys, os, re, imp, threading, signal, traceback, socket, select, struct, logging, errno Please comment below if I need to update any kind of configuration -
Django and React: how to redirect to main page after successful login
I am building a login system webapp using react + django. My question is how can I redirect a user towards the main page, if the login credentials are successful. Right now I only managed to retrieve the authentication token from the backend. How can I modify this class to also check if the login is successful and then redirect towards the main page? class Login extends Component { state = { credentials: {username: '', password: ''} } login = event => { fetch('http://127.0.0.1:8000/auth/', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(this.state.credentials) }) .then( data => data.json()) .then( data => { this.props.userLogin(data.token); } ) .catch( error => console.error(error)) } register = event => { fetch('http://127.0.0.1:8000/api/users/', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(this.state.credentials) }) .then( data => data.json()) .then( data => { console.log(data.token); } ) .catch( error => console.error(error)) } inputChanged = event => { const cred = this.state.credentials; cred[event.target.name] = event.target.value; this.setState({credentials: cred}); } render() { return ( <div> <h1>Login user form</h1> <label> Username: <input type="text" name="username" value={this.state.credentials.username} onChange={this.inputChanged}/> </label> <br/> <label> Password: <input type="password" name="password" value={this.state.credentials.password} onChange={this.inputChanged} /> </label> <br/> <button onClick={this.login}>Login</button> <button onClick={this.register}>Register</button> </div> ); } } -
How to set session variable in Django template
How to set session variable within Django template, For example: <a href="{% url 'view' request.session.data.set("First data") %}">First Button</a> <a href="{% url 'view' request.session.data.set("Second data") %}">Second Button</a> <a href="{% url 'view' request.session.data.set("Third data") %}">Third Button</a> The Reason of doing this in the template not in the view: by clicking a certain button on the page the user should be redirected with different session data (that depends on the button being clicked) The Reason of not doing this with GET parameters: The data is sensitive -
How to use values of data in Foriegn key while importing in django import export
i want to ask how to use values of the foreign key while importing data from csv file in Django import export library.? Thanks in advance , the main issue i am having is I have to import a csv file containing the data of the model that has foreign keys in it. the overall architecture is something like this: the Main model is: class Reservation(models.Model): company = models.ForeignKey(company_models.CompanyProfileModel, null=True, blank=True, on_delete=models.CASCADE) reservation_status = models.CharField(max_length=35, null=True, blank=True, choices=status_types, default=REQUESTED) reservation_no = models.CharField(max_length=40, null=True, blank=True) client = models.ForeignKey(PersonalClientProfileModel, null=True, blank=True, on_delete=models.SET_NULL) service_type = models.ForeignKey(setting_models.ServiceType, on_delete=models.SET_NULL, null=True, blank=True) sales_tax = models.ForeignKey('setting.SalesTax', on_delete=models.CASCADE, null=True, blank=True) charge_by = models.CharField(max_length=50, choices=charge_by, null=True, blank=True) pay_by = models.CharField(max_length=50, choices=payment_type, null=True, blank=True, verbose_name='Payment Method') vehicle_type = models.ForeignKey(setting_models.VehicleType, on_delete=models.SET_NULL, null=True, blank=True) vehicle = models.ForeignKey(Vehicle, null=True, blank=True, on_delete=models.SET_NULL) driver = models.ForeignKey(EmployeeProfileModel, null=True, blank=True, on_delete=models.SET_NULL) accepted_by_driver = models.BooleanField(null=True, blank=True, default=False) pickup_address = models.ForeignKey(GeoAddress, on_delete=models.SET_NULL, related_name='pickup_address', null=True, blank=True) destination_address = models.ForeignKey(GeoAddress, on_delete=models.SET_NULL, related_name='destination_address', null=True, blank=True) # pickup_address = models.CharField(max_length=200, null=True, blank=True) # destination_address = models.CharField(max_length=200, null=True, blank=True) pick_up_date = models.DateField(blank=True, null=True) pick_up_time = models.TimeField(blank=True, null=True) distance_in_miles = models.FloatField(null=True, blank=True, default=0.0) distance_covered_in_ride = models.FloatField(null=True, blank=True, default=0.0) total_hours = models.CharField(max_length=10, null=True, blank=True) from_date = models.DateField(null=True, blank=True) to_date = models.DateField(null=True, blank=True) no_of_days = models.IntegerField(null=True, blank=True, … -
Django-->TypeError: __init__() got an unexpected keyword argument 'providing_args'
I'm running my django-app-api server on docker and I'm stuck at a particular place. The server doesnt spawn due to the following error : TypeError: init() got an unexpected keyword argument 'providing_args' I'm getting the following error trace while running my django-api docker container using docker-compose myproject-api-webserver | 2022-09-23 11:09:26,477 myprojectnetwork.settings INFO ALLOWED_HOSTS environment variable ignored. myproject-api-webserver | Traceback (most recent call last): myproject-api-webserver | File "manage.py", line 25, in <module> myproject-api-webserver | execute_from_command_line(sys.argv) myproject-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line myproject-api-webserver | utility.execute() myproject-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 420, in execute myproject-api-webserver | django.setup() myproject-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup myproject-api-webserver | apps.populate(settings.INSTALLED_APPS) myproject-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate myproject-api-webserver | app_config = AppConfig.create(entry) myproject-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 193, in create myproject-api-webserver | import_module(entry) myproject-api-webserver | File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module myproject-api-webserver | return _bootstrap._gcd_import(name[level:], package, level) myproject-api-webserver | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import myproject-api-webserver | File "<frozen importlib._bootstrap>", line 991, in _find_and_load myproject-api-webserver | File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked myproject-api-webserver | File "<frozen importlib._bootstrap>", line 671, in _load_unlocked myproject-api-webserver | File "<frozen importlib._bootstrap_external>", line 843, in exec_module myproject-api-webserver | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed myproject-api-webserver … -
Static files are not getting loaded in Django
Static files are not getting loaded when running on server. I have tried the whitenoise library and referred to the Documentation (http://whitenoise.evans.io/en/stable/django.html) as well, but no luck. I am new to Django, would appreciate any help. PS: I have also collected the static folder using- python manage.py collectstatic Below is what I have in my settings.py INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_celery_beat', 'django_extensions', 'haystack', 'users.apps.UsersConfig', 'rest_framework', 'rest_framework.authtoken', 'django_db_logger.apps.DbLoggerAppConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] WSGI_APPLICATION = 'server.wsgi.application' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") -
Faceted search with django-filter and postgres full-text search
I'm trying to build a faceted search with django-filter and Postgres full-text search. I use it to search books. Furthermore, I have different values and need that after request search or filter user get relevant value. For example, I want to find books about Harry Potter. After I entered the book title in the search, after I see that the site does not have related to the book about Harry Potter in Chinese because in filter is not had Chinese I understood that is known as faceted search. If I make a mistake. I apologize. Could you give me advice how to build it better? models.py class Book(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey( "Authors", on_delete=models.SET_NULL, null=True, blank=True, ) subject = TreeManyToManyField("Subject") published_date = models.DateField(blank=True, null=True) language = models.ForeignKey( "Language", on_delete=models.SET_NULL, null=True) class Subject(MPTTModel): name = models.CharField( max_length=1000, unique=True, ) class Language(models.Model): name = models.CharField( max_length=255, unique=True, ) class Authors(models.Model): name = models.CharField( max_length=255, unique=True, ) filters.py class BookFilter(django_filters.FilterSet): search = django_filters.CharFilter( method="my_custom_filter", widget=TextInput( attrs={ "class": "form-control", "placeholder": _("Type to search"), } ), ) language = django_filters.ModelMultipleChoiceFilter( field_name="language", queryset=Language.objects.order_by("name"), widget=forms.CheckboxSelectMultiple(), ) subject = django_filters.ModelMultipleChoiceFilter( field_name="subject", queryset=Subject.objects.all(), widget=autocomplete.ModelSelect2Multiple(} ), ) class Meta: model = Book fields = { "subject", "language", "published_date", … -
Django - issue with displaying SearchHeadline object in a template
I am working on search functionality and I need to implement SearchHeadline to highlight searched words however I am struggling to do it in multiple fields. What I'd like to do is to highlight not only words in the title field but also the short_description field. I found this question and tried to implement Concat however, in my case title and short_description are placed in 2 seperated html elements so I cannot just concatenate them and display as 1 headline because I need to display the whole title and the whole short_description and highlight matching words. views.py class SearchResultsList(LoginRequiredMixin, ListView, CategoryMixin): model = QA context_object_name = "query_list" template_name = "search/SearchView.html" def get_queryset(self): query = self.request.GET.get("q") search_vector = SearchVector("title", weight="A") + SearchVector("short_description", weight="B") search_query = SearchQuery(query) search_headline = SearchHeadline('title', search_query, start_sel='<span class="text-decoration-underline sidebar-color">',stop_sel='</span>') # how to implement SearchHeadline to short_description? return QA.objects.annotate( search=search_vector, rank=SearchRank(search_vector, search_query) ).annotate(headline=search_headline).filter(rank__gte=0.3).order_by("-rank") #The code below is working but it concatenates the title with the short description and I need to separate these fields. Moreover, it shows only a preview, not the whole title and short description value # return QA.objects.annotate(search_vectors=SearchVector('title', 'short_description'), ).annotate(headline=SearchHeadline(Concat(F('title'), Value(' '), F('short_description')),SearchQuery(query),start_sel='<strong>', stop_sel='</strong>')).filter(search_vectors=SearchQuery(query)) SearchView.html {% for query in query_list %} <div class="col-12"> <a href="{{ … -
Django set ImageView of User Profile
So i've been working on a project for a while, in which I use the Django default User Instance but with additional attributes, which are stored in a "Profile"-Model. So right now i have an assigned company, and an Profile-Image for the user in the Profile Model. Now i have a detailview to edit the user's attributes (firstname, username, email, etc.). i used generic.DetailView for this View. But this is only working for the Attributes in the User-Model from Django. How can I also change Attributes in the Profile Model when editing the User? This is my Edit-View: class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = User fields = ['username', 'email', 'first_name', 'last_name'] template_name = 'inventory/edit_forms/update_profile.html' success_url = '/profile' login_url = '/accounts/login' redirect_field_name = 'redirect_to' def form_valid(self, form): profile = Profile.objects.get(user=self.request.user) profile.img = self.request.POST.get('profile_img') profile.save() return super().form_valid(form) def get_object(self): return User.objects.get(pk = self.request.user.id) This is my HTML: <form class="edit_object" action="" method="post" enctype='multipart/form-data' class="form-group"> <div style="width: 20%; margin-bottom: 1rem;"> <label>Profile Image</label> <input name="profile_img" type="file" accept="image/png, image/gif, image/jpeg"> </div> {% csrf_token %} {{form|crispy}} <input type="submit" value="Submit" class="btn action_btn"> </form> As you see i already tried using a external Input field and setting the image like that. But after submitting, the img attribute in the Profile-Model … -
'SessionStore' object has no attribute 'cart' - Django
I generated a basket with 2 products, at the level of the basket page and also on this same page I added a form to insert the customer's name. by clicking on the submit button which will send the request to a view for insert into the database. but I have an error ('SessionStore' object has no attribute 'cart') I am using django-shopping-cart 0.1 and also I am using an API to post the products Views.py def postCommande(request): for key,value in request.session.cart.items: data={ 'products':[ { 'date':'23-09-22 00:00:00', 'nameclient': request.POST['name'], 'type':'typeproduct' } ] } url='http://myapi/products/postCommande' x=requests.post(url,json=data) return render(request,'panier/succes.html') And the error is on this line (for key,value in request.session.cart.items:) -
How can i makemigrations & migrate in AWS with Django
I have a question! I'm trying to change tables (for example> add product.category111 ) my postgresql database in AWS RDS, but RDS tables weren't changed. And i have NO ERROR...(this makes me going crazy) I'd tryed almost everything that I can googling but I can't find answer. First, .ebextensions/10_django.config like this container_commands: 01_makemigrations: command: "source /var/app/venv/*/bin/activate && python /var/app/current/manage.py makemigrations --noinput" leader_only: true 02_migrate: command: "source /var/app/venv/*/bin/activate && python /var/app/current/manage.py migrate --noinput" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings.production aws:elasticbeanstalk:container:python: WSGIPath: config.wsgi:application Second, config.settings.production.DATABASES DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "HOST": get_secret("AWS_RDS_HOST"), "NAME": get_secret("AWS_RDS_NAME"), "USER": get_secret("AWS_RDS_USER"), "PASSWORD": get_secret("AWS_RDS_PASSWORD"), "PORT": "5432", } } Third, AWS cfn-init-cmd.log (when i added products.category111 table) ... [INFO] Migrations for 'products': [INFO] /var/app/current/apps/products/migrations/0001_initial.py [INFO] - Create model Category [INFO] - Create model Category111 ... [INFO] Command 02_migrate [INFO] -----------------------Command Output----------------------- [INFO] Operations to perform: [INFO] Apply all migrations: "some tables that i made", products [INFO] Running migrations: [INFO] No migrations to apply. ... as you can see, there is "Create model Category111" in makemigrations section but "No migrations to apply." in migrate section. and there is no change in RDS ofc. Any helps makes me better programmer, Thanks config command options that I'd tried (all combinations) … -
You need to create a User CRUD application using Python Django Note
You need to create a User CRUD application using Python Django Note - Create authentications. Users sign up ( FIRST NAME, LAST NAME, EMAIL, PASSWORD). A Verification should go to email to know whether it is existing or not. User sign in (Email, PASSWORD). Show a user dashboard page when sign in. Two Roles (User role and Admin role) if admin show admin dashboard, if user show user dashboard. -
Why is mail not sent? (Django)
I've written this code and I cannot figure out why the mail is not sent. In this code I check the POST field of the class request and I get the IP address inserted in a form. Once gotten the IP address I make a call to the server indicated by the IP and then I would like to send an email with the text of the response. def startPing(request): servers = Server.objects.all() context = {"servers": servers} if request.method == 'POST': indirizzoIP = request.POST.get('indirizzoIP') timer = request.POST.get('timer') indirizzoIP = "http://" + indirizzoIP while True: response = requests.get(indirizzoIP) if response != "": response = "Server OK" send_mail( 'Report server', '{}'.format(response), 'from@', ['to@'], fail_silently=False, ) print(response) sleep(float(timer)*3600) return render(request, 'homepage.html', context) -
Dynamically Limit Choices of Wagtail Edit Handler
I would like to limit the choices available of a field in the Wagtail-Admin edit view. My Wagtail version is 2.16.3. In my case, if have a page model, that describes product categories. To each category might exist some tags. There is another page model, that describes concrete products and always is a subpage of a category page. A product can now be described with some tags, but only tags, that belong to the product's category make sense, so I would like to restrict the edit handler of the products to these tags. My models.py looks similar to this: class ProductTag(ClusterableModel): name = models.CharField(_("Name"), max_length=50) category = ParentalKey( "ProductCategoryIndexPage", related_name="tags", on_delete=models.CASCADE ) class ProductPage(Page): parent_page_types = ["products.ProductCategoryIndexPage"] tags = ParentalManyToManyField("ProductTag", related_name="products") content_panels = Page.content_panels + [ FieldPanel("tags", widget=widgets.CheckboxSelectMultiple()), ] class ProductCategoryIndexPage(Page): subpage_types = ["products.ProductPage"] content_panels = Page.content_panels + [ MultiFieldPanel( [InlinePanel("tags", label="Tags")], heading=_("Produkt Tags"), ), ] My approach was to create a custom edit handler and inject the wigdet overriding the on_instance_bound method using the correct choices argument for the widget. class ProductTagEditPanel(FieldPanel): def on_instance_bound(self): self.widget = widgets.CheckboxSelectMultiple( # of_product is a custom manager method, returning only the tags, that belong to the product's category choices=ProductTag.objects.of_product(self.instance) ) return super().on_instance_bound() But … -
The Django password reset form is not working, where is the problem?
My motive is to reset the password by sending an email to the user. When the user will click on the link that sends by mail will open an Html page, which will have a password and confirm password form. The email sending system is working well, when I click on the link that sends by mail opens a password reset form. But the problem is, the password reset form is not working. Password not being changed. Where did the actual problem occur? Password not being change. Where did the actual problem occur? Please give me a relevant solution😢... helper.py: from django.core.mail import send_mail from django.conf import settings def send_forget_password_mail(email , token ): subject = 'Your forget password link' message = f'Hi , click on the link to reset your password http://127.0.0.1:8000/changepassword/{token}/' email_from = settings.EMAIL_HOST_USER recipient_list = [email] send_mail(subject, message, email_from, recipient_list) return True views.py: def ChangePassword(request, token): context = {} try: profile_obj = User.objects.filter(forget_password_token=token).first() print(profile_obj) if request.method == 'POST': new_password = request.POST.get('new_password') confirm_password = request.POST.get('reconfirm_password') user_id = request.POST.get('user_id') if user_id is None: messages.warning(request, 'No user id found.') return redirect(f'/changepassword/{token}/') if new_password != confirm_password: messages.warning(request, 'both should be equal.') return redirect(f'/changepassword/{token}/') return redirect('login_user') context = {'user_id' : profile_obj.user.id} except Exception … -
How to upload more than 2 files once in django?
I put two files in web, but i can only get one file always. can you guys do me a favour, i will be deeply grateful! in web [i have put two files in web][1] form.py ``` class UFileForm(forms.Form): file = forms.FileField(label="资料文件上传", widget=forms.ClearableFileInput(attrs={'multiple': True, 'class': 'bg-info'})) ``` view.py ```class UploadFileView(View): """ 文件上传的视图类 """ def get(self, request): form = UFileForm() return render(request, 'data_check/upload_file.html', {'form': form, 'title': '文件上传'}) def post(self, request): data = {} form = UFileForm(request.POST, request.FILES) files = request.FILES.getlist('file') # print files in request here print(files) ``` result is:[<InMemoryUploadedFile: 20220609奥莉公会-积分统计表.xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>] There is only one file. [1]: https://i.stack.imgur.com/CG97G.jpg -
django read json file with relative file path
I am attempting to deploy django in production, but have an issue with a relative file path in my models.py. When I use python3 manage.py runserver 0.0.0.0:8000, the site works fine. When I run django using http and wsgi, I get the error that the below file cannot be found. I assume this is because it is looking for the file using a relative path. How should I fix this? This is the line in my models.py, which imports the json file. data = open('orchestration/static/router_models.json').read() -
Railway.app can't find staticfiles after deployment django app
I try to deploy my app to Railway.app. App generally works but static files are not found. I have made collectstatic folder using command django manage.py collectstatic as advised in deployment tutorials but it doesn't help. Any clue what could went wrong ? settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') staticfiles folder is situated in directory that contains menage.py file deploy logs from railway.apps Not Found: /staticfiles/style.css Not Found: /staticfiles/base.css Not Found: /staticfiles/MyImage.png Not Found: /staticfiles/base.js -
Django `sender` not working for signal receiver
I am trying to create a post_save handler for when the model Client has been saved. The reason I am using a signal is because I require for the code run when a Client is added via loaddata as well. Heres the sender: # apps.py from django.db.models.signals import post_save class ClientsConfig(AppConfig): name = 'clients' verbose_name = "clients" def ready(self): """https://docs.djangoproject.com/en/4.1/topics/signals/""" # Implicitly connect signal handlers decorated with @receiver. from . import signals # Explicitly connect a signal handler. post_save.connect(signals.write_svg, dispatch_uid="clients_client_post_save") Heres the receiver: # signals.py from django.db.models.signals import post_save from django.dispatch import receiver from .models import Client @receiver(post_save, sender=Client) def write_svg(sender, instance, **kwargs): """Using a signal so that when one loaddata the DB, it performs this action too""" print('\n-----------------------------------------------------') print('Signal called, sender', sender) Here you can see it prints for a whole bunch of Session events, and many other events, instead of being filtered for only the client model: ----------------------------------------------------- Signal called, sender <class 'django.contrib.sessions.models.Session'> ----------------------------------------------------- Signal called, sender <class 'django.contrib.sessions.models.Session'> ----------------------------------------------------- Signal called, sender <class 'django.contrib.sessions.models.Session'> ----------------------------------------------------- Signal called, sender <class 'django.contrib.sessions.models.Session'> ----------------------------------------------------- Signal called, sender <class 'django.contrib.sessions.models.Session'> -
Django - separating prod and dev settings - delete original settings.py?
I'm following the below answer on separating development and production Django settings file. https://stackoverflow.com/a/54292952/15166930 After separating, would I delete the original settings.py file? Is this the common practice on separating the files? I see multiple methods on that SO post. Also, per the SO answer, I'm to update the BASE_DIR in my base.py file to BASE_DIR = Path(file).resolve().parent.parent.parent right now it's as below: settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) Just want to confirm because the two are so different.. thx (Django 2.1.7) -
error in django of -- MultiValueDictKeyError at /signup
i create a simple login and signup project but at the signup process when i sign up and redirect to the login page i got the error called "MultiValueDictKeyError" this is my signup.html file --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>sign up here</title> </head> <body> <h3>Sign Up</h3> <form action="/signup" method="POST"> {% csrf_token %} <label for="">username</label> <input type="text" id="username" name="username" placeholder="Create a user name" Required><br> <label for="">first name</label> <input type="text" id="fname" name="fmyname" placeholder="First Name" Required><br> <label for="">last name</label> <input type="text" id="lname" name="lname" placeholder="Last Name" Required><br> <label for="">email</label> <input type="email" id="email" name="email" placeholder="enter your email address" Required><br> <label for="">password</label> <input type="password" id="pass1" name="pass" placeholder="enter your password" Required><br> <label for="">re-enter password</label> <input type="password" id="pass2" name="pass2" placeholder="re enter your password" Required><br><br> <button type="submit">Sign Up</button> </form> </body> </html> and this is views.py def signup(request): if request.method == "POST": # username = request.POST.get('username') username = request.POST['username'] firsname = request.POST['fmyname'] #here i got ERROR of the multivaluedictkeyerror lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass'] pass2 = request.POST['pass2'] myuser = User.objects.create_user(username, email, pass1) myuser.first_name = firsname myuser.last_name = lname myuser.save() messages.success(request, "your account is created.") return redirect('signin') return render(request, 'authentication\signup.html') -
How to force this field to submit data?
I have a form that looks like I am trying to add a product. The description of which will be entered through this form. But my textarea dont send data to product html: <div class="col-12"> <div class="mb-2"> <label class="form-label">Текст новости</label> <div id="blog-editor-wrapper"> <div id="blog-editor-container"> <div class="editor"> <textarea name="text" class="form-control" id="text" rows="3" required>TEXT</textarea> </div> </div> </div> </div> </div> vievs: def create(request): if (request.method == 'POST'): obj, created = Posts.objects.get_or_create(title=request.POST.get("title")) obj.text=request.POST.get("text") obj.preview=request.POST.get("preview") obj.date=request.POST.get("date") obj.image=request.POST.get("image") obj.save() models: text = models.TextField('Текст статьи') Мy other fields (not custom) look like this <label class="form-label" for="blog-edit-title">Заголовок</label> <input type="text" id="blog-edit-title" class="form-control" value="" name="title" /> -
Django RedirectView CSRF verification failed. Request aborted
Ran into a problem when redirecting a request through RedirectView. Returns a 403 CSRF verification failed response. Request aborted. I'm a newbie, please explain what's wrong? project/urls.py urlpatterns = [ path('v2/partner/products/groups', RedirectView.as_view(url=f"{abm_url.ABM_URL}/v2/partner/products/groups"))] -
AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField' in Django inside Swagger
This error is thrown in django even though it's not even imported anywhere. It's thrown by OpenAPISchemaGenerator as follows: File "/opt/hostedtoolcache/Python/3.8.13/x64/lib/python3.8/site-packages/drf_yasg/inspectors/field.py", line 406, in <module> (serializers.NullBooleanField, (openapi.TYPE_BOOLEAN, None)), AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField' How do I fix this? link. It doesn't answer the question. -
AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField'
After upgrading djangorestframework from djangorestframework==3.13.1 to djangorestframework==3.14.0 the code from rest_framework.serializers import NullBooleanField Throws AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField' Reading the release notes I don't see a deprecation. Where did it go?