How do I have two fields for selection?

I am writing a website in Django and I want to have two blogs.

For each blog, I need three variables: the name (which I choose when I write my message in the admin part β€” do I understand that this is the choice?), The title (for presentation), blog_url (for the URL).

There must be a finite number of blogs, so I can choose my choice from the drop-down menu when I write a message. I can do this with only one heading and URL after the example in the Django link - with the heading would be:

class Post(models.Model): BLOG_TITLE = ( ("Title 1", "first"), ("Title 2", "second"), ) blog_title = models.CharField( max_length=20, choices=BLOG_TITLE, blank=True) 

I think I need something like

 (["Title", "url"], "blog"), 

instead

 ("Title", "blog"), 

Should I define a Blog class and reference it via ForeignKey in Post? How?

Any idea? Thanks!

+1
source share
1 answer

You must use the foreignkey relation to the new model, called, for example, a block.

Example:

 class Blog(models.Model): title = models.CharField(max_length=20) url = models.URLField() class Post(models.Model): blog = models.ForeignKey(Blog) 

To access data:

 post = Post.objects.get(id=1) post.blog.title 

You need to access the data in your template.

Example:

 def postview(request): return render('template_xyz.html', {'object': Post.objects.get(id=1) } 

Template example:

 <h1>{{ object.blog.title }} </h1> 
+4
source

Source: https://habr.com/ru/post/1206632/


All Articles