Django Admin Ask a User a List of Questions - django

I am trying to create a custom Django Admin Site for new staff members that lets a staff member edit their User first_name/last_name + get presented a list of multiple choice questions with radio select for the answer choices. The questions need to be a predefined queryset (e.g. last 5 multiple choice questions by date_created), whether a M2M entries exists already or not.
models.py
class User(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid4,
unique=True,
)
first_name = models.CharField(
max_length=100,
blank=True,
null=True,
default=None,
)
last_name = models.CharField(
max_length=100,
blank=True,
null=True,
default=None,
)
class Questions(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid4,
unique=True,
)
question_text = models.CharField(
max_length=160,
blank=True,
null=True,
default=None,
)
date_created = models.DateTimeField(
auto_now_add=True
)
users = models.ManyToManyField(
Users,
through=Questions2Users,
through_fields=('questions', 'users')
)
class AnswerChoices(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid4,
unique=True,
)
choices_text = models.CharField(
max_length=160,
blank=True,
null=True,
default=None,
)
questions = models.ForeignKey(
Questions,
related_name='questions',
on_delete=models.CASCADE,
)
class Questions2Users(models.Model):
questions = models.ForeignKey(
Questions,
on_delete=models.CASCADE
)
users = models.ForeignKey(
Users,
null=True,
blank=True,
on_delete=models.CASCADE,
)
answerchoices = models.ForeignKey(
AnswerChoices,
on_delete=models.CASCADE
)
admin.py
from django.contrib import admin
from .models import (
User,
Questions,
Answers,
Questions2Users,
)
class Questions2UsersInline(admin.TabularInline):
model = Questions2Users
class UserAdminSite(admin.ModelAdmin):
class Meta:
model = User
inlines = [
Questions2UsersInline
]
admin.site.register(User, UserAdminSite)
I have identified it as a user model admin page with an inline for the M2M model. How would I display the questions queryset all at once with question_text and choice_text?

Related

mptt not linking children and parent - Django

I'm having an issue that I seriously can't wrap my head around.
I am using Django MPTT models and evrerything seems to be working fine (i.e. I can run the migrations and insert data in the database), but for some reason the
TreeForeignKey
table and the
TreeManyToManyField
table are not linking in the database.
Here are the models in question...
from mptt.models import MPTTModel, TreeForeignKey, TreeManyToManyField
class Category(MPTTModel):
name = models.CharField(
max_length=100,
verbose_name=_('category name'),
help_text=_('format: required, max=100'),
)
slug = models.SlugField(
max_length=150,
verbose_name=_('category safe URL'),
help_text=_('format: required, letters, numbers, underscore or hyphons'),
)
is_active = models.BooleanField(default=True)
parent = TreeForeignKey(
'self',
on_delete=models.PROTECT,
related_name='children',
null=True,
blank=True,
)
class MPTTMeta:
order_insertion_by = ['name']
class Meta:
verbose_name=_('product category')
verbose_name_plural=_('product categories')
def __str__(self):
return self.name
class Product(models.Model):
web_id = models.CharField(
unique=True,
max_length=50,
verbose_name=_('product website ID'),
)
slug = models.SlugField(
max_length=255,
verbose_name=_('product safe URL'),
help_text=_('format: required, letters, numbers, underscore or hyphons'),
)
name = models.CharField(max_length=150)
description = models.TextField(help_text='Required')
category = TreeManyToManyField(Category)
is_active = models.BooleanField(
default=False,
verbose_name=_('product visibility'),
)
created_at = models.DateTimeField(
editable=False,
auto_now_add=True,
help_text=_('format: Y-m-d H:M:S'),
)
updated_at = models.DateTimeField(auto_now=True, help_text=_('format: Y-m-d H:M:S'))
def __str__(self):
return self.name
I'm following the documentation verbatum, and really I have no idea why this is not working...
If anyone has any idea please let me know

UndefinedColumn column integrations_externalrecord.oppcontact_id does not exist django postgresql

When accessing my ExternalRecord model via the django admin screen, or by querying ExternalRecord.objects.all(), I receive the error: psycopg2.errors.UndefinedColumn: column integrations_externalrecord.oppcontact_id does not exist
I am building an integration functionality, and we have a junction table that houses an external id and the instance in our database that corresponds to this external id, set up like so:
class ExternalRecord(UUIDPrimaryKey, CreatedModifiedMixin, models.Model):
integration = models.ForeignKey(
to=Integration,
related_name='external_records',
on_delete=models.CASCADE
)
emailuser = models.ForeignKey(
"accounts.EmailUser",
related_name='external_records',
null=True,
blank=True,
on_delete=models.CASCADE
)
institution = models.ForeignKey(
"institutions.Institution",
related_name='external_records',
null=True,
blank=True,
on_delete=models.CASCADE
)
oppcontact = models.ForeignKey(
"opp_contacts.OppContact",
related_name='external_records',
null=True,
blank=True,
on_delete=models.CASCADE
)
external_record_id = models.CharField(
max_length=1000
)
and so on...
When I view the OppContact model either by viewing in the django admin screen or with OppContact.objects.all(), I see that the model has a field for "id". When I rollback to the migration before applying the oppcontact field, everything returns to work as normal, meaning I can query/view ExternalRecords without getting an error.
This is my OppContact model:
class OppContact(UUIDPrimaryKey):
company = models.ForeignKey(
"accounts.Company",
on_delete=models.CASCADE,
blank=True,
null=True
)
first_name = models.CharField(
max_length=100
)
last_name = models.CharField(
max_length=100
)...
And this is another model to which my ExternalRecord can be linked, Institution:
class Institution(UUIDPrimaryKey, CreatedModifiedMixin, models.Model):
company = models.ForeignKey(
"accounts.Company",
related_name='institutions',
null=False,
blank=False,
on_delete=models.CASCADE,
)
owner = models.ForeignKey(
"accounts.EmailUser",
related_name='institutions',
null=True,
blank=True,
on_delete=models.CASCADE,
)
name = models.CharField(max_length=100, null=False, blank=False)....
The only difference I see between the models is the OppContact doesn't have the CreatedModifiedMixin or models.Model, but I thought UUIDPrimaryKey extended models.Model, so I didn't think it mattered.
I have been stuck on this for several days, so any pointers in the right direction would be helpful (: Thank you all!
For all those following along at home, the issue was actually with a constraint I added to the ExternalRecord model, which caused the migration to fail, which is why the column wasn't found.

How to make model field that can has several values in django

I want to make a blog in Django.
The blog has Article, Author ... models.
each article has many resources. it looks like this on the article page:
Resources: Medium, Hashnode, Dev community, ...
I want that while adding an article, the admin can dynamically these article resources.
for the author, I want to add social links.
every author's social media are different. one may have Facebook, LinkedIn ... and the other may have Instagram, Twitter, ...
I want the admin (or author) can add any social media for the authors.
Update:
model implementation of Article:
class Article(models.Model):
"""Model definition for Article."""
title = models.CharField(
max_length=100
)
slug = models.SlugField(
max_length=100,
unique=True,
db_index=True
)
excerpt = models.TextField(
max_length=200
)
body = models.TextField(
max_length=10000,
validators=[MinLengthValidator(10)]
)
image = models.ImageField(
upload_to='images/blog',
)
image_resource = models.CharField(
max_length=100,
verbose_name="Image Resource Name",
null=True,
blank=True
)
related_articles = models.ManyToManyField(
'self',
symmetrical=True,
related_name='related_articles',
verbose_name='Related Articles',
blank=True
)
date_published = models.DateTimeField(
auto_now_add=True
)
author = models.ForeignKey(
Author,
on_delete=models.CASCADE,
related_name='Articles',
)
category = models.ForeignKey(
'Category',
on_delete=models.CASCADE,
related_name='Articles',
blank=True,
null=True
)
tags = models.ManyToManyField(
'Tag',
verbose_name='Tags'
)
model implementation of Author:
class Author(models.Model):
"""Model definition for Author."""
first_name = models.CharField(
max_length=50
)
last_name = models.CharField(
max_length=50
)
profile_pic = models.ImageField(
upload_to='profile_pics',
default='images/boy.jpg'
)
email = models.EmailField(
max_length=254
)
bio = models.TextField(
max_length=1000
)
facebook = models.URLField(
max_length=254,
blank=True,
null=True,
verbose_name='Facebook URL'
)
instagram = models.URLField(
max_length=254,
blank=True,
null=True,
verbose_name='Instagram URL'
)
twitter = models.URLField(
max_length=254,
blank=True,
null=True,
verbose_name='Twitter URL'
)
linkedin = models.URLField(
max_length=254,
blank=True,
null=True,
verbose_name='LinkedIn URL'
)
Look for an existing Django package that might handle what you want to have happen.
Aside from that, I can't think of a way that you can dynamically add these into a particular model. You'd have to include all of the different types of social media you feel an individual could possibly have ahead of of time.
You might be able to "fake it" by setting up a Profile for your authors that enables them to add a key:value pair into a field in the model as they desire to add social media accounts but that's about all I can suggest at the moment.

Django model allow only once in many

Please excuse the title but I'm not sure howto put this into words.
I have a model "card" and a model "computer":
class card(models.Model):
name=models.CharField(
verbose_name = 'Name',
max_length=50,
null=True,
blank=True,
)
serial=models.CharField(
verbose_name = 'Serial',
max_length=50,
null=True,
blank=True,
)
class computer(models.Model):
name=models.CharField(
verbose_name = 'Name',
max_length=50,
null=True,
blank=True,
)
slot1 = models.OneToOneField(
'card',
related_name='cardslot1',
on_delete=models.SET_NULL,
null=True,
blank=True,
verbose_name = 'Slot 1',
)
slot2 = models.OneToOneField(
'card',
related_name='cardslot2',
on_delete=models.SET_NULL,
null=True,
blank=True,
verbose_name = 'Slot 2',
)
(Of course that this computer model is invalid)
The cards are unique and should only be allowed to be used in one slot - of any computer. What's the best way to achieve this? I was thinking about a in-between table, something like
card n-1 cardcomputer n-1 computer
but I'm hoping there's a better way I'm not seeing right now.
Thanks
Use the constraints meta option for your model.
from django.db import models
from django.db.models import CheckConstraint, Q
class computer(models.Model)
name=models.CharField(
verbose_name = 'Name',
max_length=50,
null=True,
blank=True,
)
slot1 = models.OneToOneField(
'card',
related_name='cardslot1',
on_delete=models.SET_NULL,
null=True,
blank=True,
verbose_name = 'Slot 1',
)
slot2 = models.OneToOneField(
'card',
related_name='cardslot2',
on_delete=models.SET_NULL,
null=True,
blank=True,
verbose_name = 'Slot 2',
)
class Meta:
constraints = [
CheckConstraint(
check = ~Q(slot1=slot2),
name = 'unique_slot',
),
]
Yagus answer is correct, but here's a pure model alternative.
class Card(models.Model):
name = models.CharField(
verbose_name='Name',
max_length=50,
null=True,
blank=True,
)
serial = models.CharField(
verbose_name='Serial',
max_length=50,
null=True,
blank=True,
)
class Slot(models.Model):
card = models.OneToOneField(Card,
on_delete=models.SET_NULL,
null=True,
blank=True
)
computer = models.ForeignKey('Computer',
on_delete=models.CASCADE,
related_name='slots'
)
class Computer(models.Model):
name = models.CharField(
verbose_name='Name',
max_length=50,
null=True,
blank=True,
)
This way you have flexibility to add/change slots per computer in the admin panel and things are imho more readable than the constraints.
You can still access Computer.slots thanks to the related name.

How to sort using foreign key field in django and avoid multiple results of same row

I want to sort Groups with their 'is_favorite' boolean field from model GroupUser. I have two models GroupUser where there is a foreign key to Group model, now when I query Group.objects.filter(is_active=True).order_by('groupuser__group_id__is_favorite')
I get groups multiple times. I tried to user distict() on final queryset still no luck. Pls suggest any other way or possible solution. TIA.
class Group(models.Model):
group_name = models.CharField(
max_length=250)
context_type = models.ForeignKey(
"contenttypes.ContentType",
on_delete=models.DO_NOTHING,
blank=True,
null=True,
related_name="content_type")
context = models.IntegerField(
blank=True,
null=True)
privacy_type = models.ForeignKey(
"commans.PrivacyType",
on_delete=models.DO_NOTHING,
blank=True,
null=True,
related_name="group_privacy_id")
is_active = models.BooleanField(
default=True,
help_text="Is Group Active")
class GroupUser(models.Model):
group = models.ForeignKey(
"Group",
on_delete=models.DO_NOTHING,
blank=True,
null=True,
related_name="groupuser_group_id")
user=models.ForeignKey(
"auth_module.User",
on_delete=models.DO_NOTHING,
blank=True,
null=True)
is_favorite = models.BooleanField(
default=False,
blank=True,
null=True)
```
We can use an annotation to count the number of favourites each Group has. Then we can use this annotation to order by
from django.db.models import Sum
Group.objects.filter(
is_active=True
).annotate(
total_favorites=Sum('groupuser_group_id__is_favorite')
).order_by(
'-total_favorites'
)