Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
502 Error while downloading a huge zip file containing multiple images in it
So,I want the user to be able to click a button and download a zip file containing a bunch of images. A view gets called upon clicking the button, which fetches the images from an SFTP server using pysftp module and creates a zip file and sends a response to the user for download. Now this thing works absolutely fine in most of the cases but in some cases the server throws a 502 proxy error which is because the images are either large in size (This is a hunch) or in number. I assume this is a timeout kinda thing where its taking a lot of time for view to process things. It would be really helpful if anyone could suggest a solution for this. I dont want "502 proxy error" to come in any case. def download_images(request): if request.GET.get('profile_id') and request.GET.get('mattersheet_id'): profile_id = request.GET.get('profile_id') mattersheet_id = request.GET.get('mattersheet_id') cnopts = pysftp.CnOpts() cnopts.hostkeys = None sftp = pysftp.Connection(host=Conf.IMG_SERV_IP, username='blabla',cnopts=cnopts) file_dir = f'''{Conf.DIR_CATALOG_PRODUCT_PATH}/{profile_id}/{mattersheet_id}/products/''' # import pdb; pdb.set_trace() response = HttpResponse(content_type="application/force-download") zip_file = ZipFile(response, 'w') products = products = MatterSheetProducts.objects.filter(matter_sheet_id=mattersheet_id).values('product_code','product_name','product_id','product_category_name').distinct('product_category_name','product_name') import time a = time.time() for product in products: try: if sftp.exists(f"{file_dir}{product.get('product_id')}.jpg"): fh = sftp.open(f"{file_dir}{product.get('product_id')}.jpg",'rb') category_name = product.get('product_category_name') if product.get('product_category_name') else '' … -
How to launch a script based on date/time field
I have set up MariaDB for the backend database for Ptyhon Django project. As it is in the initial POC stage, I will change the database also if you suggest anything. There is a table where the user data will be stored for all the entries the users create. And the table contains a data/time field. I want to trigger email when the date/time field value is equal to current time. Like, if the record1 is having value of tomorrow's 12:31 PM then immediately the email should be triggered to the email ID of the user. The email sending part we can take care but how to trigger the event when the datetime field value is equal to the current date/time. One option is to continuously run a background job to check the date/time value but that is not feasible as 1000s of records will be there. Please suggest, I am a newbie to the Python web projects. -
Django reading json and fetching data to bulk create with optimized approach and minimum resources
Basically i was wondering if i could somehow use a single for loop to achieve a task I am new to python and i am learning about the efficient ways to achieve stuff This is the current scenario json = { items: [ {'uuid': 'some uuid', 'quantity': 2}, {'uuid': 'some uuid', 'quantity': 3}, {'uuid': 'some uuid', 'quantity': 4}] } I am receiving this json and have to make a query to fetch each of these items based on the provided uuid. After fetching these items i have to create their entry in another model which is related to this model. My approach is to separate the uuids and quantity into two separate lists through a for loop for item in json: item_uuids.append(item['uuid']) item_quantities.append(item['quantity']) Fetch item objects q = Q() [q.add(Q(uuid=uuid), Q.OR) for uuid in item_uuids] items = model.objects.filter(q) Then do a list comprehension item_objs = [] [item_objs.append(model(uuid=uuid, quantity=quantity)) for uuid, quantity in zip(items, item_quantities)] Then after all of this I make the final query model.objects.bulk_create(items) Is there any efficient way to achieve this, as it constantly disturbs me i might be following the wrong approach here. Any help would be really appreciated. Thanks in advance -
heroku run python manage.py migrate do not create table on heroku server
heroku run manage.py migrate Running python manage.py migrate on ⬢ bdsharma... up, run.9363 (Free) Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, shastri Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying sessions.0001_initial... OK Applying shastri.0001_initial... OK but these migrations are not applied in reality. It gives operational error while i run this on server. OperationalError at / no such table: shastri_occasion Request Method: GET Request URL: https://bdsharma.herokuapp.com/ Django Version: 3.1.1 Exception Type: OperationalError Exception Value: no such table: shastri_occasion Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py, line 413, in execute Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.12 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Thu, 10 Sep 2020 08:19:26 +0000 I have run migrate command many time on both heroku and local server but its not working. -
Django - CheckboxSelectMultiple with horizontal options
By default, the CheckboxSelectMultiple widget is rendering in a vertical list. How can I make it to a horizontal checklists? Minimal verifiable example In [8]: from django import forms In [9]: HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] In [10]: widget = forms.CheckboxSelectMultiple(choices=zip(HTTP_METHODS, HTTP_METHODS)) In [11]: print(widget.render('GET', 'GET')) Rendered Output <ul> <li><label><input type="checkbox" name="GET" value="GET" checked> GET</label> </li> <li><label><input type="checkbox" name="GET" value="POST"> POST</label> </li> <li><label><input type="checkbox" name="GET" value="PUT"> PUT</label> </li> <li><label><input type="checkbox" name="GET" value="PATCH"> PATCH</label> </li> <li><label><input type="checkbox" name="GET" value="DELETE"> DELETE</label> </li> </ul> -
Django admin custom descending and ascending field
I am using Django Admin to visualize and edit data of my Model. One of the model's field is date and unfortunately is a CharField but with a validator ( dd.mm.yyyy ). I am trying to figure out of a solution to sort those dates in the correct way when the admin press on the sort button that is default from django. In my experience with Java it was all about overwriting the compare function of the class. data_de_montat = models.CharField(help_text="eg: 02.07.2020 or 12.9.2021", max_length=15, validators=[ RegexValidator(r'^[0-9]{1,2}.[0-9]{1,2}.[0-9]{4}$', message='It should be dd.ll.aaaa', code='wrong format' )]) -
Queries And Multiple Categories models dropdown menu filtering in django template
I want my filter in dropdown menu to get back a query from 2 models(category[video,photo]) and occasion[wedding,engagement,baptism,etc..) here is my code: models.py class Category(models.Model): class Meta: verbose_name_plural = "Categories" name = models.CharField(max_length=254) friendly_name = models.CharField(max_length=254, null=True, blank=True) def __str__(self): return self.name def get_friendly_name(self): return self.friendly_name class Occasion(models.Model): name = models.CharField(max_length=254) friendly_name = models.CharField(max_length=254, null=True, blank=True) def __str__(self): return self.name def get_friendly_name(self): return self.friendly_name class Package(models.Model): name = models.CharField(max_length=254) friendly_name = models.CharField(max_length=254, null=True, blank=True) def __str__(self): return self.name def get_friendly_name(self): return self.friendly_name class Product(models.Model): category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL) occasion = models.ForeignKey('Occasion', null=True, blank=True, on_delete=models.SET_NULL) package = models.ForeignKey('Package', null=True, blank=True, on_delete=models.SET_NULL) long_description = models.TextField() short_description = models.TextField() things_include = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) rating = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): return self.category.name + " - " + self.occasion.name def thingsInclude_as_list(self): return self.things_include.split(',') def get_name_categoryOccasion(self): return self.category.name + " " + self.occasion.name views.py here in view I have get query for all models from database def all_products(request): """ A view to show all products, including sorting and search queries """ products = Product.objects.all() query = None categories = None occasions = None if request.GET: if 'category' in request.GET: categories = … -
TemplateDoesNotExist at /travello
I have got an error. How can solve this problem. When I was browsing: http://127.0.0.1:8000/travello Got an Error: TemplateDoesNotExist at /travello index.html Request Method: GET Request URL: http://127.0.0.1:8000/travello Django Version: 3.1.1 Exception Type: TemplateDoesNotExist Exception Value: index.html Exception Location: C:\Users\musat\Envs\myenv\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\musat\Envs\myenv\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\Users\musat\projects\telusko', 'C:\Program Files\Hexagon\ERDAS IMAGINE ' '2015\usr\lib\Win32Release\python', 'C:\Users\musat\Envs\myenv\Scripts\python38.zip', 'c:\users\musat\appdata\local\programs\python\python38\DLLs', 'c:\users\musat\appdata\local\programs\python\python38\lib', 'c:\users\musat\appdata\local\programs\python\python38', 'C:\Users\musat\Envs\myenv', 'C:\Users\musat\Envs\myenv\lib\site-packages'] Server time: Tue, 08 Sep 2020 04:57:26 +0000 -
Reverse for 'show_message' with arguments '('',)' not found. 1 pattern(s) tried: ['messages/<slug:the_sender>/$']
I believe the issue lies with slugs. I am not sure what's happening though. Urls.py: path('messages/', ShowMessageView.as_view(), name='message list'), path('messages/<slug:the_sender>/$', post_detail_view, name='show_message'),] Views.py: class ShowMessageView(ListView): template_name="messages.html" model= SendMessageModel class ShowDetailView(DetailView): model= SendMessageModel slug_field = 'sender' slug_url_kwarg = 'the_sender' template_name="detailmessage.html" post_detail_view = ShowDetailView.as_view() messages.html: {% for message in object_list %} {% if message.recipient == request.session.username %} <h5>{{message.datesent|date:'Y-m-d'}}<a href= "{% url 'show_messages' message.the_sender %}"> {{message.sender}}</h5> {% endif %} {% endfor %} I am a beginner in Django so I am not really sure how most of the stuff works. Any help would be appreciated. -
ReadTimeout with django and asgi
I'm tring with some async feature with Django3.1 async # urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('api/', views.api), path('api/aggregated/', views.api_aggregated), path('api/aggregated_sync/', views.api_aggregated_sync), ] # views.py import time import httpx import asyncio from django.http import JsonResponse from django.urls import path async def api(request): await asyncio.sleep(1) payload = {"message": "Hello World"} if "task_id" in request.GET: payload["task_id"] = request.GET["task_id"] return JsonResponse(payload) def get_api_urls(num=10): base_url = "http://127.0.0.1:9006/api/" return [ f"{base_url}?task_id={task_id}" for task_id in range(num) ] async def api_aggregated(request): s = time.perf_counter() responses = [] urls = get_api_urls(num=10) async with httpx.AsyncClient() as client: responses = await asyncio.gather(*[ client.get(url) for url in urls ]) responses = [r.json() for r in responses] elapsed = time.perf_counter() - s result = { "message": "Hello Async World", "responses": responses, "debug_message": f"fecth executed in {elapsed:0.2f} seconds.", } return JsonResponse(result) def api_aggregated_sync(request): s = time.perf_counter() responses = [] urls = get_api_urls(num=10) for url in urls: r = httpx.get(url) responses.append(r.json()) elapsed = time.perf_counter() - s result = { "message": "Hello Sync World!", "aggregated_responses": responses, "debug_message": f"fetch executed in {elapsed:0.2f} seconds.", } return JsonResponse(result) I tried wiht asgi server uvicorn and start with command: uvicorn --workers 10 --reload myproject.asgi:application --port 9006 But when I … -
How to create a dependent dropdown (as subcategory)
I want to have a dropdown menu which shows all item from a choice list. The picture below shows all my items from 'Category' which is hardcoded. How can I iterate through my choice field and fill their values into my dropdown menu? But more importantly is that I want that my dropdown menu for 'Product' should only show the choices related to my selection for 'Category'. I think its too complicated to create for all of them each a class. I want to do it by an if else like: If (get.Category).is Selected then iterate: for item in 'products' present as option. Im new in coding so I am not sure where to put my variables. my filter_list.html <div class="form-group col-md-4"> <label for="inputState">Product</label> <select id="inputState2" name="item" class="form-control"> <option selected>Choose...</option> {% for item in transactionSubCategory %} <option value="{{item.value}}">{{item.title}}</option> {% endfor %} <option value="banana">banana</option> <option value="orange">orange</option> <option value="strawberry">strawberry</option> </select> </div> my models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(default='SOME STRING') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) post = models.CharField(max_length=100, default='SOME STRING') category_choices = ( ('fruits', 'Fruits'), ('nuts', 'Nuts'), ('tea', 'Tea'), ('oil', 'Oil'), ('flowers', 'Flowers'), ('veggies', 'Veggies'), ('honey', 'Honey'), ('legumes', 'Legumes'), ('wheat', 'Wheat'), ('mushroom', 'Mushroom'), ) fruit_choices= ( ('apple', … -
No module "myapp" error in django while i try to run the server [closed]
enter image description here Iam new to django I tried everything to resolve this error please help me! -
Use existing table for django authentication
I am migrating an App from Java To Django. Since this app has a legacy database how can i use existing table(members) for django authentication without changing its schema. Below is members table Column | Type | Collation | Nullable | Default | Storage | Stats target | Description --------------------+------------------------+-----------+----------+---------+----------+--------------+------------- member_id | bigint | | not null | | plain | | membertypeid | integer | | | | plain | | email | character varying(100) | | | | extended | | password | character varying(100) | | | | extended | | challenge_question | character varying(100) | | | | extended | | challenge_answer | character varying(100) | | | | extended | | datedisabled | character varying(255) | | | | extended | | disabled | boolean | | | | plain | | profiletype | integer | | | | plain | | What i have tried is from django.contrib.auth.models import ( AbstractBaseUser, PermissionsMixin, BaseUserManager ) class UserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The given email must be set') try: user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user except: … -
Postgres pgadmin4 error: Unable to connect to server: timeout expired on docker
I'm running a dockerised django app with db settings: docker compose file I want to connect the db to pgadmin4, for that created a pgadmin4 container using docker run -p 5555:80 --name pgadmin -e PGADMIN_DEFAULT_EMAIL='postgresdb' -e PGADMIN_DEFAULT_PASSWORD='password' dpage/pgadmin4; and logged in on chrome with <docker-machine ip>:5555 Initiated a new server there with Host name/address: <ip of running db service> (attained using docker inspect on the running db container) port: 5432 (which is shown as the default port open for db service) When trying to connect its delays for a second and shows this timeout error: "Unable to connect to server: timeout expired on docker" Any workaround for this issue. Although, I can connect using terminal with docker exec -it <container-id> bash, is there any way I can connect using pgadmin4. I'm new to both docker and PostgreSQL. (to check the issue, I've closed the django app and, initiated another postgres container manually using, docker run --name local-db -e POSTGRES_PASSWORD=incorrect -d -p 5432:5432 postgres:alpineand try to connect to pgadmin4 using same way it connects well, but with the django server it fails..) -
DRF nested serializers. Write only primary key, but on read get whole object
I don't need nested create/update operations. I just want to write pk of created object to FK/M2M field and after creating main object get object from this FK/M2M field. Not its primary key. For instance, I got ValueRel and Value models. This is how they are related: class ValueRel(BaseModel): table = models.ForeignKey( Table, on_delete=models.PROTECT, ) object_id = models.CharField(max_length=36) @property def related_object(self): related_model = self.table.get_model() related_object = related_model.objects.filter(pk=self.object_id).first() return related_object class Value(BaseModel): profile = models.ForeignKey( Profile, on_delete=models.SET_NULL, blank=True, null=True, related_name="app_values", ) # I want to write into this field `pk` and get its object value_rel = models.ManyToManyField( ValueRel, blank=True, related_name="values", ) ... After creating ValueRel's instance and writing it to value_rel of Value's instance I want to get ValueRel's instance like object. Actual result (JSON response from API) "value_rel": [ "6a740343-0d37-4e6b-ba56-0c60ac51477f" ] Expecting this: "value_rel": [ { "pk": "6a740343-0d37-4e6b-ba56-0c60ac51477f" "table": "Speciality", "object_id": "02548144-a27d-4c17-a90b-334ccf9e1892", "related_object": "Information system" } ] Is there a way not to adding another field just for expected object representation and get it from value_rel? -
{% translate s %} passed in {% include ... with s=s %} not in .po file
I have a basic feed I am trying to render in my Django project. I have created a feed.html file as a base template for slight variations of the same type of feed. Among those variations, is the header of the feed. Importantly, I want that header to be translated into multiple languages. I have implemented this "variation" idea using {% include "feed.html" with variation=variation %}. However, I am having problems translating those variations. I am trying the following in feed.html: {% translate header %} Then in one of the templates where I want a variation of feed.html I have: {% include "feed.html" with header="Header" %} The problem is, the string "Header" does not make it into any of my .po files and therefore remains untranslatable. What am I doing wrong? Should I use different syntax? -
How to set DB in Django forms.py and models.py, if we are using manual method for multiple database
I'm using manually method to use multiple database with one app and one model. Adding DB details in settings.py Updated views.py queries with "using('dbname')" Because I have set my template, in such a way that user can select the database from dropdown, once it is selected that details are passed to urls.py and inturn to views, so this is dynamic. Could you please help me to understand how we can export this selected DB details to forms.py and models.py, so that my form data will match with the DB which is selected by the user. Thanks and Regards, Hema -
How can i record user audio in my django chat app?
I have a simple chat app like WhatsApp, but users are complaining for not being able to record a voice message as WhatsApp or messenger, I have been searching for over a week but didn't find anything that could help me, I have the audio model ready but what I can't do is record audio from my app directly instead of the user having to leave the website to record audio and save it as a file and then send it. Here is my models.py class Message(models.Model): chat_box = models.ForeignKey( ChatBox, related_name='chat_box', null=True, on_delete=models.CASCADE) message_sender = models.ForeignKey( User, related_name='message_sender', null=True, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) message = models.TextField(blank=True, null=True) file = models.FileField( upload_to='social_group_message_images', blank=True, null=True) image = models.ImageField( upload_to='social/friend_message_images', blank=True, null=True) audio = models.ImageField( upload_to='social/friend_message_audio', blank=True, null=True) video = models.ImageField( upload_to='social/friend_message_video', blank=True, null=True) my views.py (I'm going to change it later to make it work with ajax): def send_friend_file_message(request, pk): friend = get_object_or_404(User, pk=pk) friend = get_object_or_404(User, pk=pk) chat_box = ChatBox.objects.filter( user_1=request.user, user_2=friend).first() if not chat_box: chat_box = ChatBox.objects.filter( user_1=friend, user_2=request.user).first() message = Message(chat_box=chat_box, message_sender=request.user, file=request.FILES.get('file'), image=request.FILES.get('image'), video=request.FILES.get('video'), audio=request.FILES.get('audio')) message.save() return redirect('social:chat_friend', pk=pk) Finally the html that sends document/video/AUDIO messages: <div class="modal-body"> <div> <!-- Send file --> <form action="{% url 'social:send_friend_file_message' … -
Transferring session from PHP to Django
What is the best and secured way to transfer a session from PHP to Django. I have tried sending parameters through setting sessions and cookies and also in POST method but I was unable to fetch in Cookies and Sessions from PHP. I got the parameters through POST method but I read that sending through POST form action is not secured enough. Why am I not able to get the data from request.COOKIES.get() method ? Is there any other safest and secured way to achieve this and also I want redirect back to PHP when logging out. Here is the code from PHP that I have tried. <?php // Start the session session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Set session variables $_SESSION["Username"] = "username"; $_SESSION["Password"] = "Password"; echo "Session variables are set."; echo $_SESSION["Username"]; echo "<br>"; echo $_SESSION["Password"]; echo "<br><br><br>"; $cookie_name = $_SESSION["Username"]; $cookie_pass = $_SESSION["Password"]; setcookie($cookie_name, $cookie_pass, time() + (86400 * 30), "/"); // 86400 = 1 day if(!isset($_COOKIE[$cookie_name])) { echo "Cookie Username '" . $cookie_name . "' is not set!"; } else { echo "Cookie Username '" . $cookie_name . "' is set!<br>"; echo "Cookie password: " . $_COOKIE[$cookie_name]; } if(isset($_POST['submit'])) { echo $_POST['Username']; echo $_POST['password']; … -
Django: Redirect between two apps from views.py
There are two apps: app_user and app_test. app_user contains a login.html (with custom login forms). The login is realized using a POST request in JS, which calls a function api_login in app_user.views.py. This is my very simple login function (for testing): def api_login(request): # Get post data post = json.loads(request.body) # Get username and password username = post.get('username', None) password = post.get('password', None) # Returned data object data = { "success": False, "username": username, } # Username and password if username == "" or password == "": data['success'] = False return JsonResponse(data) # Check if input is correct user = authenticate(username=username, password=password) if user is not None: data['success'] = True login(request, user) # return JsonResponse(data) <-- No data response, there should be a redirect return redirect('app_test:test-home') else: data['success'] = False return JsonResponse(data) This works well but I want to make a redirect from http://localhost:8000/login/ (included by app_user) to http://localhost:8000/test/ (included by app_test) when the login was successful. My main url pattern (urls.py). from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('test/', include('app_test.urls'), name='app_test'), path('login/', include('app_user.urls'), name='app_login'), ] Url pattern from app_user from django.urls import path from . import views urlpatterns = [ path('', views.view_login, … -
Pass django context data to frontend without inline script in template
I'm already passing django context data to my frontend part using inline scripts in my template file: <script> var variable = "{{ variable }}"; </script> But for security reasons I'm no longer able to do this. My Content Security Policy settings should be configured in a way to prevent inline scripts. Can you help me? Any ideas? -
How to check relation of one object in another models while deleting the object
When we delete object from dajngo admin side dashboard .it gives all the relation of the objects. Refer image.So how can we do this in coading ? Is there any method for that ? -
How to get template field values to Django class based view
Here is my class, I want to take values to this class from my template 'registeredUsers.html' class registeredusers(RegistrationView, PersonnelView): template_name = 'registeredUsers.html' def get_context_data(self, *args, **kwargs): context_dict = {} context_dict['employeeform']= RegistrationForm empDetails= Employee.object.all() return context_dict Template fields <input class="email" type="email" value="{{i.email}}"> <input class="email" type="email" value="{{i.email}}"> -
Django form not saving data to database with custom form
I trying to create a form for a parking lot for the user and the form will input their RFID card, their log history, license plate, name and active or not but I can't get Django form to save it to the database here is my models.py from django.db import models class data(models.Model): RFID = models.CharField(max_length=10) Name = models.CharField(max_length=10) Log = models.TextField() License_Plate = models.CharField(max_length=10) Active = models.BooleanField(default=True) My forms.py from django import forms from .models import data # import data from models.py class data_form(forms.ModelForm): class Meta: model = data fields = ['RFID', 'Name', 'Log', 'License_Plate', 'Active'] class data_custom_form(forms.Form): RFID = forms.CharField( widget=forms.TextInput(attrs={'id': 'user-rfid'}), ) Name = forms.CharField(widget=forms.TextInput( attrs={'id': 'user-name', 'cols': 40, 'rows': 1 })) Log = forms.CharField( widget=forms.TextInput(attrs={'id': 'user-log'}) License_Plate = forms.DecimalField() Active = forms.BooleanField() My views.py from django.shortcuts import render # Create your views here. from .models import data from .forms import data_custom_form def custom_form_view(request): custom_form = data_custom_form() if request.method == 'POST': custom_form = data_custom_form(request.POST) if custom_form.is_valid(): print(custom_form.cleaned_data) else: print(custom_form.errors) info = { 'form': custom_form } return render(request, 'parking.html', info) And my template <DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>parking</title> </head> <body> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="save"> … -
Heroku Redirect non-www to www on Django website
I currently have a website domain with Bluehost. Bluehost cannot redirect https://example.com to https://www.example.com using 301 redirects since I am not hosting with them. Now in my DNS settings, I have a CNAME (Alias) record that points @ to <string1>.herokudns.com and I have another CNAME (Alias) that points www to <string2>.herokudns.com. I have contacted Bluehost and they said one solution would be to point both www and @ to <string1>.herokudns.com but that does not seem to be a redirection to me. How can I manage to redirect the naked domain to www within Heroku on Python? I cannot test them a lot since Bluehost TTL is 4 hours and I cannot manage to change my configurations fast. Appreciate any help in advance!