conflict with post save and __unicode__(self) in django models - python

Apologies for the strange title, but caught on a funny problem involving a conflict with post.save (from a form) and the unicode(self) return in my model.
Models.py
class NumericTraits(models.Model):
feature_id = models.IntegerField(primary_key=True)
species = models.ForeignKey('Species')
traits = models.CharField(max_length=30)
cite = models.ForeignKey(Citation)
username = models.CharField(max_length=30)
dt = models.CharField(max_length=30)
def __unicode__(self):
return self.species_id + self.traits + self.cite_id
class Meta:
db_table = 'numeric_traits'
verbose_name = "Numeric Traits"
verbose_name_plural = "Numeric Traits"
class Citation(models.Model):
cite_id = models.CharField(primary_key=True, max_length=25, default=citation_id_create)
citation_name = models.CharField(max_length=100)
citation = models.TextField()
def __unicode__(self):
return self.citation_name
class Meta:
managed = False
db_table = 'citation'
ordering = ['citation_name']
views.py
def dbPost(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
post = form.save( commit = False)
citeId = request.POST.get("citation", "")
post.cite_id = Citation.objects.get(cite_id = citeId)
post.save()
return render(request, 'app/SaveSuccess.html')
else:
form = PostForm()
In this case, I'm posting a value of (for example) 'citation1' - which refers to the primary key I"m using here. I use "self.citation_name" (which is "Ainley et al 1995) to display an intuitive name in the django admin.
however, when I go to save, this just gives me an error (e.g., cite_id = Ainley et al 1995 does not exist).
So, it's taking the value of self.citation_name and returning it, then attempting to find the cite_id that matches. However, I want it to return the cite_id value, locate the record, while maintaining the self.citation_name in my model so I can read the admin records easier.
Any help is greatly appreciated
Thanks

of course... always something simple.. I guess when I was trying to assign "post.cite_id", it was trying to assign it to the foreign key in a funny way.. Fixed this by changing.
post.cite_id = .....
to
post.cite = .....

Related

Django get error : id() takes exactly one argument (0 given) ,save with foreign key

So I have a problem about how to save model instance with foreign key relation,
models.py
class Connect(models.Model):
username = models.CharField(max_length=255)
password = models.CharField(max_length=255,null=True, blank=True)
conft = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return unicode(self.username)
class Ip(models.Model):
class Meta:
db_table = 'autonet_ip'
connect_id = models.ForeignKey(Connect, on_delete=models.CASCADE)
ipaddr = models.CharField(max_length=255)
def __str__ (self):
return self.ipaddr
forms.py
class NacmForm(ModelForm):
password = forms.CharField(widget=forms.PasswordInput,required = False)
class Meta:
model = Connect
fields = ['username', 'password','conft']
labels = {'conft':_('Config'),}
class IpForm(ModelForm):
class Meta:
model = Ip
fields = ['ipaddr']
labels = {'ipaddr':_('IP address'),}
IpFormset = formset_factory(IpForm, extra=1)
views.py
def konfig(request):
ip_list = []
status = ''
value_bak = 1
if request.method == 'POST':
formm = NacmForm(request.POST or None)
ipform = IpFormset(request.POST)
upform = UploadForm(request.POST,request.FILES)
userValue = formm['username'].value()
passValue = formm['password'].value()
confValue = formm['conft'].value()
usernamef = get_object_or_404(Connect, pk=id)
if ipform.is_valid():
for form in ipform:
ipaddr = form.cleaned_data.get('ipaddr')
//.... some code ...//
simpanIp = form.save(commit=False)
simpanIp.connect_id = usernamef
simpanIp.save()
simpanForm.save()
return HttpResponseRedirect('/konfig')
else:
formm = NacmForm()
ipform = IpFormset()
return render(request, 'konfig.html', {'form': formm, 'logins': Connect.objects.all(), 'ipform': ipform, 'status': status })
Then, when I input all data and click submit to collect form data and on simpanIp.save(), I've got an error: id() takes exactly one argument (0 given).
I just want to know how to save the instance of Connect model to database with foreign key, thanks in advance
so i edit my models.py like this
class Connect(models.Model):
......
def get_usernameinf(self):
return ', '.join(self.usernameinf.all().values_list('username', flat=True))
and views.py like this
if request.method == 'POST':
.....some code.....
if ipform.is_valid() and formm.is_valid():
simpanForm = formm.save()
for form in ipform:
simpanIp = form.save(commit=False)
...... some code ..
simpanIp.connect_id = simpanForm
simpanIp.save()
and its work, now the result is my "connect_id" got value from "Connect id"
id is a Python builtin that gives a unique ID for an object. I would guess that you did not intend to pass it get_object_or_404 on this line:
get_object_or_404(Connect, pk=id)
The calling convention for this functions seems to be that it is meant to be an integer for the primary key in a database table. Figure out where you should be getting your primary key from and set it correctly.
Pro-tip: avoid using names that are predefined by Python (see here for a full list). It can lead to headaches like the one you just had.

Django model foreignkey queries

So i have this two models in django:
class Course(models.Model):
def get_image_path(self, filename):
return os.path.join('courses', str(self.slug), filename)
def __str__(self):
return self.name
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Course, self).save(*args, **kwargs)
name = models.CharField(max_length=255, verbose_name="Nombre")
description = models.CharField(max_length=255, verbose_name="DescripciĆ³n")
price = models.DecimalField(max_digits=12,decimal_places=2, verbose_name="Precio")
slug = models.SlugField(blank=True, max_length=255)
icon_img = models.ImageField(upload_to=get_image_path, blank=True, null=True, verbose_name="Imagen")
background_color = ColorField(default="#026085")
class Meta:
verbose_name = "curso"
verbose_name_plural = "cursos"
class UserCourse(models.Model):
user = models.ForeignKey(User)
course = models.ForeignKey(Course)
So whenever a user "buys" a course, it is stored in UserCourse. I have a view where the system shows a list of all the courses the user has bought. This is the view code:
def user_course_list_view(request, username):
context_dict = {}
try:
user_courses = UserCourse.objects.filter(user=request.user).course_set
context_dict['courses'] = user_courses
context_dict['heading'] = "Mis cursos"
except:
context_dict['courses'] = None
context_dict['heading'] = "Mis cursos wey"
return render(request, 'courses/course_list.html', context=context_dict)
I dont know where is the error and I cant seem to catch the exception (im using django with docker)
tl;dr
Something like this should work.
usercourse_objects = UserCourse.objects.filter(user=request.user).select_related('course')
user_courses = [x.course for x in usercourse_objects]
Explanation
There are multiple ways to do this, but one way would be to first get all the UserCourse objects for the current user:
usercourse_objects = UserCourse.objects.filter(user=request.user)
Then, for each UserCourse object, get the related Course:
user_courses = [x.course for x in usercourse_objects]
Now, the second line causes N database queries (one for each time we follow the course foreign key relation. To prevent this, the first line can be changed to:
usercourse_objects = UserCourse.objects.filter(user=request.user).select_related('course')
This pre-populates the course attribute of the UserCourse objects. More info about select_related() can be found here.

Related Field got invalid lookup: icontains

I am trying to include a search field inside my home page. It works for some of the module field. My problem is when I use a ForeignKey field (correct me please if I am wrong).
models.py
class Location(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
my_location = models.CharField(max_length=120, choices=LOCATION_CHOICES)
update_date = models.DateField(auto_now=True, null=True)
def __str__(self):
return self.my_location
class UserProfile(models.Model):
user = models.ForeignKey(User)
# The additional attributes we wish to include.
user_base = models.CharField(max_length=120, choices=LOCATION_CHOICES)
user_position = models.CharField(max_length=120)
user_phone = models.PositiveIntegerField()
def __unicode__(self):
return self.user.username
views.py
def search_by_location(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
locations = Location.objects.filter(my_location__icontains=q).order_by('-update_date')
else:
locations = Location.objects.order_by('-update_date')
context = {'locations': locations}
return render(request, 'index.html', context)
My problem is if I use user inside the filter query instead of my_location I receive the error:
Related Field got invalid lookup: icontains
Please any advice on how to troubleshoot or any documentation I can read.
You can use icontains lookup on text fields. user is related (integer) field. Instead of user use user__username.
locations = Location.objects.filter(user__username__icontains=q)
class SearchView(ListView):
model = Profile
template_name = 'blog/search_results.html'
context_object_name = 'all_search_results'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user_name = self.request.GET.get('search', '')
context['all_search_results'] = Profile.objects.filter(user__username__icontains=user_name )
return context
here is another example on how to filter objects. if searching for a user, remember to user user_username__icontains=user_name
also remember that if you use Profile your'll get a different id than if you use User

Getting "may not be Null" error when submitting form, even though I am submitting data. DateTime field

Django newbie here.
I've got a form with a DateTimeField that cannot be empty, but am getting an error despite giving a time and date.
Error message:
IntegrityError at /app/new_action/
app_action.event_time may not be NULL
Sample input:
02/08/2014 15:00
models.py
class Action(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
location = models.CharField(max_length=200)
event_time = models.DateTimeField()
created_by = models.ForeignKey(UserProfile)
last_modified = models.DateTimeField('Last Modified')
def __unicode__(self):
return self.name
forms.py
class ActionForm(forms.ModelForm):
event_time = forms.DateTimeField(input_formats=['%m/%d/%Y %H:%M'])
class Meta:
model = Action
fields = ('name','description','location',)
views.py
#login_required
def new_action(request):
context = RequestContext(request)
if request.method == 'POST':
form = ActionForm(request.POST)
if form.is_valid():
form.save(commit=True)
#note = form.save(commit=True)
#note.created_by = profile.id
#note.save()
return index(request)
else:
print form.errors
else:
form = ActionForm()
Extra note: If possible I would like to keep this input format. For the sake of testing I set the field back to a DateTimeField, but if I can get this fixed I will go back to using this, which produces this input format.
As mentioned by Alvaro, try changing your forms.py to
class ActionForm(forms.ModelForm):
event_time = forms.DateTimeField(input_formats=['%m/%d/%Y %H:%M'])
class Meta:
model = Action
fields = ['name','description','location', 'event_time']

How can i save manytomany field in django?

models.py:
class Tag(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=500, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now_add=True)
class Post(models.Model):
user = models.ForeignKey(User)
tag = models.ManyToManyField(Tag)
title = models.CharField(max_length=100)
content = models.TextField()
created = models.DateTimeField(default=datetime.datetime.now)
modified = models.DateTimeField(default=datetime.datetime.now)
def __unicode__(self):
return '%s,%s' % (self.title,self.content)
class PostModelForm(forms.ModelForm):
class Meta:
model = Post
class PostModelFormNormalUser(forms.ModelForm):
class Meta:
model = Post
widgets = { 'tag' : TextInput() }
exclude = ('user', 'created', 'modified')
def __init__(self, *args, **kwargs):
super(PostModelFormNormalUser, self).__init__(*args, **kwargs)
self.fields['tag'].help_text = None
what i tried in views.py: (that doesn't look the correct way)
if request.method == 'POST':
form = PostModelFormNormalUser(request.POST)
print form
print form.errors
tagstring = form.data['tag']
splitedtag = tagstring.split()
if form.is_valid():
temp = form.save(commit=False)
temp.user_id = user.id
temp.save()
post = Post.objects.get(id=temp.id)
l = len(splitedtag)
for i in range(l):
obj = Tag(name=splitedtag[i])
obj.save()
post.tag.add(obj)
post = Post.objects.get(id=temp.id)
return HttpResponseRedirect('/viewpost/' + str(post.id))
else:
form = PostModelFormNormalUser()
context = {'form':form}
return render_to_response('addpost.html', context, context_instance=RequestContext(request))
Can anyone post example complete code editing this to save into Post table, Tag table and post_tag table?
The input form will contain a textbox to type 'title' and texarea for 'content' and a textbox to type 'tag' as string. The tag string is seperated by space. I need to save those tag words into Tag table and map in post_tag table.
How can i do this?
In the Django docs regarding ModelForms and save(commit=False), you'll find information regarding the save_m2m() method. I believe that is what you're looking for.
As an aside, if you're implimenting tagging, you could just use django-tagging or django-taggit
http://code.google.com/p/django-tagging/
http://django-taggit.readthedocs.org/en/latest/index.html
http://djangopackages.com/grids/g/tagging/

Categories

Resources