I'm new in Django, I researched how to create drop-down. I tried everything, but still, the dropdown is not showing in HTML view.
My sample script is this.
This is the model.py
from django.db import models
class samplemodel(models.Model):
list = (
('sample1','SAMPLE1'),
('sample2','SAMPLE2'),
)
list_choices = models.CharField(max_length=6, choices=list)
The forms.py
from .models import samplemodel
from django.forms import ModelForm
class sampleForm(ModelForm):
class Meta:
model = samplemodel
fields = ['list_choices']
This is the views.py
from django.shortcuts import render
from .models import samplemodel
from .forms import sampleForm
from django.views.generic import CreateView
class sampleView(CreateView):
model = samplemodel
form_class = sampleForm
template_name = 'home/sample.html'
This is the home.html
{% extends 'base.html' %}
{% block head %}
<title>Home</title>
{% endblock %}
{% block body %}
<div class="container">
<form class="post">
{% csrf_token %}
{{ form.as_p }}
</form>
</div>
{% endblock %}
I tried everything that I saw on the internet. But I can't still show the drop-down. I don't know if the imports are the issue or not.
you model should be like this
from django.db import models
class SampleModel(models.Model):
list = (
('sample1','SAMPLE1'),
('sample2','SAMPLE2'),
)
list_choices = models.CharField(max_length=6, choices=list)
in your urlconf
from django.views.generic import CreateView
from app.models import Samplemodel
from django.forms import ModelForm
url(r'^sample_form$',CreateView.as_view(model=SampleModel, template_name='home/sample.html', success_url='index', name='sample_form'))
thats all you don't need forms.py . django will take care of everything
Related
I am a django beginner even programming beginner this issue I have found one day still can not work out
views.py
from django.shortcuts import render, redirect
from django.template import loader
from .models import Topic
from django.contrib.auth.models import User
from .forms import TopicForm
# Create your views here.
def home(request):
q = request.Get.get('q')
topics = Topic.objects.filter(name__icontains=q)
context = {'topics':topics}
template = loader.get_template('home.html')
return render(request, 'home.html', context)
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Topic(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
home.html
<body>
{% include 'navbar.html' %}
<div>
<div>
<h3>Topic</h3>
{% for topic in topics %}
{{topic.name}}
{% endfor %}
</div>
</div>
</body>
I tried if statment still not work
I am attempting to display .pdfs that have been uploaded by users. I can display the path to the pdf but not document itself. I attempted to use "" in the template but this is not working.
At least one issue is that the incorrect path to the document is used when the template is rendered. The correct file path is media/company1/documents/012022/document.pdf. The file path rendered in the template is: /documents/document/4/documents/012022/document.pd
Here is my model:
from django.db import models
from constrainedfilefield.fields import ConstrainedFileField
class Document(models.Model):
title = models.CharField(max_length= 200)
description = models.TextField()
file = ConstrainedFileField(
null=True,
blank=True,
upload_to='documents/%m%Y',
content_types=['application/pdf'],
max_upload_size=2097152,
)
Here is my view:
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, CreateView
from .models import Document
...
class CompanyDocumentsDetailView(DetailView):
model = Document
template_name = 'company_accounts/document_detail.html'
...
Here is my template:
<!-- templates/document_detail.html -->
{% extends 'base.html' %}
{% block content %}
<div class="section-container container">
<div class="project-entry">
<h2>{{ document.title }}</h2>
<p>{{ document.description }}</p>
<p><embed src="{{document.file}}" type="application/pdf" height="700px" width="500"/></p>
</div>
</div>
{% endblock content %}
I'm writing a code in django framework for a sales website and the number of available pieces of a certain merchandise is limited.
to obtain the number of remaining products I have to call a certain function.
Now I wanted to ask if there's any way to call this function in the models.py or forms.py modules or any other way to set this limit.
This is my view module:
from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from .forms import orderForm
from regpage.models import User
from django.views import View
class orderView(View):
def get(self, request):
form = orderForm()
return render(request, "dashboard/order.html", {'form': form,})
This is my forms module:
from django import forms
from .models import Order
class orderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['productCount']
This is my models module:
from django.db import models
from django.db.models.enums import Choices
from regpage.models import User
from django.core import validators
from django.core.validators import EmailValidator, MaxValueValidator, MinValueValidator
class Order(models.Model):
userID = models.ForeignKey(User, on_delete=models.CASCADE)
productCount = models.PositiveSmallIntegerField() #THE LIMITED FIELD
This is my html file:
{% extends 'dashboard.html' %}
{% block dashTitle %}
Order
{% endblock dashTitle %}
{% block dashContent %}
<p style="text-align:center;font-size:30px;"><b> Order Page </b> </p>
<form style="text-align:center;font-size:25px" method="POST">
{% csrf_token %}
{% for field in form %}
<div class="form-control {% if field.errors %}errors{% endif %}">
{{ field.label_tag }}
{{ field }}
{{ field.errors }}
</div>
<br>
{% endfor %}
<br>
<button type="submit">Order</button>
</form>
{% endblock dashContent %}
There's only one product in this website and one function should be called to obtain the number of remaining products.
Give this a try
class orderForm(forms.ModelForm):
quantity = forms.IntegerField(widget=forms.TextInput(
attrs={
'min':0,
'value':0,
'type':'number',
}))
class Meta:
model = Order
fields = ('__all__')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['productCount'].widget.attrs.update(
{'max': self.instance.productCount},
)
I am attempting to set up dependent dropdown lists in a Django 3.1 site. The lists are populated via another app (Django-Machina) DB tables. I attempted to adapt the example here. However I am new to Django and Python and so far, I am not able to get this to work.
My files are as follows:
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from machina.core.db.models import get_model
from django.db.models import Q
Forum = get_model("forum", "Forum")
class CustomUser(AbstractUser):
age = models.PositiveIntegerField(null=True, blank=True)
business_location_state = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, limit_choices_to={"lft":1})
business_location_county = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, related_name='county', limit_choices_to=(~Q(lft__in = (1,2))))
views.py
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
from .models import CustomUser
from django.shortcuts import render
from machina.core.db.models import get_model
from django.db.models import Q
Forum = get_model("forum", "Forum")
class SignUpView(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'registration/signup.html'
def load_counties(request):
parent_id = request.GET.get('business_location_state')
counties = Forum.objects.filter(parent_id=parent_id).order_by('name')
return render(request, 'hr/county_dropdown_list_options.html', {'counties': counties})
accounts/urls.py
# accounts/urls.py
from django.urls import path
from .views import SignUpView
from . import views
urlpatterns = [
path('signup/', SignUpView.as_view(), name='signup'),
path('ajax/load-counties/', views.load_counties, name='ajax_load_counties'), # ajax to load counties
]
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = UserCreationForm.Meta.fields + ('username', 'email', 'age', 'business_location_state', 'business_location_county')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['business_location_county'].queryset = CustomUser.objects.none()
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('username', 'email', 'age','business_location_state', 'business_location_county')
count_dropdown_list_options.html
<!-- templates/hr/county_dropdown_list_options.html -->
<option value="">---------</option>
{% for county in counties %}
<option value="{{ business_location_county.pk }}">{{ business_location_county.name }}</option>
{% endfor %}
signup.html
<!-- templates/registration/signup.html -->
{% extends 'base.html' %}
{% block title %}
Sign Up
{% endblock title %}
{% block content %}
<h2>Sign up</h2>
<form method="post" id=signupForm data-counties-url="{% url 'ajax_load_counties' %}" novalidate>
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign Up</button>
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("#id_business_location_state").change(function () {
var url = $("#signupForm").attr("data-counties-url"); // get the url of the `load_cities` view
var stateId = $(this).val(); // get the selected country ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
data: {
'business_location_state': stateId // add the state id to the GET parameters
},
success: function (data) { // `data` is the return of the `load_cities` view function
$("#id_county").html(data); // replace the contents of the city input with the data that came from the server
}
});
});
</script>
{% endblock content %}
I am not currently seeing any errors but the counties list is not changing based on the "Business location state" choice. Any ideas about what is going wrong?
I'm trying to extend the Django (version 2.0) tutorial so that it uses ModelForm to create a question with a least one or two choices. I have two models Question and Choice which have a one-to-many relationship. What do I need to do to my model, form, views, and template to generate a field(s) for choice? I've seen a few posts suggesting Inline but that seems like it's only for admin pages.
polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
polls/forms.py
from django.forms import ModelForm
from .models import Choice, Question
class QuestionForm(ModelForm):
class Meta:
model = Question
fields = ['question_text', 'pub_date', 'choice']
polls/views.py
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
from django.views import generic
from .forms import QuestionForm
from .models import Choice, Question
def create_question(request):
if request.method == 'POST':
form = QuestionForm(request.POST)
if form.is_valid():
question_text = form.cleaned_data['question_text']
pub_date = form.cleaned_data['pub_date']
question = Question(question_text=question_text, pub_date=pub_date)
question.save()
return HttpResponseRedirect(reverse('polls:index'))
else:
form = QuestionForm()
return render(request, 'polls/create-question.html', {'form': form})
polls/create-question.html
{% extends 'polls/base.html' %}
{% block scripts %}{% endblock scripts %}
{% block content %}
<div class="container">
<h1>Create question</h1>
<form action="{% url 'polls:create-question' %}" method="post">
{% csrf_token %}
{{ form }}
<input class="btn btn-lg btn-primary btn-block" type="submit" value="Create">
</form>
</div>
{% endblock content %}
To use ModelForm you should add a ManyToManyField to the Question model in order to connect choices with the certain question. For example like choices = models.ManyToManyField(Choice, on_delete=models.CASCADE).