I have the following codes:
models.py
class Job(models.Model):
jobname = models.CharField(max_length = 1000)
owner = models.CharField(max_length = 150)
enabled = models.BooleanField()
freq_type = models.IntegerField(default = 1)
freq_interval = models.IntegerField(default = 0)
freq_recurrence = models.IntegerField(default = 0)
start_date=models.CharField(max_length=10)
end_date=models.CharField(max_length=10, blank = True)
start_time=models.CharField(max_length=6)
end_time=models.CharField(max_length=6, blank = True)
date_added = models.DateTimeField(auto_now_add = True, null = True)
date_modified=models.DateTimeField(auto_now = True, null = True)
version=models.IntegerField(default = 1)
class Job_removed(models.Model):
jobname = models.CharField(max_length = 1000)
owner = models.CharField(max_length = 150)
enabled = models.BooleanField(null = True)
freq_type = models.IntegerField(default = 1)
freq_interval = models.IntegerField(default = 0)
freq_recurrence = models.IntegerField(default = 0)
start_date=models.CharField(max_length=10)
end_date=models.CharField(max_length=10, blank = True)
start_time=models.CharField(max_length=6)
end_time=models.CharField(max_length=6, blank = True)
date_added = models.DateTimeField(null = True)
date_modified=models.DateTimeField(default=timezone.now)
version=models.IntegerField(null=True)
views.py
def job_delete(request,pk):
job=Job.objects.get(pk=pk)
jobdetail = Job_detail.objects.get(job=pk)
if request.method == "POST":
jobr = JobRemovedForm(request.POST)
if jobr.is_valid():
jobr.jobname = job.jobname
print(jobr.jobname)
jobr.owner = job.owner
print(jobr.owner)
jobr.enabled = job.enabled
print(jobr.enabled)
jobr.start_date = job.start_date
print(jobr.start_date)
jobr.start_time = job.start_time
print(jobr.start_time)
jobr.date_added = job.date_added
print(jobr.date_added)
jobr.version = job.version
print(jobr.version)
jobr.save()
return redirect('/job/', {'job':Job.objects.all})
else:
jobr = JobRemovedForm()
return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail, 'jobr':jobr})
return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail})
Output of my powershell for those print commands:
In the database (SQLite):
What I am trying to do is to copy from the entry from Job Table to Job_removed Table. I assign the new entry in Job_removed with the values in Job Table. It is printing correctly in my powershell but when I check my database, none of the value are entering. Why is this happening though? Can anyone explain to me and point me to the right direction to correct this? I know there are post about how to clone data to another table but it does not fit the task that I am required to do so I am not using those answers.
Update: model for Job_detail and form for JobRemovedForm
models.py
class Job_detail(models.Model):
job_type=models.IntegerField(default=1)
json = models.CharField(max_length = 1000)
job = models.ForeignKey(Job, on_delete=models.CASCADE)
forms.py
class JobRemovedForm(ModelForm):
class Meta:
model = Job_removed
fields = []
Update 2: views (I realize i didnt do commit=False) and form fields updated
views.py
def job_delete(request,pk):
job=Job.objects.get(pk=pk)
jobdetail = Job_detail.objects.get(job=pk)
if request.method == "POST":
jobr = JobRemovedForm(request.POST)
if jobr.is_valid():
jr = jobr.save(commit=False)
jr.jobname = job.jobname
print(jr.jobname)
jr.owner = job.owner
print(jr.owner)
jr.enabled = job.enabled
print(jr.enabled)
jr.start_date = job.start_date
print(jr.start_date)
jr.start_time = job.start_time
print(jr.start_time)
jr.date_added = job.date_added
print(jr.date_added)
jr.version = job.version
print(jr.version)
jr.save()
return redirect('/job/', {'job':Job.objects.all})
else:
print(jobr.errors)
jobr = JobRemovedForm()
return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail, 'jobr':jobr})
return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail})
forms.py
class JobRemovedForm(ModelForm):
class Meta:
model = Job_removed
fields = ['jobname', 'owner', 'enabled', 'start_date', 'start_time', 'date_added', 'version']
And now my powershell is showing jobr.errors of the following:
jobnameThis field is required.ownerThis field is required.start_dateThis field is required.start_timeThis field is required.date_addedThis field is required.versionThis field is required.
Actually you do not need Job_removed model because it is unuseful and not better design for a such case in general.so first remove that model and add a field called is_deleted to your job model which value should be True for deleted jobs and False for non deleted jobs.by default i make is_deleted is False so when you deleted it you can mark it as True
class Job(models.Model):
jobname = models.CharField(max_length = 1000)
owner = models.CharField(max_length = 150)
enabled = models.BooleanField()
freq_type = models.IntegerField(default = 1)
freq_interval = models.IntegerField(default = 0)
freq_recurrence = models.IntegerField(default = 0)
start_date=models.CharField(max_length=10)
end_date=models.CharField(max_length=10, blank = True)
start_time=models.CharField(max_length=6)
end_time=models.CharField(max_length=6, blank = True)
date_added = models.DateTimeField(auto_now_add = True, null = True)
date_modified=models.DateTimeField(auto_now = True, null = True)
version=models.IntegerField(default = 1)
is_delete = models.BooleanField(default=False) # new field
Delete your model remove Job_removed
2)run python manage.py makemigrations
3)run python manage.py migrate
now let us work on your views for deleting jobs.
from django.shortcuts import render,get_object_or_404,redirect
def job_delete(request,pk):
job= get_object_or_404(Job,pk=pk,is_deleted=False)
job.is_deleted = True # delete the job if it is not deleted
job.save()
return redirect('/job/')
Note:I use get_object_or_404 to raise page not found if there is no job related to the pk and i check that the job is not deleted.
now i do not know how is your other views but you should now make a little bit of change in querying jobs.if you want to query all jobs you should query jobs that is not deleted.by doing this
Job.objects.filter(is_deleted = False)
instead of
Job.objects.all()
and better approach should be to use post method for deleting jobs not get.but for now you can keep as it is.sorry for my english if you do not understand please ask me in the comments.
Update but if you want to do is it as you did.
then you do not need a form you can just copy the data from Job to Job_removed.and if you need a form you can make these fields read only.
let us do it without form
from django.shortcuts import render,get_object_or_404,redirect
def job_delete(request,pk):
job= get_object_or_404(Job,pk=pk)
jr = Job_removed()
jr.jobname = job.jobname
print(jr.jobname)
jr.owner = job.owner
print(jr.owner)
jr.enabled = job.enabled
print(jr.enabled)
jr.start_date = job.start_date
print(jr.start_date)
jr.start_time = job.start_time
print(jr.start_time)
jr.date_added = job.date_added
print(jr.date_added)
jr.version = job.version
print(jr.version)
jr.save()
job.delete() # then delete the job
return redirect('/job/')
Form is not required in this situation.
Soft delete is the best option. Have a look in to this tutorial
Related
I got problem in django. Im creating online shop website and I add products section where my products listed(html). I add my products from admin site (models.py).
When I want to add to products i give error like this : get() returned more than one Post -- it returned 2!
These are my codes :
views.py
class PostDetail(generic.DetailView):
model = Post
template_name = "shop-single.html"
def get_context_data(self, **kwargs):
models = Post.objects.get()
context = super().get_context_data(**kwargs)
client = Client(api_key = settings.COINBASE_COMMERCE_API_KEY)
domain_url = "https://www.nitroshop.store/"
product = {"name" : f'{models.title}' , 'description': f'{models.subject}' , "local_price" : {'amount' : f'{models.product_price}' , "currency" : "USD"} , "pricing_type" : "fixed_price" , "redirect_url" : domain_url + "NXnUijYpLIPy4xz4isztwkwAqSXOK89q3GEu5DreA3Ilkde2e93em8TUe99oRz64UWWBw9gEiiZrg60GMu3ow" , "cancel_url" : domain_url + "products"}
charge = client.charge.create(**product)
context['charge'] = charge
return context
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
STATUS = (
(0 , "Draft"),
(1 , "Publish")
)
class Post(models.Model):
title = models.CharField(max_length = 200 , unique = True)
slug = models.SlugField(max_length = 200 , unique = True)
author = models.ForeignKey(User , on_delete = models.CASCADE , related_name = "shop_posts")
updated_on = models.DateTimeField(auto_now = True)
subject = models.CharField(max_length = 200 , default = "We offer you pay with Tether or Litecoin")
caption = models.TextField()
product_brand = models.CharField(max_length = 200 , default = "Add parametr")
product_price = models.CharField(max_length = 200 , default = "Add parametr")
opt = models.TextField(default = "Add parametr")
image = models.ImageField(upload_to = "images/" , default = "None")
created_on = models.DateTimeField(auto_now_add = True)
status = models.IntegerField(choices = STATUS , default = 0)
class Meta:
ordering = ["-created_on"]
def __str__(self):
return self.title
I must be use coinbase gateway for payment. I want when user go to coinbase payment the title of product(each product title) set on coinbase title and ...
But I have error like that when i want add more products
Would you please help me ?
models = Post.objects.get()
This method is to get() a single object from model. If you don't apply any parameters, then it tries to get all objects in QuerySet. If there is more than one (or None), then it will throw an error. And this is happening, because I can assume you have two Post objects in your database.
You need to pass parameter like:
models = Post.objects.get(id=some_id)
error: 'Questions' object is not iterable
models.py code:
class Questions(models.Model):
title = models.CharField(max_length = 150)
slug = models.SlugField(max_length = 10, unique = True)
body = models.TextField()
category = models.ManyToManyField(Category, related_name = "questions")
author = models.ForeignKey(User, on_delete = models.CASCADE)
created = models.DateTimeField(auto_now_add = True)
picture = models.ImageField(upload_to = "questions/%Y/%m/%d", null = True, blank = True)
status = models.BooleanField(default = True)
def get_absolute_url(self):
return reverse("questions:ques_detail", args = [self.slug, self.id])
views.py code:
def QuestionDetail(request, question, pk):
question = get_object_or_404(Questions, slug = question, id = pk)
return render(request, "questions/ques_detail.html", {"questions": question})
urls.py code:
urlpatterns = [
path('<slug:question>/<int:pk>', QuestionDetail, name = "questiondetail")
I guess there is a misunderstanding somewhere.
Indeed what do you want to achieve ?
If you want to retrieve a single instance your code looks good but it does not make any sense to iterate on an instance.
If you want to retrieve a QuerySet, then you would have to create another view. For exemple :
def questions(request):
questions = get_list_or_404(Questions)
return render(request, "questions/ques_detail.html", {"questions": questions})
Also you should take care of naming your function and variable in a pythonic way.
Some docs might be found here
Devs,
In my project I have a form that has a field that has a student name selection, it is a drop down field by the students that are currently enrolled in that particular class. It gets this information from table Section Enrollment than checks the master Student table. The filtering works out correctly, however when I submit my form, it says the student name is not a valid choice. My guess is because its submitting that student name and not a ID, I'm not 100% sure. Here is my models and view. I don't know how to fix this. Appreciate that help.
QUERY IN QUESTION:
getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True)
MODELS:
# Creation of Classrooms and Assigned Teachers
class SectionEnrollment(models.Model):
sectionenrollmentpsid = models.CharField(primary_key = True,max_length = 50, default = "")
section = models.ForeignKey(Section,on_delete = models.PROTECT, default = "" ,)
studentpsid = models.ForeignKey(Student,on_delete = models.PROTECT, default = "" ,)
entry_date = models.DateField(blank=True)
exit_date = models.DateField(blank=True)
dropped = models.BooleanField(default = False, blank = True)
class Meta:
verbose_name = "Student Section Enrollment"
def __str__(self):
return self.sectionenrollmentpsid
# Where Basic Student Data Is Stored
class Student(models.Model):
studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True)
student_name = models.CharField(max_length = 50)
first_name = models.CharField(max_length = 50, default = "")
last_name = models.CharField(max_length = 50,default = "")
gender = models.CharField(max_length = 1,default = "")
student_grade = models.CharField(max_length = 2, default = "")
home_room = models.CharField(max_length = 5, default = "")
student_enrollment = models.CharField(max_length = 2, default = "")
school_number = models.CharField(max_length = 15, default = "")
email = models.EmailField(default = "")
projected_graduation_year = models.CharField(max_length = 4, default = "")
counseling_goal = models.TextField(max_length = 255)
win_username = models.CharField(max_length = 50)
win_password = models.CharField(max_length = 50)
offsite_laptop = models.BooleanField(default = False, blank = True)
image = models.ImageField(default ="default.png", upload_to ='student_pics')
VIEW:
#login_required
def Rapid_Fire(request, classid):
if request.method == "GET":
date = datetime.date.today()
class_name = Section.objects.filter(sectionpsid=classid)
getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True)
student_selection = getstudents.all().order_by('studentpsid__student_name')
my_class_id = request.session['my_class_id']
sectionpsid = Section.objects.get(sectionpsid = my_class_id)
form = Rapid_Fire_Form()
form.fields["student_name"].queryset = getstudents
form.fields["sectionpsid"].queryset = class_name
context = ({'form': form, 'my_class_id': my_class_id, 'sectionpsid':sectionpsid,})
return render(request, 'points/rapid_fire.html', context )
elif request.method == "POST":
date = datetime.date.today()
class_name = Section.objects.filter(sectionpsid=classid)
getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True)
student_selection = getstudents.all().order_by('studentpsid__student_name')
my_class_id = request.session['my_class_id']
sectionpsid = Section.objects.get(sectionpsid = my_class_id)
form = Rapid_Fire_Form(request.POST)
form.fields["student_name"].queryset = getstudents
form.fields["sectionpsid"].queryset = class_name
if form.is_valid():
# Records logged in user to table
obj = form.save(commit= False)
userid = request.user
obj.created_by = userid
obj.save()
it seems the problem is here:
getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True)
student_selection = getstudents.all().order_by('studentpsid__student_name')
the values_list('studentpsid_id__student_name', flat = True) is collecting the students name not their id. so the form field will be field by incorrect data I think.
and if I'm right the solution may be:
students_id = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid__id', flat = True)
student_selection = Student.objects.filter(id__in=students_id).order_by('student_name')
or:
student_selection = Student.objects.filter(sectionenrollment_set__section_id=classid).order_by('student_name')
In a Django Modelform (Product_definition), i want to have a dropdown(Merchant name) which will show users only if the their designation in User form is "Merchant".
is it possible that I could get the list of users for the dropdown based on this condition .Please note that i don't require it to be a foreign key as connecting the models is not required.
This is the form which contains the Designation :
from django.contrib.auth.models import User
class UserProfileInfo(models.Model):
user = models.OneToOneField(User,on_delete = models.CASCADE)
#extra UserAttribute
MERCHANT = 'MR'
FABRIC = 'FR'
WASHING = 'WS'
PRINT = 'PR'
PLANNER = 'PL'
DESIGNATION_CHOICES =(
(PLANNER,'Planner'),
(MERCHANT,'Merchant'),
(FABRIC,'Fabric'),
(WASHING,'Washing'),
(PRINT,'Printing'),
)
Designation =models.CharField(
max_length = 20,
choices = DESIGNATION_CHOICES,
default= 'PLANNER'
)
def __str__(self):
return self.user.username
and this is the form with Merchant Name where I want the names of all merchants to appear.
class Product_definition(models.Model):
Order_number = models.CharField(max_length=25,unique = True, blank = True, null = True)
style_name = models.CharField(max_length=15, blank = True, null = True)
color = models.CharField(max_length=15, blank = True, null = True)
Order_qty = models.PositiveIntegerField()
SMV = models.FloatField()
MERCHANT = models.ForeignKey(UserProfileInfo,on_delete= models.CASCADE,default='Select')
def __str__(self):
return self.Order_number
I have created a foreign key for now but I don't require it and it doesn't list the names of only the merchant in the drop down.
I think you can do it like this using ModelChoiceField:
class ProductForm(forms.ModelForm): # please use CamelCase when defining Class Names
MERCHANT = forms.ModelChoiceField(queryset=UserProfileInfo.objects.filter(Designation=UserProfileInfo.MARCHENT)) # Please use sname_case when naming attributes
class Meta:
model = Product_definition # Please use CamelCase when defining model class name
fields = '__all__'
I have a model which I would like to change the return field from a single field to a concatenated string of fields. I have done this and it works fine, the issue comes when I try and query the foreign key related to that model.
Current Code
Models.py - Items App
class Details(models.Model):
serial_number = models.CharField(max_length = 300, unique=True, null = True, blank = True)
manufacturer = models.CharField(max_length = 300, null = True, blank = True)
model_type = models.CharField(max_length = 300, null = True, blank = True)
equipment_type = models.CharField(max_length = 300, null = True, blank = True)
class Meta:
ordering = ["serial_number"]
def __unicode__(self): # Python 3: def __str__(self):
return self.serial_number
Views.py - Instruments App: Query
queryset = InstrumentAnnual.objects.get(instrument_details__serial_number = self.object.instrument_annual, current_revision = True)
NOTE: 'InstrumentAnnual' model has a foreign key to 'Details' model called 'Instrument_Details'.
New Code
Models.py - Items App
class Details(models.Model):
serial_number = models.CharField(max_length = 300, unique=True, null = True, blank = True)
manufacturer = models.CharField(max_length = 300, null = True, blank = True)
model_type = models.CharField(max_length = 300, null = True, blank = True)
equipment_type = models.CharField(max_length = 300, null = True, blank = True)
class Meta:
ordering = ["serial_number"]
def __unicode__(self): # Python 3: def __str__(self):
return u"%s %s %s" % (self.manufacturer, self.model_type, self.equipment_type)
So my issue is how do I query the above model through a foreign key as it no longer returns self.serial_number so I can't use __serial_number in the query.
My desired result is just to display manufacturer, model_type and equipment_type in the foreign key drop down instead of just a potentially meaningless serial number. If I am going about this the wrong way please let me know. Thanks in advance.
You do not have to do the queryset the way you currently do it. If you want to get the InstrumentAnnual object that belongs to a Detail object, you can simply use self.object.instrumental_annual (given that self.object is your Detail object, as it it in your example.
As to how to fix your provided query, you are currently checking for a serial number with the string representation of the InstrumentAnnual object. But that isn't your serial number anymore. Instead you would do this
queryset = InstrumentAnnual.objects.get(instrument_details__serial_number = self.object.instrument_annual.serial_number, current_revision = True)
to specify that you in fact want to check the serial number. But as already said, there is no need for this queryset, as you can easily get the InstrumentAnnual object through self.object.instrumental_annual