select object to edit - python

I have a simple view function that's designed to allow the user to choose from items listed in an html table (records). Clicking on a record should divert the user to the template from which he can edit that specific record. The code is as follows:
def edit_record(request):
if request.method == 'POST':
a=ProjectRecord.objects.get()
form = RecordForm(request.POST, instance=a)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
a=ProjectRecord.objects.get()
form = RecordForm(instance=a)
return render_to_response('productionModulewire.html', {'form': form})
The problem is that the function works perfectly well ONLY so long as there is only 1 record in the database. As soon as I add another, I get a multiple returned item error.
I suspect it has something to do with "objects.get()" but I don't know how to correctly structure the view?
The url is simple (perhaps too much so):
(r'^edit/', edit_record),
and the model looks like this:
class ProjectRecord(models.Model):
client = models.CharField(max_length=50, choices=CLIENT_CHOICES)
account = models.CharField(max_length=50, choices=ACCOUNT_CHOICES)
project_type = models.CharField(max_length=50, choices=TYPE_CHOICES)
market = models.CharField(max_length=50, choices=MARKET_CHOICES)
agencyID = models.CharField(max_length=30, unique=True, blank=True, null=True)
clientID = models.CharField(max_length=30, unique=True, blank=True, null=True)
prjmanager = models.CharField(max_length=64, unique=False, blank=True, null=True)
acclead = models.CharField(max_length=64, unique=False, blank=True, null=True)
artdirector = models.CharField(max_length=64, unique=False, blank=True, null=True)
prdlead = models.CharField(max_length=64, unique=False, blank=True, null=True)
intlead = models.CharField(max_length=64, unique=False, blank=True, null=True)
prjname = models.CharField(max_length=200, unique=True)
prjstatus = models.CharField(max_length=50, choices=STATUS_CHOICES)
as_of = models.DateField(auto_now_add=False)
format = models.CharField(max_length=64, unique=False, blank=True, null=True)
target_studio = models.DateField(unique=False, blank=True, null=True)
mech_return = models.DateField(unique=False, blank=True, null=True)
comp_return = models.DateField(unique=False, blank=True, null=True)
target_release = models.DateField(unique=False, blank=True, null=True)
record_added = models.DateField(auto_now_add=True)
record_modified = models.DateTimeField()
studio_name = models.CharField(max_length=64, unique=False, blank=True, null=True)
studio_process = models.CharField(max_length=64, unique=False, blank=True, null=True, choices=PROCESS_CHOICES)
to_studio = models.DateTimeField(unique=False, blank=True, null=True)
from_studio = models.DateTimeField(unique=False, blank=True, null=True)
studio_name2 = models.CharField(max_length=64, unique=False, blank=True, null=True)
studio_process2 = models.CharField(max_length=64, unique=False, blank=True, null=True, choices=PROCESS_CHOICES)
to_studio2 = models.DateTimeField(unique=False, blank=True, null=True)
from_studio2 = models.DateTimeField(unique=False, blank=True, null=True)
comments = models.TextField(max_length=500, unique=False, blank=True, null=True)
summary = models.TextField(max_length=500, unique=False, blank=True, null=True)
upload_pdf = models.CharField(max_length=50, unique=False, blank=True, null=True)
upload_achive = models.CharField(max_length=50, unique=False, blank=True, null=True)
def __unicode__(self):
return u'%s' % self.prjname
class Admin:
pass
from which the model form "RecordForm" was derived.

The important thing about get is "get what?"
When you say
a=ProjectRecord.objects.get()
you neglected to provide any selection criteria. Which row do you want from the database?
Which row? Hmmmm... How does the GET transaction know which row is going to be edited?
Usually, we put that in the URL.
So, you'll need to update your urls.py to include the record ID on the URL path. You'll need to update your view function definition to accept this record ID. Finally, you'll need to update GET and POST to use this record identification which came from the URL.
Update urls.py to include the object id. See http://docs.djangoproject.com/en/1.1/topics/http/urls/#named-groups
urlpatterns = patterns('',
(r'^class/(?P<object_id>\d+?)/$', 'app.views.edit_record'),
Update your view function
def edit_record( request, object_id = None ):
if request.method == "POST":
if object_id is None:
return Http_404
ProjectRecord.objects.get( pk = int(object_id) )
etc.

Without more information it is hard to tell what you need to change, but your guess is correct, the problem is with your ProjectRecord.objects.get() call.
You should be passing some sort of information to get in order to limit the list down to one.
In most cases, you will need:
ProjectRecord.objects.get(pk=id)
Where id is the primary key value of the ProjectRecord you are trying to edit.
Could you show the relevant code from your urls.py as well as more information on your ProjectRecord model?

Related

Django model ordering in another models

I can't find the answer to the following question about learning application building:
I have task model, which has one-to-many relations with other models: text_message, image_message, video_message, quiz_message, web_page_message (let's call them blocks) and I want to allow the user to choose the order in which these blocks will be sent.
The issue is that if I just add small integer field called 'order' in these blocks' classes - user still can choose a number that would be much bigger than the overall number of existing blocks.
So what is the best way to make such ordering?
Thank you for your answers.
UPD.:
Sorry if the code is not perfect, it is my first real Django project.
Added my models.
Questions: 
How to make an order through all these messages?
How to design models in such a way to give the ability to the user to change this ordering?
 
class task(models.Model):
employees_appointed_id = models.ManyToManyField(profile, related_name='task_to_appointed_users')
employees_finished_id = models.ManyToManyField(profile, related_name='task_to_users_finished', blank=True, null=True)
creator_user_id = models.ForeignKey('profile', on_delete=models.CASCADE, related_name='who_created_task')
description = models.TextField(max_length=1000)
created_datetime = models.DateTimeField(models.DateTimeField(auto_now=True))
deadline = models.DateTimeField(blank=True, null=True)
title = models.CharField(max_length=55)
course = models.ForeignKey('course', on_delete=models.CASCADE)
mentor = models.ManyToManyField(profile, blank=True, null=True, related_name='task_to_profile')
class text_message(models.Model):
text = models.CharField(max_length=3900)
number_by_order = models.IntegerField()
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='message_to_task')
creator_user_id = models.ForeignKey('profile', on_delete=models.CASCADE, related_name='message_to_creator_user')
course_id = models.ForeignKey('course', on_delete=models.CASCADE, related_name='messages_to_course')
created_datetime = models.DateTimeField(auto_now=True)
class video_message(models.Model):
description = models.CharField(max_length=1024)
media = models.ForeignKey('media', on_delete=models.CASCADE)
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='video_message_to_task')
class web_page_message(models.Model):
link = models.CharField(max_length=255)
description = models.TextField(max_length=2000, blank=True, null=True)
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='web_page_to_task')
class image_message(models.Model):
media = models.ForeignKey('media', on_delete=models.CASCADE)
description = models.TextField(max_length=1024)
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='image_message_to_task')
class quiz_message(models.Model):
question = models.CharField(max_length=300)
option_1 = models.CharField(max_length=100)
option_2 = models.CharField(max_length=100)
option_3 = models.CharField(max_length=100, blank=True, null=True)
option_4 = models.CharField(max_length=100, blank=True, null=True)
option_5 = models.CharField(max_length=100, blank=True, null=True)
option_6 = models.CharField(max_length=100, blank=True, null=True)
option_7 = models.CharField(max_length=100, blank=True, null=True)
option_8 = models.CharField(max_length=100, blank=True, null=True)
option_9 = models.CharField(max_length=100, blank=True, null=True)
option_10 = models.CharField(max_length=100, blank=True, null=True)
explanation = models.CharField(max_length=200, blank=True, null=True)
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='quiz_message_to_task')

Two dependent conditions in exclude DJANGO

I want to check whether the current user already has the same movie id in his personal list or not. If he has it then I want to exclude that movie from my trending list.
I want it to be something like this.
views.py
trending = list(Movies.objects.exclude(mid in mymovies WHERE uid = request.user.id))
models.py
class Movies(models.Model):
mid = models.CharField(max_length=255, primary_key=True)
title = models.CharField(max_length=255, null=True, blank=True)
rating = models.CharField(max_length=5, null=True, blank=True)
type = models.CharField(max_length=255, null=True, blank=True)
genre = models.CharField(max_length=255, null=True, blank=True)
rdate = models.CharField(max_length=255, null=True, blank=True)
language = models.CharField(max_length=255, null=True, blank=True)
cover = models.CharField(max_length=255, null=True, blank=True)
description = models.TextField(null=True, blank=True)
sequal = models.CharField(max_length=255, null=True, blank=True)
trailer = models.CharField(max_length=255, null=True, blank=True)
year = models.CharField(max_length=5, null=True, blank=True)
objects = models.Manager()
def __str__(self) -> str:
return self.title
class MyMovies(models.Model):
mid = models.ForeignKey(Movies, on_delete=CASCADE)
uid = models.ForeignKey(User, on_delete=CASCADE, null=True, blank=True)
watched = models.BooleanField()
date = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
You can .exclude(…) with:
trending = Movies.objects.exclude(mymovies__uid=request.user)
If you specified a related_query_name=… [Django-doc] or a related_name=… [Django-doc], then you need to use that to make a JOIN with your Movies model:
trending = Movies.objects.exclude(related_name_of_fk__uid=request.user)
Note: normally a Django model is given a singular name, so MyMovie instead of MyMovies.
Note: Normally one does not add a suffix _id to a ForeignKey field, since Django
will automatically add a "twin" field with an _id suffix. Therefore it should
be user, instead of uid.

created_by not working with ManyToManyField django

Hello everyone I'm trying top build a task manager web app using django, I need to assign task to one or multiple users I'm using manytomany relation in models.py and in views.py I'm adding created_by user automatically.
My problem is that when I do that I see that no users selected in assigned users but if I add created by user from the form it worked well.
class Task(models.Model):
task_id = models.AutoField(primary_key=True)
shortcode = models.CharField(max_length=15, unique=True, blank=True, null=True)
task_name = models.CharField(max_length=200)
task_progress = models.ForeignKey(TaskProgressStatus, on_delete=models.CASCADE, blank=True, null=True)
customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=True, null=True)
task_priority = models.ForeignKey(TaskPriority, on_delete=models.CASCADE)
assigned_to_employee = models.ManyToManyField(User)
paid = models.BooleanField(default=False)
on_account = models.BooleanField(default=False)
currency = models.ForeignKey(Currency, on_delete=models.CASCADE, blank=True, null=True)
net_amount = models.DecimalField(decimal_places=2, max_digits=20, blank=True, null=True)
vat = models.IntegerField(default=11)
quote_validity = models.CharField(max_length=200, default='1 Month from offer date')
delivered = models.BooleanField(default=False)
delivered_date = models.DateTimeField(null=True, blank=True)
creation_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
due_date = models.DateTimeField(null=True, blank=True)
created_by = models.ForeignKey(User, related_name='created_by_username', on_delete=models.CASCADE, null=True, blank=True)
project = models.ForeignKey(Project, null=True, blank=True, on_delete=models.CASCADE)
file_name = models.FileField(upload_to='projects_files', null=True, blank=True)
notes = models.TextField()
def __str__(self):
return str(self.task_name)
#login_required
def addtask(request):
form = taskForm()
if request.method == 'POST':
form = taskForm(request.POST)
if form.is_valid():
newform = form.save(commit=False)
newform.created_by = request.user
newform.save()
return HttpResponseRedirect(request.path_info)
else:
context = {'form':form}
return render(request, 'tasks/add_task.html', context)
Update
As well pointed out by Ahmed I. Elsayed there is some inconsistency in the title of the question, since the created_by field is actually a ForeignKey, not a ManyToManyField.
That being said, your issue is actually with the foreign key.
My suggestion is to first of all be sure that your form is actually valid. You can do that by printing something inside the if form.is_valid() block.

Django model query

I have question about Django query models. I know how to write simple query, but Im not familiar with LEFT JOIN on two tables. So can you give me some advice on his query for better understanding DJango ORM.
query
select
count(ips.category_id_id) as how_many,
ic.name
from
izibizi_category ic
left join
izibizi_product_service ips
on
ips.category_id_id = ic.id
where ic.type_id_id = 1
group by ic.name, ips.category_id_id
From this query I get results:
How many | name
0;"fghjjh"
0;"Papir"
0;"asdasdas"
0;"hhhh"
0;"Boljka"
0;"ako"
0;"asd"
0;"Čokoladne pahuljice"
0;"Mobitel"
2;"Čokolada"
And I have also try with his Django query:
a = Category.objects.all().annotate(Count('id__category',distinct=True)).filter(type_id=1)
But no results.
My models:
models.py
class Category(models.Model):
id = models.AutoField(primary_key=True)
type_id = models.ForeignKey('CategoryType')
name = models.CharField(max_length=255)
def __str__(self):
return str(self.name)
class Product_service(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255, blank=True, null=True)
selling_price = models.DecimalField(decimal_places=5, max_digits=255, blank=True, null=True)
purchase_price = models.DecimalField(decimal_places=5, max_digits=255, blank=True, null=True)
description = models.CharField(max_length=255, blank=True, null=True)
image = models.FileField(upload_to="/", blank=True, null=True)
product_code = models.CharField(max_length=255, blank=True, null=True)
product_code_supplier = models.CharField(max_length=255, blank=True, null=True)
product_code_buyer = models.CharField(max_length=255, blank=True, null=True)
min_unit_state = models.CharField(max_length=255, blank=True, null=True)
state = models.CharField(max_length=255, blank=True, null=True)
vat_id = models.ForeignKey('VatRate')
unit_id = models.ForeignKey('Units')
category_id = models.ForeignKey('Category')
If you culd help me on this problem.
You should add a related name on the category_id field like:
category_id = models.ForeignKey('Category', related_name="product_services")
so that in your query you can do:
a = Category.objects.all().annotate(Count('product_services',distinct=True)).filter(type_id=1)
and then you can access the individual counts as:
a[0].product_services__count

Django query for many to many relationship

I have following two models
class Questionnaire(models.model)
name = models.CharField(max_length=128, null=True, blank=True)
type = models.CharField(max_length=128,choices=questionnaire_choices)
class TestPopulation(models.Model)
user = models.ForeignKey(User, blank=True, null=True)
age = models.CharField(max_length=20, blank=True, null=True)
education = models.CharField(max_length=50, blank=True, null=True,
choices=EDUCATION_CHOICES)
questionnaire = models.ManyToManyField(Questionnaire, blank=True, null=True)
Now how can i get number of questionnaires for the specific user (logged in user). ?
test_population = TestPopulation.objects.get(user=user)
test_population.questionnaire.all()
questionnaire.objects.filter(test_population__user=user).count()

Categories