Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Locked out from my server after a few hours ssh
I am trying to deploy my django-mysql application. I am successfully able to deploy however after a few hours I cannot ssh into the server + access the site. ssh: connect to host port 22: Operation timed out This deploy issue is happening to me twice and trying to figure out why. Steps that I have taken to deploy. sudo yum install -y python3 python3-devel gcc python3 -m venv env and source env/bin/activate Upload project to /home/user pip3 install -r requirements.txt Install and cofigure my sql, migrate sudo yum install -y httpd httpd-devel pip3 install mod_wsgi sudo vi /etc/httpd/conf.d/my_conf.conf LoadModule wsgi_module /home/user/my_project/env/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so WSGIScriptAlias / /home/user/my_project/my_project/wsgi.py WSGIPythonHome /home/user/my_project/env WSGIPythonPath /home/user/my_project DocumentRoot /home/user/my_project/ <Directory /home/user/my_project/my_project> <Files wsgi.py> Require all granted </Files> </Directory> <Location /lock> AuthType Digest AuthName "Private" AuthUserFile /etc/httpd/password/digest Require valid-user </Location> chmod 755 /home/user sudo service httpd start and sudo systemctl enable httpd.service Setup digest authentication using htdigest Able to deploy but can't ssh into the server + access the site after a few (10~) hours Is there anything that I am doing wrong? Any help is appreciated. -
'DatabaseOperations' object has no attribute 'select' error when integrating Azure SQL database with django
I recently changed from using a Postgres / PostGIS database backend for my Django application to a SQL database on Azure. I have a geometry column in my data table. I can query the geometry column from Azure Data Studio just fine, and using raw SQL queries in my view. However, when I try to return a view using Django's ORM, I get this error (longer traceback below): AttributeError at /building/1/ 'DatabaseOperations' object has no attribute 'select' Request Method: GET Request URL: http://localhost:8000/building/1/ Django Version: 2.1.15 Exception Type: AttributeError Exception Value: 'DatabaseOperations' object has no attribute 'select' From what I can see, it seems like it is a settings / config issue and most posts say to properly configure Postgis, however I need to use an Azure SQL database, not Postgis. Here are my settings: DATABASES = { "default": { "ENGINE": "sql_server.pyodbc", "NAME": "Buildings", "USER": "BuildingsUser", "PASSWORD": "*************", "HOST": "buildings-test-db.database.windows.net", "PORT": "1433", "OPTIONS": { "driver": 'FreeTDS', 'host_is_server': True, # 'MARS_Connection': 'True', }, }, } Has anyone successfully configured an Azure database with geospatial columns for a django app, and used the Django ORM? Maybe I need a different engine for a SQL server db with geospatial columns? I would really … -
Herokuapp not updating my website content
I changed the meta content for my Django herokuapp and deployed again, but now still it's showing the previous content. Do I need to clear the cache? If so how to do that? Is that possible from heroku bash? GitHub is my repository. -
How to get django-tenants-celery-beat to schedule periodic tasks
I am a little newer to Celery and Celery Beat but I already have tenant_schemas_celery running in my project: import os from celery.schedules import crontab from tenant_schemas_celery.app import CeleryApp as TenantAwareCeleryApp from config import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') app = TenantAwareCeleryApp() app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) In a apps.periodic_testing.tasks.py file I have: from celery.schedules import crontab from celery.utils.log import get_task_logger from django_tenants_celery_beat.utils import generate_beat_schedule from config.celery import app logger = get_task_logger(__name__) @app.task def add(x=1, y=2): z = x + y print(z) app.conf.beat_schedule = generate_beat_schedule( { "tenant_task": { "task": "app.tasks.add", "schedule": crontab(minute=0-59), "tenancy_options": { "public": False, "all_tenants": True, "use_tenant_timezone": True, } }, "hourly_tenant_task": { "task": "app.tasks.add", "schedule": crontab(minute=0-59), "tenancy_options": { "public": False, "all_tenants": True, "use_tenant_timezone": False, } }, } ) But I can't seem to get the scheduler working. Any idea of what I could be doing wrong? -
Json data not saving in django database Admin
I am building a BlogApp and I am trying to access user location through geoplugin BUT it was sending through json so i made a view to send json data to database BUT json data is not saving in Database (Admin). When i click on link then it is showing :- 'NoneType' object has no attribute 'json' BUT then i use json.loads then it is showing :- the JSON object must be str, bytes or bytearray, not NoneType models.py class Location(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) city = models.JSONField() views.py def jsonLocation(request): r = request.POST.get('http://www.geoplugin.net/javascript.gp') # data = json.loads(r) data = r.json() for x in data: title = x["geoplugin_city"] user = request.user addin = Location.objects.create(city=title,user=request.user) addin.save() return HttpResponse("Successfully submitted!") I have seen many answers but did't find any solution. And it is still not saving in database. Any help would be Appreciated. -
how to auto scale django project in Elasticbeanstalk?
I have my Django setup on Elastic beanstalk, it's working properly considering on single instance. But when tested with ALB, the auto-scaled instance appears to be missing application code when it gets launched which it should have taken from s3 I assume (I had used console and uploaded my source bundle directly). I want to have source code reflected in autoscaled instance. What am i missing, is there any way for it or to automate this? -
Convert sensor SQL into json in Python
mydb = mysql.connector.connect( host="db-instance.rds.amazonaws.com", user="root", passwd="test", database="test" ) mc = mydb.cursor() sql = "INSERT INTO robot1_sensor (robot_id, x, y, ultrafine_dust, fine_dust, co2, formaldehyde, co, no2, radon,tvoc,temperature,humidity) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"; def air_info_recv(msg) : global mc global sql global mydb global robot_id global x global y print ("sub0000") air_info_dict = dict() print(msg.Dust_PM2_5_ugm3) print ("sub111") Fine_dust = msg.Dust_PM10_ugm3 Ultrafine_dust = msg.Dust_PM2_5_ugm3 CO2 = msg.CO2_ppm Formaldehyde = msg.HCHO_ugm3 CO = msg.CO_ppm NO2 = msg.NO2_ppm Radon = msg.Rn_Bqm3 Organic_compounds = msg.TVOCs_ugm3 Temperature = msg.temp_celcius Humidity = msg.hum_RHp print ("sub2222") val = (robot_id,x,y,Ultrafine_dust,Fine_dust,CO2,Formaldehyde,CO,NO2,Radon,Organic_compounds,Temperature,Humidity) mc.execute(sql, val) print ("sub33333") mydb.commit() print(mc.rowcount, "insert record") I want to change the python sql above to json and send it to server api. Server api is working with django. I need your help on how to change it. And if there is a good way, please recommend it. Thank you. -
django ajax ajaxify non-database image upload
I have some code from somewhere that let's the client display an uploaded image that is not saved to the database on the page. Is it possible to make it do so with ajax? I tried, but I clearly don't know what i'm doing or if it's even possible or if there's client safe way to do so. I keep getting fakepath and the name of the image. Here is the code without my embarrassing ajax attempts: views.py def upload_render(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['image'] data = file.read() # Calling .decode() converts bytes object to str encoded = b64encode(data).decode() mime = 'image/jpeg;' context = {"image": "data:%sbase64,%s" % (mime, encoded), 'form': form} return render(request, 'upload_render.html', context) else: form = FileForm() return render(request, 'upload_render.html', {'form': form}) upload_render.html <h2>Image upload</h2> <form method="post" enctype='multipart/form-data'> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% if image %} <img src="{{ image }}"> {% endif %} forms.py class FileForm(forms.Form): image = forms.ImageField(help_text="Upload image: ", required=True) -
Django: Model does not appear on admin panel
This is the model that I want to show on the admin panel. I'm registering the model via admin.py file with admin.site.register(Ad). I tried to re-write the register line twice, and an exception appeared that the model is already registered. class Ad(AdModel): plate = models.CharField(max_length=50, unique=True) description = models.TextField(max_length=500) ad_type = models.CharField( max_length=255, choices=AdTypes.get_choices(), default=AdTypes.OFFERING, ) price = models.PositiveIntegerField( default=0, help_text='In cents' ) location = models.CharField( max_length=255, choices=AdLocations.get_choices(), default=AdLocations.VILNIUS, ) user = models.ForeignKey(User, on_delete=models.PROTECT) approved_date = models.DateField(null=True, blank=True) approved_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name='approved_by', null=True ) The two base models: class UUIDBaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) class Meta: abstract = True class AdModel(UUIDBaseModel): expires_at = models.DateTimeField(null=True) is_draft = models.BooleanField(default=False) is_active = models.BooleanField(default=False) class Meta: abstract = True This is really strange, maybe that could be the problem because of the naming 'Ad'? I have a serializer for this model and everything works just fine, but the admin panel doesn't want to display it. views.py class AdCreateViewSet(ModelViewSet, CreateModelMixin): serializer_class = AdCreateSerializer permission_classes = (AllowAny,) filter_backends = [DjangoFilterBackend] search_fields = ('plate', 'description', 'user__email') queryset = Ad.objects.select_related('user') def perform_create(self, serializer): user = User.objects.first() serializer.save(user=user) # self.request.user) serializers.py class AdCreateSerializer(CustomAdSerializer): class Meta: model = Ad exclude = … -
Javascript - Editing Form with Fetch
I'm trying to edit an existing form on my site, and save the edits using Javascript (without requiring a refresh of the page). I'm using Django as well. So far, when the user clicks 'edit' on the page, the form appropriately appears, showing the information already saved there. But when I click 'save' I get a 404 error. The issue is in the Javascript function edit_post. I'm not sure if I have used stringify correctly either, I'm new to using Javascript with Django. Any help is appreciated. function edit_handeler(element) { id = element.getAttribute("data-id"); document.querySelector(`#post-edit-${id}`).style.display = "block"; document.querySelector(`#post-content-${id}`).style.display = "none"; // everything above this works and opens up the form for editing edit_btn = document.querySelector(`#edit-btn-${id}`); edit_btn.textContent = "Save"; edit_btn.setAttribute("class", "text-success edit"); if (edit_btn.textContent == "Save") { edit_post(id, document.querySelector(`#post-edit-${id}`).value); //here edit_btn.textContent = "Edit"; edit_btn.setAttribute("class", "text-primary edit"); }} function edit_post(id, post) { const body = document.querySelector(`#post-content-${id}`).value; fetch("/edit_post/", { method: "POST", body: JSON.stringify({ body:body }) }).then((res) => { document.querySelector(`#post-content-${id}`).textContent = post; document.querySelector(`#post-content-${id}`).style.display = "block"; document.querySelector(`#post-edit-${id}`).style.display = "none"; document.querySelector(`#post-edit-${id}`).value = post.trim(); }); } Relevant html - this is inside a card, for the post itself in the html file: <span id="post-content-{{i.id}}" class="post">{{i.text}}</span> <br> <textarea data-id="{{i.id}}" id="post-edit-{{i.id}}" style="display:none;" class="form-control textarea" row="3">{{i.text}}</textarea> <button class="btn-btn primary" data-id="{{i.id}}" id="edit-btn-{{i.id}}" … -
login manually fails first time in Django
I am trying to authenticate and login user manually, but it fails first time and going to login page asking for the credentials again, but next time onwards it works, is there anything related to session I should add, any help is appreciated, here is my code def admin_login(request): user = authenticate(username='admin_user', password='admin_user') if user is not None: login(request, user) return redirect('xxxx') else: return redirect('xxxx') return render(request, 'xxxx.html', {}) -
Calculating a field value based on PK in Django
Goal: Set customer_number to a calculated value of b_country + id + 10000. models.py class Customer(models.Model): id = models.BigAutoField(primary_key=True) customer_number = models.CharField("Customer #", max_length=10, default=0) b_country = models.TextField("Country", max_length=2, choices=COUNTRY_OPTIONS) @property def get_customer_number(self): a = self.b_country b = (self.id + 10000) return a + str(b) def save(self, *args, **kwarg): self.customer_number = self.get_customer_number super(Customer, self).save(*args, **kwarg) Issue: When the form is submitted to create a new customer (new record) then I get the following error: a 'CA' self Error in formatting: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'> When I already have a record (updating and existing Customer's info) then the code works fine. It is my understanding that it isn't able to get the id as it is still validating the data before being sent to the model, hence no Customer.id to pull for this instance. Question: Is there a cleaner way of setting a customer_number that is based on the PK? -
DJANGO media images not showing
Hello I am trying to display an image from media/images On my html I have this code: index.html {% extends 'basic_app/base.html' %} {% block metablock %} <title>CBV - Index</title> {% endblock metablock %} {% block bodyblock %} <div class="container-fluid"> <h1>Hello {{word}}</h1> <img src="/media/images/bobcatminer.jpg" alt="bobcat"> </div> {% endblock bodyblock %} on settings.py I have this for media MEDIA_ROOT = Path.joinpath(BASE_DIR,'media') MEDIA_URL = '/media/' I do not know what is going wrong, please help. Thanks beforehand. -
How to over write or add words to Django URL?
When I go on my product detail page I get http://xxx.x.x.x:x000/product/PN/ I want to change the URL from PN to the name of the product. So my URL should look like this if everything works right http://xxx.x.x.x:x000/product/name/: model.py class Product(): name = models.CharField(max_length=400, db_index=True) PN = models.CharField(max_length=100, default=random_string) view.py def product_detail(request, PN): product = get_object_or_404(Product, PN=PN) return render(request, 'productdetail.html', {'product': product}) url.py urlpatterns = [ url(r"^", include("users.urls")), path('product/<str:PN>/', productdetail, name='productdetail') ] -
Django model instance caching - for the same record
I've a standard django model class and I'd like to cache a method's return value: class Sth(models.Model): pr = models.CharField(max_length=128) ... def some_method(self): return 'some result' . So, if an Sth instance has not been saved, I'd like to cache the result of the some_method, but if it has been saved, I'd like to recalculate the result of the some_method method for the first run. Is there any solution for that? I've memcached for cache, and to make it complicated, Django version is 1.11.16 . -
Passing a parameter to a ModelForm and using min_value
I want to pass a parameter to my ModelForm so I can use it as an argument for min_value. I also don't know where can I use min_value inside a ModelForm. views.py: return render(request, "page.html", { "form": createBiding(minAmount) }) forms.py: class createBiding(forms.ModelForm): #How do i accept minAmount as a parameter #where do i put min_value class Meta: model = bid fields = [ 'bidAmount' ] widgets = { 'bidAmount': forms.NumberInput(attrs={ 'class': "form-control", 'style': '', 'placeholder': 'Place your bid' }) } I am new to Django and programing in general. Help is appreciated. -
Return a value of a model based on the max value of another field of the model
My Model class Energy_Consuption(models.Model): name=models.IntegerField() meter=models.IntegerField() class Meta: db_table:'Energy_Consuption' My Views def details (request): top_meter = Energy_Consuption.objects.aggregate(Max('meter')) return render(request,'details.html', {'top_meter':top_meter}) hello guys, I am having a model in Django with two fields, name and meter. I have created a views file and I want to find and print the name with the biggest meter. The code below find and prints the biggest meter itself which is good but now what I want. I want to print the name that is related to that meter. Any idea how to do so? def details (request): top_meter = Energy_Consuption.objects.aggregate(Max('meter')) return render(request,'details.html', {'top_meter':top_meter}) the view is connected to an HTML page -
Django Scopes - How to get current tenant?
I'm fairly new to Django and I'm building a multi tenant app. I'm not really sure how to get the logged in user's current tenant in order to use it as a filter in views. Example: Post.objects.filter(tenant=current_tenant) Example Models: from django.db import models class Tenant(models.Model): name = models.CharField(…) class Post(models.Model): tenant = models.ForeignKey(Tenant, …) title = models.CharField(…) class Comment(models.Model): post = models.ForeignKey(Post, …) text = models.CharField(…) Where should I write the get_current_tenant function and how should I write it? Any help would be greatly appreciated. -
Django iterate through a dictionary and render to a template
This code gives me the output that I need on the terminal but when I try to render it in the template it gives me only the last result. I read a couple of other answers but nothing leads me to understand where is the mistake. Thank you. def forecast(request): if request.method == 'POST': city = urllib.parse.quote_plus(request.POST['city']) source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/forecast?q='+ city +'&units=metric&appid=ab3d24d85590d1d71fd413f0bcac6611').read() list_of_data = json.loads(source) pprint.pprint(list_of_data) forecast_data = {} for each in list_of_data['list']: forecast_data['wind_speed'] = each["wind"]['speed'] forecast_data['wind_gust'] = each["wind"]['gust'] forecast_data['wind_deg'] = each["wind"]['deg'] forecast_data["coordinate"] = str(list_of_data['city']['coord']['lon']) + ', ' + str(list_of_data['city']['coord']['lat']) forecast_data["name"] = list_of_data["city"]["name"] forecast_data["dt_txt"] = each["dt_txt"] # uncomment for see the result in the terminal print(forecast_data) fore = {'forecast_data':forecast_data} else: list_of_data = [] fore = {} return render(request, "WindApp/forecast.html",fore) and this is the HTML part: <div class="row"> {% for x,y in forecast_data.items %} <div class="col d-flex justify-content-center" "> <div id="output" class=" card text-black bg-light mb-6"> <div id="form" class=" card-body"> <h4><span class="badge badge-primary">City:</span> {{forecast_data.name}}</h4> <h4><span class="badge badge-primary">Coordinate:</span> {{forecast_data.coordinate}}</h4> <h4><span class="badge badge-primary">Day/Time:</span> {{forecast_data.dt_txt}}</h4> <h4><span class="badge badge-primary">Wind Speed: </span> {{forecast_data.wind_speed}} Kt</h4> <h4><span class="badge badge-primary">Wind Gust : </span> {{forecast_data.wind_gust}} Kt <img src="{% static 'img/wind.png' %}" width="64" height="64" alt="wind"></h4> <h4><span class="badge badge-primary">Wind direction : </span> {{forecast_data.wind_deg}} <img src="{% static 'img/cardinal.png' %}" width="64" height="64" alt="dir"></h4> </div> … -
How to append element to div in a specific order?
I have 4 div and n elements that I want to append like this: 1el in 1div 2el in 2div 3el in 3div 4el in 4div And 5el in 1div so on and so forth I am using python and django. Any help would be highly appreciated... -
Each user will have a subdomaine (username.domaine.com) + the possibility to add a custom domaine (ustomUserDomaine.com)?
Basically what am creating is a platform which is simillar to Shopify, it's simillar because each user will have his own profile at a subdomaine: user.domaine .com, also I want to give the user the possibility to link his own custom domain userDomaine .com, so instead of the subdomaine, he will have a custom domain linking to his profile, of couse by adding the CNAMS. So I need from Django to generate a new subdomain for each new user and also the possibility to link a custom domaine to be used instead of the subdomaine. How can I achieve all this ?? any infos ? any tutorials ? any packages that will help ?? thank you in advance. -
Unable to makemigrations with PostgreSQL setup
I am trying to setup PostgreSQL locally on my computer, but when I try to initially set up my Django application with it using python manage.py makemigrations, I am given this warning: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': fe_sendauth: no password supplied My database table in my settings.py is as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get("DB_NAME"), 'USER': os.environ.get("DB_USER"), 'PASSWORD': os.environ.get("DB_PASSWORD"), 'HOST': os.environ.get("DB_HOST"), 'PORT': os.environ.get("DB_PORT"), } } My .env file is located in the same directory as my manage.py file: DB_NAME=Smash DB_PASSWORD=root DB_USER=SmashDatabase DB_HOST=localhost DB_PORT=5432 DEBUG=1 I tried following this link's instructions but none of the offered solutions fixed the problem. I don't know what is wrong or what causes this issue. -
django get_or_create throws Integrity Error
I have read this thread: get_or_create throws Integrity Error But still not fully understand when get_or_create returns False or IntegrityError. I have the following code: django_username = 'me' user = get_user_model().objects.filter(username=django_username).first() action_history, action_added = ActionModel.objects.get_or_create( date=date_obj, # date object account_name=unique_name, # e.g. account1234 target=follower_obj, # another model in django user=user, # connected django user defaults={'identifier': history['user_id']} ) While the model looks like: class ActionModel(models.Model): """ A model to store action history. """ identifier = models.BigIntegerField( _("identifier"), null=True, blank=True) # target id account_name = models.CharField(_("AccountName"), max_length=150, null=True, blank=True) # account name of the client date = models.DateField(_("Date"), auto_now=False, auto_now_add=False) # action date target = models.ForeignKey(Follower, verbose_name=_("Target"), on_delete=models.CASCADE) # username of the done-on action user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, editable=False, db_index=True, ) # django user that performed the action class Meta: verbose_name = _("Action") verbose_name_plural = _("Actions") unique_together = [ ['account_name','date','target'], ] Sometimes it return IntegrityError, and sometimes (when unique constrain exists it will return False on created). -
how to use aws secret manager values of a postgres database in terraform ecs task definition
I have the settings.py file below of a django application using terraform , docker compose and im trying to get the value of the database stored in aws secret manager in ecs task definition settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ.get("POSTGRES_DB"), "USER": os.environ.get("POSTGRES_USER"), "PASSWORD": os.environ.get("POSTGRES_PASSWORD"), "HOST": os.environ.get("POSTGRES_HOST"), "PORT": 5432, } } task definition resource "aws_ecs_task_definition" "ecs_task_definition" { family = "ecs_container" network_mode = "awsvpc" requires_compatibilities = ["FARGATE"] cpu = 256 memory = 512 execution_role_arn = data.aws_iam_role.fargate.arn task_role_arn = data.aws_iam_role.fargate.arn container_definitions = jsonencode([ { "name" : "ecs_test_backend", "image" : "${aws_ecr_repository.ecr_repository.repository_url}:latest", "cpu" : 256, "memory" : 512, "essential" : true, "portMappings" : [ { containerPort = 8000 } ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-region": "us-east-1", "awslogs-group": "/ecs/ecs_test_backend", "awslogs-stream-prefix": "ecs" } } "environment" : [ { "name": "POSTGRES_DB", "value": "${var.POSTGRES_NAME}" <=== HERE }, { "name": "POSTGRES_PASSWORD", "value": "${var.POSTGRES_PASSWORD}" <=== HERE }, { "name": "POSTGRES_USERNAME", "value": "${var.POSTGRES_USERNAME}" <=== HERE }, { "name": "POSTGRES_PORT", "value": "${var.POSTGRES_PORT}" <=== HERE }, { "name": "POSTGRES_HOST", "value": "${var.POSTGRES_HOST}" <=== HERE }, ] } ]) } The configuration below var.XXX does not seem to work as the task logs return psycopg2.OperationalError: FATAL: password authentication failed for user "root" It probably because its not able to read … -
JavaScript Delete Button Implementation Issues
I am a student studying JavaScript and Django. When I select the current option, I want to create a page where I can check the information (product name, option name, etc.) of the selected option is added. Choosing the option is currently implemented, but I also want to implement the function of deleting the added information after selecting it, so I wrote JavaScript as follows: I have designed the delete button to appear one by one next to the option information, and my goal is to delete only the corresponding information when I press the delete button. However, I am upset that all the information added disappears as soon as I press the delete button. I don't know how to solve it. Can't I just delete the information I want to delete without deleting all the added information? Coding geniuses, please help me. It's a problem that hasn't been solved in a week. If you help me, I will be touched with all my heart. Code : <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>Option</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">Select Option.</option> {% for …