how to retreive the body text alone of a webpage
hi I am writing an application to find out if the body text of a web page of given url has been modified-added or removed.Is there some way to find out the length of body text alone? I wrote a function that can read and return the data length.But is there some way I can read the body text alone ?The idea is to ignore length change due to tracking id etc that comes with the page and take into account only the body text. def get_page_data(url): f=urllib.urlopen(url) return len(f.read()) Any help appreciated thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: how to retreive the body text alone of a webpage
thanks guys, I tried this.. from BeautifulSoup import BeautifulSoup import urllib def get_page_body_text(url): h=urllib.urlopen(url) data=h.read() soup=BeautifulSoup(data) body_texts = soup.body(text=True) text = ''.join(body_texts) return text ... while True: #print 'size=%d'%len(get_page_body_text('http:// www.google.com')) print 'size=%d'%len(get_page_body_text('http:// sampleblogbyjim.blogspot.com/')) time.sleep(5) when google.com is the url ,the code gets the correct length of data.Then I tried a blog which I created for fun, This causes the code to crash with an error File "/usr/lib/python2.6/HTMLParser.py", line 115, in error raise HTMLParseError(message, self.getpos()) HTMLParser.HTMLParseError: bad end tag: u"", Any idea how this can be taken care of?The blog site must be creating bad html..How do you deal with such a problem? thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
cannot find django.core.management
hi In my django app I wanted to use some task scheduling .So ,i built and installed celery from celery-2.0.3.tar.gz.Then later I found a blog about django-celery and ghettoq at http://bitkickers.blogspot.com/2010/07/djangocelery-quickstart-or-how-i.html I installed those two through easy-install ,added apps to settings and ran syncdb. Then the blog mentions running celery daemon from command line >>sudo ./manage.py celeryd -v 2 -B -s celery -E -l INFO Here I am getting an Import Error File "./manage.py", line 2, in from django.core.management import execute_manager ImportError: No module named django.core.management I have Django1.2.1 in PYTHONPATH and when I try in python shell >>import django >>django.VERSION (1, 2, 1, 'final', 0) >>> from django.core.management import execute_manager >>> It works ok,and I can run python manage.py syncdb,python manage.py runserver ,they work without problems. I have set the settings in .bashrc DJANGO_SETTINGS_MODULE=mydjproject.settings export DJANGO_SETTINGS_MODULE Why am I getting this error when I try to start the celery daemon? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
unit test :how to call a single test method alone
hi In my application,I have the following structure for tests myapp---__init__.py | | tests- __init__.py #contains from functional import * from utility import * | | functional - __init__.py | -utility__init__.py #from myutil_tests import * | myutil_tests.py in myutil_tests.py ,I have import unittest class UtilTests(unittest.TestCase): def setUp(self): pass def test_some_testA(self): ... def test_some_testB(self): ... When I run python manage.py test myapp ,all the given tests are executed.I would like to know ,how I can call test_some_testA() alone. I tried python manage.py test myapp.utility.myutil_tests.UtilTests.test_some_testA but I am getting ValueError: Test label 'myapp.utility.myutil_tests.UtilTests.test_some_testA' should be of the form app.TestCase or app.TestCase.test_method Can someone help me correct this? thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
unittest fixture doesn't load from TestCase
hi I have a 'sample.json' that has some data I use for unittesting my app.I have put it in fixtures folder of myapp alongside 'initial_data.json'.In my TestCase subclass,I put it as, class MyTC(TestCase): fixtures=['sample.json'] def setUp(self): ... However,when I run the unittest ,only the data in 'initial_data.json' gets installed. I tried from the command line python manage.py loaddata sample.json and the data gets installed.But ,I need the unittest to install it in the testdb..,not manually in the main db. Can someone tell me why this is happening? thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
dictionary doesn't get properly updated
hi In my django view ,I am creating a Thread subclass and adding it to a ThreadManager TM to keep in a dictionary with name of thread as key and instance as value.I have implemented TM as a singleton and verified that only one instance of TM exists .However,when the view calls tm.add_mythread() ,I find that the dictionary inside is empty and the currently added instance becomes the only member. I hope the code will make this clear.Please tell me what I did that was wrong.I unit tested the TM using Dummy thread class and found that the add works correctly .It is only when the view calls tm.add that the above behaviour occurs The view is like this, def add_new_threadobj(request,page_title,template_name): if request.method=='POST' and form.is_valid(): tobj=MyThread(some_post_data..) tm=SingletonTM() print 'tm=',tm # to check if same instance tm.add_mythread(tobj) tobj.start() TM is a singleton class TM(MySingleton): def __init__(self): self.threads={} def add_thread(self,th): if th.name in self.threads.keys(): print 'already in' else: print 'TM::before::threads:',self.threads self.threads[th.name]=th print 'TM::',self,'add_thread()::added=%s'%th.name print 'TM::after::threads:',self.threads def remove_thread(tname): if tname in self.threads.keys(): del self.threads[tname] When the view add_new_threadobj() is executed a couple of times,this is the print output adding for the first time, tm= TM::before::threads: {} TM:: add_thread()::added=threadname1 TM::after::threads: {'threadname1':} adding another, tm= TM::before::threads: {} TM::after::threads: {'threadname2':} This is what I couldn't make out, the dictionary should now contain 2 kv pairs.Since the tm instance is the same,the self.threads should have printed the initially added thread's name and instance. Please tell me if I am missing something thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: dictionary doesn't get properly updated
hi this is what I wrote class MySingleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(MySingleton, cls).__new__(cls) return cls._instance I did unit test on this .. def setUp(self): self.tm=TM() def test_single_instance(self): #create two instances of TM, check if they are the same tm1=TM() self.assertTrue(self.tm is tm1) Also,printing the object instance shows same value (ie ) thanks for the reply jim On Oct 7, 8:23 pm, Daniel Roseman wrote: > On Oct 7, 3:20 pm, jimgardener wrote: > What is the MySingleton superclass? There's nothing in the code you've > posted that shows that TM is actually a singleton. > -- > DR. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: dictionary doesn't get properly updated
I am using the development server..will that cause such a problem? jim > Are you sure that everything is being run in the same process? If (for > example) you are using Apache as a front-end then, as I understand it, > there are no guarantees about that. > > regards > Steve > -- > DjangoCon US 2010 September 7-9http://djangocon.us/ -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: dictionary doesn't get properly updated
right..that is what was happening.. thanks for pointing it out.. regards jim On Oct 7, 11:41 pm, Doug wrote: > Could it be that garbage collection is deleting your "tm" instance > when it falls out of scope at the end of the view call? If that is > the only place you've instantiated it, I'm guessing the reference > count would go to zero 'singleton' or not. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
how to avoid error opening a url
hi In my application I am taking user given url strings.The user is likely to enter 'www.google.com' instead of 'http:// www.google.com' .When I try to open the url import urllib2 page=urllib2.urlopen(url) can give a ValueError if the user fails to enter 'http'.How can this problem be addressed?do I have to prepend 'http' to every urlstring before trying to open it using urlopen? thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
design problem..how to store web page's data for later comparison
hi I am trying to write an application that checks a web page today and again checks it after somedays and compares them.For this purpose I need to store the page data on these 2 occassions in my program . How can I do this?I can get the page data of current moment as a string using urllib.urlopen and store it in a variable, say current_page_data.But ,how do I store yesterday's data so that I can compare the two?Do I need to store it as a field in database?(I am not very familiar with database programming..I am using postgres for web app development with django.So I don't know if storing such a large string like that is possible). I considered writing the data to a file..but suppose a lot of users want to do the comparison of 2 versions of many pages..?I would be creating so many files =usercount * number_of_url_by_each_user .If the time duration between 2 comparisons was some seconds/minutes then I can just use 2 local variables andmay not need persistence.But ,to compare data of yesterday and today I may need some such mechanism.. I guess this may be a common problem and there may some solution for this. Can someone comment/suggest how this can be done? thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: design problem..how to store web page's data for later comparison
thank Jonathan..it was very helpful.. jim > Good luck, > Jonathan > -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
how to add login info while opening url
hi I was trying to get data from different web pages using urlopen and read. from urllib import urlopen def get_page_data(url): f=urlopen(url) return f.read() when I gave this url ,it produces a 'forbidden' response print get_page_data('http://groups.google.com/group/django-users/ topics') ==> ... Forbidden Your client does not have permission to get URL /group/django- users/topics from this server. ... I understand that it needs my login info..In a client program ,how do I add this?My django app maintains a list of urls entered by a user and at a user given time opens and reads from each of the urls.In the db I am storing the url string ,a user object and a datetime value entered by the user .Suppose one of those urls needs login info as in the above case,how can I store those?The same user may have different login username,passwords for different urls.I don't think storing user password in db is a good idea.. Is there a way to deal with this? Any suggestions? regards jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
file read/write location
hi I have a django project at /home/dev/python/django/myproject .In an app in this project I have some utility programs which has a file writing function. myproject/myapp/utilities/filewritingutility.py def write_to_file(filename,data): with open(filename,'w') as f: f.write(data) this function is called by another view function. myproject/myapp/views.py def record_inputdata(request,..): data=get_data_from_user() write_to_file('myfile.txt',data) When the record_inputdata() is executed, the file 'myfile.txt' is created in the myproject folder.Why is this?How does python determine the file location?Suppose I want to create the file in some other folder ,say myproject/myapp/data how should I make the changes to the code? I have the same doubt about reading the file also. In another function in the myapp/utilities/filereadutility.py ,when I call get_data_from_file(somefilename) ,python looks at the myproject folder for this file.How can I change this? thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: file read/write location
I was writing a lot of wep page content to the files for later comparison.So I thought ,writing to file was better than writing to db.. thanks jim > Also, if you dont mind me asking, why not just use the database for > recording and retrieving data, thats whats its there for. > > Rob :) -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
how to use tkinter widget in django
is it possible to use the sliderlike Scale widget from tkinter in django?I am coding a web app where I need to get a numerical value entered by the user.I thought ,instead of asking the user to enter a value in a textfield ,I would provide a slider which he can move between the minimum and maximum values. Originally I designed the model and form like this class MyModel(django.models.Model): user_enrty=models.IntegerField() class MyModelForm(django.forms.ModelForm): class Meta: model=MyModel In tkinter ,I can create a scale widget like master = Tk() w = Scale(master, from_=0, to=100) w.pack() and get the current position using w.get() How can I use this in django?Can I directly put the tkinter widget in my model like , class MyModel(django.models.Model): user_enrty=tkinter.Scale(...) Any help would be greatly appreciated thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: how to use tkinter widget in django
thanks for the replies.. I am wondering if javascript is the only alternative if I want to use such a custom widget. If anyone knows about any such python widget please tell me.. regards jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: how to use tkinter widget in django
hi thanks for the link. I tried this,In firefox3.6.11 ,it is rendered as a text field In chrome it shows a slider. ... select numerical value using slider: {{myform.user_entry.errors}} ... However,I am getting validation error upon processing the form I put the field as an IntegerField in my model .I am not sure if that is ok. class MyModel(django.models.Model): user_enrty=models.IntegerField() class MyModelForm(django.forms.ModelForm): class Meta: model=MyModel In the view ,I checked for validity of form ... form_data=get_form_data(request) form=MyModelForm(form_data) if request.method=='POST': print 'request.POST=',request.POST form_is_valid=form.is_valid() print 'form is valid:',form_is_valid if form_is_valid: newentry=form.save() print 'newentry=',newentry return redirect('home') else: print 'form is not valid' ... Chrome complains that the slider field is required .The request.POST is printed without the 'user_entry' key I tried the same with firefox(which rendered the slider as textbox) There also I get 'field is required error' Any idea how I can correct this? Why do the data in input type="range" not coming in the request.POST querydict? thanks jim On Oct 26, 7:11 pm, ringemup wrote: > Try the HTML5 . On some current browsers, it'll > just appear as a text field, although you can supplement it with > javascript. Moving forwards, as more browsers support HTML5 forms, > it'll appear as a slider widget. See [1]. > > [1]http://diveintohtml5.org/forms.html#type-range -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: how to use tkinter widget in django
thanks elijah..that worked how come id="id_user_entry" not enough? regards jim On Oct 26, 11:54 pm, elijah rutschman wrote: > > > min="0" > > max="1000" > > step="2" > > value="6" id="id_user_entry"/> > > Try adding a name="user_entry" attribute to the input. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
for loop logic in template
hi I have a model with 3 fields class Employee(models.Model): name=models.CharField(max_length=50) home_address=models.TextField(blank=True) change_filter=models.IntegerField() I am creating a modelform using this class as model. class EmployeeForm(ModelForm): class Meta: model=Employee In my template,I want to give the IntegerField some special treatment ..ie,I want to render it as input type="range" instead of a text field. I can do this like, ... Enter name: {{empform.name}} {{empform.name.errors}} Enter address: {{empform.home_address}} {{empform.home_address.errors}} select change filter value: {{empform.change_filter.errors}} Here ,I am using the same logic for the first two fields.. I want to render the change_filter using an input type="render".. so I thought I can take care of this using a for loop. {% for field in empform %} {% ifequal field.name "change_filter" %} select change filter value: {% else %} {{ field.label_tag }}: {{ field }} {% endifequal %} {%if field.errors %} {{field.errors}} {% endif %} {% endfor %} This gives the desired effect..But I am wondering if hardcoding the field's name in the ifequal tag is the correct way.Can I check the type of field instead?I am not sure how to do this.. Any advice would be nice.. thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
how to do object lookup using hour ,minute
hi I am a beginner with python and django and am writing my first application.I need to retrieve some objects of my model class created at different minutes in an hour.The class stores a datetime value in a 'creationtime' ( DateTimeField )and have an associated 'subject' string which can get repeated in many objects(ie object has one to many relation with subject).Only the 'creationtime' is unique for an object. How can I get a unique object using MyModel.objects. get()? When I checked the lookup docs ,it says it cannot do lookup on hour or minute ,but only on year,month,day.. Also I want to display the details of a single object.Do I need to create a unique slug? Is it possible to create a slug from DateTimeField 's value? (The prepopulated_fields in ModelAdmin doesn't accept DateTimeField and ForeignKey ..so I am not sure if I can use it in slug field). Also, how should I create the get_absolute_url for the class? If someone can give any pointers -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
problem with get_absolute_url
hi I am new to django..and was trying out the permalink method I have defined a get_absolute_url for my Entry class and used permalink. class MyEntry(models.Model): pub_time=models.DateTimeField(default=datetime.now) mycategory=models.ForeignKey() def __unicode__(self): return "%s%s"%(self.mycategory.name,self.pub_time) def get_absolute_url(self): return ('myapp_entry_detail',[self.id]) get_absolute_url=models.permalink(get_absolute_url) In my urls/entries.py I have given these url mappings (r'^(?P\d+)/$' ,'myapp.views.entry_detail','myapp_entry_detail'), (r'^$','myapp.views.entry_archive_index'), and in the archive template am using the get_absolute_url like {% for x in object_list %} {{x}} {% endfor %} where object_list is passed to the template in entry_index method def entry_archive_index(request): entryset=MyEntry.objects.all() entry_info={'object_list' : entryset} return render_to_response('myapp/myentry_archive.html',entry_info) Still when the archive page shows all the created entries,the link on them doesn't point to the entry detail url which should be like myapp/ 1/ where 1 is the id of created entry. (When I hardcode 'return "/myapp/%i/"% self.id ' in the get_absolute_url of the class ,it works.But I know that is not the correct way ) When I checked the source of archive page the url part looks like this MyCat2009-12-27 01:00:36 Can someone give me some pointer to correct this? thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: problem with get_absolute_url
Thanks Mike for the reply. I rewrote the method as @models.permalink def get_absolute_url(self): return("myapp_entry_detail",(),{'id':self.id}) When I go to the admin interface's edit page for an entry and click the viewsite button it causes the following error, NoReverseMatch,Reverse for 'myapp_entry_detail' with arguments '()' and keyword arguments '{'id': 6}' not found. When I try in browser http://127.0.0.1:8000/myapp/1/ causes ValueError,dictionary update sequence element #0 has length 1; 2 is required is this caused by the name 'myapp_entry_detail' in the urlpattern below? (r'^(?P\d+)/$','myapp.views.entry_detail','myapp_entry_detail'), The following is the entry_detail method which I defined def entry_detail(request,id): entry=MyEntry.objects.get(id=id) entry_detail_dict={'object':entry} return render_to_response('myapp/ myentry_detail.html',entry_detail_dict) I can't figure out why these errors are occuring..Everything works fine when I hardcode the url and omit the name 'myapp_entry_detail' in the urlpattern.If I don't omit that name in urlpattern ,the Request URL http://127.0.0.1:8000/myapp/1/ causes the ValueError which I mentioned earlier. Any help will be much appreciated thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
editing an entry ,how to call the form action
hi I created a view function to edit an entry. def edit_entry(request,id): entry=get_object_or_404(MyEntry,id=id) if request.method=='POST': form=MyEntryForm(request.POST,instance=entry) if form.is_valid(): form.save() redirect('myapp_entry_archive_index') else: form=MyEntryForm(instance=entry) #for GET method and invalid forms return render_to_response('myapp/myentry_edit_entry.html', {'entryform':form}) then I created the urls like url(r'^editentry/(?P\d+)/ $','myapp.views.edit_entry',name='myapp_edit_entry'), My problem here is how I should give the action in form in the template. I tried {{entryform.as_ul }} But since the /myapp/editentry/ doesn't match any urls ,it gives a 404. How should I pass the id of entry(which is to be edited) to action? I know this is a silly doubt..But I am a newbie to web programming..If anyone can help please do jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: editing an entry ,how to call the form action
thanks rebus -jim > > > {{entryform.as_ul }} > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
newbie doubt about editing an objects field
hi, I am new to this framework and was trying out some code..I created a MySubject model with name and description fields.I am using name as a unique field and description can be an empty string.I provided add and edit views as well as a ModelForm.I wanted to deal with the following usecases. In add_subject 1.If the user enters a name that already is in the database,I would like to warn the user that a subject of that name already exists. 2.if user mistakenly enters ' python' (with leading spaces )and a subject 'python' is in db,and tries to modify the description,then I would like to edit the original object 's description field. I am having some doubts as to how to code the view for the second usecase. def add_or_edit_subject(request,instance=None): ... if request.method=='POST': form=MySubjectForm(request.POST,instance=instance) if form.is_valid(): subname=form.cleaned_data['name'] if subject_is_new(subname.strip()): form.save() else: #HOW TO DO THIS? I need to update the description field def subject_is_new(name): sub=Subject.objects.filter(name__iexact =name.strip()) if len(sub)==0: return True else: return False class MySubject(models.Model): name=models.CharField(unique=True,max_length=50) description=models.TextField(blank=True) class MySubjectForm(ModelForm): class Meta: model=MySubject Can somebody please help with some pointers/suggestions. thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: newbie doubt about editing an objects field
On Feb 24, 9:55 pm, Timothy Kinney wrote: >Just add > the option *unique=True* when you define the field in the model and the > database will not allow two entries with the same value for that field. I have defined the name field to be unique in the model. name=models.CharField(unique=True,max_length=50) if I try to give ' python' as subject name and that would cause an IntegrityError if a subject already has name 'python'. I have defined the clean_name() method to do stripping of spaces as Shawn advised. Now,using subject_is_new(name) I am checking whether an object of that name exists and calls form.save() only if the check returns True. But my problem is the else branch as shown in my code.I am not sure how I can modify the description field of the existing subject (please see below) if form.is_valid(): subname=form.cleaned_data['name'] if subject_is_new(subname): form.save() else: #HOW TO DO THIS? I need to update the description field class SubjectForm: ... def clean_name(self): name=self.cleaned_data['name'] name=name.strip() return name -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: newbie doubt about editing an objects field
On Feb 24, 10:51 pm, Timothy Kinney wrote: > You can define a variable called error_message which is None when you pass > it into the template initially. Then you can fill it with the desired > message and do something like this: > {% if error_message %} > # display some information Well,actually,it is not an error..The user 'IS ALLOWED' to enter ' python' instead of 'python' and the program should proceed to EDIT the original 'python' object with the new description. to illustrate, First ,user adds a subject with name='python' and description='my python lesson' Now I have 1 subject in db. Then user adds another subject name=' python' with description='lesson by guido' Note the three space characters at the beginning of the name. Now ,this should cause the original record in db to be updated.No new record is created. Now db contains 1 subject with name='python' and description='lesson by guido' this is the functionality I am trying to achieve..(I have marked the else branch in the snippet) any help would be welcome jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
displaying validation errors
hello guys, I wanted to display validation errors in the form .I tried this class BookForm(ModelForm): class Meta: model=Book def clean_bookname(self): bkname=self.cleaned_data['bookname'] bkname=bkname.strip() if Book.objects.filter(bookname__iexact=bkname).count()!=0: self._errors.update({'duplicate book':'a book of this name already exists'}) raise ValidationError('duplicate book %s' % bkname) return bkname This causes validationerror to be raised when user tries to enter a duplicate book name in the CharField 'bookname' .But I wish to show an error message about the duplicate book name.How do I do this? I tried to pass the form to template and print {{form.errors}} but nothing is shown Can someone please help thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: how to check size of a dict or list in template
what exactly does object_status.0 mean? I got an error when I tried it in python shell jim On Mar 3, 1:10 pm, Alessandro Pasotti wrote: > 2010/3/3 harryos > > {%if not object_status.0 %} > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
how to add author to entry,newbie doubt about IntegrityError
hi, I am more or less a beginner with django and databases.I was trying to set the author field of an entry from the request.user instead of letting the user select from a drop down list of users.I designed the models like class Entry(models.Model): pub_date=models.DateField(default=date.today) description=models.TextField() author=models.ForeignKey(User) class EntryForm(ModelForm): class Meta: model=Entry exclude = ('author',) In views.py I created an add_entry function, def add_entry(request,template_name,page_title): form_data=get_form_data(request) form=EntryForm(form_data) if request.method=='POST' and form.is_valid() : newentry=form.save() some other ops... newentry.author=request.user newentry.save() However ,when I tried a testcase using def test_add_entry(self): self.client.login(username='me',password='mypass') self.post_data={ 'pub_date':'2010-03-08', 'description':'my new entry' } response=self.client.post(reverse('myapp_add_entry'),self.post_data) I get this IntegrityError, saying that 'null value in column "author_id" violates not-null constraint' The error occurs at the first occurrence of line newentry=form.save() in the add_entry()method Can someone help me figure out how to add the author value correctly? since I am using client.login() shouldn't the author field be taken from the logged in user thru request.user? thanks jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: how to start with django
grab the ebook written by James Bennet, one of the best ever written Subhransu Sekhar Mishra wrote: > hi,i am subhransu and new to django . i want to know how to start > django ?i have not done any project before. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
making query using filter()
Hi I need to make a query as follows Select all entries where categories=mycategory In the db there are entries and categories as follows Category.objects.all() -->[ ,,] MyEntry.objects.all() --> [ ,, ] I tried like this mycategory=Category.objects.get(name='mycategory') MyEntry.objects.filter(categories=mycategory) But this returns entries where the categories field contains 'mycategory' and 'hiscategory' also. How do I mention to retrieve only 'mycategory'. I went through the Queryset docs ..but couldn't figure it out... Any help would be appreciated thanks jim p.s: My models are class MyEntry(models.Model): categories=models.ManyToManyField(Category) class Category(models.Model): name=models.CharField(unique=True,max_length=50) -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.