when i save the form in template.
The error says:
CustomUser matching query does not exist.
Line number 104: teacher=CustomUser.objects.get(id=teachers_id)
Model.py
class Subjects(models.Model):
id=models.AutoField(primary_key=True)
subject_name=models.CharField(max_length=255)
course_id=models.ForeignKey(Courses,on_delete=models.CASCADE,default=1)
teachers_id=models.ForeignKey(CustomUser,on_delete=models.CASCADE)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now_add=True)
objects=models.Manager()
views.py
def add_subject_save(request):
if request.method!="POST":
return HttpResponse("<h2>Method Not Allowed</h2>")
else:
subject_name=request.POST.get("subject_name")
course_id=request.POST.get("course")
course=Courses.objects.get(id=course_id)
teachers_id=request.POST.get("teacher")
teacher=CustomUser.objects.get(id=teachers_id)
try:
subject=Subjects(subject_name=subject_name,course_id=course,teachers_id=teacher)
subject.save()
messages.success(request,"Successfully Added Subject")
return HttpResponseRedirect("add_subject")
except:
messages.error(request,"Failed to Add Subject")
return HttpResponseRedirec("add_subject")
I dont know how to solve this error.
To my understanding, the Django ForeignKeys stores an object, not an integer like you would use in SQL. I think teacher=CustomUser.objects.get(id=teachers_id) is the bandit here. I would try teacher=CustomUser.objects.filter(teacher_id__exact=teacher_id).get(). This will give you an error however if there are more than one objects in the CustomUser model with the same teacher object. There is more information about this on the Django Docs.
Related
I have a simple Django ForeignKey relationship between two models in postgreSQL. The logic here is the Sample object can optionally have a foreign key into a type of sample control.
from django.contrib.postgres.fields import CICharField
from django.db import models
class Sample(models.Model):
controls_applied = models.ForeignKey(SampleControl, null=True,
blank=True,
on_delete=models.SET_NULL)
class SampleControl(models.Model):
id = CICharField(max_length=200, primary_key=True)
On the admin changelist for Sample, I am trying to create filter that queries all or none of Samples that have a specific control (in this case, we'll use a SampleControl with id='runcontrol'). I'm trying to craft the specific URI string to append to my changelist url as I have other filters I'm trying to run in conjunction.
To get all samples with controls_applied= 'runcontrol', I can simply append the following string to my URL (notice the reference to the id of the foreign key):
?controls_applied__id=runcontrol
But if I want to get all samples that are not run control, it's more complicated. Wasn't sure what to do, so I decided to use 'startswith', which has a convenient 'notstartswith' companion that will do the inverse. When I use this, I see that the following works:
?controls_applied__id__startswith=runcontrol
However, the inverse
?controls_applied__id__notstartswith=runcontrol
gives me an error: Unsupported lookup 'notstartswith' for CICharField or join on the field not permitted, perhaps you meant startswith or istartswith?
Which leads to me the simple question: is there a way to specify NOT EQUALS in the query string of the URL on Django's admin site? Thank you!
I don't think admin URLs are capable of representing an exclude queryset filter, unless you create your own SimpleListFilter.
Try this in your admin.py:
class WithoutControlListFilter(admin.SimpleListFilter):
title = ('Without Control')
parameter_name = 'without_control'
def lookups(self, request, model_admin):
return (
('runcontrol', ('Run Control')),
)
def queryset(self, request, queryset):
return queryset.exclude(controls_applied=self.value())
class SampleAdmin(admin.ModelAdmin):
list_filter = (WithoutControlListFilter,)
There is a bit of info about admin filters in the Django ModelAdmin docs.
I want to create a viewset/apiview with a path like this: list/<slug:entry>/ that once I provide the entry it will check if that entry exists in the database.
*Note: on list/ I have a path to a ViewSet. I wonder if I could change the id with the specific field that I want to check, so I could see if the entry exists or not, but I want to keep the id as it is, so
I tried:
class CheckCouponAPIView(APIView):
def get(self, request, format=None):
try:
Coupon.objects.get(coupon=self.kwargs.get('coupon'))
except Coupon.DoesNotExist:
return Response(data={'message': False})
else:
return Response(data={'message': True})
But I got an error: get() got an unexpected keyword argument 'coupon'.
Here's the path: path('check/<slug:coupon>/', CheckCouponAPIView.as_view()),
Is there any good practice that I could apply in my situation?
What about trying something like this,
class CheckCouponAPIView(viewsets.ModelViewSet):
# other fields
lookup_field = 'slug'
From the official DRF Doc,
lookup_field - The model field that should be used to for performing
object lookup of individual model instances. Defaults to pk
I asked a similar question today (Django: exclude User list from all Users ), the sollution was to write a symmetrical query. Since I changed my models with a many-to-many relation, this solution isn't valid anymore.
How can I exclude a list of users from user instances? With this method:
class Shift(models.Model):
shift_location = models.CharField(max_length=200)
users = models.ManyToManyField(User)
def get_shift_users(self):
return self.users.all()
def get_other_users(self):
return User.objects.all().exclude(self.users.all())
I get the error: AttributeError: 'User' object has no attribute 'split'
You need to use the in operator:
User.objects.exclude(id__in=self.users.all())
By using an unevaluated queryset (self.users.all()), it is transformed in a subquery, so the result will be fetched in a single query.
Maybe something like this:
User.objects.all().exclude(id__in=[u.id for u in self.users.all()])
I'm using this snippet from the documentation:
class ArticleAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
I've used the admin site and successfully created entries in the model, but now when I try to edit the entry, clicking submit generates a TypeError:
Database is trying to update a relational field of type CharField with a value of type User. Make sure you are setting the correct relations
I don't understand why it would throw this error now and not during the initial creation.
Is there a way around it?
ADDENDUM:
Reexamining the traceback for the error above, I also took at look at the local variables. It looks like there isn't any username information at all in the request variable, so I'm having my doubts that this works at all in the case of an update.
PS Since the traceback only shows a picture of the request object, the 'user' attribute is probably not displayed, but it could be there.
PPS: I found that the documentation on the user attribute explains that middleware must be activated, and when I check, I see that Heroku already added those settings for me. The attribute is indeed django.contrib.auth.models.User, whose username attribute is what I'm looking for.
It says that, whatever class obj belongs to, the user attribute of that class is not a foreign key to the User class that you are referring to, but just a CharField. Change the type of that attribute in the class that obj belongs to, migrate the database and then you will find this working.
If you just want it to be a string, not a foreign key relation, then use:
class ArticleAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.user = request.user.username
obj.save()
I'm thinking about this for a while now,
I'm creating a chat application, in chat.models a class Room is specified, however, a Room can be related to anything in my project, since it uses a generic relation in it's foreign key.
Is there a way to know which model that Room is related knowing only the models name?
Like:
ctype = 'user'
related_to_user = Room.objects.filter(content_type=ctype)
The problem I'm having is, the code below is in a view:
doc = get_object_or_404(Document, id=id)
# get *or create* a chat room attached to this document
room = Room.objects.get_or_create(doc)
If I don't want to use Document model, if I want a model associated to a string, a string that can be anything, without having to write tons of if's to get a specific Model for the specific string. Is there a way to find a model just by it's 'name'?
Thanks
http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#methods-on-contenttype-instances
user_type = ContentType.objects.get(app_label="auth", model="user")
user_type = ContentType.objects.get(model="user")
# but this can throw an error if you have 2 models with the same name.
Very similar to django's get_model
from django.db.models import get_model
user_model = get_model('auth', 'user')
To use your example exactly:
ctype = ContentType.objects.get(model='user')
related_to_user = Room.objects.filter(content_type=ctype)