Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Blog Archive-- Display List of Years and Months that Include Post
I'm trying to do something that I thought would be relatively simple, considering Django was built for news sites. Just want to get an archive list grouped by year/month count on the sidebar of my blog. Something like 2018 -Mar(3) -Feb (2) -Jan (6) I've done a lot of searching on here, but seems like it's been a while since anyone was looking to do something like this and everything else is outdated. I have been able to figure out how to create a monthly archive url/view/tempate and can display a month's posts by going to blog/2018/03 here is my blog's views class BlogListView(generic.ListView): model = Post context_object_name = 'post_list' queryset = Post.objects.all() template_name = 'post_list.html' class ArticleMonthArchiveView(MonthArchiveView): queryset = Post.objects.all() date_field = "posted" allow_future = True def blog_post(request, slug): blog_post = Post.objects.get(slug=slug) context = {'blog_post': blog_post} return render(request, 'blog/blog_post.html', context) and my urls (please ignore mix of url and path for now--working on that!) urlpatterns = [ url(r'^$', BlogListView.as_view(), name='blog'), url(r'^(?P<slug>[\w-]+)/$', blog_post, name='blog_post'), path('<int:year>/<int:month>/', ArticleMonthArchiveView.as_view(month_format='%m'), name="post_archive_month"), ] I think i will need to create another context field on all of my views in order to do this? But i don't really know where to start. I know that I … -
best practices in REST api design - Django/Angular
This is best practices/approach problem or in other words - what is optimal and expected approach. There are 4 models all linked in one-to-many (details below) I'm currently on DRF/Django and Angular interaction level. I need to identify all Authors where page.type=color and iterate foreach author in authors: console.log (author.author) foreach page in pages: console.log (page.content) Given it is fully linked relation, there are multiple options. Considered option was: a) nested router - cons: it requires upfront knowledge of IDs. b) filtering - cons: I couldn't find a way how to do it yet. Currently I don't have a direct pointer from page, back to Author, but theoretically it is one of the options possible however some (small) data overlap would be the case here then. For larger production deployment, which option is preferred (if any). Nested query requires two more SQL queries which might be more "expensive" than adding column to Page, pointing directly back to author. Or maybe approach should be the opposite, start from Author and go down through filtering to page level? At the end of the day, I need list of unique authors (where their book-edition-page fulfills type=) and then iterate through page elements fulfilling … -
Python string to list of dictionaries, access one dictionary to insert into django model
i'm new to python, using django.. i've searched many posts but am still having trouble getting a desired result: 1.- i have the following string received from an ajax post in a django view(its 2 rows of a angular ui-grid): data=[{"part_name":"33029191913","id":"5","qty":"3","ticket":"","comments":""},{"part_name":"3302919777","id":"3","qty":"323","ticket":"","comments":"test"}] 2.- then i am doing json.loads(data), which gives me the following: data ={'part_name': '3302919191', 'id': '5', 'qty': '33', 'ticket': '', 'comments': '33'}{'part_name': '3302919191', 'id': '5', 'qty': '33', 'ticket': '', 'comments': '33'} 3.- i want to create a dictionary that looks like the following in order to insert it into my model, via MyModel(**data): {'part_name': '3302919191', 'id': '5', 'qty': '33', 'ticket': '', 'comments': '33'} 4.- if i try to access one element of the data, example : data[0]['part_name'], it correctly shows '3302919191', but if i do data[0] or data[1], it gives me only the apparent keys: part_nameidqtyticketcomments, how can i separate the string received by ajax into dictionaries? thanks -
Heroku Django rest_framework module not found
I am getting the following when I try to push my code to heroku. ModuleNotFoundError: No module named 'rest_framework' I have got the following in my requirements.txt diff-match-patch==20121119 dj-database-url==0.5.0 Django==2.0.3 django-filter==1.1.0 django-heroku==0.3.1 djangorestframework==3.6.2 et-xmlfile==1.0.1 gunicorn==19.7.1 jdcal==1.3 Markdown==2.6.11 odfpy==1.3.6 openpyxl==2.5.1 psycopg2-binary==2.7.4 pytz==2018.3 PyYAML==3.12 tablib==0.12.1 whitenoise==3.3.1 xlrd==1.1.0 xlwt==1.3.0 -
django not displaying image in my post
I started with a django app and tried displaying an image in the post page. But the image is not getting displayed. plzz any help urls.py from django.conf.urls.static import static from django.conf import settings from django.conf.urls import url,include from django.contrib import admin from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^home/', views.home,name='home'), url(r'^posts/', views.post_all,name='all_posts'), url(r'^post/(\d+)?', views.post_id,name='post'), url(r'^tst', views.tst,name='tst'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py pic = models.ImageField(upload_to="upload_images",blank='True',default='default.jpg') settings.py BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,"public/static") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,"public/media") post.html {% for post in pst %} <h2>{{ post.title }}</h2> <div> <img src="{{ post.pic.url }}"> </div> {{ post.content|linebreaks }} {% empty %} <h1>(vide)</h1> {% endfor %} i didn't understand where is the problem -
how to change temporary folder on django / gunicorn / nginx
I'm currently using django + gunicorn + nginx for my local service. I want to share big files (70Go maximum). thanks to lvm, I have now a 50Go partition (standard) for ubuntu + nginx +django + gunicorn and 5,4To (2 disk with lvm) for my file storage. my first probleme is that I store tmp file in my 50Go disk. When i have a file which is biiger than 50Go it can't work (obviously). I searched how to change the tmp file for django/gunicorn/nginx but my solutions didn't work. my second issue is when I upload a 22Go file, the 50Go disk seems to store my file Twice (I begin at 5Go taken and finish at 50Go) so I'm wondering how to reduce this space. -
subprocess not working in docker container
I'm literally going crazy and pulling my hair out because I can't seem to solve this particular problem. So here's the problem: I have a two containers: Django and celery. The user uploads a word document and the celery worker converts that word document to pdf and uploads to a s3 bucket. I'm using libreoffice --headless to convert it. So a user sends the file to an API endpoints and saves the word document in a folder called original and celery calls convert_office_to_pdf.delay which needs to convert the file and put it into another folder converted. Everything is working as intended apart from the celery function. This is how the code looks: def convert_office_to_pdf(original_file): ws = websocket.WebSocket() ws.connect('ws://web:8000/ws/converter/public/') #how the command will look like print('libreoffice --headless --convert-to pdf original/{} --outdir ./converted'.format(original_file)) subprocess.call('libreoffice --headless --convert-to pdf original/{} --outdir ./converted'.format(original_file), shell=True) ws.send(json.dumps({ 'message': '{}.pdf'.format(pure_file_name), 'progress': 75})) upload_file_to_s3(pure_file_name, 'pdf', ws) However, the function get's executed and nothing happens. This is output from docker-compose web_1 | [2018/03/22 22:57:52] HTTP GET /converter/ 200 [0.06, 172.17.0.1:32788] web_1 | [2018/03/22 22:57:52] HTTP GET /static/css/normalize.css 304 [0.02, 172.17.0.1:32788] web_1 | [2018/03/22 22:57:52] WebSocket HANDSHAKING /ws/converter/public/ [172.17.0.1:32798] web_1 | [2018/03/22 22:57:52] WebSocket CONNECT /ws/converter/public/ [172.17.0.1:32798] fileshiffty_data_1 exited with code … -
Django REST Framework - How to quickly checks user permissions?
I usually use the permission_required the decorator to quickly deny users from accessing the view. from django.contrib.auth.decorators import permission_required @permission_required('my_app.view_mymodel',login_url='/sign_in/') def my_view(request): ... Now, I'm using DRF and I'm trying to find a proper way to checks user permissions. Right now, I'm using the DjangoModelPermissions which is fine, but since it works according to the defined view's queryset, sometimes I need to checks permissions that are not the ones defined for the view's queryset. Is there a way to quickly check permissions just by providing a list of perms' strings? Note: I know that I can extend BasePermission and define my own logic, but would produce a lot of classes. -
Dynmically add arguments to queryset filter call in django
I have a list of strings, which will be generated dynamically. So it will be of variable length: keywords = ['apples','oranges','bananas'] I have a model Fruitsalad, with a field 'description'. Lets say I want to find all Fruitsalads with either 'apples', 'oranges' or 'bananas' in the 'description' field results = Fruitsalad.objects.filter(Q(description__icontains=keywords[0]) | Q(description__icontains=keywords[1] | Q(description__icontains=keywords[2]) How could I generate the above query when I don't know in advance how long the 'keywords' list will be? -
New values on page w/o refreshing page (Flask)
from flask import Flask import random app = Flask(__name__) @app.route('/') def home(): x = random.randint(0,100) return 'X = {}'.format(x) app.run(debug=True) I have this code and i need to refresh("F5") this page every time if i want new value for "X", so how I can get different values for "X" without refreshing the page? -
Migrating from webpack to angular-cli
we are using angular and django BFF as single project. We are trying to migrate from webpack to angular-cli In webpack we are using webpack-bundle-tracker plugin which generates webpack-stats.json file in dist directory on doing "npm run build" webpack.config.js plugins: [ new BundleTracker({path: __dirname, filename: './assets/webpack-stats.json'}) ] Output in webpack-stats.json looks like below: { "status":"done", "chunks":{ "app":[{ "name":"app-0828904584990b611fb8.js", "publicPath":"http://localhost:3000/assets/bundles/app-0828904584990b611fb8.js", "path":"/home/user/project-root/assets/bundles/app-0828904584990b611fb8.js" }] } } Above file is read by Django to do hot reload. My question is How can we generate webpack-stats.json file using angular cli. I tried to do below in package.json file which generates stats.json but file format is different. "ng build --prod --aot=false --stats-json" -
django ajax post empty data
I'm trying to post data to a django view using ajax. I have no errors just there is no data returned. Here is my javascript ajax: function PostGoal(){ console.log('POSTGOAL!!!') data_s = { 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), 'goal': { 'name':'gg','box':'sasa' } } $.ajax({ method: "POST", url: "http://127.0.0.1:8000/",//"{% url 'home' %}",//"/",//"{% url 'home' %}", contentType: 'application/json', //data: JSON.stringify(data_s), data: {'QQww': "1"}, //dataType: 'json',//expected type of response success: function (data) { console.log('aa'+JSON.stringify(data)) }, error: function(xhr,errmsg,err){ console.log('err: '+JSON.stringify(err)+' msg:'+errmsg) } }); } here is my view function: def analyzer(request): if request.method == 'POST': post_data = request.POST print(post_data) print (' ajax:',request.is_ajax()) The boolean request.is_ajax() is ajax is always False request.data or request.POST.data do not exist and same for GET: request.GET is empty. However I can see in the log in the terminal : [22/Mar/2018 22:15:26] "GET /?QQww=1 HTTP/1.1" 200 9746 so essentially the data are parsed in the url? Thanks in advance. -
Site users logged out after Django 1.8 > 1.11 upgrade
We recently upgraded one of our projects from Django 1.8 to 1.11 (one point release at a time). This seems to have logged out all of our site end users. It's not the end of the world, but it was somewhat disruptive, and probably something that we would have attempted to code around if we had taken the time to discover that it would happen. Is there any documentation on why this happens (a backwards-incompatible migration for the Session object... a change to the way the session cookie is checked... maybe something like that?) and which upgrade(s) may cause users to be logged out? Also, for future 1.8 > 1.9 > 1.10 > 1.11 upgrades (as well as future upgrades) is there any sort of interim authentication middleware that can be implemented to authenticate existing sessions into the new system?) -
From where i can learn to develop social website from django, javascript and mongo?
I have studied Django and javascript basics, can you please suggest sources from where I can learn to develop a social networking site. -
Django: getting the link of a generatet token to send it with an email?
So I created a registration Email to confirm that the User is really using the email he used for registration. This is the registration view: def registration(request): if request.method == 'POST': form = StudentForm(request.POST) if form.is_valid(): fname = request.POST.get('Vorname', 'None') lname = request.POST.get('Nachname', '') email = request.POST.get('Email', '') pwd = request.POST.get('Passwort', '') pwd2 = request.POST.get('Passwort_wiederholen', '') if not pwd: raise ValueError('User must have a pwd') if pwd == pwd2: new_user = User( fname = fname, lname = lname, email = BaseUserManager.normalize_email(email), user_type = 'S', is_active = False ) new_user.set_password(pwd) new_user.save() #email code token = default_token_generator.make_token(new_user) uid = urlsafe_base64_encode(force_bytes(new_user.pk)) send_mail( 'Welcome!', f'Link: {#what should I put in here? }', settings.EMAIL_HOST_USER, [str(new_user.email)], fail_silently=False) return HttpResponse('Pls activate your account using the link we send you too your email') else: form = StudentForm() return render(request, 'account/registration.html', {'form' : form}) This is the url I have in my urls.py for the token: url(r'^users/validate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z] {1,13}-[0-9A-Za-z]{1,20})/$', views.activation_view, name='user-activation-link') Since I don't now how to get this link, I'm not even sure if it's even properly working or if it's even getting generated. However I guess so since the code is running without any errors so far. How can I get access to the link that the user … -
Django Set Session Variable
Hello awesome developers! I got stack with session variables. At the moment I have two functions. In the first one I am trying to set session var, it looks like that everything works fine, but in the second I am trying to access this var and I am getting None. Does any one have an idea why is it so?.. Views.py @api_view(['POST']) def login(request): if request.method == 'POST': response = requests.post(CORE_ADDRESS + 'login/', json=request.data) if response.status_code == 200: response = response.json() request.session["authentication_token"] = response.get('authentication_token') request.session["session_user_id"] = response.get('id') print('token -> ', request.session["authentication_token"]) #token prints fine here return Response(response) @api_view(['GET']) def session_user(request): if request.method == 'GET': print(request.session.get('authentication_token')) #and here it prints None Settings.py INSTALLED_APPS = [ 'backend', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', ] MIDDLEWARE_CLASSES = [ #'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', #'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', #'django.contrib.auth.middleware.AuthenticationMiddleware', #'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', #'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] ROOT_URLCONF = 'myapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'myapp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': … -
How to change output-file extension of django-dbbackup module?
I am trying to use django-dbbackup module to backup my database. After running dbbackup it saves a db dump with a name something like this: default-user-2018-03-22-220805.psql Then I delete 1 last row in one tables of my db. Next I run dbrestore and get the follow: > Finding latest backup Restoring backup for database 'default' and > server 'None' > Restoring: default-user-2018-03-22-220805.psql > Restore tempfile created: 407.0 KiB > Are you sure you want to continue? > [Y/n] y > Following files were affected But after that - nothing happens. The deleted row is not restored in my db. I have read some where (unfortunately already lost that page) that to restore my db the dump file must be in .tar format. Also I have tried to use that .psql with pgAdmin 4 - to restore db via UI tool. But got an error that input file is not a valid archive. And last I tried to use that file with Windows cmd running pd_restore and got: pg_restore: [archiver] input file does not appear to be a valid archive So the question is: how to use django-dbbackup dbrestore with its generated file or how to change the extension format of … -
Django: Admin fields not editable?
I imported a project from Django builder, managed to install the dependencies, and start the admin, but I have an issue. All of the fields in admin are not editable! None of them. Here's a screenshot of the issue: Here's the relevant files: Admin.py from django.contrib import admin from django import forms from .models import Tours, Locations, Photos, PlaceLocations, Information class ToursAdminForm(forms.ModelForm): class Meta: model = Tours fields = '__all__' class ToursAdmin(admin.ModelAdmin): form = ToursAdminForm list_display = ['name', 'slug', 'created', 'last_updated', 'Tags', 'Photo', 'Description', 'Duration'] readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Tags', 'Photo', 'Description', 'Duration'] admin.site.register(Tours, ToursAdmin) class LocationsAdminForm(forms.ModelForm): class Meta: model = Locations fields = '__all__' class LocationsAdmin(admin.ModelAdmin): form = LocationsAdminForm list_display = ['name', 'slug', 'created', 'last_updated', 'Photo', 'MainLocLat', 'MainLocLon', 'MainLocRad', 'Audio', 'Description'] readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Photo', 'MainLocLat', 'MainLocLon', 'MainLocRad', 'Audio', 'Description'] admin.site.register(Locations, LocationsAdmin) class PhotosAdminForm(forms.ModelForm): class Meta: model = Photos fields = '__all__' class PhotosAdmin(admin.ModelAdmin): form = PhotosAdminForm list_display = ['name', 'slug', 'created', 'last_updated', 'Photo'] readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Photo'] admin.site.register(Photos, PhotosAdmin) class PlaceLocationsAdminForm(forms.ModelForm): class Meta: model = PlaceLocations fields = '__all__' class PlaceLocationsAdmin(admin.ModelAdmin): form = PlaceLocationsAdminForm list_display = ['name', 'slug', 'created', 'last_updated', 'Latitude', 'Longitude', 'Radius'] readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Latitude', … -
Heroku deploying trounles
After deploying my django-site get this lines in heroku's logs: 2018-03-22T20:02:04.357161+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 352, in import_app 2018-03-22T20:02:04.357162+00:00 app[web.1]: __import__(module) 2018-03-22T20:02:04.359538+00:00 app[web.1]: ModuleNotFoundError: No module named 'Django_work' 2018-03-22T20:02:04.360261+00:00 app[web.1]: [2018-03-22 20:02:04 +0000] [8] [INFO] Worker exiting (pid: 8) 2018-03-22T20:02:04.440542+00:00 app[web.1]: [2018-03-22 20:02:04 +0000] [9] [INFO] Booting worker with pid: 9 2018-03-22T20:02:04.551144+00:00 app[web.1]: [2018-03-22 20:02:04 +0000] [4] [INFO] Reason: Worker failed to boot. 2018-03-22T20:02:04.550981+00:00 app[web.1]: [2018-03-22 20:02:04 +0000] [4] [INFO] Shutting down: Master 2018-03-22T20:02:04.683774+00:00 heroku[web.1]: Process exited with status 3 2018-03-22T20:02:07.203169+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=boiling-wildwood-73678.herokuapp.com request_id=35542afb-486a-4cee-9d10-9f3ccca71362 fwd="178.64.164.115" dyno= connect= service= status=503 bytes= protocol=https 2018-03-22T20:02:51.134012+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=boiling-wildwood-73678.herokuapp.com request_id=430b2ce4-1041-4791-b965-18c341e3f32f fwd="178.64.164.115" dyno= connect= service= status=503 bytes= protocol=https Project link: https://github.com/AlfredMulder/Django_work -
What is the securest way to get image from users in Django
I already can get image from user and save it successfully but I'm wondering something after see so many warning about getting image from users in Django documents. Django says that we can't exactly trust the image file which come from users. Because it can be another file (like an HTML file) but with another header/meta data (like JPG/PNG). So, our system can't understand that isn't a real image file. There are security risks if you are accepting uploaded content from untrusted users! See the security guide’s topic on User-uploaded content for mitigation details. said on Django docs. Here is more: Django’s media upload handling poses some vulnerabilities when that media is served in ways that do not follow security best practices. Specifically, an HTML file can be uploaded as an image if that file contains a valid PNG header followed by malicious HTML. This file will pass verification of the library that Django uses for ImageField image processing (Pillow). When this file is subsequently displayed to a user, it may be displayed as HTML depending on the type and configuration of your web server. So, what is the safest way to handle images coming from users? I want to … -
Django pre_save many_to_many relation
class Category(Model): name = models.CharField(max_length=45) class Animal(Model): name = models.CharField(max_length=45) categories = models.ManyToManyField(Category) @receiver(pre_save, sender=Animal) def animal_create_update(sender, **kwargs): # get the selected categories and do something print(categories) I'm trying to find a way to get access to categories during the pre_save signal. Is it possible? -
NoneType is not iterable
I am building an application using Django 2.0 and Python 3, but I am having some issues with parsing a file using a custom class I have created this class: class MailWareConfiguration: _configuration = {} def __init__(self, data, *args, **kwargs): if self._configuration == {}: self._configuration = self.dot(data) def accessible(self,key): if self.exists(key) and (self._configuration[key] and not self._configuration[key] == ''): return True else: return False def dot(self, data, prepend = ''): print('MailwareConfiguration.dot started') results = {} print('RAW: ' + str(data)) for key,value in data.items(): print('RAW VAL: '+str(value)) if isinstance(value, dict): print('KEY: ' + str(key) + ' DICT: '+str(value)) results = results.update(self.dot(value,prepend+key+'.')) else: print('KEY: ' + str(key) + ' VALUE: '+str(value)) results[prepend+key] = value print('RAW PROCESSED: ' + str(data)) print('MailwareConfiguration.dot finished') return results def exists(self, key): if key in self._configuration: return True else: return False def get(self, key, default): if self.accessible(key): return self._configuration[key] else: return default The purpose of this class is to process a dict into a flat structure dict where each subsequent level would be seperated by a dot, similar to what the config function does in Laravel PHP. This is done, so that I can easily provide a readable implementation of a .json file outside of Git, so that sensitive … -
How to display AUTH_LDAP_PROFILE_ATTR_MAP
I am trying to map certain attributes of an ldap user by using django-auth-ldap. At the moment, I can not figure out how to display AUTH_LDAP_PROFILE_ATTR_MAP but AUTH_LDAP_USER_ATTR_MAP works because it compatible with the user-model in django. Settings.py AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", } AUTH_LDAP_PROFILE_ATTR_MAP = { "salutation": "titel", "phone": "telephoneNumber", "mobile": "mobile", } views.py def view_profile(request, pk=None): if pk: user = User.object.get(pk=pk) else: user = request.user args = {'user': user} return render(request, ('accounts/profile.html'), args) profile template <tr><td><input value="{{ user.first_name}}"></input></td></tr> <tr><td><input value="{{ user.last_name}}"></input></td></tr> <tr><td><input value="{{ user.email}}"></input></td></tr> <tr><td><input value="{{ user.salutation }}"></input></td></tr> <tr><td><input value="{{ user.phone}}"></input></td></tr> <tr><td><input value="{{ user.mobile}}"></input></td></tr> As you can probably guess first_name, last_name and email work the other three don't. I am really looking for an answer as I can not work without this. Thanks in advance. -
Removing image and clearing corresponding value in JSON
I am using Gridster widget for webpage.I have widgets which have images on them.There is a JSON which gives data about what image should be there on each grid(I get text from JSON and then get corresponding image from database).I want a button on each image which will delete the image from the widget and also remove the corresponding value from JSON. My JS loop which generates widgets: for(var index=0;index<json.length;index++) { {% load static %} gridster.add_widget('<li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% get_static_prefix %}images/'+json[index].html+'"></li>',json[index].size_x,json[index].size_y,json[index].col,json[index].row); }; My JSON var json = [{ "html": 'abc.png', "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.png", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.png", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "abc.png", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "def.png", "col": 4, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "abc.png ", "col": 6, "row": 3, "size_y": 1, "size_x": 1 } ]; My HTML: <div class="gridster"> <ul> </ul> </div> The Fiddle is what I am trying to do In fiddle I have added a button to delete the image but it doesnt seem to work and after image … -
Getting value from drop-down in Django
been struggling to work out how to get a value from my drop-down. I'm pretty sure the problem is in text = form.cleaned_data['fields'] but I'm unsure how the method works. Can anyone point me in the right direction? My end-goal is to modify the user's choice and feed it back to them. forms.py from .models import Rating from django import forms class AuthorityForm(forms.ModelForm): class Meta: model = Rating fields = ('authority_name',) views.py from django.shortcuts import render from django.views.generic import CreateView, DetailView from .models import Authority, Rating from .forms import AuthorityForm from django.shortcuts import redirect # Create your views here. class HomeCreateView(CreateView): template_name = 'home.html' model = Rating def get(self, request): form = AuthorityForm return render(request, self.template_name, {'form':form}) #success_url = '/' def post(self, request): form = AuthorityForm(request.POST) if form.is_valid(): text = form.cleaned_data['fields'] args = {'form':form, 'text':text} return render(request, self.template_name, args) home.html <h2>Choose Authority:</h2> <form method="post" novalidate> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">Submit</button> </form> <h2> {{ text }} </h2> models.py from django.db import models # Create your models here. class Authority(models.Model): authority_name = models.CharField(max_length = 100) authority_url = models.URLField() def __str__(self): return self.authority_name class Rating(models.Model): authority_name = models.ForeignKey('Authority', on_delete=models.CASCADE) ratings = models.CharField(max_length = 20000) # Could this be …