I faced the error when I tried to capture the POST data from a form. Weird, because the same algorithm works with another django app model.
The models:
class Item(models.Model):
code = models.CharField(max_length=200, unique=True)
barcode = models.CharField(max_length=300)
desc = models.CharField('Description',max_length=500)
reg_date = models.DateField('registered date')
registrar = models.CharField(max_length=100)
def __unicode__(self):
return self.code + ' : ' + self.desc
class ItemInfo(models.Model):
model = models.ForeignKey(Item)
supplier = models.ForeignKey(Supplier)
stock_on_hand = models.IntegerField()
stock_on_order = models.IntegerField()
cost = models.IntegerField()
price = models.IntegerField()
unit = models.CharField(max_length=100)
lead_time = models.IntegerField()
def __unicode__(self):
return Item.code + ' : ' + supplier
class ItemForm(ModelForm):
class Meta:
model = Item
class ItemInfoForm(ModelForm):
class Meta:
model = ItemInfo
exclude = ('model')
And the views.py function for non-working (Item) is like this:
def register(request):
csrf_context = RequestContext(request)
current_user = User
if request.user.is_authenticated():
if request.POST:
item = Item()
item_info = ItemInfo()
header_form == ItemForm(data=request.POST,instance=item)
details_form == ItemInfoForm(data=request.POST, instance=item_info)
if header_form.is_valid():
header = header_form.save()
if details_form.is_valid():
details = details_form.save(commit=False)
details.supplier = header
details.save()
return HttpResponseRedirect('/item/')
else:
return render_to_response('error/denied_data_entry.html')
else:
header_form = ItemForm()
details_form = ItemInfoForm()
return render_to_response('item/register.html',{'header_form' : header_form, 'details_form' : details_form}, csrf_context)
else:
return render_to_response('error/requires_login.html', csrf_context)
The working views.py function for another working (Supplier) model is here:
def register(request):
csrf_context = RequestContext(request)
current_user = User
if request.user.is_authenticated():
if request.POST:
supplier = Supplier()
supplier_info = SupplierInfo()
header_form = SupplierForm(data=request.POST, instance=supplier)
details_form = SupplierInfoForm(data=request.POST, instance=supplier_info)
if header_form.is_valid():
header = header_form.save()
if details_form.is_valid():
details = details_form.save(commit=False)
details.model = header
details.save()
return HttpResponseRedirect('/supplier/')
else:
return render_to_response('error/denied_data_entry.html')
else:
return render_to_response('error/denied_data_entry.html')
else:
header_form = SupplierForm()
details_form = SupplierInfoForm()
return render_to_response('supplier/register.html', {'header_form' : header_form, 'details_form' : details_form}, csrf_context)
else:
return render_to_response('error/requires_login.html', csrf_context)
The traceback page shows that the POST did pass some variable. Help me please, I cant figure it out why it works on Supplier, but not Item.
P/S: Sorry for the indentation.
The problem is here:
# ...
header_form == ItemForm(data=request.POST,instance=item)
details_form == ItemInfoForm(data=request.POST, instance=item_info)
You're not assigning, you're comparing.
Related
Below is my models.py.
class Report(models.Model):
company_name = models.CharField(max_length = 40, default = "-")
favorite = models.ManyToManyField(settings.AUTH_USER_MODEL,
through='Fav', related_name='favorite_reports')
def __str__(self):
return self.company_name
class Fav(models.Model) :
report = models.ForeignKey(Report, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name='favs_users')
class Meta:
unique_together = ('report', 'user')
def __str__(self) :
return '%s likes %s'%(self.user.username, self.report.company_name[:10])
Below is views.py
def post(self, request, pk) :
t = Report.objects.get(id = pk)
fav = Fav(user=request.user, report=t)
try:
fav.save() # In case of duplicate key
print(request.user.favorite_reports) #home.Report.None
print('t =', t.favorite) # t = auth.User.None
print('fav =',fav.report, fav.user) # fav = untitle hello1
print('uesr =',request.user, request.user.favorite_reports,request.user.favs_users) #uesr = hello1 home.Report.None home.Fav.None
except IntegrityError as e:
pass
return redirect('home:homepage')
I want to show different button color to user whether user fav some report or not. So I checked request.user.favorite_reports and request.user.favs_users after I save Fav but it return home.Report.None home.Fav.None
But When I print fav.report, fav.user It returns well. Why this happened?
How can I check user Fav some report in template?
like {% if report.company_name in user.favorite_reports %} But It dosen't works.
You should call request.user.favorite_reports.all()
I'm currently working on a Django app that will parse the contents of an uploaded log file to the associated database in my Django project. I've managed to get it all running as expected except it won't associate my uploaded data with the model's ForeignKey. I can assign null=True which resolves the integrity error but then of course, it doesn't assign any of the uploaded data to that ForeignKey. Here's the code:
models.py
class Case(models.Model):
case_ref = models.CharField(max_length=8)
oic = models.CharField(max_length=50)
subject = models.CharField(max_length=100)
submitted_date = models.DateTimeField(default=datetime.now, blank=True)
def get_absolute_url(self):
return reverse('case_list', kwargs={'pk': self.pk})
def __str__(self):
return self.case_ref + " " + self.subject
class TeamviewerLogs(models.Model):
case = models.ForeignKey(Case, on_delete=models.DO_NOTHING)
teamviewer_id = models.IntegerField()
teamviewer_name = models.TextField()
connection_start = models.TextField()
connection_end = models.TextField()
local_user = models.TextField()
connection_type = models.TextField()
unique_id = models.TextField()
def get_absolute_url(self):
return reverse('case_list', kwargs={'pk': self.pk})
def __str__(self):
return str(self.teamviewer_id) + " - " + str(self.teamviewer_id)
forms.py
class UploadLog(forms.ModelForm):
file = forms.FileField()
class Meta:
model = TeamviewerLogs
fields = [
'file'
]
views.py
def add_logs(request, pk):
case = get_object_or_404(Case, pk=pk)
if request.method == 'POST':
form = UploadLog(request.POST, request.FILES)
if form.is_valid():
teamviewer = form.save(commit=False)
teamviewer.case = case
log_file = request.FILES['file']
log_file = filter(None, (line.rstrip() for line in log_file))
for lines in log_file:
split = lines.decode('utf-8').split('\t')
teamviewer_id = split[0]
teamviewer_name = split[1]
connection_start = split[2]
connection_end = split[3]
local_user = split[4]
connection_type = split[5]
unique_id = split[6]
teamviewer = TeamviewerLogs(teamviewer_id=teamviewer_id, teamviewer_name=teamviewer_name,
connection_start=connection_start, connection_end=connection_end,
local_user=local_user, connection_type=connection_type, unique_id=unique_id)
teamviewer.save()
return redirect('tv_log_details', pk=case.pk)
form.save()
else:
form = UploadLog()
return render(request, 'teamviewer/add_logs.html', {'form': form})
But when I click to upload the file I'm hit with:
When it tries to execute teamviewer.save().
I've been trying to resolve this issue for hours and have tried so many different variations of answers from Stackoverflow or previous code I've used that has worked for different models but I've hit a brick wall...hard!
Any help anyone can offer would be greatly appreciated.
Ok, so here's an example of the concept I've suggested in the comments.
I've got a view which passes some data to the a form;
class ListingDetailView(DetailView):
""" Listing detail page """
model = Listing
template_name = 'listing.html'
def get_form_kwargs(self):
"""Return the kwargs for the form"""
kwargs = {}
initial = {
'listing': self.object,
}
kwargs['initial'] = initial
return kwargs
def get_form(self):
form = ApplicationSignupForm(
**self.get_form_kwargs()
)
return form
def get_context_data(self, **kwargs):
""" Add our form to the context """
context = super().get_context_data(**kwargs)
context['form'] = self.get_form()
return context
The form then makes use of that initial data and sets the field it relates to as hidden. I don't validate this data, but I'll try to show how you might do that;
class ApplicationSignupForm(forms.ModelForm):
class Meta:
""" Setup the form """
fields = (
'listing',
...
)
model = Application
widgets = {
'listing': forms.HiddenInput()
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
initial_data = kwargs['initial']
self.listing = initial_data.get('listing')
def clean(self):
"""
Custom form cleaning
"""
cleaned_data = super().clean()
listing = cleaned_data.get('listing')
if listing != self.listing:
self.add_error('listing', "You can't modify this value")
return cleaned_data
I am trying to add customer and salon to their respective tables according to what option is selected by the user.I gave "Customer" and 'Salon owner" in dropdown menu.The name given in dropdown menu is "category". If a user select "Customer" from dropdown menu, registration form details should be added to customerlogin and customerreg tables.Similarly, in the case of "Salon owner".But unfortunately when any of these two option is selected,details were added to both customerlogin table and salonlogin table but not to other two tables.
Views.py
def register(request):
if request.method == 'POST':
ufname = request.POST.get('fname')
ulname = request.POST.get('lname')
uemail = request.POST.get('email')
upassword = request.POST.get('password')
umobile = request.POST.get('mobile')
ucategory = request.POST.get('category')
uaddress = request.POST.get('address')
if (salonreg.objects.filter(Email=uemail).exists() or customerreg.objects.filter(Email=uemail).exists()):
messages.info(request, "Email ID Already Taken")
return redirect('register')
elif (salonreg.objects.filter(Mobile=umobile).exists() or customerreg.objects.filter(Mobile=umobile).exists()):
messages.info(request, "Mobile Number Already Taken")
return redirect('register')
elif (ucategory=="Customer"):
cloginobj = customerlogin()
cloginobj.Username = uemail
cloginobj.Password = upassword
cloginobj.save()
cuserreg = customerreg()
cuserreg.Login_id_id = cloginobj
cuserreg.First_name = ufname
cuserreg.Last_name = ulname
cuserreg.Email = uemail
cuserreg.Password = upassword
cuserreg.Mobile = umobile
cuserreg.Address = uaddress
cuserreg.save()
cuserdetail = customerreg.objects.get(Email=uemail)
request.session["userid"] = cuserdetail.id
return render(request, "profile.html", {'userdetail': userdetail})
else:
sloginobj = salonlogin()
sloginobj.Username = uemail
sloginobj.Password = upassword
sloginobj.save()
ssalonreg = salonreg()
ssalonreg.Login_id = sloginobj.id
ssalonreg.First_name = ufname
ssalonreg.Last_name = ulname
ssalonreg.Email = uemail
ssalonreg.Password = upassword
ssalonreg.Mobile = umobile
ssalonreg.Address = uaddress
ssalonreg.save()
ssalondetail = salonreg.objects.get(Email=uemail)
request.session["salonid"] = ssalondetail.id
return render(request, "salon_owner.html", {'userdetail': userdetail})
else:
return render(request, "register.html")
models.py
from django.db import models
# Create your models here.
class salonlogin(models.Model):
Username=models.EmailField(max_length=50)
Password=models.CharField(max_length=20)
class salonreg(models.Model):
Login_id=models.ForeignKey(salonlogin,on_delete=models.CASCADE)
First_name=models.CharField(max_length=50)
Last_name=models.CharField(max_length=50)
Email=models.EmailField(max_length=50)
Password=models.CharField(max_length=20)
Mobile= models.CharField(max_length=20)
Address=models.CharField(max_length=250)
class customerlogin(models.Model):
Username=models.EmailField(max_length=50)
Password=models.CharField(max_length=20)
class customerreg(models.Model):
Login_id=models.ForeignKey(salonlogin,on_delete=models.CASCADE)
First_name=models.CharField(max_length=50)
Last_name=models.CharField(max_length=50)
Email=models.EmailField(max_length=50)
Password=models.CharField(max_length=20)
Mobile= models.CharField(max_length=20)
Address=models.CharField(max_length=250)
Can anyone suggest a best way to solve this issue.
Correct these two lines in views
ssalonreg.Login_id = sloginobj
cuserreg.Login_id = cloginobj
also correct the mistake in models.py
class customerreg(models.Model):
Login_id=models.ForeignKey(salonlogin,on_delete=models.CASCADE)
to
class customerreg(models.Model):
Login_id=models.ForeignKey(customerlogin,on_delete=models.CASCADE)
I keep receiving the above error and I am still not sure what component of my code is violating this. Below is my modely.py:
def get_image_path(instance, filename):
return os.path.join('photos', str(instance.id), filename)
# Create your models here.
class Textbook(models.Model):
founder = models.CharField(max_length=256)
title = models.CharField(max_length=256)
cover = models.ImageField(upload_to=get_image_path, blank=True, null=True)
def __str__(self):
return self.title
class Page(models.Model):
textbook = models.ForeignKey(Textbook,related_name="pages",blank=True, null=True)
page_title = models.CharField(max_length = 256,blank=True, null=True)
page_num = IntegerRangeField(min_value=0,max_value=256, blank=True, null=True)
def getTextID(self):
return self.textbook.id
def __str__(self):
return self.page_title
def iterSave(self):
pages = self.textbook.pages
MAX_PAGE = pages.aggregate(Max('page_num'))
try:
cpy = pages.get(page_num = self.page_num)
for page in pages:
if page.page_num >= self.page_num:
obj,created = Page.objects.update_or_create(page_title = page.page_title, page_num = page.page_num+1, textbook = page.textbook)
except:
if self.page_num > MAX_PAGE:
obj,created = Page.objects.update_or_create(page_title = self.page_title, page_num = self.page_num+1, textbook = self.textbook)
def save(self, *args,**kwargs):
self.iterSave()
super(Page,self).save(*args, **kwargs)
class Section(models.Model):
page = models.ForeignKey(Page,related_name="sections")
section_title = models.CharField(max_length=256)
text = RichTextField(config_name='awesome_ckeditor')
def __str__(self):
return self.section_title
I understand it has something to do with the query functions but I am not sure what I have done incorrectly to generate this error.
Here is my admin.py if it helps:
admin.site.register(Section)
admin.site.register(Textbook)
admin.site.register(Page)
and here is a helper function I have:
from django.db import models
class IntegerRangeField(models.IntegerField):
def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
self.min_value, self.max_value = min_value, max_value
models.IntegerField.__init__(self, verbose_name, name, **kwargs)
def formfield(self, **kwargs):
defaults = {'min_value': self.min_value, 'max_value':self.max_value}
defaults.update(kwargs)
return super(IntegerRangeField, self).formfield(**defaults)
and my views.py:
def index(request):
books = Textbook.objects.all()
ret = {}
for o in books:
ret[o.id] = o
ret['books'] = books
return render(request,'index.html', ret)
def genpage(request, bid = -1, pid = 1):
b = Textbook.objects.get(id = int(bid))
page = b.pages.get(page_num = int(pid))
sections = page.sections.all()
if b.pages.filter(page_num = page.page_num+1).exists():
next_page = page.page_num+1
else:
next_page = -1
if b.pages.filter(page_num = page.page_num-1).exists():
prev_page = page.page_num-1
else:
prev_page = -1
ret = {
'prev_page':prev_page,
'next_page':next_page,
'book':b,
'page_title': page.page_title,
'sections': sections,
}
I am pretty stumped by this because its an error I am so unfamiliar with. The error comes up in relation to calling super in the save function of page but other than that I do not know what to do.
It looks as if your ForeignKey used order_with_respect_to at one point, which adds an _order field to your model.
Now that you have removed order_with_respect_to, you need to remove the field from your database. Hopefully, creating a new migration and migrating will fix the problem.
I'm writing a chat app for a hypothetical social network but when I try to open the chat page I give the following error 'AnonymousUser' object has no attribute 'profile' error .
I think there may be problem in the models file but I can't really figure out how to fix it and I'm really confused now!? can anyone give any suggestions??
parts of the chat views.py
def index(request):
if request.method == 'POST':
print request.POST
request.user.profile.is_chat_user=True
logged_users = []
if request.user.username and request.user.profile.is_chat_user:
context = {'logged_users':logged_users}
cu = request.user.profile
cu.is_chat_user = True
cu.last_accessed = utcnow()
cu.save()
return render(request, 'djangoChat/index.html', context)
try:
eml = request.COOKIES[ 'email' ]
pwd = request.COOKIES[ 'password' ]
except KeyError:
d = {'server_message':"You are not logged in."}
query_str = urlencode(d)
return HttpResponseRedirect('/login/?'+query_str)
try:
client = Vertex.objects.get(email = eml)
context = {'logged_users':logged_users}
cu = request.user.profile
cu.is_chat_user = True
cu.last_accessed = utcnow()
cu.save()
if client.password != pwd:
raise LookupError()
except Vertex.DoesNotExist:
sleep(3)
d = {'server_message':"Wrong username or password."}
query_str = urlencode(d)
return HttpResponseRedirect('/login/?'+query_str)
return render_to_response('djangoChat/index.html',
{"USER_EMAIL":eml,request.user.profile.is_chat_user:True},
context_instance=RequestContext(request))
#csrf_exempt
def chat_api(request):
if request.method == 'POST':
d = json.loads(request.body)
msg = d.get('msg')
user = request.user.username
gravatar = request.user.profile.gravatar_url
m = Message(user=user,message=msg,gravatar=gravatar)
m.save()
res = {'id':m.id,'msg':m.message,'user':m.user,'time':m.time.strftime('%I:%M:%S %p').lstrip('0'),'gravatar':m.gravatar}
data = json.dumps(res)
return HttpResponse(data,content_type="application/json")
# get request
r = Message.objects.order_by('-time')[:70]
res = []
for msgs in reversed(r) :
res.append({'id':msgs.id,'user':msgs.user,'msg':msgs.message,'time':msgs.time.strftime('%I:%M:%S %p').lstrip('0'),'gravatar':msgs.gravatar})
data = json.dumps(res)
return HttpResponse(data,content_type="application/json")
def logged_chat_users(request):
u = Vertex.objects.filter(is_chat_user=True)
for j in u:
elapsed = utcnow() - j.last_accessed
if elapsed > datetime.timedelta(seconds=35):
j.is_chat_user = False
j.save()
uu = Vertex.objects.filter(is_chat_user=True)
d = []
for i in uu:
d.append({'username': i.username,'gravatar':i.gravatar_url,'id':i.userID})
data = json.dumps(d)
return HttpResponse(data,content_type="application/json")
and parts of my chat models:
class Message(models.Model):
user = models.CharField(max_length=200)
message = models.TextField(max_length=200)
time = models.DateTimeField(auto_now_add=True)
gravatar = models.CharField(max_length=300)
def __unicode__(self):
return self.user
def save(self):
if self.time == None:
self.time = datetime.now()
super(Message, self).save()
def generate_avatar(email):
a = "http://www.gravatar.com/avatar/"
a+=hashlib.md5(email.lower()).hexdigest()
a+='?d=identicon'
return a
def hash_username(username):
a = binascii.crc32(username)
return a
# the problem seems to be here ??!
User.profile = property(lambda u: Vertex.objects.get_or_create(user=u,defaults={'gravatar_url':generate_avatar(u.email),'username':u.username,'userID':hash_username(u.username)})[0])
and finally parts of the another app(ChatUsers):
class Vertex(models.Model,object):
user = models.OneToOneField(User)
password = models.CharField(max_length=50)
#user_id = models.CharField(max_length=100)
username = models.CharField(max_length=300)
userID =models.IntegerField()
Message = models.CharField(max_length=500)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
email = models.EmailField(max_length=75)
is_chat_user = models.BooleanField(default=False)
gravatar_url = models.CharField(max_length=300,null=True, blank=True)
last_accessed = models.DateTimeField(auto_now_add=True)
Because that user has not logged in yet. Django treat them as AnonymousUser and AnonymousUser does not have the profile property.
If the view is only for logged in user, you can add the login_required decorator to the view function to force the login process. Otherwise, you need to judge whether a user is anonymous with the is_authenticated function.
Reference: Using the Django authentication system