Pretty new to Django. I am trying to switch the ForeignKey field student_information.project back to a null value. As well my student_remove object doesn't seem to be defining properly as 'Remove' should be an object.
Error Code
AttributeError at /project_list/projects/1/
type object 'Student_Information' has no attribute 'student_remove'
Request Method: GET
Request URL: http://127.0.0.1:8000/project_list/projects/1/?Remove=sathya
Django Version: 1.10.5
Exception Type: AttributeError
Exception Value:
type object 'Student_Information' has no attribute 'student_remove'
Exception Location: /media/rms/Sathya's Dr/mysite/projects/views.py in post_detail, line 27
Python Executable: /usr/bin/python
Python Version: 2.7.12
My views.py
def post_detail(request, pk):
post = get_object_or_404(Project, pk=pk)
students = Student_Information.objects.filter(project=post)
if request.GET.get('Remove'):
Remove = request.GET.get('Remove')
obj = Student_Information.objects.get(RCSID=Remove)
#obj.project = None
return render(request, 'projects/post_detail.html', {'post': post, 'students': students})
obj = Student_Information.objects.get(RCSID=Remove)
is throwing an, should specify that RCSID is a foreignkey, it seems like it's trying to find a primary key of 'sathya' where it should just get a string. How do I make it match the string? As if RCSID is automatically RCSID_id.
invalid literal for int() with base 10: 'sathya'
The error message is pretty clear. Student_Information model doesn't have any field named student_remove.
Apart from that, there are so many things wrong with your code.
In Django, you don't update the Model class. You update an instance of Model class. Records are saved as instances of Model class. So line Student_Information.student_remove.project = "---------", needs to be fixed.
student_information.project can be set to null by simply calling student_information.project = None. But here student_information is an instance of Student_Information model.
filter returns a Queryset, not an instance.
You need to call save on the Model instance to update it in the database.
I would recommend you to go through official polls app tutorial.
I made it work by passing id instead of RCSID so that they matched. Easy fix.
Related
I'm getting the user ID and I need this in INT format, but I only get with function return. How to convert from function to INT? I'm using Django 2.1.7 and python 3.7.
from django.contrib.auth import authenticate
from django.http import HttpRequest
request=HttpRequest
username='myuser'
password='mypass'
user = authenticate(username=username, password=password)
def user_id(request):
UID = request.user
return(UID)
UID=user_id
print(type(UID))
<class 'function'>
print(UID)
<function user_id at 0x106cd9158>
print(user.id)
19
views.py:
def get_userid(request):
if User.is_authenticated:
UID = request.user.id
return (UID)
if User.is_anonymous:
UID = 14
return (UID)
def opsearch(request):
item = request.POST['item']
dic = MLRun(item)
return render(request, 'main/layout/results.html', {'dictionary': dic})
my code which call template:
def to_DB(item, dic):
UID = get_userid
date_started = (timezone.now())
item_searched = item
Q = OPQuery(date_started=date_started,
item_searched=item_searched, id_user=UID)
Q.save()
QID = Q.id
QUID = OPQuery.objects.get(id=QID)
The error:
TypeError at /main/search/
int() argument must be a string, a bytes-like object or a number, not 'function'
Request Method: POST
Request URL: http://127.0.0.1:8000/main/search/
Django Version: 2.1.7
Exception Type: TypeError
Exception Value:
int() argument must be a string, a bytes-like object or a number, not 'function'
Exception Location: /usr/local/Cellar/python/3.7.2_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 1807
Python Executable: /Users/Documents/PycharmProjects/OP/bin/python
Python Version: 3.7.2
This code is really full of problems. Here are some of them.
In to_DB:
You don't actually call the get_userid function, you just reference it. This is the cause of your immediate error. In Python you always need to use () to call a function.
You don't pass the request argument to that function.
You don't return anything from that function.
Since you already created the OPQuery object, why do you then immediately query it back from the db? You already have it.
You don't use the dic parameter anywehere.
In get_userid:
is_authenticated needs to be called on the current user instance, not the user class. It should be request.user.is_authenticated.
Similarly for is_anonymous.
You don't need parentheses around return values.
This whole function is pointless, in any case.
Being as constructive as possible, you are struggling with basic Python concepts here. You really need to go back and do an introductory Python tutorial and then the Django tutorial.
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'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 have following model:
class comment(models.Model):
userid=models.CharField(max_length=140)
apparelid=models.IntegerField(blank=True)
desc=models.TextField(blank=True)
def __unicode__(self):
return self.userid
form :
class commentForm(ModelForm):
class Meta:
model=comment
exclude=('userid','apparelid',)
and view as follows:
def comment(request,title_id):
if request.method=='POST':
form=commentForm(request.POST)
if form.is_valid():
new=form.save(commit=False)
new.userid=request.user.username
new.apparelid=title_id
new.save()
return HttpResponseRedirect('/')
else:
form=commentForm()
template=loader.get_template('apple3/comment.html')
context=RequestContext(request,{
'form':form,
}
)
return HttpResponse(template.render(context))
whenever i open my page containg above form it show an error as follows:
Exception Type: AttributeError
Exception Value: 'function' object has no attribute 'objects'
You probably import comment model from inside your view and then use comment again as view name. That's why the error gets thrown.
Please use different name for your view and model if you use them in the same module.
Problem at hand seems to be solved by #mariodev. Additionaly, I'd recommend two following steps as a mean of avoiding similar problems in future:
Read PEP8, the Style Guide for Python Code thoroughly
Use only packages and modules import.
Following those two links will make your code more pythonic and less error-prone.
The name of the model class and the view function is same which is resulting in the error:
Exception Value: 'function' object has no attribute 'objects'
You may use a different naming conventions for your classes and functions. As per PEP8, first letter of the class name should be capital/uppercase and the function's name should be lowercase.
So in your case, if you have to keep the names exactly same, you may rename your Model Class to Comment and let your view function's name be comment and that should solve the problem.
I am trying to use django-datatrans to translate a MarkupField (from django-markitup) on a model. Both apps work correctly independently, but when I register datatrans to translate a MarkupField then I can't add objects in the admin anymore.
Relevant code:
from django.db import models
from markitup.fields import MarkupField
from datatrans.utils import register
class Work(models.Model):
title = models.CharField(max_length=500)
content = MarkupField(help_text=MARKDOWN_HELP)
class WorkTranslation(object):
fields = ('title', 'content')
register(Work, WorkTranslation)
When I try to add a new Work-object in the admin I get the following error:
'unicode' object has no attribute 'raw'
The error happens here, in the markitup-module (in the line rendered = render_func(value.raw):
.../lib/python2.7/site-packages/markitup/fields.py in pre_save
def pre_save(self, model_instance, add):
value = super(MarkupField, self).pre_save(model_instance, add)
rendered = render_func(value.raw)
setattr(model_instance, _rendered_field_name(self.attname), rendered)
return value.raw
Local vars when failing:
add: False
model_instance: <Work: This is the title>
value: u'This is the content.'
self: <markitup.fields.MarkupField: content>
I have tried to inspect the variable value when the Work class is not registered for translation. In that case (and then it does work correctly) it is not a unicode string but an instance of markitup.fields.Markup.
I have not been able to figure out why the type changes and I realize this question is pretty specific. But I hope someone has insights anyway..
Had the same issue with django-modeltranslation and django-markitup when testing it:
class ModelTests(TestCase):
def test_my_class(self):
self.assertRaises(IntegrityError, models.MyClass.objects.create)
It works for me with:
class ModelTests(TestCase):
def test_my_class(self):
with self.assertRaises(IntegrityError):
models.MyClass.objects.create(info='', info_de='')
Where my installed languages are en and de. My default language is en. info is my field with markitup and translation. (I'm testing here that a field is required on MyClass, therefore the IntegrityError.)
(Btw. this produces a slightly different error:
class ModelTests(TestCase):
def test_my_class(self):
self.assertRaises(IntegrityError, models.MyClass.objects.create(info=''))
Error:
AttributeError: 'NoneType' object has no attribute 'raw'
)
Maybe this helps someone.