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.
Related
I'm adding an additional column repath to the Django.admin site, according to the document, it oughts to work, but once I introduced re package to this function, things went wrong.
here's code sample:
class InfoAddrAdmin(ModelAdmin):
list_display = ('id', 'machineId', 'uptime', 'repath')
list_filter = ('machineId',)
def repath(self, obj):
res = re.search(r"10\.1\d+\.\d+\.\d+", obj.ipaddr)
return res.group()<-Exception comes from here
and the related Model is defined as:
class RemoteAddress(models.Model):
id = models.AutoField(primary_key=True)
machineId = models.CharField(max_length=32)
uptime = models.DateTimeField(default=now)
ipaddr = models.TextField()
A piece of text with lots of IP addresses(i.e. the result of command ipconfig) is stored in the ipaddr field, and that regex searchs for an IP with prefix like '10.1xx.xxx.xxx', which proved working fine.
The main error is:
AttributeError: 'NoneType' object has no attribute 'group'
Using debuging tools, the res is not a None, Just the opposite, it contains the correct value, I'm confused why django believes it is None.
Complete Error stack is avaliable at https://pastebin.com/8WUBdg1F
You may find some information from https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
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.
I am quiet new to Django and I come from ASP.Net background.
I am trying to achieve OOP concept in one of the web application.
I have a model which maintains a movie list
url.py
from movies import views
url(r'^recent/$', views.recentlyadded)
models.py
from django.db import models
class MovieManager(models.Model):
def title_count(self, keyword):
return self.filter(title__icontains=keyword).count()
class Movie(models.Model):
movieid = models.AutoField(primary_key=True)
title = models.CharField(max_length=250)
objects = MovieManager()
I am trying to return the movie titles based on the keyword using custom manager MovieManager
views.py
from movies.models import Movie
def recentlyadded(request):
r = Movie.objects.title_count('night')
return HttpResponse("test")
This throws error AttributeError: 'Manager' object has no attribute 'title_count'
How to call models.py method in recentlyadded view.py function?
I want to use recentlyadded() method in multiple views/ functions in view.
The view code is correct, but not the model - MovieManager should inherit from models.Manager, not from models.Model. Not finding an explicitely declared Manager, the metaclass overwrite Movie.objects with a default manager.
FWIW you could have found out by yourself by inspecting Movie.objects in a Python shell (or by reading the source code for django.db.models.base.ModelBase).
To return the movie title. You probably would have this one the model.py file
Do it at the end if the model file
def __unicode__(self):
return self.title
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 performing a basic Django ModelForm create/validate/save operation. My custom clean methods are not being called when is_valid() is being called when running the code under the Eclipse debugger and I set a breakpoint after the form creation and the call to is_valid().
I have traced through the Django base code numerous times and it appears that the error dictionary on the ModelForm class is never set to None, which triggers the validation. I suspect that this is due to an interaction with the debugger accessing the _errors attribute of the ModelForm to display in the variables pane.
When I remove all breakpoints and let the code flow naturally, I can prove that the custom clean code is running by issuing print statements.
Is this a flaw in the Django ModelForm design, an Eclipse problem or am I barking up the wrong tree?
models.py:
from django.db import models
class TestModel1(models.Model):
field1 = models.CharField(max_length=45)
field2 = models.IntegerField(default=2)
field3 = models.CharField(max_length=45, null=True, blank=True)
forms.py:
from order.models import TestModel1
from django.forms import ModelForm
class OrderTestForm(ModelForm):
def clean_field1(self):
return self.cleaned_data['field1']
def clean_field2(self):
return self.cleaned_data['field2']
class Meta:
model = TestModel1
My test harness:
from forms import OrderTestForm
row = {'field1': 'test value', 'field2': '4', }
ff = OrderTestForm(row)
#ff.full_clean()
if ff.is_valid():
ff.save()
else:
print ff.errors
I have found the "answer" which is sort of a non-answer. The exact use case was receiving a CSV file from a customer. After inspection of the customer's actual data file, the data fields were padded with spaces -- many spaces. I trimmed the input and shoved that trimmed dictionary into the form and everything worked. Still does not explain why eclipse choked on this.
I had the same problem and tried to dig a little deeper and debug the framework.
There's probably a difference between regular forms and model forms which causes this not to work, but this hack (overriding is_valid() instead of clean(...)) worked for me:
def is_valid(self):
#run whatever ModelForm validations you need
return super(OrderTestForm, self).is_valid()
What if you try:
from order.models import TestModel1
from django.forms import ModelForm
class OrderTestForm(ModelForm):
class Meta:
model = TestModel1
def clean_field1(self):
value = self.cleaned_data['field1']
print value
return value
def clean_field2(self):
value = self.cleaned_data['field2']
print value
return value