I want add a course to the users purchased_course. I am unable to figure out how to add it. The Buy Button Link I added on the Course Listview and Detailview I want that particular course to be added in in the users purchased_course which is many to many field.
My models
class Course(models.Model):
...
title = models.CharField(max_length=1000)
class User(AbstractUser):
...
purchased = models.ManyToManyField(Course, blank=True, related_name="buyers")
My views
I want the function here
#login_required
def puchases_chaeckout(request):
user=request.user
return redirect('student-gome-page')
Please Help
its simple!
list_of_courses = user.purchased.all()
please read Django documents
Related
When giving users a choice of things to choose in choices list for a model, if they do not find the choice they are looking for, how can you make them add a new one, and store their choice as the value they added.
There are several approaches for what you want to do, if you want that all the users can have the new choice, you have to save everything in a model and take out the choices from there, if you want to have a "preset of variables" and then just save the new one just for your user, just save the new one in the user choice in a charfield directly, if you tell me what approach you want, I can give you a more extensive explanation.
This is not what choices on a field are made for. They are used for a set of choices that does not change if the code does not change.
If you need choices that can be modified without modifying the code, the natural approach is to use the database. A foreign key is the right tool to use:
class Gender(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
def __str__(self):
return self.name
class Person(models.Model):
first_name = models.CharField(max_length=32)
last_name = models.CharField(max_length=100)
gender = models.ForeignKey(Gender)
In your admin.py:
from .models import Gender
from django.contrib import admin
admin.site.register(Gender, admin.ModelAdmin)
Now admins can add extra genders, which will be available for all.
In my model, I have the following M2M field
class FamilyMember(AbstractUser):
...
email_list = models.ManyToManyField('EmailList', verbose_name="Email Lists", blank=True, null=True)
...
The EmailList table looks like this:
class EmailList(models.Model):
name = models.CharField(max_length=50, default='My List')
description = models.TextField(blank=True)
is_active = models.BooleanField(verbose_name="Active")
is_managed_by_user = models.BooleanField(verbose_name="User Managed")
In the app, the user should only see records that is_active=True and is_managed_by_user=True.
In the Admin side, the admin should be able to add a user to any/all of these groups, regardless of the is_active and is_managed_by_user flag.
What happens is that the Admin assigns a user to all of the email list records. Then, the user logs in and can only see a subset of the list (is_active=True and is_managed_by_user=True). This is expected behavior. However, what comes next is not.
The user deselects an email list item and then saves the record. Since M2M_Save first clears all of the m2m records before it calls save() I lose all of the records that the Admin assigned to this user.
How can I keep those? I've tried creating multiple lists and then merging them before the save, I've tried passing the entire list to the template and then hiding the ones where is_managed_by_user=False, and I just can't get anything to work.
What makes this even more tricky for me is that this is all wrapped up in a formset.
How would you go about coding this? What is the right way to do it? Do I filter out the records that the user shouldn't see in my view? If so, how do I merge those missing records before I save any changes that the user makes?
You might want to try setting up a model manager in your models.py to take care of the filtering. You can then call the filter in your views.py like so:
models.py:
class EmailListQuerySet(models.query.QuerySet):
def active(self):
return self.filter(is_active=True)
def managed_by_user(self):
return self.filter(is_managed_by_user=True)
class EmailListManager(models.Manager):
def get_queryset(self):
return EmailListQuerySet(self.model, using=self._db)
def get_active(self):
return self.get_queryset().active()
def get_all(self):
return self.get_queryset().active().managed_by_user()
class EmailList(models.Model):
name = models.CharField(max_length=50, default='My List')
description = models.TextField(blank=True)
is_active = models.BooleanField(verbose_name="Active")
is_managed_by_user = models.BooleanField(verbose_name="User Managed")
objects = EmailListManager()
views.py:
def view(request):
email = EmailList.objects.get_all()
return render(request, 'template.html', {'email': email})
Obviously there is outstanding data incorporated in my example, and you are more than welcome to change the variables/filters according to your needs. However, I hope the above can give you an idea of the possibilities you can try.
In your views you could do email = EmailList.objects.all().is_active().is_managed_by_user(), but the loading time will be longer if you have a lot of objects in your database. The model manager is preferred to save memory. Additionally, it is not reliant on what the user does, so both the admin and user interface have to talk to the model directly (keeping them in sync).
Note: The example above is typed directly into this answer and has not been validated in a text editor. I apologize if there are some syntax or typo errors.
I want the admin interface to show disctrict field only if I choose 'B' as the category. If I choose 'W' I want all fields of Offer model to be displayed. Is it possible to show selected (filtered) fields in admin page depending on the choice in other field in the same model? Thanks in advance for your help.
My models:
class Category(models.Model):
NAME_CHOICES = (
('B', 'BLACK'),
('W', 'WHITE'),
)
name = models.CharField(max_length=200, choices=NAME_CHOICES)
class Meta:
verbose_name_plural = 'Categories'
def __unicode__(self):
return self.get_name_display()
class Offer(models.Model):
category = models.ForeignKey(Category, verbose_name='Kategoria')
city = models.CharField(max_length=128, verbose_name='Miasto')
province = models.CharField(max_length=3)
district = models.CharField(max_length=128, verbose_name='Dzielnica')
def __unicode__(self):
return "Offer number %s" % (self.id)
First of all I must to tell, that django works only in sync way. So if you want to choose which input to use, you must send a request and wait a feedback. In my opinion there're no straight way to do this task correctly.
And I see a few solutions:
1) You can use jQuery for that. But the main problem is that django has a own admin system with a built-in widgets. You can try to customize it in two ways:
Take an app with this option (for example, django-admin-tools) and create custom behavior on your form;
manage.py collectstatic and after that going to admin folder and create custom jQuery script.
2) Build a custom admin form for your model with ModelChoiceField. I don't quit sure about this field behavior really help you, but you can investigate that.
If I need to do this task, I choose first way with admin static and custom jQuery.
I have built out a Django voting application. The models are pretty simple.
I have a category , an entry , and participant model
class Category(models.Model):
name = models.CharField(max_length=30)
slug = models.SlugField()
class Participant(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Entry(models.Model):
votes = models.IntegerField()
category = models.ForeignKey(Category)
participant = models.ForeignKey(Participant)
def __unicode__(self):
output = 'Entry For {0} in Category {1}'.format(self.participant, self.category)
return output
Pretty straightforward. You can add a category an entry and a participant using the default django admin models. This works really well.
Now the question:
In the admin, I want user to click a button and is presented with the listing of all winners for all the categories in the db. I have an idea on how to implement this, where I basically want a user to submit a form in the admin interface. I know the admin interface is implemented via the way all djanog apps are MVC style. But I don't know where I can extend because the adminBaseModel / adminModel acts like a models and view controllers, and url-confs at the same time. It's seems difficult to rewire alot of the internets there.
Can someone point me in the right direction? Just want to simply implement my own view that merely extends the admin view with my own context and method calls.
I hope that was clear. Thanks for all your help guys.
models:
class Detail(models.Model):
def __unicode__(self):
return self.title
title = models.CharField(max_length=32)
class Cars(models.Model):
def __unicode__(self):
return self.name
name = models.CharField(max_length=32, unique=True)
details = models.ManyToManyField(Detail)
So, every car has a many details - wheels, engine, etc. How to do this: in Django Admin situated Cars menu, in that menu we have a many lines of details (like in tutorial).
In admin I use:
class DetailInline(admin.TabularInline):
model = Detail
extra = 6
class CarsAdmin(admin.ModelAdmin):
inlines = [DetailInline]
But it has error: Detail has no ForeignKey to Cars. How to fix it?
Django does not natively let you add a reverse inline.
i.e. You can have the Detail page contain an inline admin of all the Cars that contain a ForeignKey to that particular Detail. However, the reverse is not natively possible.
There is a workaround though wherein you have to override the admin template a bit. There is a previous SO question about this here: Inline-like solution for Django Admin where Admin contains ForeignKey to other model