synonyms and antonyms in a django dictionary app for local language - django

sorry for this question, but I had a problem with making a dictionary app for a local language, so I wouldn't need English dictionary, my problem is synonyms, I can't figure out how to implement it in my models
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
# Create your models here.
class Voca(models.Model):
name = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("voca:detail", kwargs={"id": self.id, "name": self.name})
class Defination(models.Model):
voca = models.ForeignKey(Voca, related_name='definations')
defination = models.CharField(max_length=500)
example = models.CharField(max_length=500)
etymology = models.CharField(max_length=500)
author = models.ForeignKey(User, default=1)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('created',)
def __str__(self):
return 'Defination given by {} on {}'.format(self.author, self.voca)
class Synonym(models.Model):
words = models.ManyToManyField(Voca, blank=True, related_name='synonyms')
I would like for users to add words, synonyms, antonyms definitions to the database themselves since it is a slang language, so if I can get any help especially for antonyms and synonyms I would really appreciate... thanks

My suggestion would be to remove the Synonym model and add fields to your Defination model.
class Defination(models.Model):
voca = models.ForeignKey(Voca, related_name='definations')
...
synonyms = models.ManyToManyField(Voca, related_name='synonyms')
antonyms = models.ManyToManyField(Voca, related_name='antonyms')

Related

Cannot access field in Django Graphene

The field which is specified in my models file is not included in the GraphiQL, I have tried to rename the field, delete it and define it again, even changing the type of field also updating the graphene-django package. None of these I have mentioned didn't work. The name of the field I can't get is named book
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from books.models import Book
class Borrowing(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
book = models.OneToOneField(Book, null=True, on_delete=models.CASCADE)
date = models.DateTimeField(default=timezone.now)
returned = models.BooleanField(default=False)
date_borrowed = models.CharField(blank=True, null=True, max_length=50)
date_returned = models.CharField(blank=True, null=True, max_length=50)
class Meta:
ordering = ['-date']
def __str__(self):
return f'{self.user.username} borrowed {self.book.title}'
schema.py
import graphene
from .mutations.borrowings import *
from backend.functions import pagination
PAGE_SIZE = 12
class BorrowingMutation(graphene.ObjectType):
borrow_book = BorrowBook.Field()
return_book = ReturnBook.Field()
class BorrowingQuery(graphene.ObjectType):
borrowings = graphene.List(BorrowingType)
users_borrowings = graphene.List(BorrowingType, page=graphene.Int())
def resolve_borrowings(self, info):
return Borrowing.objects.all()
def resolve_users_borrowings(self, info, page):
user = info.context.user
borrowings = Borrowing.objects.filter(user=user, returned=False)
borrowings = pagination(PAGE_SIZE, page, borrowings)
return borrowings
Type
class BorrowingType(DjangoObjectType):
class Meta:
model = Borrowing

Django model of a rent contract using Generic Foreign Key

I'm trying to model a rent contract in Django and use the admin form to insert and modify it.
Both owner and tenant can be companies (VAT number) or individuals (no VAT number). Companies and individuals are stored in two different models (Company and Individual).
I'm trying to solve this problem using Generic Foreign Key but I'm not able to show the tenant name in the admin page, only an integer field not friendly at all.
gestimm is the name of the app and that's my oversimplified models:
# my gestimm/models.py
#
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Individual(models.Model):
name = models.CharField(max_length=100, help_text='Name')
def __str__(self):
return self.name
class Company(models.Model):
name = models.CharField(max_length=100, help_text='Name')
def __str__(self):
return self.name
class Contract(models.Model):
description = models.CharField(max_length=30)
start = models.DateField()
stop = models.DateField()
def __str__(self):
return self.description
class Tenant(models.Model):
limit = models.Q(app_label='gestimm', model='individual') | models.Q(app_label='gestimm', model='company')
contract = models.ForeignKey(Contract, on_delete=models.CASCADE,
null=True, blank=True)
content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT,
help_text='Tenant', null=True,
limit_choices_to=limit)
object_id = models.PositiveIntegerField(null=True)
tenant = GenericForeignKey('content_type', 'object_id')
How I tried to solve the problem:
# my gestimm/admin.py
#
from django.contrib import admin
from .models import Individual, Company, Contract, Tenant
class TenantInline(admin.StackedInline):
model = Tenant
extra = 1
class ContractAdmin(admin.ModelAdmin):
inlines = [TenantInline]
admin.site.register(Individual)
admin.site.register(Company)
admin.site.register(Contract, ContractAdmin)
I found some old discussions but none of the proposed solutions worked.
Problem solved: I installed django-grappelli.
My new admin.py:
class TenantInline(admin.TabularInline):
model = Tenant
extra = 1
related_lookup_fields = {
'generic': [['content_type', 'object_id']],
}
class ContractAdmin(admin.ModelAdmin):
inlines = [
TenantInline,
]
admin.site.register(Contract, ContractAdmin)
As intended

How to access variables from foreign models in django

I just started out django and python so bear with me. (Just a newbie)
I have 3 models Programme, Module and Lecture.
Programme has a variable 'code' which is a foreign key to module.
Module has in turn also a variable 'code' which is a foreign key to lecture.
In lecture I have implemented a function to get dynamic path for uploading files based on the 'code' of programme, 'code' of module and 'title' of lecture.
Here is a snippet of my models.py
from django.db import models
class Programme(models.Model):
code = models.CharField(blank=True, max_length=20, primary_key=True)
title = models.CharField(blank=True, max_length=120)
synopsis = models.TextField(blank=True)
pub_date = models.DateTimeField(blank=True, auto_now=False, auto_now_add=True)
def get_programme_code(self):
return self.code
def __str__(self):
return self.title
class Module(models.Model):
code = models.CharField(blank=True, max_length=20, primary_key=True)
programme = models.ForeignKey(Programme, on_delete=models.CASCADE)
title = models.CharField(blank=True, max_length=120)
synopsis = models.TextField(blank=True)
pub_date = models.DateTimeField(blank=True, auto_now=False, auto_now_add=True)
def get_module_code(self):
return self.code
def __str__(self):
return self.title
class Lecture(models.Model):
def get_upload_to(self):
return 'uploads/%s/%s/%s/%s' % (Programme().get_programme_code(),Module().get_module_code,self.title,filename)
title = models.SlugField(max_length=100)
module = models.ForeignKey(Module, on_delete=models.CASCADE)
lecture_pdf = models.FileField(upload_to=get_upload_to)
lecture_video = models.FileField(upload_to=get_upload_to)
def __str__(self):
return self.title
I know that there is something wrong with my code by the way of accessing 'code's from programme and modules but I cannot figure it out.
And here is a snippet of my unit testing of the models.
from django.test import TestCase
from module_content.models import Programme, Module, Lecture
from django.utils import timezone
from django.core.urlresolvers import reverse
class ProgrammeTest(TestCase):
def create_programme(self, code="E318", title="Computer Science", synopsis="Englobes all computer related fields"):
return Programme.objects.create(code =code, title=title, synopsis=synopsis, pub_date=timezone.now())
def test_programme_creation(self):
t = self.create_programme()
self.assertTrue(isinstance(t, Programme))
self.assertEqual(t.__str__(), t.title)
def test_get_programme_code(self):
t = self.create_programme()
self.assertEqual(t.get_programme_code(), t.code)
class ModuleTest(TestCase):
def create_module(self, code="CSE2233", title="Computer Networks", synopsis="About data transmission"):
v = ProgrammeTest().create_programme()
return Module.objects.create(code=code, programme=v, title=title, synopsis=synopsis, pub_date=timezone.now())
def test_module_creation(self):
t = self.create_module()
self.assertTrue(isinstance(t, Module))
self.assertEqual(t.__str__(), t.title)
class LectureTest(TestCase):
def create_lecture(self, title="Lecture 1"):
t = ModuleTest().create_module()
return Lecture.objects.create(title=title, module=t)
def test_lecture_creation(self):
s = self.create_lecture()
self.assertTrue(isinstance(s, Lecture))
self.assertEqual(s.__str__(), s.title)
def test_get_upload_to(self):
s = self.create_lecture()
self.assertEqual( s.get_upload_to(), 'uploads/E318/CSE2233/lecture-1')
I put the field of title for lecture to be a slugfield, so does django put it automatically as a slug ?
I tried the slugfield and it just return the title as "Lecture 1" instead of "lecture-1", or maybe I'm missing something.
So how can I access the foreign keys from the models and test it that the dynamic upload path is working properly?
I just needed to access the other models by their foreign keys such as self.module.programme.code - to retrieve the code of the programme.

how to populate django models randomly

I am following a tutorial online for Django. The presenter loads in random data as follows:
for i in xrange(100): Vote(link = Link.objects.order_by('?')[0],voter=a).save()
From what I could understand, it goes from 0 to 100 and creates a new vote. The vote object has a link object. I don't understand what the order_by('?') means.
Here is the model.py file:
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Count
class LinkVoteCountManager(models.Manager):
def get_query_set(self):
return super(LinkVoteCountManager, self).get_query_set().annotate(
votes=Count('vote')).order_by("-votes")
class Link(models.Model):
title = models.CharField("Headline", max_length=100)
submitter = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now=True)
rank_score = models.FloatField(default=0.0)
url = models.URLField("URL", max_length=250, blank=True)
description = models.TextField(blank=True)
with_votes = LinkVoteCountManager()
objects = models.Manager()
def __unicode__(self):
return self.title
class Vote(models.Model):
voter = models.ForeignKey(User)
link = models.ForeignKey(Link)
def __unicode__(self):
return "%s voted %s" %(self.voter.username, self.link.title)

Django Inline Forms newly added Foreign Key Field but not showing in newly added inline rows

I am quite newbie in Django world. My question is I ve two models shown below. It works quite well with Grapelli and inline-sortables. Only problem is whenever I add a new foreign key for "equipment" or "image type" fields. They don't show up in the drop down menu of newly added inline rows. I went through internet but couldn't find a smilar problem and a solution.
I would appreciate some help with this.
My model is:
from django.db import models
from datetime import datetime
from thumbs import ImageWithThumbsField
from positions.fields import PositionField
class Artist(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return self.name
class ImageType(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return self.name
class Equipment(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return self.name
class Image(models.Model):
name = models.CharField(max_length=255)
image_file = models.ImageField(upload_to = "images/%Y-%m-%d")
Image_Type = models.ForeignKey(ImageType)
upload_date = models.DateTimeField('date_published',default=datetime.now)
artist = models.ForeignKey(Artist)
equipment = models.ForeignKey(Equipment)
order = PositionField(collection='artist')
def __unicode__(self):
return self.name
class Meta:
ordering = ['order']
And My admin.py is:
from gallery.models import Image,ImageType,Artist,Equipment
from django.contrib import admin
class ImageUploadAdmin(admin.ModelAdmin):
fields = ['name','artist','equipment','image_file','Image_Type','upload_date']
list_filter = ['upload_date']
date_hierarchy = 'upload_date'
class ImageInline(admin.TabularInline):
model = Image
list_display = ('name','equipment','image_file','Image_Type','upload_date')
sortable_field_name = "order"
exclude = ('upload_date',)
extra = 0
class ArtistAdmin(admin.ModelAdmin):
inlines = [
ImageInline,
]
admin.site.register(Artist,ArtistAdmin)
admin.site.register(Image, ImageUploadAdmin)
admin.site.register(ImageType)
admin.site.register(Equipment)