Creating a ModelForm with an arugment
I have some simple models of questions and answers.
#models.py
class Question(models.Model):
question_text = models.CharField(max_length=200)
question_info = models.TextField()
def __str__(self):
return self.question_text
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
answer_text = models.CharField(max_length=200)
correct = models.BooleanField(default=False)
def __str__(self):
return self.answer_text
I am trying to create a ModelForm that takes all the answers for a given question and displays them with radio buttons. I can do this in views.py and the template just fine.
#views.py
def index(request):
q1 = Question.objects.get(pk=1)
context = {
'q1`': q1,
}
return render(request, 'questions/index.html', context)
\#index.html
<head>
<meta charset="utf-8" />
<title>Django</title>
</head>
<body>
<h1>Welcome!</h1>
<h2> {{ q_1.q_text }}</h2>
<form action="" method="POST">
{% csrf_token %}
{% for answer in q_1.answer_set.all %}
<input type="radio" name="answer" id="answer{{ forloop.counter }} value="{{ answer.id }}" />
<label for="choice{{ forloop.counter }}"> {{ answer.answer_text }} </label></br/>
{% endfor %}
<input type="submit" value="Submit" />
</form>
With this I can't call is_valid() so I tried to make a form for the model.
\#forms.py
class AnswerForm(forms.ModelForm):
class Meta:
model = Answer
a1 = Answer.objects.get(id=1)
a2 = Answer.objects.get(id=2)
a3 = Answer.objects.get(id=3)
a4 = Answer.objects.get(id=4)
a5 = Answer.objects.get(id=5)
fields = [
'correct',
]
widgets = {
'correct': forms.RadioSelect(choices = [
(a1.correct, Answer.objects.get(id=1)),
(a2.correct, Answer.objects.get(id=2)),
(a3.correct, Answer.objects.get(id=3)),
(a4.correct, Answer.objects.get(id=4)),
(a5.correct, Answer.objects.get(id=5))
]
)
}
This allows me to use the is_valid() method for validating the form but it is obviously inefficient as it only works for this one question. I would ideally like to the be able to pass a parameter into the ModelForm so that it uses that value to get the question whether from the id/pk or some other value. My thinking for this would then be that the ModelForm uses lets say id as its argument then I could also set up a url that takes the id of a question also and then when I pass the id in the view along with the request that id also gets used in the ModelForm. So I guess my questions are:
1. Is creating a ModelForm with an arugment for a specific object in the model possible?
2. Is the logic behind using the url id to pass to the ModelForm able to work as well?
Any help is appreciated, Thanks.
/r/djangolearning
http://redd.it/5adqqi
I have some simple models of questions and answers.
#models.py
class Question(models.Model):
question_text = models.CharField(max_length=200)
question_info = models.TextField()
def __str__(self):
return self.question_text
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
answer_text = models.CharField(max_length=200)
correct = models.BooleanField(default=False)
def __str__(self):
return self.answer_text
I am trying to create a ModelForm that takes all the answers for a given question and displays them with radio buttons. I can do this in views.py and the template just fine.
#views.py
def index(request):
q1 = Question.objects.get(pk=1)
context = {
'q1`': q1,
}
return render(request, 'questions/index.html', context)
\#index.html
<head>
<meta charset="utf-8" />
<title>Django</title>
</head>
<body>
<h1>Welcome!</h1>
<h2> {{ q_1.q_text }}</h2>
<form action="" method="POST">
{% csrf_token %}
{% for answer in q_1.answer_set.all %}
<input type="radio" name="answer" id="answer{{ forloop.counter }} value="{{ answer.id }}" />
<label for="choice{{ forloop.counter }}"> {{ answer.answer_text }} </label></br/>
{% endfor %}
<input type="submit" value="Submit" />
</form>
With this I can't call is_valid() so I tried to make a form for the model.
\#forms.py
class AnswerForm(forms.ModelForm):
class Meta:
model = Answer
a1 = Answer.objects.get(id=1)
a2 = Answer.objects.get(id=2)
a3 = Answer.objects.get(id=3)
a4 = Answer.objects.get(id=4)
a5 = Answer.objects.get(id=5)
fields = [
'correct',
]
widgets = {
'correct': forms.RadioSelect(choices = [
(a1.correct, Answer.objects.get(id=1)),
(a2.correct, Answer.objects.get(id=2)),
(a3.correct, Answer.objects.get(id=3)),
(a4.correct, Answer.objects.get(id=4)),
(a5.correct, Answer.objects.get(id=5))
]
)
}
This allows me to use the is_valid() method for validating the form but it is obviously inefficient as it only works for this one question. I would ideally like to the be able to pass a parameter into the ModelForm so that it uses that value to get the question whether from the id/pk or some other value. My thinking for this would then be that the ModelForm uses lets say id as its argument then I could also set up a url that takes the id of a question also and then when I pass the id in the view along with the request that id also gets used in the ModelForm. So I guess my questions are:
1. Is creating a ModelForm with an arugment for a specific object in the model possible?
2. Is the logic behind using the url id to pass to the ModelForm able to work as well?
Any help is appreciated, Thanks.
/r/djangolearning
http://redd.it/5adqqi
URLconf for foreign key in a model
Not sure how to title this but I was trying to look up how to put a foreign key value into the URL address.
Here is some example code of what I am trying to do:
#models.py
class Client(models.Model):
name = models.CharField(max_length = 13)
class Product(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
name = models.CharField(max_length = 80)
description = models.TextField(blank=True, null=True)
# views.py
class ClientView(generic.DetailView):
model = Client
template_name = 'app/client.html'
class ProductView(generic.DetailView):
model = Product
template_name = 'app/product.html'
#url.py
urlpatterns = [
url(r'^profile/(?P<pk>[0-9]+)/$', views.ClientView.as_view(), name='client'),
## This I am trying to preserve the foreign key and use it here for client
url(r'^profile/(?P<client__pk>[0-9]+)/(?P<pk>[0-9]+)/$', views.ProductView.as_view(), name='product'),
]
Basically I am trying to add the primary key from client into the URL for the product page. Is there a good way to do this?
/r/djangolearning
https://redd.it/75ncw5
Not sure how to title this but I was trying to look up how to put a foreign key value into the URL address.
Here is some example code of what I am trying to do:
#models.py
class Client(models.Model):
name = models.CharField(max_length = 13)
class Product(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
name = models.CharField(max_length = 80)
description = models.TextField(blank=True, null=True)
# views.py
class ClientView(generic.DetailView):
model = Client
template_name = 'app/client.html'
class ProductView(generic.DetailView):
model = Product
template_name = 'app/product.html'
#url.py
urlpatterns = [
url(r'^profile/(?P<pk>[0-9]+)/$', views.ClientView.as_view(), name='client'),
## This I am trying to preserve the foreign key and use it here for client
url(r'^profile/(?P<client__pk>[0-9]+)/(?P<pk>[0-9]+)/$', views.ProductView.as_view(), name='product'),
]
Basically I am trying to add the primary key from client into the URL for the product page. Is there a good way to do this?
/r/djangolearning
https://redd.it/75ncw5
reddit
URLconf for foreign key in a model • r/djangolearning
Not sure how to title this but I was trying to look up how to put a foreign key value into the URL address. Here is some example code of what I...
Concrete inheritance: not seeing much benefit over traditional one-to-one relationships in Django models
This is less of a code problem and more of a Django philosophy/implementation question. Django is the first time I've had the option of *concrete model inheritance*. It seems like a good idea with the potential for lots of added convenience in template variables. After messing with it for a few hours, I have very mixed feelings about the feature.
I have a fairly complex model scheme for industrial parts/spares coming from an old database schema. I used to subclass using 1-1 tables off of a master product table. For example:
#models.py
class Product(models.Model):
name = models.CharField(max_length=50)
model_number = models.CharField(max_length=50)
fkmanufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
fkproducttype = models.ForeignKey(ProductType, on_delete=models.CASCADE)
class Bearing(models.Model):
id = models.OneToOneField(Product, on_delete=models.CASCADE, primary_key=True)
inner_race = models.CharField(max_length=10)
outer_race = models.CharField(max_length=10)
I thought this was pretty easy to use as it was. Defaults to drop-downs in the admin interface, easy to filter once the 1-1 relationships are defined, and easy to use the variables in practice:
>>>b = Bearing.objects.get(id=1)
>>>b.id.name
'Timken 6308'
So then I see concrete inheritance, and I read about some of the reasons one might want to use it. It makes sense to give it a try.
#models.py
...
class Bearing(Product):
inner_race = models.CharField(max_length=10)
outer_race = models.CharField(max_length=10)
At first I find this migration difficult, as any "products" that should be "bearings" are a little harder to track down and add, since there's no direct access to the `OneToOneField` anymore. I can get over that with some new forms and a type field. Not a big deal, just different than what I'm used to.
As per the Docs, my existing id field gets replaced with `product_ptr_id`. I believe in the philosophy of "explicit is better than implicit". So I explicitly state that as "id" again:
class Bearing(Product):
id = models.OneToOneField(Product, on_delete=models.CASCADE, primary_key=True, db_column='id')
inner_race = models.CharField(max_length=10)
outer_race = models.CharField(max_length=10)
As I expected, this raises a `FieldError: Local field 'id' in class 'Bearing' clashes with field of the same name from base class 'Product'.` So I rename that field to `product`.
class Bearing(Product):
product = models.OneToOneField(Product, on_delete=models.CASCADE, primary_key=True, db_column='id')
inner_race = models.CharField(max_length=10)
outer_race = models.CharField(max_length=10)
This causes weird behavior in forms because I didn't add `parent_link=True`, so I fix that:
class Bearing(Product):
product = models.OneToOneField(Product, on_delete=models.CASCADE, primary_key=True, db_column='id', parent_link=True)
inner_race = models.CharField(max_length=10)
outer_race = models.CharField(max_length=10)
This works a little more as expected. The database tables appear to look and behave just the same as my initial design without inheritance. As intended, I can reference parent class fields directly from the `Bearing` class:
>>>t = Bearings.objects.get(pk=1)
>>>t.product
<Product: 6308 Bearing>
>>>t.model_number
'6308'
**So my real question is:** *what practical advantage does this use of concrete inheritance actually serve?* It seems like all I've done is save myself the three keystrokes it takes to change model instances. Is there some benefit down the road where I'll wish that I'd used one form or the other?
This may seem a trivial or subjective question, but it's just a really odd transition since I'm much more accustomed to working directly with databases that didn't utilize such features. Two Scoops "strongly recommend[s] against using it", and spe
This is less of a code problem and more of a Django philosophy/implementation question. Django is the first time I've had the option of *concrete model inheritance*. It seems like a good idea with the potential for lots of added convenience in template variables. After messing with it for a few hours, I have very mixed feelings about the feature.
I have a fairly complex model scheme for industrial parts/spares coming from an old database schema. I used to subclass using 1-1 tables off of a master product table. For example:
#models.py
class Product(models.Model):
name = models.CharField(max_length=50)
model_number = models.CharField(max_length=50)
fkmanufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
fkproducttype = models.ForeignKey(ProductType, on_delete=models.CASCADE)
class Bearing(models.Model):
id = models.OneToOneField(Product, on_delete=models.CASCADE, primary_key=True)
inner_race = models.CharField(max_length=10)
outer_race = models.CharField(max_length=10)
I thought this was pretty easy to use as it was. Defaults to drop-downs in the admin interface, easy to filter once the 1-1 relationships are defined, and easy to use the variables in practice:
>>>b = Bearing.objects.get(id=1)
>>>b.id.name
'Timken 6308'
So then I see concrete inheritance, and I read about some of the reasons one might want to use it. It makes sense to give it a try.
#models.py
...
class Bearing(Product):
inner_race = models.CharField(max_length=10)
outer_race = models.CharField(max_length=10)
At first I find this migration difficult, as any "products" that should be "bearings" are a little harder to track down and add, since there's no direct access to the `OneToOneField` anymore. I can get over that with some new forms and a type field. Not a big deal, just different than what I'm used to.
As per the Docs, my existing id field gets replaced with `product_ptr_id`. I believe in the philosophy of "explicit is better than implicit". So I explicitly state that as "id" again:
class Bearing(Product):
id = models.OneToOneField(Product, on_delete=models.CASCADE, primary_key=True, db_column='id')
inner_race = models.CharField(max_length=10)
outer_race = models.CharField(max_length=10)
As I expected, this raises a `FieldError: Local field 'id' in class 'Bearing' clashes with field of the same name from base class 'Product'.` So I rename that field to `product`.
class Bearing(Product):
product = models.OneToOneField(Product, on_delete=models.CASCADE, primary_key=True, db_column='id')
inner_race = models.CharField(max_length=10)
outer_race = models.CharField(max_length=10)
This causes weird behavior in forms because I didn't add `parent_link=True`, so I fix that:
class Bearing(Product):
product = models.OneToOneField(Product, on_delete=models.CASCADE, primary_key=True, db_column='id', parent_link=True)
inner_race = models.CharField(max_length=10)
outer_race = models.CharField(max_length=10)
This works a little more as expected. The database tables appear to look and behave just the same as my initial design without inheritance. As intended, I can reference parent class fields directly from the `Bearing` class:
>>>t = Bearings.objects.get(pk=1)
>>>t.product
<Product: 6308 Bearing>
>>>t.model_number
'6308'
**So my real question is:** *what practical advantage does this use of concrete inheritance actually serve?* It seems like all I've done is save myself the three keystrokes it takes to change model instances. Is there some benefit down the road where I'll wish that I'd used one form or the other?
This may seem a trivial or subjective question, but it's just a really odd transition since I'm much more accustomed to working directly with databases that didn't utilize such features. Two Scoops "strongly recommend[s] against using it", and spe
Nesting serializers in nested serializers
My current serializers.py file is looking very complicated and I am not sure if it is the best way to do it.
Current my models.py looks something like
#models.py
class Subject(models.Model):
subjectname = models.CharField()
class Topic(models.Model):
topicname = models.CharField()
subject = models.ForeignKey(Subject, ondelete=models.CASCADE, relatedname='topics')
class Chapter(models.Model):
chaptername = modeks.CharField()
topic = models.ForeignKey(Topic, ondelete=models.CASCADE, relatedname='chapters'
My [views.py](https://views.py) looks something like
class ChapterListView(ListAPIView):
queryset = Subject.objects.all()
serializerclass = ChapterSerializer
filterbackends = [DjangoFilterBackend] #filters only the Subject
filtersetfields = 'subject_name'
My serializers.py looks something like
class ChapterSerializer(serializers.ModelSerializer):
class NestedTopicSerializer(serializers.ModelSerializer):
class NestedChapterSerializer(serializers.ModelSerializer):
/r/django
https://redd.it/ni8d9u
My current serializers.py file is looking very complicated and I am not sure if it is the best way to do it.
Current my models.py looks something like
#models.py
class Subject(models.Model):
subjectname = models.CharField()
class Topic(models.Model):
topicname = models.CharField()
subject = models.ForeignKey(Subject, ondelete=models.CASCADE, relatedname='topics')
class Chapter(models.Model):
chaptername = modeks.CharField()
topic = models.ForeignKey(Topic, ondelete=models.CASCADE, relatedname='chapters'
My [views.py](https://views.py) looks something like
class ChapterListView(ListAPIView):
queryset = Subject.objects.all()
serializerclass = ChapterSerializer
filterbackends = [DjangoFilterBackend] #filters only the Subject
filtersetfields = 'subject_name'
My serializers.py looks something like
class ChapterSerializer(serializers.ModelSerializer):
class NestedTopicSerializer(serializers.ModelSerializer):
class NestedChapterSerializer(serializers.ModelSerializer):
/r/django
https://redd.it/ni8d9u
reddit
Nesting serializers in nested serializers
My current [serializers.py](https://serializers.py) file is looking very complicated and I am not sure if it is the best way to do it. Current my...
How do I add a new entry to my many to many related table in Django?
I have two models Course and Educators. Course has 3 fields course\_name, course\_educators and course\_past\_educators which link Educators to Courses by many to many. I want to write a function so that whenever a new entry is added to course\_educators that entry will be copied over to course\_past\_educators.
#models.py
#code for Educators model
class Educators(models.Model):
educator_name=models.CharField(max_length=20,default=None)
educator_img = models.ImageField(upload_to='educators_img',default=None)
#code for Courses model
class Course(models.Model):
course_name = models.CharField(max_length=100)
course_educators=models.ManyToManyField(Educators, related_name='current_educators', default=None, blank=True)
course_past_educators=models.ManyToManyField(Educators, related_name='past_educators', default=None, blank=True)
#views.py
#This is the function I wrote so that entries into course_past_educators are automatically added when course_educators is added with another entry.
u/receiver(m2m_changed, sender=Course.course_educators.through)
def create_past_educator_on_add(sender, instance, action, reverse, model, pk_set, **kwargs):
if action == 'post_add' and reverse is False:
/r/djangolearning
https://redd.it/1cq2j42
I have two models Course and Educators. Course has 3 fields course\_name, course\_educators and course\_past\_educators which link Educators to Courses by many to many. I want to write a function so that whenever a new entry is added to course\_educators that entry will be copied over to course\_past\_educators.
#models.py
#code for Educators model
class Educators(models.Model):
educator_name=models.CharField(max_length=20,default=None)
educator_img = models.ImageField(upload_to='educators_img',default=None)
#code for Courses model
class Course(models.Model):
course_name = models.CharField(max_length=100)
course_educators=models.ManyToManyField(Educators, related_name='current_educators', default=None, blank=True)
course_past_educators=models.ManyToManyField(Educators, related_name='past_educators', default=None, blank=True)
#views.py
#This is the function I wrote so that entries into course_past_educators are automatically added when course_educators is added with another entry.
u/receiver(m2m_changed, sender=Course.course_educators.through)
def create_past_educator_on_add(sender, instance, action, reverse, model, pk_set, **kwargs):
if action == 'post_add' and reverse is False:
/r/djangolearning
https://redd.it/1cq2j42
Reddit
From the djangolearning community on Reddit
Explore this post and more from the djangolearning community
Problems with Django Autocomplete Light
So, I'm stuck, I'm trying to make two selection boxes, one to select the state, the other to select the city. Both the code and the html are not crashing, but nothing is being loaded into the selection boxes.
Any help would be greatly appreciated!
#models.py
class City(models.Model):
country = models.CharField(maxlength=50)
state = models.CharField(maxlength=50)
city = models.CharField(maxlength=50)
def str(self):
return f"{self.name}, {self.state}"
class City(models.Model):
country = models.CharField(maxlength=50)
state = models.CharField(maxlength=50)
city = models.CharField(maxlength=50)
def str(self):
return f"{self.name}, {self.state}"
#forms.py
class CreateUserForm(forms.ModelForm):
def init(self, args, kwargs):
super().__init__(args, kwargs)
# Ensure city field has proper empty queryset initially
/r/djangolearning
https://redd.it/1kxt7bn
So, I'm stuck, I'm trying to make two selection boxes, one to select the state, the other to select the city. Both the code and the html are not crashing, but nothing is being loaded into the selection boxes.
Any help would be greatly appreciated!
#models.py
class City(models.Model):
country = models.CharField(maxlength=50)
state = models.CharField(maxlength=50)
city = models.CharField(maxlength=50)
def str(self):
return f"{self.name}, {self.state}"
class City(models.Model):
country = models.CharField(maxlength=50)
state = models.CharField(maxlength=50)
city = models.CharField(maxlength=50)
def str(self):
return f"{self.name}, {self.state}"
#forms.py
class CreateUserForm(forms.ModelForm):
def init(self, args, kwargs):
super().__init__(args, kwargs)
# Ensure city field has proper empty queryset initially
/r/djangolearning
https://redd.it/1kxt7bn
Reddit
From the djangolearning community on Reddit
Explore this post and more from the djangolearning community