How to save foreign key fields in django rest framework - python

I have a Question and Answer model as follows:
class Question(models.Model):
text = model.textField()
class Answer(models.Model):
question = model.ForeignKey(Question)
text = model.textField()
correct = model.BooleanField()
i want to save four answers while saving a question and in which only one answer can be correct. Also one answer must be correct out of four.

Well, I think your best option is to make use of Django Forms and do that validation on its clean method.
An example of its use can be found in https://docs.djangoproject.com/en/1.6/ref/forms/validation/ . It provides nice documentation and shows you how to validate fields on a form (which is what you need). If you don't know how to create a form, visit this https://docs.djangoproject.com/en/1.6/topics/forms/ first and then check out how it is done and check if it is what you were looking for. If it isn't, try to make your question a bit clearer, please =)

Related

Conditional field rendering django admin

I am new to Django. I would like to show some fields in the Django Admin only if a specific value has been selected on a dropdown.
For instance, I have a question model. I would like to let the user select the type of question. If it is a multiple choice question, I would like to show fields to let the user fill the possible answers.
I have found this link but it seems that it is not done for the Django Admin.
How should I proceed to achieve what I need ?
If the object already exists (meaning it's not a creation form) I think this could help you: ModelAdmin.get_fields().

Order items with the django-admin interface

Lets say I have a django model looking like this:
class question(models.Model):
order = models.IntegerField('Position')
question = models.CharField(max_length= 400)
answer = models.TextField()
published = models.BooleanField()
def __unicode__(self):
return self.question
In my view I show all of the questions ordered ascending by the order field.
My question is: Is there an easy way to edit the order field in the django admin interface? Right now, I have to go to edit the Question, then look up what number to put in the order field and maybe even reorder all the other items. What i really want would be some "up and down"-arrows on the admin page where all the questions are listed.
Is that possible?
Check this: django-orderedmodel.
This is a really simple implementation of abstract base class for items which can be ordered with admin interface. No external dependencies and easy to use.
Sure, here is an example of admin.py file with up and down links to change items order:
https://github.com/alexvasi/django-simplemenu/blob/master/simplemenu/admin.py
Basically, you just need to override get_urls method to add your custom views (move_up and move_down in this example).
More famous example would be django-treemenus, but there is some extra code to support older versions of django.
You can check:
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_editable
In case someone else is seeking the solution for that issue in 2017, I found the great package Django Admin Sortable
You can use django-admin-sortable2 to easily change the order of items including inline items as well.

Django -- How to filter objects with an "author" from a set of "authors"(users)?

How to filter objects with an "author" from a set of "authors"(Users)?
The "objects" are Posts, having an author(ForeignKey to User).
I'm pretty much stumped by this, so I'd appreciate help with it. Of course one could go about this the naive way, by manually filtering them, but that would hit the database real hard. Thanks anyway.
EDIT:
Listing of Post:
class Post(models.Model):
'''A Post or a Status Update.
'''
content=models.CharField(max_length=200)
author=models.ForeignKey(django.contrib.auth.models.User, related_name="author")
tags=models.ManyToManyField(Tag)
replyTo=models.ManyToManyField(django.contrib.auth.models.User, related_name="replyTo")
# Snip model methods
Clarification: I'm trying to filter based upon a set of users and not a single user (which is trivially easy to do)
when=models.DateTimeField(auto_now=True)
Thanks to everyone who helped with the previous question. Now I have one final thing to ask:
Code excerpt from UserProfile (connected to User):
def get_updates():
return Post.objects.filter(author__in=(list(self.friends.all()) + [self]))
Is this the most efficient way to get all the posts by an author and its friends? (Note: This is a naive implementation, as it doesn't handle pagination, etc. Will do that later)
Something like:
Post.objects.filter(author=user)
Where user is the relevant user should work, but it's hard to give a good answer with no models
EDIT
Now that I understand your question, try this:
Post.objects.filter(author__in=users)
Where users is the set of users
Post.objects.filter(author__in=setofusers)
Post.objects.filter(attribute__in = list_of_ids)

Validating a slug in Django

I'm guessing this is going to involve regexp or something, but I'll give it a shot. At the minute, a user can break a website by typing something similar to £$(*£$(£#$&£($ in the title field, which is converted into a slug using Django slugify.
Because none of these characters can be converted, Django returns an error. My question is, what should I put in the form validation method to raise a forms.ValidationError when the user uses a title like this?
Thanks.
This question is half a decade old so in updating my question I should explain that I'm at least nodding to the past where some features might not have existed.
The easiest way to handle slugs in forms these days is to just use django.models.SlugField. It will validate itself for you and imply that this field is an index.
If you're not using this on a model, you can still hook in the same validator that SlugField uses:
from django.core.validators import validate_slug
slug = forms.CharField(..., validators=[validate_slug])
If you just want to do behind-the-scenes checking or write your own validator, you can use a similar technique to pull in Django's definition of a valid slug. It's just the compiled regex that validate_slug above uses:
from django.core.validators import slug_re
if slug_re.match(...):
...
I can't imagine it will change, but by locking yourself to Django's idea of a slug, you'll ensure consistency if Django does change one day.
SLUG_REGEX = re.compile('^[-\w]+$')

How can I programmatically obtain the max_length of a Django model field?

Say I have a Django class something like this:
class Person(models.Model):
name = models.CharField(max_length=50)
# ...
How can I programatically obtain the max_length value for the name field?
Person._meta.get_field('name').max_length will give you this value. But having to use _meta suggests this is something you shouldn't do in normal usage.
Edit: as Carl pointed out, this naming is misleading and it does seem quite acceptable to use it: http://www.b-list.org/weblog/2007/nov/04/working-models/
Read more at Django Docs:
https://docs.djangoproject.com/en/dev/ref/models/meta/#django.db.models.options.Options.get_field
The question is regarding models, but for people trying to do the same for forms (that's how I ended up in this thread), I think this approach is quite simple and clear:
1. In a template:
{{form.name.field.max_length}}
2. In python code (e.g. in the view)
form.name.field.max_length

Categories

Resources