Django : change the id with another field in the views page - django

How do I tell to Django to replace the Column type_id to the name field in the views (html page).
and here I have foreignkey, it gave me id (type_id), and this screentshot of fabrication class:
the column type_id is comming from the composant_type class,
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.base import Model
from CentreCout.models import CentreCoutDB
class fiche(models.Model):
centre_cout = models.CharField(max_length=150)
number = models.CharField(max_length=100)
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.name
class unite(models.Model):
name = models.CharField(max_length= 150, unique=True)
def __str__(self):
return self.name
class composant_type(models.Model):
name = models.CharField(max_length=150, unique=True )
def __str__(self):
return f"({self.name})"
class composant_fab(models.Model):
type = models.ForeignKey(composant_type, to_field='name', on_delete=models.CASCADE)
name = models.CharField(max_length=150, unique=True)
def __str__(self):
return f"({self.name})"
class fabrication(models.Model):
grade = models.ForeignKey(fiche, to_field='name',on_delete=models.CASCADE)
type = models.ForeignKey(composant_type, on_delete=models.CASCADE, blank=True, null=True)
composant = models.ForeignKey(composant_fab , to_field='name', on_delete=models.CASCADE, null=True, blank=True)
unite = models.ForeignKey(unite, to_field='name',on_delete=models.CASCADE)
composant_value = models.FloatField(blank=True, null=True)
def __str__(self):
return f"({self.grade}-{self.composant}-{self.composant_value}-{self.unite})"
views.py
from django.shortcuts import render
from django import views
from django.http import HttpResponse
from .models import *
import pandas as pd
def fabrications(request):
lesfichestab = fiche.objects.all()
fabricationtab = fabrication.objects.all().values()
df = pd.DataFrame(fabricationtab)
context = {
'lesfichestab':lesfichestab,
'fabricationtab':df.to_html()
}
return render(request,'fabrications/fabricationpage.html', context)
Note: I use Pandas method, because i have to do some Filtering and pivoting of the table.

I get an answer from here :
Django with Pandas accessing ForeignKey
admin_data = pd.DataFrame.from_records(
administrations.values(
"id",
"study__name", # <-- get the name through the foreign key
"url_hash",
)
).rename(
columns={
"id": "administration_id",
"study__name": "study_name",
"url_hash": "link",
}
)

Related

Mutation in django graphene for model with foreign key and many to many relationship

I have 2 models in my django app, the first is Tags model and the second is Post model, the problem is when i try to use mutation for the Post model to add a post from the graphql it doesn't work but it works fine in the Tags model, also the Queries works fine when i try to get data from the database.
Here's my Code:
model.py:
from django.db import models
from django.utils.translation import gettext as _
from django.conf import settings
from django.contrib.auth import get_user_model
User = get_user_model()
# Create your models here.
class Tag(models.Model):
name = models.CharField(_("Tag Name"), max_length=50, unique=True)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(_("Title"), max_length=50, unique=True)
slug = models.SlugField(_("Post Slug"), unique=True)
body = models.TextField(_("Post Content"))
createdAt = models.DateTimeField(auto_now_add=True)
updatedAt = models.DateTimeField(auto_now=True)
published = models.BooleanField(_("Published"), default=False)
author = models.ForeignKey(User, verbose_name=_("Author"), on_delete=models.CASCADE)
tags = models.ManyToManyField("Tag", verbose_name=_("Tags"), blank=True)
class Meta:
ordering = ['-createdAt']
def __str__(self):
return self.title
schema.py:
import graphene
from graphene_django import DjangoObjectType
from django.contrib.auth import get_user_model
from .models import Post, Tag
User = get_user_model()
class PostType(DjangoObjectType):
class Meta:
model = Post
class TagType(DjangoObjectType):
class Meta:
model = Tag
fields = ('id', 'name',)
class TagInput(graphene.InputObjectType):
name = graphene.String(required=True)
class CreatePostMutation(graphene.Mutation):
class Arguments:
title = graphene.String()
body = graphene.String()
published = graphene.Boolean()
author_id = graphene.ID()
tags = graphene.List(graphene.Int)
success = graphene.Boolean()
post = graphene.Field(PostType)
#classmethod
def mutate(cls, root, info, title, body, published, author_id, tags):
author = User.objects.get(pk=author_id)
post_instance = Post(
title=title,
body=body,
published=published,
author=author,
)
post_instance.save(commit=False)
if tags:
tag_objects = Tag.objects.filter(pk__in=tags)
post_instance.tags.set(tag_objects)
post_instance.save()
return CreatePostMutation(success=True, post=post_instance)
class CreateTagMutation(graphene.Mutation):
class Arguments:
name = graphene.String(required=True)
tag = graphene.Field(TagType)
#classmethod
def mutate(cls, root, info, name):
tag = Tag(name=name)
tag.save()
return CreateTagMutation(tag=tag)
class Mutation(graphene.ObjectType):
create_post = CreatePostMutation.Field()
create_tag = CreateTagMutation.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
Here's what it returns:
{
"data": {
"createPost": {
"post": null
}
}
}

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: AUTO ADD THE RESPECTIVE FOREIGN KEY VALUE IN CREATE VIEW

I am creating a CreateView with the following models:
from django.db import models
from uuid import uuid4
from django.core.validators import MinValueValidator,MaxValueValidator
from questions.models import Question
from django.urls import reverse
class ExamPaper(models.Model):
id = models.UUIDField(primary_key=True, default=uuid4)
name = models.CharField(max_length=300)
for_class = models.PositiveSmallIntegerField(
validators=(
MinValueValidator(1),
MaxValueValidator(12),
))
date = models.DateField(null=True, blank=True)
PARTS = (
("A", "A"),
("B", "B"),
("C", "C"),
("D", "D"),
("E", "E"),
)
part = models.CharField(
max_length=1, choices=PARTS, null=True,blank=True)
def __str__(self):
return f"{self.name} ({self.get_part_display()})"
def get_absolute_url(self):
return reverse("exam_detail", args=[str(self.pk)])
class ExamQuestions(models.Model):
exam = models.ForeignKey(
ExamPaper, on_delete=models.SET_NULL, null=True,
related_name="examquestions")
question = models.ForeignKey(
Question, on_delete=models.CASCADE,)
marks = models.PositiveSmallIntegerField(
validators=(MaxValueValidator(20), ))
def __str__(self):
return self.question.question[:150]
def get_absolute_url(self):
return reverse("exam_detail", args=[str(self.exam.pk)])
I am trying to make a form using CreateView in which I can add questions and marks to a ExamPaper. I have allready created a CreatView using ExamPaper model and added a link in it to add questions.
What i want is that whenever I add questions the exam field gets assigned to that question.
views.py
class ExamCreateView(CreateView):
model = ExamPaper
template_name = "exam_new.html"
fields = "__all__"
class ExamQuestionsView(CreateView):
model = ExamQuestions
fields = "question", "marks",
template_name = "exam_ques_new.html"
I am able to get a form for both but in ExamQuestionView I have to select exam from the whole list.

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)