Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django asking for instance instead of value
I have a django app with these models (only relevant fields): class Device(models.Model): serial = models.PositivewSmallIntegerField(unique=True, defeult=0000) …. class Conexion(models.Model): serial = models.ForeignKey(Device, to_field='serial', null=True, blank=True, on_delete=models.DO_NOTHING) …. When I try to assign a integer value to serial in Conexión, django asks for a Device instance. But this is wrong, because I have set to_field='serial'. I have exactly the same Foreign key in another model and it works ok. This is the exception: ValueError: Cannot assign "11": "Conexión.serial" must be a "Device" instance -
Is there any way to use the return value of custom python script to django template?
I'm trying to run a custom python script and return its value to template. The return function from custom script is returning value in the script but i can't use it in template. This is my custom script which returns the label value: def genre(f): K.clear_session() model = joblib.load('music/finalized_CNNmodel.sav') print(model.layers[0].input_shape) mel_spec(f) test_image=image.load_img(f'media/{f.file.name}.png', target_size=(256,256), color_mode='rgb') test_image=image.img_to_array(test_image) test_image=np.expand_dims(test_image,axis=0) result=model.predict(test_image) label = np.argmax(result) return label I'm calling this function through views as: def model_form_upload(request): documents = Document.objects.all() if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): print(request.FILES) newdoc = Document(file=request.FILES['file']) newdoc.save() print(newdoc.file.name) genre(newdoc) return render(request,'music/result.html', {'documents':documents,'form':form}) else: form = DocumentForm() return render(request,'music/result.html', {'documents':documents,'form':form}) This is my template: {% if genre.label == 0 %} CLASSICAL {% elif genre.label == 1 %} DOHORI {% else %} POP {% endif %} I expected to show the result in the template but the return value is not passing to the template. -
Path to image in Django Template for emails not work
I want to add the images to my html template for the emails. In my project settings i have MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'django.template.context_processors.media', ], }, }, ] in my url i have urlpatterns = [ ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my project structure my email method message = render_to_string('recovery_password.html', { "code": code, "MEDIA_URL": settings.MEDIA_URL }) mail_subject = 'Recovery password' email = EmailMessage(mail_subject, message, to=[to_email], ) email.content_subtype = "html" email.send() and in the recovery_password.html i have link on the image <a><img src="{{MEDIA_URL}}image1.png/></a> But my image in the email not work. It doesnt display in the temlate -
How to Solve Name Error Global Name Not Defined
I am getting a Name Error when trying to render my view. It says the global name 'form' is not defined. But when I look at my code, I feel like I am defining the name form. I am getting the error for the code below : if form.is_valid() def manifest(request): form = CreateManifestForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() return redirect('edit_manifest_frombrowse') else: reference_id = request.POST.get('Reference_Nos') data = Manifests.objects.all().filter(reference=reference_id) form = CreateManifestForm(initial={'reference': Orders.objects.get(reference=reference_id)}) context = { 'reference_id': reference_id, 'form': form, 'data': data, } return render(request, 'edit_manifest_frombrowse.html', context) TRACEBACK Environment: Request Method: POST Request URL: http://127.0.0.1:8000/manifest_reference_view Django Version: 1.10 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'unit'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/andrews/Desktop/WBU/web_unit/unit/views.py" in manifest_reference_view 236. if form.is_valid(): Exception Type: NameError at /manifest_reference_view Exception Value: global name 'form' is not defined -
Nginx server error 500?The detail view works on development system but on the server gives server error (500)?
I have a Django app configured with Nginx and gunicorn on ubuntu machine. The detail view works fine on my machine but when deployed it gives Server Error (500) I checked the python versions on the virtual env of the server and my machine and both are Python 3.6.5 I checked the logs of Gunicorn and Nginx and nothing suspicious, I enabled the debugging and still, nothing was found. I checked if the template file reference matched in the views.py what should I do next? -
How to Fix the Code In Order to lets the Function Working
I'm getting a django project to fix the error inside the code, may i know what is the problem of this few line of code which cause the add and delete button on the webpage does not function well? I've try fix some typo error in the code, but it's still not working so i changing bck the code to its original way. {% extends "app/layout.html" %} {% block content %} <script> $(document).ready(function () { var i=1; $("#add_row").click(function(){ $('#addr'+i).html("<td>"+ (i+1) +"</td><td><input name='item_id' type='item_id' placeholder='Item ID' class='form-control input-md' /> </td><td><input name='item_name' type='text' placeholder='Item Name' class='form-control input-md'></td><td><input name='description' type='text' placeholder='Description' class='form-control input-md' ></td><td><input name='quantity' type='text' placeholder='Quantity' class='form-control input- md' /> </td><td><input name='unit_price' type='text' placeholder='Price Per Unit' class='form-control input-md' /> </td>"); $('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>'); i++; }); $("#delete_row").click(function(){ if(i>1){ $('#addr'+(i-1)).html(''); i--; } }); }); </script> <div class="formpurchaseorder margintop" > <form class="purchaseordersubmission" action="purchaserequisitionconfirmation" method="POST"> {% csrf_token %} <div class="row margintop"> <div class="col"> <input type="text" class="form-control" name="purchase_requisition_id" value="{{purchase_requisition_id}}" placeholder="Purchase Requisition ID" readonly> </div> <div class="col"> <input type="text" class="form-control" name="person_id" id="person_id" value="{{person_id}}"placeholder="Person ID" readonly> </div> </div> <br/> <div class="row clearfix"> <div class="col-md-12 column"> <table class="table table-bordered table-hover" id="tab_logic"> <thead> <tr > <th class="text-center">#</th> <th class="text-center">Item ID</th> <th class="text-center">Item Name</th> <th class="text-center">Description</th> <th class="text-center">Quantity</th> <th class="text-center">Price Per Unit</th> </tr> … -
Wagtail modeladmin: Pass data to create_view_class
Im creating a modeladmin with special viewmodels for create/edit/delete. I need to pass data to the create view (a pk for a foreign key that is not part of the form). What is the best way to go about this? -
"No display of image in django when got access to aws s3 bucket"
"I tried to display images in django from aws s3 bucket the image is not displaying no error is shown" "This is a django server and images are from aws s3 bucket AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')enter code here AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' "The display of image is expected in django profile" error: no display of any image and no error is shown -
How to get cors to work properly with angular (apollo client ) and django/graphene
I am trying to build an application with python-graphene and django to persist data on the database side and using angular on the client side. I have developed both sides and they are working well independently, angular using the in-memory-web-api and graphene using insomnia (a postman style application for linux). To integrate them, I am trying to use apollo-angular. However, the request is returning a 404. I am fairly new to web development, so I might be missing something trivial. Searching online I found out that because the server is running on http://localhost:8000 and the application is running on http://localhost:4200, I needed to have CORS setup on the server side. I have followed the instructions on the manual: Install corsheaders via pip install django-cors-headers. Add corsheaders to INSTALLED_APPS. Add corsheaders.middleware.CorsMiddleware topmost at MIDDLEWARE. But still the error persisted. That is when I came across this thread and the answers seemed to be relevant. That is when I: Added CORS_ORIGIN_ALLOW_ALL = True and CORS_ALLOW_CREDENTIALS = True to settings.py at the server. Removed django.middleware.clickjacking.XFrameOptionsMiddleware from MIDDLEWERE. Added the withCredentials header to the request at the client side. Cleaned the browser cashed data and cookies. But still the error persisted. Here is my … -
How to display python variable values in Django template without using Models?
I'm new to Django and am facing this problem currently. I want to calculate the area and perimeter of a circle and post the result in the Django Template. I used a form to allow a user to input any number which will be considered as the radius. Using the POST method, it will process it and output me the area and perimeter (in views.py file). However, I'm not able to display the area and perimeter values in my Django template HTML page. The only values I store in my model is the radius value inputted by the user. Please do help. myapp/models.py: from django.db import models # Create your models here. class Circle(models.Model): radius = models.IntegerField(default = 0) def __str__(self): return str(self.radius) myapp/forms.py from django import forms from myapp.models import Circle class CircleForm(forms.ModelForm): class Meta: model = Circle fields = ["radius"] myapp/views.py import math from django.shortcuts import render from django.views.generic import TemplateView, CreateView, ListView from myapp.forms import CircleForm from django.urls import reverse_lazy from myapp.models import Circle from django.http import HttpResponseRedirect # Create your views here. class HomeView(TemplateView): template_name = 'home.html' class CircleView(CreateView): form_class = CircleForm template_name = 'insert_radius.html' def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): radius … -
Django how to save to multiple sub-directories, without getting SuspiciousFileOperation
I'm still new to django, i got stuck in managing users' pictures' upload. here is what i'm doing: i have two apps in my project "travellers" and "drivers" both have a photo field, which have to be uploaded to its right directory. well here is the MEDIA_ROOT settings: MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads/media/') here are the models: class Driver(Person): rating = models.DecimalField(default=0, decimal_places=1, max_digits=3) driving_license = models.CharField(max_length=50, null=True) insurance_number = models.CharField(max_length=50, null=True) company = models.ForeignKey(TransportCompany, on_delete=models.DO_NOTHING, null=True) photo = models.ImageField(null=True, upload_to='drivers/profile_pictures') class Traveller(Person): photo = models.ImageField(null=True, upload_to='travellers/profile_pictures') this is how my project is structured: backend- --bus --drivers --travellers --uploads- --media- --drivers- --profile_pictures --travellers- --profile_pictures well, when i try to add a traveller, or a driver, i get this error: SuspiciousFileOperation at /travellers/traveller/add/ The joined path (C:\mypath\web\backend\uploads\media\travellers\profile_pictures\cats.jpg) is located outside of the base path component (C:\mypath\web\backend\uploads\media\) -
is there a way to add new skin in django-ckeditor?
I'm trying to add new skin in django-ckeditor but its doesnt work and it shows a blank screen in django-admin I have installed the kama skin and extracted in static\ckeditor\ckeditor\skins\kama but doesnt seem to work. Below im showing my ckeditor config options: CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, 'toolbarCanCollapse': True, 'skin': 'kama', 'uiColor': '#b7d6ec', }, } Can someone please resolve this issue?I m very new to django ckeditor and its config and building my first website. Thanks in advance ! -
Django unable to hide sensitive variables
I have hooked my app to Sentry, and I'm trying to check if I can prevent sensitive varaiables from being logged. Here's my code: @sensitive_variables('user', 'pw', 'cc') def get(self, request): user = "foobar" raise Exception(f"{user}") My expectation was the it would replace the value of user with stars (**********), according to the docs: https://docs.djangoproject.com/en/2.2/howto/error-reporting/#filtering-sensitive-information However, the exception printed out its actual value -- and the sentry logs reflected this. How do i get it to replace the value of sensitive information with stars? -
While connecting to amazon web services s3 storage its throwing an error 'type error expected string or byte like object'
I am new Django website development and now I am trying to connect my django website to amazon web services but the error which is I am facing is that I am not able to solve it. I thought anybody here could help . settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') #This key I have set in another file AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') #This is also the same stored in another file AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #It's backend And the profile is also not opening its showing an value error. Can please help me out? Here is the error: if VALID_BUCKET.search(bucket) is None: TypeError: expected string or bytes-like object [02/Aug/2019 15:19:06] "POST /adform/ HTTP/1.1" 500 199049 I expected the output that the photo I upload should link with s3 storage but while linking its throwing an error . -
MQTT-Django. How can I implement it?
I´m trying to implement a Django-Mqtt system, but I´m a bit lost. I would like to update my models constantly with the data I receive from the topics. I´ve managed to update the model data with this function in views.py: def dhtDetail(request): member = request.user.userprofile listDHT = member.dht.all() for sensor in listDHT: topic = sensor.topic #This topic (sensor.topic) has temperature and humidity data m = subscribe.simple(topic, hostname="Broker IP", retained=False) mes = str(m.payload) mes = men.replace("'", "") mes = men.replace("b", "") mes = men.replace("Hum", "") mes = men.replace("Temp", "") mes = men.split(" ") sensor.temp = float(mes[3]) sensor.hum = float(mes[1]) sensor.save() member.dht.add(sensor) listDHT = member.dht.all() return render(request, 'web/dhtDetail.html', {'listDHT':listDHT}) Clearly, this only connects to broker and updates the data when "dhtDetail.html" is reloaded. How can I implement MQTT with Django to constantly update the models? -
how to get COUNT from id field of database using abstract user
how to get a count of total users in the database using an abstract user model. I want to use the id field to get the count of total users -
Wagtail ModelAdmin: Does not hide widget label
I have written an own panel that utilizes the django modeladmin. The modeladmin is connected to another model via a foreign key, but I dont want the user to be able to change the foreign key relation, only the other data on the form. I have therefor tried to hide the widget via the panels argument on the model admin: panels = [ FieldPanel("event_detail", widget=HiddenInput), FieldPanel("title"), FieldPanel("content"), FieldPanel("send_time"), ] This handles the input field correctly in the modeladmin, but sadly I still see the label in the modeladmin, which will confuse my users. How can I make sure that not only the field is removed but also the label? -
AttributeError: module 'profile' has no attribute 'run'
So I have an extended User model (extended AbstractUser) called Profile. This was in a seperate app called "profiles". I was plugging in the standard login and realised it was looking for a "profile" app name as standard, so I renamed it (directories, code, DB schema) which I thought should work. app_name was actually already set to "profile" in apps.py, so didn't need to rename url references. No dice. I get the error in the title. So I removed all migrations (I'm at the stage where I can still do this OK :) ) and deleted the sqlite DB that I'm currently working with, thinking I'd just rerun the migrations and recreate everything. Same error. The stack trace is: λ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\base.py", line 361, in execute self.check() File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\debug_toolbar\apps.py", line 18, in … -
Showing count of total objects in Django template
I have a Djanjo project where I add code snippets to a database, I would like to show display, in my template, a count of total snippets. Here is my model file: import datetime from django.utils import timezone from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Snippet(models.Model): snippet_name = models.CharField(max_length=200) description = models.TextField(max_length=600) code = models.TextField(default="null") approval_stage = models.CharField(max_length=200) updated = models.DateField('updated date') is_automated = models.BooleanField(default=False) def __str__(self): return self.snippet_name def total_snippets(self): return snippet_name.count() And here is the section of my template file where I want to display the number of snippets: <h5>{{ total_snippets }} total snippets</h5> This is rendering blank, with by value, on the final template. I've copied this code from another model, where I show a similar count of objects, and this works as expected, what am i missing here? -
Programing error: relation "api_role does not exist while makemigrations
Setting up a new brand new virtual environment and postgres db and can't even makemigrations. The system is running well on 2 other pc's python3.5 is installed virtual env created apps "requirements.txt" is sucessfully installed manage.py recognize the postgres server with the config created dev_henrique_desktop.py from .base import * DEBUG = True # Allow specific host headers only ALLOWED_HOSTS = ['localhost', '127.0.0.1', '.proregatta.com','10.0.2.2'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'proregatta', 'USER': 'postgres', 'PASSWORD': '*****', 'HOST': 'localhost', 'PORT': '5432', } } both py and postgres are on PATH virtual env activated checked pgAdmin III for the super user created "postgres" when installing psql then beggins the problem already forced drop db searched for the "api_role" related problem in the migrations in every answer i get my eyes on. every one says makemigrations. what about when you can't make the inicial makemigrations delete all migrations and fresh "makemigrations" unnistall and install formatted the pc when problem persisted I expected to at the very least to make the inicial makemigrations noticed that the other machines probably have this missing relation in the db but not in migrations. Traceback (most recent call last): File "C:\Users\henri\Documents\Projects\backend-django\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) … -
All urls are not mapped by django rest framework swagger
I implement Django-rest-swagger for documentation my API but swagger UI not showing all URLs. When ı add permission_classes = [AllowAny] in my View than show the URL on swagger UI but this time all user will connect my DB ı don't want to do this. I want when the user login then gets the JWT token, after that click the Authorize button on swagger than will access my APIs. How can ı implement correctly JWT Bearer auth on my swagger UI? django-rest-swagger-2.1.1 djangorestframework Version: 3.9.0 Django Version: 2.2.3 Settings: SWAGGER_SETTINGS = { 'LOGIN_URL': 'rest_framework:login', 'LOGOUT_URL': 'rest_framework:logout', 'USE_SESSION_AUTH': False, 'DOC_EXPANSION': 'list', 'APIS_SORTER': 'alpha', 'JSON_EDITOR': False, 'api_version': '0.1', 'SUPPORTED_SUBMIT_METHODS': [ 'get', 'post', ], 'SECURITY_DEFINITIONS': { "api_key": { "type": "apiKey", "name": "Authorization", "in": "header", "description": "JWT authorization" }, },} Urls.py: schema_view = get_swagger_view(title='Unite.Ad Api') router = routers.SimpleRouter() router.register(r'company', CompanyViewSet, basename="company") router.register(r'brands', BrandsViewSet, basename="company_brands") router.register(r'brand-categories', BrandCategoriesViewSet, basename="company_brand_categories") router.register(r'customer-representative', CustomerRepresentativeViewSet, basename="customer_representative") router.register(r'sectors', SectorViewSet, basename="company_sectors") router.register(r'brief', BriefViewSet, basename="briefs") router.register(r'brief-categories', BriefCategoriesViewSet, basename="briefs-categories") router.register(r'country', CountryViewSet, basename="country") router.register(r'province', ProvinceViewSet, basename="province") urlpatterns = [ path('', schema_view), path('', include(router.urls)), path('admin/', admin.site.urls), path('user/register/', RegistrationView.as_view()), path('user/login/', AuthTokenViewSet.as_view()), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('api-token-auth/', obtain_jwt_token), path('api-token-verify/', verify_jwt_token), ] CompanyViewSet.py: class CompanyViewSet(ModelViewSet): """ retrieve: Return the given company. list: Return a list of logged user company and … -
How to hyperlink data from database on django
I am trying to build a simple search function on django that leads me to the link when I click on it. (I know api links are json links so clicking on them gives you no output of value but the point is to be able to click on them) i tried using but it doesnt work from my results.html: {% for dataset in datasets %} <br/> {{ dataset.datasets_available }} <br/> {{ dataset.data_source }} <br/> {{ dataset.brief_description_of_datasets }} <br/> {{ dataset.country }} <br/> <a href='https://www.google.com'>{{ dataset.api_documentation }}<a> <br/> #^ is the part i wanna fix <br/> {% endfor %} {% else %} <p style="font-family:Cambria">No search results for this query</p> {% endif %}` from views.py: def results(request): query = request.GET.get('q') if query: datasets = api_data.objects.filter(Q(datasets_available__icontains=query)) context = { 'datasets': datasets, } return render(request, 'Search/results.html', context) from models.py: class api_data(models.Model): data_source = models.TextField() brief_description_of_data = models.TextField() datasets_available = models.TextField() brief_description_of_datasets = models.TextField() country = models.TextField() api_documentation = models.TextField() class Meta: verbose_name_plural = "api_data" api_documentation is currently urls in strings. i want to be able to click on the output in html and view the actual website -
Send AJAX request to Django view with vanilla JS
I'm trying to send a GET AJAX request to a Django view using vanilla JS. is_ajax() passes but I could not retrieve the request object properly. Here is my JS code. With/out JSON.stringify(data) doesn't work. document.querySelector('#testForm').onsubmit = () => { let data = {category : 'music'}; const request = new XMLHttpRequest(); request.open('GET', 'test/', true); request.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); request.onload = () => { const data = JSON.parse(request.responseText); console.log(data); } request.send(data); return false; }); And here is my Django view: def test(request): if request.is_ajax(): print('Yes!') data = {'category': request.GET.get('category', None)} return JsonResponse(data) else: raise Http404 It prints Yes! to the terminal but I get back a {category: null} in the console. This JQuery code works and I get the expected {category: "music"} response: $.ajax({ url: 'cart/', type: 'GET', data: data, dataType: 'json', success: function (data) { console.log(data); } }); I'm wondering what I'm missing in the vanilla JS code or in my Django view. -
Iterate through a string array in JSON
I'm looking to import data from a local JSON file into my DB Django. However, I have a problem because my JSON file contains a String array for each element and I can't iterate it. Example of the JSON file: [ { "key": "sword", "name": "Sword", "tier": 1, "tab": [ "damages", "cac" ] }, { "key": "bow", "name": "Bow", "tier": 1, "tab": [ "damages", "distance" ] }, ... ] I import this data using a script as follows: class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('json_file', type=str) def handle(self, *args, **options): with open(options['json_file']) as f: data_list = json.load(f) for data in data_list: Item.objects.get_or_create( key=data['key'], name=data['name'], tier=data['tier'], ) for build in data['tab']: Build.objects.get_or_create( key = build ) The above script does not work and I have the following error in the console: KeyError: 'tab' -
Django: reset password of user as the Django administration
I have a section for website's staff, where they can manage users (register, update users info, deactivate...) like in the Django administration. Is there a way to reset user's password like in /admin/auth/user/<int:id>/password/ ? Here what I have done so far: forms.py class UpdateForm(UserChangeForm): is_active = forms.BooleanField(required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ] group_name = forms.ChoiceField(choices=Group) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'group_name', 'is_active', 'password',) views.py # Update status of user @login_required @group_required('Staff') def updateUserView(request, id): if request.method == 'POST': form = UpdateForm(request.POST, instance=User.objects.get(id=id)) if form.is_valid(): user = form.save() group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) return redirect('accounts:users') else: form = UpdateForm(instance=User.objects.get(id=id)) return render(request, 'accounts/update_user.html', {'form': form})