Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I resize only the width in django Imagefield
Intro: I need to reduce the size of django images in my Profile Images such that the width is 300px and the height is decided automatically as proportionate to the original picture. How do I do that with my below code class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(upload_to='profile_images/', default='', blank=True, null=True) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): # Opening the uploaded image im = Image.open(self.profile_image) output = BytesIO() # Resize/modify the image im = im.resize((300, 250)) #Here the width is 300 and height is 250. I want width to be 300 and height to be proportionately added. How do I modify the above code # after modifications, save it to the output im.save(output, format='JPEG', quality=100) output.seek(0) # change the imagefield value to be the newley modifed image value self.profile_image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.profile_image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(Profile, self).save() -
Display Image from another website on Django template
I'm here wondering over one problem since 2 days and still not getting the solution. The problem is, I have one website URL e.g. "www.something.org/abc/xyz/". On this website there is a list of URLs which contains some images in JPG format. This URLs are like e.g."2019_01_03_11_12_12_..>" and when I click it, it opens as "www.something.org/abc/xyz/2019_01_03_11_12_12_648626_155_72_6372_6835.jpg". I also want to store these Image Name values separately in database models with certain fields like FacultyID, CourseID, Datetime and likewise. Image must will be stored on server or some other location. Now what I have to do is, I have to display these images from the website on my Django Template. I tried several approaches for doing this. First I tried to scrap this website data and stored it in textfile on my local machine. But after that I din get how to use this data to display images. Now please help me out to find the proper approach of this problem in Django- Python. Forget my approach and suggest me something which carry out the results. I'm waiting for the answers. Please help and get me out of this. -
django rest-auth/registration email validation
I have the following in my settings in the django rest framework app: #settings.py REST_USE_JWT = True SITE_ID = 1 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'mytestaccount@gmail.com' EMAIL_HOST_PASSWORD = 'mytestaccountPassword' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER ACCOUNT_EMAIL_REQUIRED = True with this settings I can sign up a new user and the following message pops up in console upon registration : """""From: mytestaccount@gmail.com To: test3@gmail.com Date: Sat, 05 Jan 2019 05:15:11 -0000 Message-ID: <154666531119.43600.12499673333763651759> Hello from example.com! You're receiving this e-mail because user amir3 has given yours as an e-mail address to connect their account. To confirm this is correct, go to http://127.0.0.1:8000/rest-auth/registration/account-confirm-email/OA:1gfeIh:QM0KigIvCJXX5otapkQccUMfbwk/ Thank you from example.com! example.com"""""" my question is that how can I make it to actually email me rather than just printing in console. I tried the following setting instead: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' but what happens is that the user will be added to the database with no email sent, let alone verifying by clicking the link, Would you please let me know what am I missing here, Thanks, -
How to use slave database when master database is locked in django?
I am using sqlite3 and MySQL databases. When sqlite3 is locked is there any way to use MySQL? -
Nonetype object has no attribute is_ajax
I am using Django-bootstrap-modal-forms in my project. But I want little customization and have added Upload and Author field as foreign key. If I do as of the library it works fine. But here I am getting Nonetype object has no attribute is_ajax. I don't know why it is Nonetype even though I am logged in. Model : class File(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) visible_to_home = models.ManyToManyField(Home, blank=True) # when none visible to all home visible_to_company = models.ManyToManyField(Company, blank=True) # when none visible to all company # To determine visibility, check if vtc is none or include company of user and if true, check same for home created_date = models.DateTimeField(auto_now=True) published = models.BooleanField(default=True) upload = models.FileField(blank=True, null=True, upload_to=update_filename) title = models.CharField(max_length=225, blank=True, null=True) description = models.TextField(blank=True, null=True) Forms class FileForm(PopRequestMixin, CreateUpdateAjaxMixin, forms.ModelForm): class Meta: model = File fields = ('title', 'description', 'upload') View class FileCreateView(PassRequestMixin, SuccessMessageMixin, CreateView): template_name = 'file/upload-file.html' form_class = FileForm success_message = 'File was uploaded successfully' success_url = reverse_lazy('home') def post(self, *args, **kwargs): """ Handle POST requests: instantiate a form instance with the passed POST variables and then check if it's valid. """ #form = self.get_form() form = self.form_class(self.request.POST, self.request.FILES) if self.request.method … -
serve static files from Django Docker to nginx
I'm dockerizing Django application but static files are not being served. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(os.path.dirname(BASE_DIR), 'static_my_project') ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn', 'static_root') docker-compose.yml services: nginx: image: nginx:alpine container_name: "originor-nginx" ports: - "10080:80" - "10443:43" volumes: - .:/app - ./config/nginx:/etc/nginx/conf.d - originor_static_volume:/app/static_cdn/static_root - originor_media_volume:/app/static_cdn/media_root depends_on: - web web: build: . container_name: "originor-web" command: ["./wait-for-it.sh", "db:5432", "--", "./start.sh"] volumes: - .:/app - originor_static_volume:/app/static_cdn/static_root - originor_media_volume:/app/static_cdn/media_root ports: - "9010:9010" depends_on: - db db: image: postgres:11 container_name: "originor-postgres-schema" volumes: - originor_database:/var/lib/postgresql/data ports: - "5432:5432" pgadmin: image: dpage/pgadmin4 container_name: "originor_pgadmin" volumes: - originor_pgadmin:/var/lib/pgadmin volumes: originor_database: originor_static_volume: originor_media_volume: originor_pgadmin: and nginx.conf server { ... location / { proxy_pass http://web; } location /static/ { alias originor_static_volume; } } But on access /admin/ in browser, it consoles f032d416bce1_originor-web | Not Found: /static/admin/css/login.css f032d416bce1_originor-web | Not Found: /static/admin/css/responsive.css f032d416bce1_originor-web | Not Found: /static/admin/css/base.css f032d416bce1_originor-web | Not Found: /static/admin/css/base.css I can verify the files there in /app/static_cdn/static_root directory by executing docker exec -it <container_id> ls -la /app/static_cdn/static_root -
How to make a reverse in DefaultRouter()
I'm setting up a new tests, and i want to make an reverse. router = DefaultRouter() router.register('profile', views.UserProfileViewSet, base_name='profile') urlpatterns = [ url(r'', include(router.urls)) ] So , i want make a reverse in tests.py. my shot is: CREAT_USER_URL = reverse('profile-create') And I simply get: Reverse for 'profile-create' not found. 'profile-create' is not a valid view function or pattern name. How should I set up a reverse in this case. -
Running setup.py install for mod-wsgi-packages: finished with status 'error'
I get this error below when i am trying to deploy my python app on heroku. Attached here are my requirements.txt file. certifi==2018.11.29 cfe==0.0.15 chardet==3.0.4 Cython==0.29.2 dj-database-url==0.5.0 Django==2.1.2 gitdb2==2.0.5 GitPython==2.1.11 gunicorn==19.9.0 idna==2.8 libsass==0.16.1 mod-wsgi==4.6.5 numpy==1.15.4 olefile==0.46 Pillow==5.3.0 pipenv==2018.11.26 psycopg2==2.7.6.1 pystan==2.18.0.0 pytz==2018.7 requests==2.21.0 setuptools==40.5.0 six==1.12.0 smmap2==2.0.5 urllib3==1.24.1 virtualenv==16.2.0 virtualenv-clone==0.4.0 wheel==0.32.2 the error message: remote:Running setup.py install for mod-wsgi-packages: started remote:Running setup.py install for mod-wsgi-packages: finished with status remote:adding packages/apr/build-1/mkdir.sh remote:adding packages/apr/build-1/libtool remote:adding packages/apr/build-1/make_exports.awk remote:adding packages/apr/build-1/apr_rules.mk remote: adding packages/apr/build-1/make_var_export.awk . . . . remote:/usr/bin/ld: final link failed: Bad value remote:collect2: error: ld returned 1 exit status remote:error: command 'gcc' failed with exit status 1 remote: remote: ---------------------------------------- remote:Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-3h0_r0m2/mod- wsgi/setup.py';f=getattr(tokenize, 'open', open) (file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install -- record /tmp/pip-z7cobg1q-record/install-record.txt --single-version- externally-managed --compile" failed with error code 1 in /tmp/pip- build-3h0_r0m2/mod-wsgi/ remote:Push rejected, failed to compile Python app. remote: remote:Push failed remote: Verifying deploy... remote: remote:Push rejected to python-tehila. remote: To https://git.heroku.com/python-tehila.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/python- tehila.git' -
Django & beforeunload event
I wanted to use the following code to fade the page out when the beforeunload event is fired. window.addEventListener("beforeunload", function (event) { $(document.body).fadeOut(600); }); I noticed that the page fades as expected when leaving and going to a different site, but the page does not fade when going from one app in my Django-powered site to another. Can anyone explain this behavior to me? I am just curious as to how Django is not causing the beforeunload event to fire. -
Some changes in docker container not being reflected in local code
Inside the docker container, I can make changes to /app directory and the changes will be reflected in my local code. Similarly, I can make changes in my local code and these changes will be reflected in the docker container. Inside the /app folder I have got /static directory. I can make changes inside /static and I can run the updated application, however these changes are not reflected in my local code. So basically changes to anything in static folder is not being reflected in local code. I thought it could be a permissions problem, ls -l showed that every folder in the /app directory was owned by user 'm' and group 'm', except the static directory which was owned by the user 'm' but belonged to the group 'root', but changing the group using chgrp didnt fix the issue. I thought I would try and seek some solution before attempting docker system prune. version: '3.2' services: app: #build: . image: tutorial:v1 volumes: - .:/app - static_volume:/app/static/ networks: - nginx_network - db_network depends_on: - db nginx: image: nginxtest ports: - 8000:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/app/static/ depends_on: - app networks: - nginx_network db: image: tutorialdb:v1 env_file: - .env restart: always … -
Django-React app puts Error when deploying to heroku
I've created a very simple Django - React app which actually shows only the main page. I used create-react-app. when I type git push heroku master I receive that error: remote: Building source: remote: remote: -----> Node.js app detected remote: remote: -----> Creating runtime environment remote: remote: NPM_CONFIG_LOGLEVEL=error remote: NODE_ENV=production remote: NODE_MODULES_CACHE=true remote: NODE_VERBOSE=false remote: remote: -----> Installing binaries remote: engines.node (package.json): 8.10.0 remote: engines.npm (package.json): 3.5.2 remote: remote: Resolving node version 8.10.0... remote: Downloading and installing node 8.10.0... remote: Bootstrapping npm 3.5.2 (replacing 5.6.0)... remote: npm 3.5.2 installed remote: remote: -----> Building dependencies remote: Installing node modules (package.json) remote: npm ERR! Linux 4.4.0-1031-aws remote: npm ERR! argv "/tmp/build_0a81cf9bbf3f1ba3a96d3d0cf2296f25/.heroku/node/bin/node" "/tmp/build_0a81cf9bbf3f1ba3a96d3d0cf2296f25/.heroku/node/bin/npm" "install" "--production=false" "--unsafe-perm" "--userconfig" "/tmp/build_0a81cf9bbf3f1ba3a96d3d0cf2296f25/.npmrc" remote: npm ERR! node v8.10.0 remote: npm ERR! npm v3.5.2 remote: npm ERR! code MODULE_NOT_FOUND remote: remote: npm ERR! Cannot find module 'internal/util/types' remote: npm ERR! remote: npm ERR! If you need help, you may report this error at: remote: npm ERR! <https://github.com/npm/npm/issues> remote: remote: npm ERR! Please include the followingfile with any support request: remote: npm ERR! /tmp/build_0a81cf9bbf3f1ba3a96d3d0cf2296f25/npm-debug.log remote: remote: -----> Build failed remote: remote: We're sorry this build is failing! You can troubleshoot common issues here: remote: https://devcenter.heroku.com/articles/troubleshooting-node-deploys remote: remote: Some possible problems: … -
Sending Data from jsavascript to python
I have read through all the postings and cannot find anything that will work for my program. I am using the mapbox js framework and want to send the users location 'position' to my python view code to store it in a database. When I do a console.log() in the js code it doesnt print anything. When I do a print in python it prints 'None'. I tried ajax like other posts had but nothing seems to work. Maybe I am going about passing data from templates to python code in the wrong way... Please help home.html {% extends "geotracker/base.html" %} {% load static %} {% block content %} <body> <div id='map' width='100%' style='height:400px'></div> <form id="myform" name="myform"> {% csrf_token %} <input type="hidden" id="location" name="location"/> </form> <script> mapboxgl.accessToken = 'mytoken'; var map = new mapboxgl.Map({ container: 'map', // container id style: 'mapbox://styles/mapbox/streets-v9', center: [-96, 37.8], // starting position zoom: 3 // starting zoom }); // Add geolocate control to the map. var geolocate = new mapboxgl.GeolocateControl(); map.addControl(geolocate); geolocate.on('geolocate', function(e) { var lon = e.coords.longitude; var lat = e.coords.latitude var position = [lon, lat]; var element = document.getElementById('location'); element.innerHTML = position; //console.log(position); var frm = $('#myform'); frm.submit(function (ev) { console.log('submitting...'); $.ajax({ type: … -
Django Authentication credentials separate from user data
I am building a system where many accounts will not have login credentials (e.g companies) unless specifically provided. In order to achieve this, I have the following account model (not implemented yet, currently designing on a piece of paper): Table: Account Fields: ID, fname, lname, type, created_at, activated_at Table: AccountCredentials Fields: Account ID, email, password Relations: Account <- 1-to-1 -> AccountCredentials All permissions, operations etc will be performed over the Account model; so, the Account model will be the django auth user model. I have used custom User models and managers before; however, this is something I am not sure how to implement. How should I tell the AbstractBaseUser model to authenticate using credentials.email and credentials.password (credentials being the relation name between Account and AccountCredentials)? From checking AbstractBaseUser source code and checking some files, it seems like I can override get_username method; so that, the username field is being read from credentials. However, I am not sure how to do the same for password as it is hard coded in model. -
Django optional field with format check
i want to make the key field optional at the signup. but i dont know why i can't use == None here. The form always responses that it expected data for the key field. how do i skip this check if no key has been provided? It should only get checked if the user has provided a key. def signup(request): if request.method == 'POST': form = RegistrationForm(request.POST) key = Key.from_blob(request.POST['key'].rstrip("\r\n"))[0] if form.is_valid(): if key == None: form.save() messages.add_message(request, messages.INFO, "Thanks for you Registration, you are now able to login.") return redirect(reverse('login')) if key.key_algorithm == KeyAlgorithm.RSAEncryptOrSign: form.save() messages.add_message(request, messages.INFO, "Thanks for you Registration, you are now able to login.") return redirect(reverse('login')) else: messages.add_message(request, messages.INFO, "Only RSA keys are allowed.") else: return render(request, 'signup.html', {'form': form}) else: form = RegistrationForm() args = {'form': form} return render(request, 'signup.html', args) -
django-admin dbshell raises django.core.exceptions.ImproperlyConfigured
I know this question has been asked before, but none of them worked for me so far, so I'm going to give it a chance here. I'm trying to use MySQL as my database in django, but when I modify the settings.py and run the command: django-admin dbshell I get the following error: django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. What I did: - I'm running windows 10. using pipenv, I create fresh virtual environment. install django. start new project. edit the settings.py in the settings.py I change the DATABASES to the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test_db', 'USER': 'root', 'PASSWORD': '****', 'HOST': '127.0.0.1', 'PORT': '3306', } } also pip installed mysqlclient Weird thing is that when I make migrations, new tables are created, which means that DB works. why doesn't the command django-admin dbshell work? -
Django, How to enforce model Foreinkeys to have same value
In Django I want to enforce that a model which has two foreinkeys of differents models which has the same type of field to be the same, in example: class Model1(models.Model): f1 = models.CharField(max_length=48) class Model2(models.Model): f1 = models.CharField(max_length=48) class Model3(models.Model): field1 = models.ForeignKey(Model1) field2 = models.ForeignKey(Model2) I want that creation of objects of Model3 would be made only if f1 field of Model1 and Model2 are the same. Thanks, -
What is the right way to handle views for multiple layers of user privileges?
Imagine this scenario: I want to set up a simple blog with three layers of privileges: author, moderator and admin. I am wondering what the best way to manage templates would be. Depending on the user type, all pages of the app should look in a different way. For example, moderators should have "mod panel" in the navbar and little red "crosses" allowing them to delete comments. Admins should be able to delete posts, etc. The only common element that appears on every page is the navbar. Thus, I have created four basic templates: logged.html, not-logged.html, mod.html and admin.html. Now, let's say that I need the index page to look differently for all types of users - this leads to not-logged-index.html, logged-index.html, mod-index.html, admin-index.html Then, I repeat the same routine for all pages that need to be altered depending on the user. My attempt solves this problem, but the number of templates escalates very quickly. Is there a better way to tackle this? -
Django - getting a syntax error in a class generic views
Right now I`m learning django and going through documentation. And when I try to use generic views it gives me an exeption: File "/home/jeffr/Рабочий стол/codetry/mysite1/polls/views.py", line 8 def IndexView(generic.ListView): ^ SyntaxError: invalid syntax This is my views.py: from django.views import generic from .models import Choice, Question def IndexView(generic.ListView): template_name = 'polls/index.html' contest_object_name = 'latest_question_list' get_queryset(self): """Return the last five published questions""" return Question.objects.order_by('-pub_date')[:5] def DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' The full traceback paste can be found here: http://dpaste.com/3QMN3A0 Any help would be greatly appreciated, Thanks -
Do I even need Django?
I'm currently building a website where vendors from my city can authenticate and post their products, so users can search and buy them. I started building the website with Django; in the meantime, I was taking a beautiful ReactJS 30+ hours online course and learning how much you can do with it: not only pure frontend, e.g. Routing, GET/POST requests, Forms and validation, Authentication. My initial idea was building the website with Django Rest (backend) AND React (frontend), but now I have a question: Can I build my buy&sell website with React ONLY? (maybe using some pre-made backend networks like Firebase to save/fecth data to/from a database, to save time). In your opinion would I need some backend functionalities which would be impossible/inconvenient to implement with React, Firebase or other services? Please consider that I'm talking about a quite standard buy&sell website with authenticated vendors and buyers. Thank you very much for any advice. -
jquery accordion cutting off buttons
I was trying to get fancy and wire in a jquery accordion into my form (to split up parts of the form they may never really want to ever change and keep it out of the way). The original django form was in the html under: just a cold-md-12 with other md-6s to split form into two columns. Now with accordion I have it based on the example on the website (http://jqueryui.com/accordion/#default) : {% block page-js %} $( function() { $( "#accordion" ).accordion({ heightStyle: "content" }); } ); {% endblock %} <div id="accordion"> <h1> Section 1</h1> <div> <div class="col-md-12"> <h2>Group</h2> <form id="group_create_form" action="." class="form-horizontal" method="post"> {% csrf_token %} {{ group_form.non_field_errors }} <div class="col-md-6"> {{ group_form.group_name.errors }} {{ group_form.group_name.label_tag }} {{ group_form.group_name }} </div> ..rest of form.. ..then two form groups side by side <div class="form-group col-md-6"> <label for="provider_search_name">Name: </label> <div class="col-md-6"> <input id="search_name" name="search_name" class="form-control"/> <input type="hidden" id="search_name_id" name="search_name_id" value="" /> </div> <div class="col-md-6"> <button type="button" class="btn" id="SearchAdd">Add</button> <button type="button" class="btn" id="SearchClear">Clear</button> </div> <label for="add_name">Click on name to remove </label> <div class="col-md-12"> <select id='add_name' name='add_name' class='form-control' size='5' multiple='multiple'> {% for pro in associated_providers %} <option value="{{ pro.value }}">{{ pro.label }}</option> {% endfor %} </select> </div> </div> <div class="form-group col-md-6"> ..another … -
Django React CSRF Issues
Building my first app using Django as back end and React as front end. Locally, I have both running on port 8000 and 3000 respectively. I have a short snippet of code I found online to help me test whether or not my CSRF and CORS policies are set correctly: const API_HOST = 'http://localhost:8000'; let _csrfToken = null; async function getCsrfToken() { if (_csrfToken === null) { const response = await fetch(`${API_HOST}/csrf/`, { credentials: 'include', }); const data = await response.json(); _csrfToken = data.csrfToken; } return _csrfToken; } async function testRequest(method) { const response = await fetch(`${API_HOST}/ping/`, { method: method, headers: ( method === 'POST' ? {'X-CSRFToken': await getCsrfToken()} : {} ), credentials: 'include', }); const data = await response.json(); return data.result; } class App extends Component { constructor(props) { super(props); this.state = { testGet: 'KO', testPost: 'KO', }; } async componentDidMount() { this.setState({ testGet: await testRequest('GET'), testPost: await testRequest('POST'), }); } render() { return ( <div> <p>Test GET request: {this.state.testGet}</p> <p>Test POST request: {this.state.testPost}</p> </div> ); } } export default App; When I run this code locally, I get the correct response which is, the "KO" gets changed to "OK" when the responses come back valid. This only works … -
SQL Query logic to Django ORM Query logic
I have tried to think about how the following SQL query would be structured as a Django ORM query but I have had no luck in my multiple attempts. Can anyone help? SELECT targets_genetarget.gene, count(targets_targetprediction.gene) as total FROM targets_genetarget LEFT OUTER JOIN targets_targetprediction on targets_targetprediction.gene = targets_genetarget.gene WHERE list_name LIKE %s GROUP BY targets_genetarget.gene -
Looping through list to store variables in dictionary runs in error
What I want to do: Get user input from HTML form, store input in variables within Django and perform calculations with variables. To accomplish that, I use following code: my_var = requst.POST.get('my_var') To prevent having 'None' stored in 'my_var' when a Django page is first rendered, I usually use if my_var == None: my_var = 1 To keep it simple when using a bunch of variables I came up with following idea: I store all variable names in a list I loop through list and create a dictionary with variable names as key and user input as value For that I wrote this code in python which works great: list_eCar_properties = [ 'car_manufacturer', 'car_model', 'car_consumption',] dict_sample_eCar = { 'car_manufacturer' : "Supr-Duper", 'car_model' : "Lightning 1000", 'car_consumption' : 15.8, } dict_user_eCar = { } my_dict = { 'car_manufacturer' : None, 'car_model' : None, 'car_consumption' : None, } for item in list_eCar_properties: if my_dict[item] == None: dict_user_eCar[item] = dict_sample_eCar[item] else: dict_user_eCar[item] = my_dict[item] print(dict_user_eCar) Works great - when I run the code, a dictionary (dict_user_eCar) is created where user input (in this case None simulated by using a second dictionary my_dict) is stored. When User leaves input blank - Data from dict_sample_eCar … -
Django/Ajax/Javasdript JSON.parse convert string to JavaScript object
I am using Ajax to to send a get request from the sever, i am querying and getting a particular product from the product model, i want to return result as JavaScript objects but its return this '{' as i try to access the first value from the responseText[0]. How can i convert data return to js object. here is my code views.py def edit_product(request): product_id = request.GET.get('product_id') print('THIS IS PRODUCT ID ', product_id) product = Product.objects.get(pk=product_id) data = [ { 'name':product.name, 'brand':product.brand, 'price':product.price, 'description':product.description } ] return HttpResponse(data) ajax.js function getProductEditId(product_id){ //alert(id) document.getElementById('gridSystemModalLabel').innerHTML='<b> Edit product </b>'; //change modal header from Add product to Edit product var request = new XMLHttpRequest(); request.open('GET', '/edit_product/?product_id=' + product_id, true); request.onload = function(){ console.log('hello world', product_id) //var data = request.responseText var data = JSON.parse(JSON.stringify(request.responseText)); console.log(data[0]) } request.send(); } -
How can I redirect to a Thank you for contacting us page after user submits a form with Django?
I need to redirect the user to a new page that says, "Thank you for contacting us" after submitting a form with Django. I have tried using HttpResponseRedirect, reverse but I don't know how to implement it to all of the necessary files of my project.enter image description here When I click submit, it sends the data to the Django database so the form does work but the user does not know that because after they click submit it doesn't redirect to a thank you page.