Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the request-id from snmp response
Using wireshark i can see a request-id goes on when i run this program (How to get the value of OID in Python using PySnmp), can i get the request-id number using python program similarly, when i run this program i basically give community:public and version v2c, but in get-response i get request-id, this is what is need to fetch. Please help me out how to do it. Here is the image of snmp response in wireshark. https://i.imgur.com/aH5gO4B.png -
Bokeh plot not showing up in django template
I am trying to embed a bokeh plot into a django template, but the plot is not showing up. What am I doing wrong? views.py from bokeh.plotting import figure from bokeh.models import ColumnDataSource, Axis, NumeralTickFormatter, HoverTool, Range1d, LinearAxis from bokeh.layouts import row, widgetbox, gridplot, column from bokeh.resources import CDN from bokeh.embed import components def customer_view(request, customer_id): data = dict() template = 'dashboard/includes/customer/partial_customer_view.html' customer = get_object_or_404(Customer, customer_id=customer_id) contacts = ContactPerson.objects.filter(Q(customer__customer_id=customer_id)).all() plot = figure() plot.circle([1,2], [3,4]) script, div = components(plot) context = { "customer": customer, "contacts": contacts, "the_script": script, "the_div": div, } data['html_form'] = render_to_string(template, context, request=request) return JsonResponse(data) base.html <head> {% load static %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Dashboard</title> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700|Roboto:300,400,500" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"> <link rel="stylesheet" type="text/css" href="../static/styles/css/style.css"> <link rel="stylesheet" href="http://cdn.pydata.org/bokeh/release/bokeh-0.12.14.min.css"> <script src="http://cdn.pydata.org/bokeh/release/bokeh-0.12.14.min.js"></script> {{the_script|safe}} </head> pip freeze --> bokeh==0.12.14 template <div class="graphs"> {{ the_div | safe }} </div> When I inspect the template I can see that the following shows up in the template. <div class="bk-root"> <div class="bk-plotdiv" id="bdbe8a80-d589-4532-9d9d-c7a12bba4aff"> </div> </div> -
How to create backbone of my Django web-application
I have the following problem. I am building a calculation web application using Django. The app will have the following models: User Project ( a user will have one or more projects) System (a project has one or more hydraulic systems) Circuit (a system will have one or more hydraulic circuits) Component (a hydraulic circuit will have one or more hydraulic components) How should I organize my code. Should I create 5 different apps? How to organize my urls.py for the various apps? Basically the problem seems to be that there are 5 nested models. I already implemeted user and project. Currently the mysite.urls is something like: urlpatterns = [ path('', include('core.urls')), # handles the User path('project/', include('project.urls')), path('admin/', admin.site.urls), ] The project.urls is given by: app_name = 'project' urlpatterns = [ path('', views.ProjectIndexView.as_view(), name='index'), path('create/', views.ProjectCreateView.as_view(), name='create'), path('create_project/', views.create_project, name='create_project'), path('<int:pk>/', views.ProjectDetailView.as_view(), name='detail'), path('<int:project_id>/change_project/', views.change_project, name='change_project'), path('<int:pk>/results/', views.ProjectResultsView.as_view(), name='results'), path('<int:pk>/delete_project/', views.ProjectDeleteView.as_view(), name='delete_project') ] So far so good, but how should I next configure the urls to include the System model? If I should create 5 apps, i.e.: Core (handels the user), Project, System, Circuit and Component, should the app folders be on the same level? Or should the app … -
Not able to upload file using django-filer django
I am new to Django and trying to migrate one old python project. In one module while i am trying to upload file it is throwing below error: KeyError: '32' File "django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "django/views/decorators/csrf.py", line 57, in wrapped_view return view_func(*args, **kwargs) File "filer/admin/clipboardadmin.py", line 88, in ajax_upload 'thumbnail': file_obj.icons['32'], Version Django==1.6.8 easy-thumbnails==2.2 django-filer==0.9.4 So how to fix it? -
Exception while resolving variable 'title' in template 'index.html'
Django website works fine in debug mode in local server. But in production it does not work. I checked the logs (0.001) SELECT "blog_entry"."id", "blog_entry"."title", "blog_entry"."image", "blog_entry"."description", "blog_entry"."body", "blog_entry"."slug", "blog_entry"."publish", "blog_entry"."created", "blog_entry"."modified" FROM "blog_entry" ORDER BY "blog_entry"."created" DESC; args=() (0.000) SELECT "work_work"."id", "work_work"."image", "work_work"."header", "work_work"."description" FROM "work_work"; args=() (0.000) SELECT "project_project"."id", "project_project"."image", "project_project"."Header", "project_project"."description" FROM "project_project"; args=() Exception while resolving variable 'title' in template 'index.html'. Traceback (most recent call last): File "/media/sanjeev/Work/source/backend/new/local/lib/python2.7/site-packages/django/template/base.py", line 907, in _resolve_lookup (bit, current)) # missing attribute VariableDoesNotExist: Failed lookup for key [title] in u"[{'False': False, 'None': None, 'True': True}, {u'csrf_token': <SimpleLazyObject: <function _get_val at 0x7fbac8d4f7d0>>, 'user': <SimpleLazyObject: <function <lambda> at 0x7fbac97a8140>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x7fbac8d51190>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'WARNING': 30, 'SUCCESS': 25, 'ERROR': 40}, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7fbac97a3290>, u'request': <WSGIRequest: GET '/'>}, {}, {u'queryset': <QuerySet [<Entry: Best Action Cameras>, <Entry: 5 Best DSLR Cameras>, <Entry: Blackberry KEYone>, <Entry: BEST SMARTPHONES (2017)>]>, u'project_list': <QuerySet []>, u'bruhh': u'title', u'form': <contactForm bound=False, valid=Unknown, fields=(name;email;comment)>, u'work_list': <QuerySet []>}]" Exception while resolving variable 'confirm_message' in template 'index.html'. Traceback (most recent call last): File "/media/sanjeev/Work/source/backend/new/local/lib/python2.7/site-packages/django/template/base.py", line 907, in _resolve_lookup (bit, current)) # missing attribute VariableDoesNotExist: Failed lookup for key [confirm_message] in u"[{'False': False, 'None': None, 'True': True}, … -
Passing a matplotlib image to render via context in Django
I am trying to render a call to a query, some text and a matplotlib image on a webpage using Django. I have the following views.py file: def getinput(request): if request.method == 'POST': form = get_data(request.POST) if form.is_valid(): down = form.cleaned_data['get_down'] ytg = form.cleaned_data['get_ytg'] yfog = form.cleaned_data['get_yfog'] map_data = next_play.objects.filter(last_dwn__exact=down, last_yfog__exact=yfog, last_ytg__exact=ytg) fig = plot_playoutcomes(map_data) context = {'form': form, 'query_data': map_data, 'img': fig} return render(request, 'play_outcomes/output.html', context) else: form = get_data() return render(request, 'play_outcomes/getinput.html', {'form': form}) This calls a query from my model that it stores in map_data. I then want to plot an image and call plot_playoutcomes(map_data). Here is the code for that: from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import numpy as np from django.http import HttpResponse, HttpResponseRedirect def plot_playoutcomes(playdata): fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) x = np.arange(-2,1.5,.01) y = np.sin(np.exp(2*x)) ax.plot(x, y) response = HttpResponse(content_type='image/png') canvas.print_png(response) return response Note - that in the function I DO NOT use map_data, but rather plot a simple picture. Here is the template - it displays some text, the image, and the data I queried. <h1>Thanks for entering data!!!!</h1> {{ query_data }} {{ img }} <ul> {% for game in query_data %} <li>{{ game.dwn … -
How can axios get the status code in .catch()?
In the Axios document: axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }); we know we can catch the error in the .catch() method. But when I use the Django-Rest-Framework as the backend API provider. it only provide the data, there is no status in it: You see the error: {username: ["A user with that username already exists."]} but in the browser, we can know the status code: Before asking this question, I have read How can I get the status code from an http error in Axios? this post. But the post seems different with mine. EDIT-1 In my Django-Rest-Framework project: the view: class UserCreateAPIView(CreateAPIView): serializer_class = UserCreateSerializer permission_classes = [AllowAny] queryset = User.objects.all() the serializer: class UserCreateSerializer(ModelSerializer): """ user register """ … -
django tastypie bundle.object returns F('value')
posmenu = POSMenuResource() request_bundle = posmenu.build_bundle(request=request, data = m_new) bundle_data = posmenu.obj_create(request_bundle) Here if i print bundle_data.obj.id it gets the latest value But if i print bundle_data.obj.version it gives F('version') + 1 as result (which is how it is defined in obj_create of the same resource) How to get the exact value instead of function value -
React, react-router, django
I have a SPA-application on React with Redux. React talk with Django only with rest api. Otherwise, frontend and backend - different parts. Also, I know that have another way - standart Django scheme (render to template, when in template - connect with React). Which way is more good? Different parts or Django-way? Sorry, if this question is a strange. Thanks a lot. -
How do i display multiple images uploaded via a formset on my template?
I'm trying to create a site that displays a list of construction projects carried out by my company whereby i want each project on the list to have a gallery of images related to it which i will later loop over in my project details template, i have tried to use formsets but i cant figure out how to loop over the images in the formset to show in the template?can anyone please help me or give me a better approach to my problem? i'm using this approach on this question currently -
in doesnt work for queryset
I have tried to use the built in Groups system in Django to pass through whether a user is part of a group or not to the template: def is_contributor(request): group = Group.objects.get_or_create(name='contributor') return { 'is_contributor': True if group in request.user.groups.all() else False } The following will pass through False even if the user is part of the group. Specifically, if I pass through the following: request.user.groups.all() I get: <QuerySet [<Group: contributor>]> Which leads me to believe that the 'in' in this case is not working over the queryset. Are there limitations to using in over a queryset? Is there a better approach? -
Can't compare string in Django template
Here's my template: <p>{{ instance.video_source }}</p> #"youtube" {% if instance.video_source == "youtube" %} <h1>YOUTUBE</h1> #doesn't print "YOUTUBE" {% endif %} Any idea why the if statement doesn't fire? I've also tried {% if instance.video_source == youtube|stringify %} which is this template tag here: def stringify(obj): return str(obj) and the if statement still doesn't fire. And this also doesn't work {% if instance.video_source == youtube|stringformat:"s" %} <h1>YOUTUBE</h1> {% endif %} Here's the origin of instance.video_source: @property def video_source(self): return "youtube" Any idea why the if statement isn't working? -
Django - Sorting boolean using annotate
Let's imagine I have this model and I would like to sort them by logical operation n1 != n2: class Thing(Model): n1 = IntegerField() n2 = IntegerField() ... def is_different(self): return self.n1 != self.n2 If I sort them by sorted built-in function, I found that it does not return a Queryset, but a list: things = Thing.objects.all() sorted_things = sorted(things, key=lambda x: x.is_different()) Now, if I use annotate sorted_things = things.annotate(diff=(F('n1') != F('n2'))).order_by('diff') it raises the following error: AttributeError: 'bool' object has no attribute 'resolve_expression'. I found a solution using extra queryset: sorted_things = things.extra(select={'diff': 'n1!=n2'}).order_by('diff') but following Django docs (https://docs.djangoproject.com/en/2.0/ref/models/querysets/#extra): Use this method as a last resort This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods. If you do need to use it, please file a ticket using the QuerySet.extra keyword with your use case (please check the list of existing tickets first) so that we can enhance the QuerySet API to allow removing extra(). We are no longer improving or fixing bugs for this method. Then, what is the optimal way to do it? Thanks! -
Django-material frontend widget override
I'm using material frontend, i'm trying to override widgets as I do that in an admin form, although it seems overridden in my IDE. I cannot get it to work in the frontend. The goal is to replace certain field's widget with a custom one i.e I want range instead of text input. Anyone with experience with Django material that can show me a way to bypass the original rendering of the widgets. -
UPSERT with Django. Many rows
I try to do UPSERT with Django 2.0, Postgres 9.5. My table: \d+ candle Table "public.candle" Column | Type | Modifiers | Storage | Stats target | Description -------------------+--------------------------+-----------------------------------------------------+---------+--------------+------------- id | integer | not null default nextval('candle_id_seq'::regclass) | plain | | mts | timestamp with time zone | not null | plain | | open | numeric(200,40) | not null | main | | close | numeric(200,40) | not null | main | | high | numeric(200,40) | not null | main | | low | numeric(200,40) | not null | main | | volume | numeric(200,40) | not null | main | | pair_timeframe_id | integer | not null | plain | | Indexes: "candle_pkey" PRIMARY KEY, btree (id) "candle_mts_84b62390_uniq" UNIQUE CONSTRAINT, btree (mts) "candle_pair_timeframe_id_3f7b76ce" btree (pair_timeframe_id) Foreign-key constraints: "candle_pair_timeframe_id_3f7b76ce_fk_pair_timeframe_id" FOREIGN KEY (pair_timeframe_id) REFERENCES pair_timeframe(id) DEFERRABLE INITIALLY DEFERRED Implemented it like this: with connection.cursor() as cursor: g = ''' INSERT INTO candle ( pair_timeframe_id, mts, open, close, high, low, volume ) VALUES %s ON CONFLICT (mts) DO UPDATE SET open = EXCLUDED.open, close = EXCLUDED.close, high = EXCLUDED.high, low = EXCLUDED.low, volume = EXCLUDED.volume WHERE candle.pair_timeframe_id = %s; ''' % (data, str(pairs_timeframes_id)) Values might be me many, but in … -
TemplateDoesNotExist at / (home.html)
I'm working on an example Placeholder Image Server. This uses a single file approach, so urls, views, settings, are all in just one file called placeholder.py. Each time I try visiting http://localhost:8000 (the homepage), I get TemplateDoesNotExist at / thrown at me. I can't figure out what's wrong. Below is the project structure: /placeholder placeholder.py /templates home.html /static style.css Here's the content of each file: placeholder.py import hashlib import os import sys from io import BytesIO from PIL import Image, ImageDraw from django.conf import settings from django import forms from django.urls import path, reverse from django.core.cache import cache from django.core.wsgi import get_wsgi_application from django.http import HttpResponse, HttpResponseBadRequest from django.shortcuts import render from django.views.decorators.http import etag from django.core.management import execute_from_command_line # settings likely to change between environments DEBUG = os.environ.get('DEBUG', 'on') == 'on' SECRET_KEY = os.environ.get('SECRET_KEY', 'soj-4^4nho$ifsxsoi1+a8&6o&dya)tcivwcg9g_82&8sg*q^9') ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost').split(',') BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # settings settings.configure( DEBUG=DEBUG, SECRET_KEY=SECRET_KEY, ALLOWED_HOSTS=ALLOWED_HOSTS, ROOT_URLCONF=__name__, MIDDLEWARE_CLASSES=( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ), INSTALLED_APPS=( 'django.contrib.staticfiles', ), TEMPLATES=[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': os.path.join(BASE_DIR, 'templates'), } ], STATICFILES_DIRS=( os.path.join(BASE_DIR, 'static'), ), STATIC_URL='/static/', ) # simple form to validate the height and width of an image class ImageForm(forms.Form): '''form to validate requested placeholder image''' width = forms.IntegerField(min_value=1, max_value=2000) height = forms.IntegerField(min_value=1, … -
Django send_mail returns 1, but email not received
I am trying to send email via Amazon SES but it does not seem to work for me despite doing all the configuration. I have also tried to setup a local SMTP server but still the same, If I don't specify any email backend / SMTP host, I still get the same response. It seems like Django is not picking up my email backend. How can I debug this? Am I missing something? Django 2.0.3 Python 3.6.2 "boto": { "version": "==2.48.0" }, "boto3": { "version": "==1.6.8" }, "botocore": { "version": "==1.9.8"} My config: EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_REGION_NAME = 'us-west-2' AWS_SES_REGION_ENDPOINT = 'email.us-west-2.amazonaws.com' AWS_SES_ACCESS_KEY_ID = "<access key>" AWS_SES_SECRET_ACCESS_KEY = "<secret key>" DEFAULT_FROM_EMAIL = "notify@domain.com" I tried to do this and It just returns 1 but the mail is not received. from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) However, when I send emails using smtp lib, it goes through. import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_email(): mail_subject, mail_body = generate_mail_body("John Doe", 2867) from_name = "Notifications <notifications@domain.com>" from_address = "notifications@domain.com" to_address = "user@domain.com" # Setup Message message = MIMEMultipart() message['From'] = from_name message['To'] = to_address message['Subject'] = mail_subject # Record … -
Failed to load resource: Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin
I have a Vue.js frontend project, which start at the 8080 port. I access the site by: http://localhost:8080/register and I use the Python/Django write the backend site. using Django-Rest-Framework provide the APIs. My backend APIs server is start as: http://0.0.0.0:8001/ But when I register( access the api ), I get bellow Access-Control-Allow-Origin error: Failed to load resource: Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin. In my Python backend project settings.py code are: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '8cyiv%(rkpv33s_(n8x_5&+6-9&s!ddc!0)98la3=9(y8=k$4u' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_docs', # API docs 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', 'wx_numbers', 'users_management', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # corsheaders 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'http://localhost:8080', 'http://localhost:8081', 'http://localhost', 'http://localhost:8888', ) ROOT_URLCONF = 'wx_backup.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'wx_backup.wsgi.application' AUTH_USER_MODEL = … -
how to impliment Haystacksearch fetched autocomplete
I want implement fetching in autocomplete, here is my autocomplete function def autocomplete(request): fetch_field = request.GET.get('fetch_field') sqs = SearchQuerySet().autocomplete( content_auto=request.GET.get( 'query', ''))[ :5] s = [] for result in sqs: d = {"value": result.title, "data": result.object.slug} s.append(d) output = {'suggestions': s} print('hihi' ,output) return JsonResponse(output) Now I can get fetch fields but I don't know how to fetch with SearchQuerySet. -
Bootstrap-table How to make height adjust to shown data
I am using bootstrap-table to create my table, and it functions perfectly, but it looks a bit strange because the height seems to just be fixed, regardless of how much data is in it. So if I only have 6 records, there is just this awkward empty space underneath. Here is my html: <table class="table" data-toggle="table" data-page-size="10" data-pagination="true" data-search="true"> <thead> <tr> <th data-sortable="true">Username</th> <th data-sortable="true">Full Name</th> <th data-sortable="true">Points</th> {% for subject in subjects %} <th data-sortable="true">{{ subject }}</th> {% endfor %} </tr> </thead> <tbody> {% for user in users %} <tr> <td> <a href="{% url 'profile' username=user.username %}">{{ user.username }}</a> </td> <td>{{ user.first_name }} {{ user.last_name }}</td> {% for item in user.profile.points %} <td>{{ item.1 }}</td> {% endfor %} </tr> {% endfor %} </tbody> And here is a screenshot of my page: Any ideas on how to fix this? -
Hashes of static files collected with CachedFilesMixin as STATICFILES_STORAGE don't match between the collecstatic phase and the serve phase?
I'm trying to setup static file versioning in my django app that uses django-pipeline as a compressor. The documentation says that django-pipeline doesn't directly support versioning because django-storages supports cache-busting natively. So I simply did the following: STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' However, when I do collectstatic, my files are generated with a certain hash, e.g. /media/static/css/mycss.12345678.css, and when I subsequently serve my files, I get a different hash, e.g. /media/static/css/mycss.87654321.css. And that results in a 404. What might I be missing? -
How to use AWS Cognito in Django Application
How to replace Django Authentication with AWS Cognito. And also how to sync my Django users with AWS. Thanks in advance. -
Display User Profile getting ERROR: 'AnonymousUser' object has no attribute '_meta'
I have a simple view that is suppose to check if there is post data, if so update the user data using UserChangeForm. Else get the form data of user and display. Issue: AttributeError at /profile/edit 'AnonymousUser' object has no attribute '_meta' I think it might be this line in the edit_profile view # Handles the get request - if no post info is submitted then get the form and display it on the edit profile page. else: form = UserChangeForm(instance=request.user) args = {'form': form} return render(request, 'accounts/profile_edit.html', args) Not sure what. Here is the view.py edit_profile def edit_profile(request): # Handle post request - if the user submits a form change form details and pass the intance user if request.method == 'POST': form = UserChangeForm(request.POST, intance=request.user) if form.is_valid(): form.save() return redirect('accounts/profile') # Handles the get request - if no post info is submitted then get the form and display it on the edit profile page. else: form = UserChangeForm(instance=request.user) args = {'form': form} return render(request, 'accounts/profile_edit.html', args) profile_edit.html {% extends 'base.html' %} {% block head %} <title>Profile</title> {% endblock %} {% block body %} <div class="container"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save Changes</button> </form> </div> {% … -
How to style registration form in django using bootstrap
So I have set up a user registration portal for my website. It is in form of plain HTML text. I have downloaded a bootstrap file for registration portal but it simply does not work. from django import forms class UserRegistrationForm(forms.Form): username = forms.CharField( required=True, max_length=30, label='User Name', ) name = forms.CharField( required=True, max_length=30, label='Full Name', ) last = forms.CharField( required=True, max_length=30, label='Last Name', ), email = forms.CharField( required=True, max_length=30, label='Email', ) password = forms.CharField( required=True, max_length=30, label='Password', widget=forms.PasswordInput(), ) Below is my bootstrap. Can you tell me the error here. It simply does not work <body> <form method="POST" class = "signup"> {% csrf_token %} {{ form.as_p }} <div class="loginBox"> <img src="user.png" class="user"> <h2>Resgister Here</h2> <p>Email</p> <input type="text" name="email" placeholder=""> {{ form.email }} <p>Username</p> <input type="text" name="username" placeholder=""> {{ form.username }} <p>Name</p> <input type="text" name="name" placeholder=""> {{ form.name }} <p>Password</p> <input type="password" name="password" placeholder="••••••"> {{ form.password }} <input type="submit" name="" value="register"> </div> </form> </body> </html> -
Application's pages should not get open on pasting the url in a different browser in django
I have faced an issue like applcation pages should not get open on pasting the url in a different browser in django