I have model with a ForeignKey "log_written_by" and I want that to be the logged in user.
How should i state that in my forms.py as a hiddenfield?
class AssetLog(models.Model):
# Relationships
log_written_by = models.ForeignKey("auth.User", on_delete=models.SET_NULL, blank=True, null=True)
asset_case = models.ForeignKey("asset_app.AssetCase", on_delete=models.CASCADE)
# Fields
date_time_log = models.DateTimeField()
notes = models.TextField(max_length=1024)
created = models.DateTimeField(auto_now_add=True, editable=False)
class Meta:
pass
def __str__(self):
return str(self.pk)
def get_absolute_url(self):
return reverse("asset_app_AssetLog_detail", args=(self.pk,))
def get_update_url(self):
return reverse("asset_app_AssetLog_update", args=(self.pk,))
You can do the following:
class AssetLogForm(forms.ModelForm):
class Meta:
model = AssetLog
fields = ('log_written_by ', '...,')
widgets = {'log_written_by ': forms.HiddenInput()}
See this related StackOverflow post here.
Related
I am getting Issue while edit a record based on CHatquestion ID, if option is null then i need to add a record based on same chatquestion id, if chatqustion id exist in option it will work,
i am trying to multiple way to solve this issue but still can't find solution.
Models.py # thease are all 3 models
class Problem(models.Model):
Language = models.IntegerField(choices=Language_CHOICE, default=1)
type = models.CharField(max_length=500, null=True, blank=True)
def __str__(self):
return self.type
class ChatQuestion(models.Model): # Eding record based on chatquestion id
question = RichTextField(null=True, blank=True)
problem_id = models.ForeignKey(
Problem,
models.CASCADE,
verbose_name='Problem',
)
def __str__(self):
return self.question
is_first_question = models.BooleanField(default=False)
class Option(models.Model):
option_type = models.CharField(max_length=250, null=True, blank=True)
question_id = models.ForeignKey(
ChatQuestion,
models.CASCADE,
verbose_name='Question',
null=True,
blank=True
)
problem=models.ForeignKey(
Problem,
models.CASCADE,
verbose_name='Problem',
null=True,
blank=True
)
next_question_id = models.ForeignKey(ChatQuestion, on_delete=models.CASCADE, null=True, blank=True,
related_name='next_question')
def __str__(self):
return self.option_type
forms.py
class EditQuestionForm(forms.ModelForm):
class Meta:
model = ChatQuestion
fields =('question','problem_id')
class EditOptionForm(forms.ModelForm):
class Meta:
model = Option
fields =('option_type',)
views.py
def question_edit(request,id=None):
if id is not None:
queryset = get_object_or_404(ChatQuestion,pk=id)
queryset1=get_object_or_404(Option,question_id=queryset )
else:
queryset = None
queryset1 = None
if request.method=="POST":
form = EditQuestionForm(request.POST ,instance=queryset)
form1=EditOptionForm(request.POST, instance=queryset1)
if form.is_valid() and form1.is_valid():
question=form.cleaned_data['question']
option_type=form1.cleaned_data['option_type']
if id:
queryset.question=question
queryset.save()
queryset1.option_type=option_type
queryset1.save()
messages.success(request,'Sucessful')
return redirect('/fleet/list_chatbot')
else:
print(form.errors)
messages.error(request,'Please correct following',form.errors)
elif id:
form = EditQuestionForm(instance=queryset)
form1=EditOptionForm(instance=queryset1)
if not queryset1:
form1=EditOptionForm()
else:
form = EditQuestionForm()
form1=EditOptionForm()
context={
'form':form,
'form1':form1
}
return render(request,'chatbot/question_edit.html',context=context)
I have a model form that creates a new job entry, and on submission, I need an invisible field job_time_estimation to be set to a sum of 'service_stats_estimate_duration' values from ServiceItemStats objects associated with the JobEntry by a many-to-many relationship when submitting the form.
For example, if in my NewJobEntryForm I chose two existing ServiceItemStats objects that have service_stats_estimate_duration values 60 and 90, on submission, I want a value 150 to be saved in that JobEntry object's job_time_estimation attribute.
I tried doing this using aggregation by defining a save() method in the model but I am getting an error "name 'serviceItemStats' is not defined".
I am not sure if I am going about this the right way. Any help would be appreciated.
My code:
models.py:
class ServiceItemStats(models.Model):
service_stats_name = models.CharField(primary_key=True, max_length=20)
service_stats_estimate_duration = models.IntegerField()
# Many-to-many relationship with JobEntry.
def __str__(self):
return self.service_stats_name
class JobEntry(models.Model):
# PK: id - automatically assigned by Django.
jo
b_entry_date_time = models.DateTimeField(default=timezone.now)
jo
b_date = models.DateField(blank=True, null=True)
job_checked_in = models.BooleanField()
job_checked_out = models.BooleanField(default=False)
job_priority = models.IntegerField()
job_time_estimation = models.IntegerField(blank=True, null=True)
job_comments = models.TextField(max_length=200, blank=True, null=True)
job_parts_instock = models.BooleanField(default=False)
job_started = models.BooleanField(default=False)
job_finished = models.BooleanField(default=False)
job_expand_fault_evidence = models.ImageField(blank=True, null=True)
job_expand_comments = models.ImageField(blank=True, null=True)
job_expand_parts_required = models.CharField(max_length=200, blank=True, null=True)
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) #One-to-one relationship
customer = models.ForeignKey(Customer, on_delete=models.CASCADE) #One-to-one relationship
serviceBay = models.ForeignKey(ServiceBay, on_delete=models.CASCADE, blank=True, null=True) #One-to-one relationship
serviceItemStats = models.ManyToManyField(ServiceItemStats, blank=True) #Many-to-many relationship
def __str__(self):
return self.id
def save(self, *args, **kwargs):
if not self.job_time_estimation:
self.job_time_estimation = serviceItemStats.objects.all().aggregate('service_stats_estimate_duration')
return super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse("jobs:job_detail",kwargs={'pk':self.pk})
views.py
class JobCreateView(FormView):
template_name = "jobs/jobentry_form.html"
form_class = NewJobEntryForm
success_url = reverse_lazy("jobs:job_list")
def form_valid(self, form):
form.save()
return super(job_list, self).form_valid(form)
forms.py
class NewJobEntryForm(ModelForm):
class Meta:
model = JobEntry
fields = ['vehicle', 'customer', 'job_date', 'job_checked_in', 'job_priority', 'job_comments', 'job_parts_instock', 'serviceItemStats']
widgets = {
'job_date' : forms.DateInput(format=('%m/%d/%Y'), attrs={'class':'form-control', 'placeholder':'Select a date', 'type':'date'}),
'ServiceItemStats' : forms.CheckboxSelectMultiple(),
'job_priority' : forms.RadioSelect(choices=priorityOptions),
}
You can try this.
from django.db.models import Sum
class JobCreateView(FormView):
template_name = "jobs/jobentry_form.html"
form_class = NewJobEntryForm
success_url = reverse_lazy("jobs:job_list")
def form_valid(self, form):
job=form.save()
estimation = job.serviceItemStats.all().aggregate(total=Sum('service_stats_estimate_duration'))
job.job_time_estimation = estimation['total']
job.save()
return super(job_list, self).form_valid(form)
When i try to create a new by post by posting the following Json:
{
"title": "This is serialzer title",
"content": "This is serialzer content",
}
I get the following error:
NOT NULL constraint failed: blog_post.views
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now
# Create your models here.
class Post(models.Model):
sno = models.AutoField(primary_key=True)
title = models.CharField(max_length=255)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
views = models.IntegerField()
slug = models.CharField(max_length=100)
timeStamp = models.DateTimeField(default=now)
def __str__(self):
# return self.title + ' by ' + self.author
return self.title + ' by ' + self.author.username
class BlogComment(models.Model):
sno = models.AutoField(primary_key=True)
comment = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True)
timeStamp = models.DateTimeField(default=now)
def __str__(self):
return self.comment[0:13] + "..." + " by " + self.user.username
views.py
#api_view(['POST'])
def api_create_blog_view(request):
user = User.objects.get(pk=1)
blog_post = Post(author=user)
if request.method == "POST":
serializer = PostSerializer(blog_post, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.py
from blog.models import Post
from rest_framework import serializers
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['title', 'content']
I don't know how to solve this please help me to solve this error.DB has already been cleared. Locations have been created by using the admin interface. I know that the issue is something trivial, but I just can't get it to work.
You need to set a value for the views. You can do so by specifying a default value:
from django.conf import settings
class Post(models.Model):
sno = models.AutoField(primary_key=True)
title = models.CharField(max_length=255)
content = models.TextField()
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
blank=True,
null=True
)
views = models.IntegerField(default=0)
slug = models.CharField(max_length=100)
timeStamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title + ' by ' + self.author.username
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
Note: According to the PEP-8 Style Guide, the classes should be written in PerlCase, and the fields in snake_case.
I have a question in django rest framework. Since I'm learning how to use some advanced options, I do not quite understand. I need to currently change a booleanfield every time a foreignkey is inserted into table.
How can I do this in model ?
Model:
class Persona(models.Model):
name = models.CharField(max_length=32)
cart = models.ForeignKey(Credit,null=True)
rg = models.IntergerField()
end = models.CharField(max_length=256)
details = models.TextField(blank=True, null=True)
order = models.ForeignKey(Order, null=True)
def __str__(self):
return self.cart
class Meta:
db_table='person'
app_label = 'bank'
class Credit(models.Model):
number = models.CharField(max_length=16, unique=True)
create_at = models.DateField(auto_add_now=True)
updated_at = models.DateField()
available = models.BooleanField()
def __str__(self):
return self.number
class Meta:
db_table = 'credit'
app_label = 'bank'
Serializer:
class PersonaSerializer(serializers.ModelSerializer):
order__id = serializers.ReadOnlyField(source='order.id')
class Meta:
model = Persona
fields = '__all__'
class Persona(viewsets.ModelViewSet):
allowed_methods = ('GET', 'POST', 'PUT', 'PATCH')
queryset = Persona.objects.all()
serializer_class = PersonaSerializer
You can override the create method on the ModelSerializer to achieve this:
def create(self, validated_data):
cart = validated_data['cart']
persona = super(PersonaSerializer, self).create(validated_data)
cart.available = True # update boolean
cart.save()
return persona
You can read more about this in the docs
If you want to handle this in your model you can override the Persona model save method:
class Persona(models.Model):
name = models.CharField(max_length=32)
cart = models.ForeignKey(Credit,null=True)
rg = models.IntergerField()
end = models.CharField(max_length=256)
details = models.TextField(blank=True, null=True)
order = models.ForeignKey(Order, null=True)
def __str__(self):
return self.cart
class Meta:
db_table='person'
app_label = 'bank'
def save(self, *args, **kwargs):
# Will only update the available field when the Persona
# instance is created and the cart field is not null
if not self.pk and self.cart:
self.cart.available = True
self.cart.save()
return super(Persona, self).save(*args, **kwargs)
I'm new to Django and I'm building a Document Visibility/Status application. Each document, called an "Indent", has some "Attributes", and these attributes have multiple "Status".
On the dashboard of the application, I need to dynamically render the attributes as columns, and the statuses as choices in a dropdown list.
I'm thinking that I'll need to return a dictionary as follows - but if you have a better suggestion, please let me know.
{ 1 : ['status1','status2', 'status3'], 2 : ['status1','status2', 'status3'], ... }
Where the number is the attribute ID.
Here are my models:
class Indent(models.Model):
dateCreated = models.DateTimeField(auto_now=True)
indentNumber = models.CharField(max_length=75)
creator = models.ForeignKey(settings.AUTH_USER_MODEL)
def __str__(self):
return '%s' % (self.indentNumber)
class Meta:
verbose_name = 'Indents'
verbose_name_plural = "Indents"
class Files(models.Model):
fileLink = models.FileField(upload_to='indents/', null=True) #Add 'indents/userID'
indent = models.ForeignKey(Indent, on_delete=models.CASCADE)
def __str__(self):
return '%s' % (self.indent)
class Meta:
verbose_name = 'Files'
verbose_name_plural = "Files"
"""
TO-DO
REMOVE NULL CONSTRAINT
"""
class Attribute(models.Model):
name = models.CharField(max_length=75)
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True)
def __str__(self):
return '%s' % (self.name)
class Meta:
verbose_name = 'Attributes'
verbose_name_plural = "Attributes"
"""
TO-DO
For the names of Status objects, it needs to be more descriptive and accurate
"""
class Status(models.Model):
name = models.CharField(max_length=255)
attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE)
def __str__(self):
return '%s' % (self.name)
class Meta:
verbose_name = 'Status'
verbose_name_plural = "Status"
class IndentAttribute(models.Model):
indent_id = models.ForeignKey(Indent, on_delete=models.CASCADE)
attribute_id = models.ForeignKey(Attribute, on_delete=models.CASCADE)
status_id = models.ForeignKey(Status, on_delete=models.CASCADE, null=True)
def __str__(self):
return '%s - %s' % (self.indent_id, self.attribute_id)
class Meta:
verbose_name = 'Indent_Attribute'
verbose_name_plural = "Indent_Attribute"
Here's an example of the dashboard we're building:
Dashboard Example
Take a look at Django's QuerySet values_list(). Here's a modified example from there to demonstrate how it works:
>>> Status.objects.values_list('name', flat=True)
<QuerySet ['Okay', 'Not Okay', 'Uh-oh', ...]>
You should be able to use that to help construct that dict pretty quickly.