Re: Custom Admin Form for ManyToMany, missing Green Plus Sign?
Maybe I didnt fully explain the issue, and it seems that Google added a couple of extra lines to the code above. Ive got an app with 2 Model classes. The first one describes a product (the Item model above). The second one (the Stuff model above), along with other data references the Product via a ManyToMany key. The basic default Admin settings, which work correctly, allow the addition of new Products via the Green Plus Sign and a Pop-up Window. Everything works fine. However when adding new Products, the Admin interface sorts the ManyToMany field by ID, instead of a much more intelligible Product Name. Lots of Products, too hard to find a particular one in the list. Thus I wrote up a Custom Admin Form to sort these Products in the ManyToMany field. This works great, the Products are sorted in ABC order. But, with this Custom Admin Form, the ability to Add another Product via the Little Green Plus Sign has been removed, the Plus Sign just isnt there, and therefore cannot spawn the Pop-up Window to add another Product to the Items model DB table. It seems that this should be an easy fix, but I cant find any docs that dont involve reinventing the wheel. Yes, the Items model data can be accessed through another part of the Admin interface, but I think the purpose of the Green Plus Sign was to alleviate this extra step. -- 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: AJAX Autocompletion Field
Hi Jon, I have used this very successfully: http://loopj.com/2009/04/25/jquery-plugin-tokenizing-autocomplete-text-entry/ The demo is here: http://loopj.com/tokeninput/demo.html One thing that differentiates it from the jquery autocomplete package is that it allows you to specify multiple selections, which was something I needed. It also comes with css that gives it a very nice look and feel. I had almost no jquery experience at the time I started with it and was able to get it to work very well. That said, there are a bunch of people that continue to ask for help or report problems, and the author doesn't really seem to respond, so it is not well supported and if you need enhancements, you have to dive in and understand the code. Margie On Feb 13, 2:46 pm, Jon Loeligerwrote: > Folks, > > For likely the umpteenth time, can someone recommend a good > AJAX auto completion tutorial or example that I might use > to crib-together a text-field selection that would otherwise > be a very large drop-down selection field? > > My use case would be essentially like having a table full > of say, recipie ingredients, and letting the user select > which one to add into a recipe. I'd like to have the user > simply start typing a few first characters and then let an > autocompleter search for matches and present them to the user. > The source of the matches would be a "Name" TextField in > some model. > > What is the current Best Practice or even Good Advice? :-) > Pros and cons for jQuery or extjs or something else? > A good "How To" or a pointer to a write up? > > Thanks, > jdl -- 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: Custom Admin Form for ManyToMany, missing Green Plus Sign?
On Feb 14, 9:30 am, johnwrote: > Hi, I just had fun creating a new Custom Admin Form to sort a > ManyToMany field by ABC order (why isnt it in ABC order by default on > the "def __unicode__" item?) It works great, but now the Green Plus > Sign to add more items to the list is missing, where did it go? I > guess its not enabled by default? > > Does anyone know where I can search on this more, and/or what this > Green Plus Sign is called? Is this just an extra command that needs > to be entered or do I have to reinvent the wheel to get this back to > working? > > thanks! > > This is the Green Plus Sign im looking for (even though this is for a > ForeignKey field):http://docs.djangoproject.com/en/dev/_images/admin10.png > > My code if you want to take a look (sorry that a lot of it has to be > redacted): > > # more xyz/admin.py > from abc.xyz.models import Items,Stuff > from django.contrib import admin > from django import forms > > class StuffForm(forms.ModelForm): > > item=forms.ModelMultipleChoiceField(queryset=Items.objects.order_by('item')) > > class Meta: > model=Stuff > > class StuffAdmin(admin.ModelAdmin): > exclude=('items',) > form=StuffForm > > admin.site.register(Stuff, StuffAdmin) > > # more xyz/models.py > class Items(models.Model): > item=models.CharField(max_length=100) > > def __unicode__(self): > return self.item > > class Stuff(models.Model): > items=models.ManyToManyField(Items) I found it rather hard to follow your code, but I think the problem might be that you haven't registered the object that is missing the 'green plus sign' with the admin. Without it, you cannot create new objects of that type. You can access existing objects from other models, however, which provides the behaviour you describe. Matt. -- 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.
Custom tag within template
Hi All - I'm a bit of a newbie with django, but I think I bit off more than I can chew. I'm trying to build a brick wall via html table, tds and colspans: 0. The "bricks" will lay out as follows | -- | 20 | 21 | 22 | - | | 16 | 17 | 18 | 19 | -- | | -- | 12 | 13 | 14 | 15 | | 8 | 9 | 10 | 11 | -- | | -- | 4 | 5| 6 | 7 | | 0 | 1 | 2 | 3 | -- | 1. I have a list of objects called storys from the database 2. I've generated a list of rows via range and reverse. ie. [5, 4, 3, 2, 1, 0] 3. I've generated a list of cols via range. ie. [0, 1, 2, 3] 4. I've registered a custom tag to calculate an offset into my story list given a row and col offset = row * BRICK_PER_ROW + col 5. I pass the rowlist, collist and storylist to my template Question: So, as I loop through rows and columns, how do I use my custom tag to find and index into my story list. I know I am describing the problem rather than showing you the code, but most everything I've tried returns a "Could not parse the remainder" error and most custom tag examples on the web feel like custom filter examples to me. I don't know how to pass the parameters (row and col) to my custom tag? {{ story.offset.attribute }} where "offset" is my custom tag? Trial and error and web searches aren't helping this time, so I place myself at the mercy of the court. Please go gentle with me. Django has been supercool so far, but this "no business logic rule" in my presentation layer has got me baffled. Thanks in advance for your support and counsel. Sincerely, Pete -- 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: Session errors with mod_wsgi
I've given up. There seems to be an issue with pickling some objects when you're using mod_wsgi - rather than using xlrd, I just attempted to add the uploaded file (small file held in memory) to the session data. The error log was essentially the same, but complaining about an attempt to pickle a CStringIO object or something instead... So instead, I'm writing the file to a known disk location and then loading it back again on the view page, instead of holding it in session memory. It's dirty and it isn't scalable, but it works for me :D Very strange how this all 'just works' when you use the built in dev server... David On Feb 14, 12:50 pm, DavidMckwrote: > Hmm: > > My relevant codes seems to be: > > @login_required > def upload(request): > if request.method == "POST": > form = ExcelUploadForm(request.POST, request.FILES) > if form.is_valid(): > request.session['sheet'] = form.cleaned_data["excelfile"] > > If I put something boring into the session (like a string, instead of > the form.cleaned_data item), the problem goes away. If I leave that > last line as it is, it comes back... > > David -- 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: InlineModelAdmin related items on two levels
Oh, and it is not flawless, there were still some issues I didn't get sorted out. I had some validation errors of some sort, I think, when updating data under certain circumstances, but I never quite completely tracked it down. -- 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: InlineModelAdmin related items on two levels
On Feb 14, 6:19 am, Ogi Vranesicwrote: > Hi all > > I read the very good tutorial > onhttp://docs.djangoproject.com/en/dev/ref/contrib/admin/ > and understood that the admin interface has the ability to edit models on the > same page as a parent model and these are called inlines. For two related > models is this easy: > > class A (models.Model): > name =... > > class B(models.Model): > a = models.ForeignKey(A) > title = ... > > in admin.py: > > class B(admin.TabularInline): > model = B > > class AAdmin(admin.ModelAdmin): > inlines = [ > B, > ] > > and the result ist, that in add/change of A we can also add/change its child > models B > > My Problem is that I however by B model have also child models: > class C > b = models.ForeignKey(B) > name = ... > > My Question is : > Is it possible than one can add/edit models of A on the one page together with > child models B and C as child models of B. > > Any hint or idee would be very appreciated Sounds like you want nested inlines. There is no built-in way to do this with django. I did some work (and got a solution working), but it required significant change to the installed django. I was planning on trying to make it into an installable app, but didn't get far. I do have a diff: I've just put it at http://pastie.org/823968 - this is with a fairly old trunk though, so it may not merge back in that well right now. It was based on another nested-inline diff I had come across, but I don't seem to have the link any more. Matt. -- 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: Session errors with mod_wsgi
Hmm: My relevant codes seems to be: @login_required def upload(request): if request.method == "POST": form = ExcelUploadForm(request.POST, request.FILES) if form.is_valid(): request.session['sheet'] = form.cleaned_data["excelfile"] If I put something boring into the session (like a string, instead of the form.cleaned_data item), the problem goes away. If I leave that last line as it is, it comes back... David -- 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.
Session errors with mod_wsgi
Alo! Written an app, works fine on dev server, gives a 500 Internal Server Error with apache + mod_wsgi. It's a form to upload an excel file - the file is uploaded, verified (using xlrd) and then one of the excel sheets is saved as session data. Redirect to a "view" page which retrieves the sheet from session and displays the data. I can't even figure out which bit is causing the crash - relevant log file is this: -- mod_wsgi (pid=1788): Exception occurred processing WSGI script 'C:/ Users/David/webpages/kb_roster/apache/django.wsgi'., referer: http://rosters.davidmck.com/admin/upload/ -- Traceback (most recent call last):, referer: http://rosters.davidmck.com/admin/upload/ -- File "C:\\django\\django\\core\\handlers\\wsgi.py", line 245, in __call__, referer: http://rosters.davidmck.com/admin/upload/ -- response = middleware_method(request, response), referer: http://rosters.davidmck.com/admin/upload/ -- File "C:\\django\\django\\contrib\\sessions\\middleware.py", line 36, in process_response, referer: http://rosters.davidmck.com/admin/upload/ -- request.session.save(), referer: http://rosters.davidmck.com/admin/upload/ -- File "C:\\django\\django\\contrib\\sessions\\backends\\db.py", line 58, in save, referer: http://rosters.davidmck.com/admin/upload/ --session_data = self.encode(self._get_session(no_load=must_create)),, referer: http://rosters.davidmck.com/admin/upload/ -- File "C:\\django\\django\\contrib\\sessions\\backends\\base.py", line 88, in encode, referer: http://rosters.davidmck.com/admin/upload/ --pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL), referer: http://rosters.davidmck.com/admin/upload/ -- PicklingError: Can't pickle : attribute lookup mod_wsgi.Log failed, referer: http://rosters.davidmck.com/admin/upload/ It's frustrating that it works in dev mode, so I'm really struggling to work out where to start looking to track this down. Everything else seems A-OK (including session access (in a different view) ). David -- 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: Django Generator
Brice: Very nice start. There is a long history of similar tools and they all have a place and a purpose. I remember fondly of some tool that generated CRUD dbase apps from a db schema .. that was last century ... So carry on! Just a few notes: - the generator page takes quite a bit of vertcal real estate: a more compact display may be better? - if the goal is to provide a tool for non-developers, you may be expose a bit too much of django internals: for instance such a user may not care for the field types, know what a model is, etc. Yet if it is for hand-holding django newbies you introduce many concepts that a newbie may not know about yet. So my 2 cents would be to pick a target user and focus on one or the other. As I see it today, only a django user would be able to make sense of it. - the license you picked seems to me a bit odd for software http://github.com/debrice/djangogenerator/blob/master/LICENSE , you may want to consider something more common: the same as django is usually the simplest and best. - some pointers on some similar tools may give you some more ideas, google web site generator there are many similar tools for RAILS, PHP, JSP, ASP, etc Bon courage! Philippe -- 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.
Custom Admin Form for ManyToMany, missing Green Plus Sign?
Hi, I just had fun creating a new Custom Admin Form to sort a ManyToMany field by ABC order (why isnt it in ABC order by default on the "def __unicode__" item?) It works great, but now the Green Plus Sign to add more items to the list is missing, where did it go? I guess its not enabled by default? Does anyone know where I can search on this more, and/or what this Green Plus Sign is called? Is this just an extra command that needs to be entered or do I have to reinvent the wheel to get this back to working? thanks! This is the Green Plus Sign im looking for (even though this is for a ForeignKey field): http://docs.djangoproject.com/en/dev/_images/admin10.png My code if you want to take a look (sorry that a lot of it has to be redacted): # more xyz/admin.py from abc.xyz.models import Items,Stuff from django.contrib import admin from django import forms class StuffForm(forms.ModelForm): item=forms.ModelMultipleChoiceField(queryset=Items.objects.order_by('item')) class Meta: model=Stuff class StuffAdmin(admin.ModelAdmin): exclude=('items',) form=StuffForm admin.site.register(Stuff, StuffAdmin) # more xyz/models.py class Items(models.Model): item=models.CharField(max_length=100) def __unicode__(self): return self.item class Stuff(models.Model): items=models.ManyToManyField(Items) -- 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: dynamic variable in templates
On Feb 13, 7:20 pm, Madiswrote: > http://push.cx/2007/django-template-tag-for-dictionary-access > > This is basically what I'm looking for but I'm not sure that this is > the best way to do this. Yes, this is the right way to do it. -- 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: AJAX Autocompletion Field
I don't know of any cons regarding jQuery, unless the others who you work with or communicate with all use something else. Here's a fully-working example (from which you can easily create yours). It's not exactly a tutorial, but it should be all you need. http://docs.jquery.com/Plugins/Autocomplete If you're looking for best-practices for integrating it with Django, then maybe someone can chime in. For speed it's obviously a good idea to have the data on the page if you can, although that can lead to large pages. Add Django's gzip middleware to help with that. I like using views that return JSON and just have the JavaScript work with that, but I'm doing things a little less "visual" than auto-complete. Shawn -- 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: Returning array of integers as part of json dump, how to access in Javascript
Unfortunately your question is not clear, and this "clarification" does not really help matters. As far as I can tell, obj.PythonList is already an array. If you do: jArray = [obj.PythonList] then yes, jArray[0] is indeed the whole contents of obj.PythonList. But I don't understand why you want to do this - why not just obj.PythonList[0] which should be 3? -- DR. On Feb 13, 7:04 pm, robinnewrote: > I put in wrong variable name: > > > var PIDS = obj.PackageIDS; //this brings back 3,2 for example, an > > array of integers. > > should be... > > var PIDS = obj.PythonList; > > On Feb 13, 10:10 am, robinne wrote: > > > > > I am trying to pass an array of integers from a view to javascript in > > an ajax call. > > > I know how to return json dump from a View so that javascript can > > access it as an object like this: > > > VIEW > > response_dict = {"PythonList": MyList, "EditType": edittype} > > return HttpResponse(simplejson.dumps(response_dict), mimetype='text/ > > javascript') > > > where MyList is a... python list created by: > > MyList = [] > > for p in packages: > > MyList.append(p.id) > > > in javascript, I can access the json by: > > var obj = YAHOO.lang.JSON.parse(o.responseText); > > var PIDS = obj.PackageIDS; //this brings back 3,2 for example, an > > array of integers. > > > I cannot get at PIDS as an array in javascript. When I try to convert > > to an array, the first item in the array is always all values (3,2) > > instead of just the first one (3). The most simplistic attempt at this > > was: > > > var jArray = [obj.PythonList] > > > Any suggestions? -- 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: AJAX Autocompletion Field
There probably isnt a good whole tutorial. Which looks at the operation from client side to server side... You should read about writing your own autocomplete field in JS. And for server side look at writing a view which returns a JSON or list of options which corresponds with the JS / JS framework you are using. I dont think there is a best practice, basically all autocomplete forms are a hack made to look like a menu appearing under a form field. Below is an example using prototype/ scriptalicious client side. Read: http://wiki.github.com/madrobby/scriptaculous/ajax-autocompleter Django Forms Component: class MyForm(forms.Form): myAutocompleteField = forms.CharFIeld(max_length=80, required=True, widget=forms.TextInput(attrs={'autocomplete':"off", "onkeyup":"nameOfJavascriptMethod('arg1', 'arg2', this.value);", 'size':'35'})) Template Part of a form template: Turning on Javascript will help you complete this field by providing suggestions! {{form.myAutocompleteField}} {{form.myAutocompleteField.errors}} Javascript: function postcodeLocationEvent(txtfieldid, resultsdivid, value) { new_url = '/findmyautocompletestr/'; new Ajax.Autocompleter(txtfieldid, resultsdivid, new_url, { method: 'post', paramName: 'locationinput', minChars: 3, parameters: {'locationinput':value}, indicator: 'indicator1' }); } View: def getLocationViaSuburbOrPostcode(request): #basically whatever you model is storing, some access query probably using startswith or contains loc_af = postcodeorsuburbfind(request) # would be Model.objects.filter(somefield__istartswith=.POST['someParameter']).values('') places = [] places.append('') if loc_af is None: return HttpResponse(status=500) if len(loc_af) is 0: return HttpResponse(status=500) for l in loc_af: if l.has_key('airfield_name'): if l.has_key('ycode'): #in this example just formatting html to be compliant with the scriptalicious API for autocompleter places.append('%s,%s,%s,%s'%(l['airfield_postcode'],l['airfield_name'],l['ycode'],l['state__state_abbrev'])) else: places.append('%s,%s,ALA,%s'%(l['airfield_postcode'],l['airfield_name'],l['state__state_abbrev'])) else: places.append('%s,%s,%s'%(l['postcode'],l['suburb'],l['state__state_abbrev'])) places.append('') return HttpResponse(places) Thats absically it. You can choose to write your own JS for the autocompleter, its a lot of work, i wrote my own but current project is using prototype+scriptalicious so i dont bother using it. cheers -sam On Sun, Feb 14, 2010 at 9:46 AM, Jon Loeligerwrote: > Folks, > > For likely the umpteenth time, can someone recommend a good > AJAX auto completion tutorial or example that I might use > to crib-together a text-field selection that would otherwise > be a very large drop-down selection field? > > My use case would be essentially like having a table full > of say, recipie ingredients, and letting the user select > which one to add into a recipe. I'd like to have the user > simply start typing a few first characters and then let an > autocompleter search for matches and present them to the user. > The source of the matches would be a "Name" TextField in > some model. > > What is the current Best Practice or even Good Advice? :-) > Pros and cons for jQuery or extjs or something else? > A good "How To" or a pointer to a write up? > > Thanks, > jdl > > -- > 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. > > -- 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.
AJAX Autocompletion Field
Folks, For likely the umpteenth time, can someone recommend a good AJAX auto completion tutorial or example that I might use to crib-together a text-field selection that would otherwise be a very large drop-down selection field? My use case would be essentially like having a table full of say, recipie ingredients, and letting the user select which one to add into a recipe. I'd like to have the user simply start typing a few first characters and then let an autocompleter search for matches and present them to the user. The source of the matches would be a "Name" TextField in some model. What is the current Best Practice or even Good Advice? :-) Pros and cons for jQuery or extjs or something else? A good "How To" or a pointer to a write up? Thanks, jdl -- 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.
nested lists
Could someone please explain what kind of a list would make this work: {% for country in countries %} {% for city in country.city_list %} Country #{{ forloop.parentloop.counter }} City #{{ forloop.counter }} {{ city }} {% endfor %} {% endfor %} Example is taken from is taken from http://www.djangobook.com/en/1.0/chapter04/ -- 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: Getting uploaded images to show
If your images are uploaded_to='media' I do in my settings.py STATIC_DOC_ROOT = os.path.join(ROOT,'media') ADMIN_MEDIA_PREFIX = '/media/admin/' MEDIA_ROOT = STATIC_DOC_ROOT MEDIA_URL = '/media/' And my urls.py includes this: urlpatterns = patterns('', . . . (r'^admin/media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DOC_ROOT}), (r'^admin/', include(admin.site.urls)), ) I hope that kind of helps. Currently I use django-picasa ( http://code.google.com/p/django-googledata/ ) to store my uploaded images and show them. It will even show you an thumbnail in your admin view ! Thanos On Feb 13, 5:14 am, holgerwrote: > I am new to django and I am trying to get an image upload to work. > > I am using the admin interface with a ImageField in the model. > > imagefilename = models.ImageField(upload_to = 'uploads/') > > My media url is > MEDIA_URL = 'http://127.0.0.1:8000/media/' > > and my media_root is > MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media') > > where project_root points to the root folder for the project > > So I want the images to be uploaded tohttp://127.0.0.1:8000/media/uploads/ > > I can see the images being uploaded to the directory but I can´t > access the file through the url in the template. > > What am I missing? -- 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: INSERT INTO "db_model" ("id") VALUES (DEFAULT)
Hi Karen, I just hoped it would sound like something familiar, to give me a clou for the direction to search. Obviously it isn't. I'll make a scale down of the problem and try to make the question more specific. Regards, Petr van Blokland On Feb 13, 2010, at 7:42 PM, Karen Tracey wrote: > In the future please click the "Switch to copy-and-paste view" and post just > the contents of the resulting text box. > > You started out by saying you had defined a Django model named Element with a > couple of fields (CharField name, IntegerField elementtype) and that you got > this error when you tried to save() an Element after filling in the fields > (you didn't say where?). > > I don't see anything like any of that in the traceback you've posted. Instead > you've got: > > Environment: > > Request Method: GET > Request URL: http://127.0.0.1:8080/hello/html/app-composer > Django Version: 1.1.1 > Python Version: 2.5.4 > Installed Applications: > [] > Installed Middleware: > ('django.middleware.common.CommonMiddleware', > 'django.contrib.sessions.middleware.SessionMiddleware', > 'django.contrib.auth.middleware.AuthenticationMiddleware') > > > Traceback: > File "/Library/Python/2.5/site-packages/django/core/handlers/base.py" in > get_response > 92. response = callback(request, *callback_args, > **callback_kwargs) > File "/developr/django/mysite/../mysite/hello/views.py" in hello_html > 12. MyApp(request, result, params).build() > File "/developr/xierpad/builders/sitebuilder.py" in build > 1672. self.setup() > File "/developr/xierpad/builders/sitebuilder.py" in setup > 199. self.installSession() > File "/developr/xierpad/builders/sitebuilder.py" in installSession > 311. self.session.save() > File "/Library/Python/2.5/site-packages/django/db/models/base.py" in save > 410. self.save_base(force_insert=force_insert, > force_update=force_update) > File "/Library/Python/2.5/site-packages/django/db/models/base.py" in save_base > 452. self.save_base(cls=parent, origin=org) > File "/Library/Python/2.5/site-packages/django/db/models/base.py" in save_base > 498. result = manager._insert([(meta.pk, > connection.ops.pk_default_value())], return_id=update_pk, raw_values=True) > File "/Library/Python/2.5/site-packages/django/db/models/manager.py" in > _insert > 177. return insert_query(self.model, values, **kwargs) > File "/Library/Python/2.5/site-packages/django/db/models/query.py" in > insert_query > 1087. return query.execute_sql(return_id) > File "/Library/Python/2.5/site-packages/django/db/models/sql/subqueries.py" > in execute_sql > 320. cursor = super(InsertQuery, self).execute_sql(None) > File "/Library/Python/2.5/site-packages/django/db/models/sql/query.py" in > execute_sql > 2369. cursor.execute(sql, params) > > Exception Type: ProgrammingError at /hello/html/app-composer > Exception Value: relation "db_model" does not exist > LINE 1: INSERT INTO "db_model" ("id") VALUES (DEFAULT) >^ > That shows (I assume) your view code (hello_html in mysite/hello/views.py) > calling: > > MyApp(request, result, params).build() > > What is MyApp? The execution path is proceeding into code in > /developr/xierpad/builders/sitebuilder.py. What is that? These things are > bearing no resemblance to what you initially said you were doing. > > One very odd thing in your configuration is you appear to have nothing listed > in INSTALLED_APPS. Why? > > Please start at the beginning describing what you are doing, what, if any, > add-on packages you are using, etc. If you have not done it already, you may > want to start by working through the Django tutorial. > > Karen > > -- > 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. > --- Petr van Blokland b...@petr.com | petr.com | twitter.com/petrvanblokland --- __ This email has been scanned by the McAfee® Email Security System. For more information please visit http://www.mcafee.com __ -- 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: dynamic variable in templates
http://push.cx/2007/django-template-tag-for-dictionary-access This is basically what I'm looking for but I'm not sure that this is the best way to do this. On Feb 13, 8:55 pm, Madiswrote: > Sorry for not explaining it more: > > chain is a dictionary of lists chains {'project1': ['item1', 'item2'], > 'project2': ['item3']} > So the key to the dictionary is basically a project name which I get > when looping over the projects in the first loop. Now the second loop > should be over the list of chains but the dictionary key is changing > because the name of the project is changing but I can not find a way > to do this in Django templates. > > On Feb 13, 8:47 pm, Karen Tracey wrote: > > > > > On Sat, Feb 13, 2010 at 1:30 PM, Madis wrote: > > > I'm trying to write the following but there seems to be no solution on > > > the web for this. > > > > In a template: > > > {% for project in projects %} > > > {% for chain in chains.project.name %} <--- project.name should be > > > dynamic > > > {% endfor %} > > > {% endfor %} > > > What is chains? What is chains.project? What do you mean project.name should > > be dynamic? How does whatever happens when you try to render that template > > differ from what you are expecting? > > > Karen -- 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.
InlineModelAdmin related items on two levels
Hi all I read the very good tutorial on http://docs.djangoproject.com/en/dev/ref/contrib/admin/ and understood that the admin interface has the ability to edit models on the same page as a parent model and these are called inlines. For two related models is this easy: class A (models.Model): name =... class B(models.Model): a = models.ForeignKey(A) title = ... in admin.py: class B(admin.TabularInline): model = B class AAdmin(admin.ModelAdmin): inlines = [ B, ] and the result ist, that in add/change of A we can also add/change its child models B My Problem is that I however by B model have also child models: class C b = models.ForeignKey(B) name = ... My Question is : Is it possible than one can add/edit models of A on the one page together with child models B and C as child models of B. Any hint or idee would be very appreciated Ogi -- 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: Returning array of integers as part of json dump, how to access in Javascript
I put in wrong variable name: > var PIDS = obj.PackageIDS; //this brings back 3,2 for example, an > array of integers. should be... var PIDS = obj.PythonList; On Feb 13, 10:10 am, robinnewrote: > I am trying to pass an array of integers from a view to javascript in > an ajax call. > > I know how to return json dump from a View so that javascript can > access it as an object like this: > > VIEW > response_dict = {"PythonList": MyList, "EditType": edittype} > return HttpResponse(simplejson.dumps(response_dict), mimetype='text/ > javascript') > > where MyList is a... python list created by: > MyList = [] > for p in packages: > MyList.append(p.id) > > in javascript, I can access the json by: > var obj = YAHOO.lang.JSON.parse(o.responseText); > var PIDS = obj.PackageIDS; //this brings back 3,2 for example, an > array of integers. > > I cannot get at PIDS as an array in javascript. When I try to convert > to an array, the first item in the array is always all values (3,2) > instead of just the first one (3). The most simplistic attempt at this > was: > > var jArray = [obj.PythonList] > > Any suggestions? -- 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: Check if django is getting a page from memcache
2010/2/13 Alessandro Ronchi> Thank you. > It seems it's working. > It's strange because some time requests waits 300ms to be processed > (calculated by firefox firebug plugin), and other times (few seconds after) > the same page waits 1.5seconds to begin downloading. > > I'm using mod_python. > > Is there a way to profile a request and understand if it's django, apache > or mysql? > > I've several sites connecting to the same memcached (with 8 threads), but > together they don't do more than 2000 pageviews a day... > Another strange thing it that the get response uses etags (which I've disabled), and it gets the same page everytime also if I put conditional get in my middleware. It seems sometimes the server things my request doesnt' have to be fetched from memcached, and other times it has (in the same minute). Maybe I made some mistakes in my settings: here is my MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', "django.middleware.common.CommonMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", PROJECTNAME + ".custom.middleware.UrlMiddleware", "django.middleware.locale.LocaleMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.middleware.doc.XViewMiddleware", 'django.middleware.http.ConditionalGetMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', "satchmo.shop.SSLMiddleware.SSLRedirect", "django.contrib.flatpages.middleware.FlatpageFallbackMiddleware", 'pagination.middleware.PaginationMiddleware', ) CACHE_BACKEND = "memcached://127.0.0.1:11211" CACHE_MIDDLEWARE_SECONDS = 3600*12 CACHE_MIDDLEWARE_KEY_PREFIX= PROJECTNAME + "_store" CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True CACHE_TIMEOUT = 3600*12 CACHE_PREFIX = PROJECTNAME + "_store" Of course I'm not in debug and not logged in when I make my tests. -- Alessandro Ronchi http://www.soasi.com SOASI - Sviluppo Software e Sistemi Open Source http://hobbygiochi.com Hobby & Giochi, l'e-commerce del divertimento -- 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: dynamic variable in templates
Sorry for not explaining it more: chain is a dictionary of lists chains {'project1': ['item1', 'item2'], 'project2': ['item3']} So the key to the dictionary is basically a project name which I get when looping over the projects in the first loop. Now the second loop should be over the list of chains but the dictionary key is changing because the name of the project is changing but I can not find a way to do this in Django templates. On Feb 13, 8:47 pm, Karen Traceywrote: > On Sat, Feb 13, 2010 at 1:30 PM, Madis wrote: > > I'm trying to write the following but there seems to be no solution on > > the web for this. > > > In a template: > > {% for project in projects %} > > {% for chain in chains.project.name %} <--- project.name should be > > dynamic > > {% endfor %} > > {% endfor %} > > What is chains? What is chains.project? What do you mean project.name should > be dynamic? How does whatever happens when you try to render that template > differ from what you are expecting? > > Karen -- 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: dynamic variable in templates
On Sat, Feb 13, 2010 at 1:30 PM, Madiswrote: > I'm trying to write the following but there seems to be no solution on > the web for this. > > In a template: > {% for project in projects %} > {% for chain in chains.project.name %} <--- project.name should be > dynamic > {% endfor %} > {% endfor %} > What is chains? What is chains.project? What do you mean project.name should be dynamic? How does whatever happens when you try to render that template differ from what you are expecting? Karen -- 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.
dynamic variable in templates
I'm trying to write the following but there seems to be no solution on the web for this. In a template: {% for project in projects %} {% for chain in chains.project.name %} <--- project.name should be dynamic {% endfor %} {% endfor %} -- 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.
INSERT INTO "db_model" ("id") VALUES (DEFAULT)
In the future please click the "Switch to copy-and-paste view" and post just the contents of the resulting text box. You started out by saying you had defined a Django model named Element with a couple of fields (CharField name, IntegerField elementtype) and that you got this error when you tried to save() an Element after filling in the fields (you didn't say where?). I don't see anything like any of that in the traceback you've posted. Instead you've got: Environment: Request Method: GET Request URL: http://127.0.0.1:8080/hello/html/app-composer Django Version: 1.1.1 Python Version: 2.5.4 Installed Applications: [] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/Library/Python/2.5/site-packages/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/developr/django/mysite/../mysite/hello/views.py" in hello_html 12. MyApp(request, result, params).build() File "/developr/xierpad/builders/sitebuilder.py" in build 1672. self.setup() File "/developr/xierpad/builders/sitebuilder.py" in setup 199. self.installSession() File "/developr/xierpad/builders/sitebuilder.py" in installSession 311. self.session.save() File "/Library/Python/2.5/site-packages/django/db/models/base.py" in save 410. self.save_base(force_insert=force_insert, force_update=force_update) File "/Library/Python/2.5/site-packages/django/db/models/base.py" in save_base 452. self.save_base(cls=parent, origin=org) File "/Library/Python/2.5/site-packages/django/db/models/base.py" in save_base 498. result = manager._insert([(meta.pk, connection.ops.pk_default_value())], return_id=update_pk, raw_values=True) File "/Library/Python/2.5/site-packages/django/db/models/manager.py" in _insert 177. return insert_query(self.model, values, **kwargs) File "/Library/Python/2.5/site-packages/django/db/models/query.py" in insert_query 1087. return query.execute_sql(return_id) File "/Library/Python/2.5/site-packages/django/db/models/sql/subqueries.py" in execute_sql 320. cursor = super(InsertQuery, self).execute_sql(None) File "/Library/Python/2.5/site-packages/django/db/models/sql/query.py" in execute_sql 2369. cursor.execute(sql, params) Exception Type: ProgrammingError at /hello/html/app-composer Exception Value: relation "db_model" does not exist LINE 1: INSERT INTO "db_model" ("id") VALUES (DEFAULT) ^ That shows (I assume) your view code (hello_html in mysite/hello/views.py) calling: MyApp(request, result, params).build() What is MyApp? The execution path is proceeding into code in /developr/xierpad/builders/sitebuilder.py. What is that? These things are bearing no resemblance to what you initially said you were doing. One very odd thing in your configuration is you appear to have nothing listed in INSTALLED_APPS. Why? Please start at the beginning describing what you are doing, what, if any, add-on packages you are using, etc. If you have not done it already, you may want to start by working through the Django tutorial. Karen -- 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: Check if django is getting a page from memcache
2010/2/13 Daniel Roseman> On Feb 13, 4:50 pm, Rob Hudson wrote: > > You can telnet to memcached and run the `stats` command. That'll tell > > you overall hits and misses (plus other info). If you're using > > Django's page caching middleware, you'll see 2 hits per page because > > Django caches both headers and page content. The page load you should > > see 2 misses. Then all subsequent page loads you should see the hits > > counter increase. > > > > -Rob > > Thank you. It seems it's working. It's strange because some time requests waits 300ms to be processed (calculated by firefox firebug plugin), and other times (few seconds after) the same page waits 1.5seconds to begin downloading. I'm using mod_python. Is there a way to profile a request and understand if it's django, apache or mysql? I've several sites connecting to the same memcached (with 8 threads), but together they don't do more than 2000 pageviews a day... -- Alessandro Ronchi http://www.soasi.com SOASI - Sviluppo Software e Sistemi Open Source http://hobbygiochi.com Hobby & Giochi, l'e-commerce del divertimento -- 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: Reversing post_change_redirect argument in django.contrib.auth.views.password_change
On Sat, 13 Feb 2010 13:22:54 +, Kev Dwyer wrote: > Hello List, > > > Does anyone know how I can avoid hardcoding the post_change_redirect > argument to change_password, either in urls.py or perhaps by some > trickery in the template or form? > > Many thanks, > > Kev I've worked around this by copying the auth.views.change_password() function into my app's views.py and modifying it so it attempts to reverse() the post_change_redirect argument, thus permitting post_change_redirect to be a view. The reverse() is wrapped by a try/except NoReverseMatch block so that if the reverse() fails the original post_change_redirect string will be used for the redirect. Two questions: - Does this seem like a sensible thing to do or am I reinventing the wheel somehow? - Assuming that I'm not reinventing the wheel, does anyone think it's worthwhile submitting this as a patch? Cheers, Kev -- 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.
Returning array of integers as part of json dump, how to access in Javascript
I am trying to pass an array of integers from a view to javascript in an ajax call. I know how to return json dump from a View so that javascript can access it as an object like this: VIEW response_dict = {"PythonList": MyList, "EditType": edittype} return HttpResponse(simplejson.dumps(response_dict), mimetype='text/ javascript') where MyList is a... python list created by: MyList = [] for p in packages: MyList.append(p.id) in javascript, I can access the json by: var obj = YAHOO.lang.JSON.parse(o.responseText); var PIDS = obj.PackageIDS; //this brings back 3,2 for example, an array of integers. I cannot get at PIDS as an array in javascript. When I try to convert to an array, the first item in the array is always all values (3,2) instead of just the first one (3). The most simplistic attempt at this was: var jArray = [obj.PythonList] Any suggestions? -- 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: Getting uploaded images to show
> 2010/2/13 holger: > > I am new to django and I am trying to get an image upload to work. > > > > My media url is > > MEDIA_URL =3D 'http://127.0.0.1:8000/media/' > > > > and my media_root is > > MEDIA_ROOT =3D os.path.join(PROJECT_ROOT, 'media') > > > > where project_root points to the root folder for the project > > > > So I want the images to be uploaded to http://127.0.0.1:8000/media/uploads/ > > > > I can see the images being uploaded to the directory but I can't > > access the file through the url in the template. > > > > What am I missing? > > > Do you have this code in urls.py? > > if settings.DEBUG: > urlpatterns +=3D patterns('', > (r'^media/(?P.*)$', > 'django.views.static.serve', {'document_root':'./media/'}), > ) > > In DEBUG mode you need such a code to serve static media. I also had difficulty even with the suggested d.v.static.serve as suggested above. I had to change the ADMIN_MEDIA_PREFIX in my settings.py to be different from MEDIA_ROOT as well. HTH, jdl -- 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: Check if django is getting a page from memcache
On Feb 13, 4:50 pm, Rob Hudsonwrote: > You can telnet to memcached and run the `stats` command. That'll tell > you overall hits and misses (plus other info). If you're using > Django's page caching middleware, you'll see 2 hits per page because > Django caches both headers and page content. The page load you should > see 2 misses. Then all subsequent page loads you should see the hits > counter increase. > > -Rob Or check out the django-memcache-status project, which provides the information as a nice graphic in your admin site home page. http://github.com/bartTC/django-memcache-status -- 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: INSERT INTO "db_model" ("id") VALUES (DEFAULT)
On Sat, Feb 13, 2010 at 11:47 AM, Petr van Bloklandwrote: > Hi, > I got at question, that may or may not sound familiar and gives me some > direction where to search. > I made a normal model description including > > class Element(models.Model): > name = models.CharField() > elementtype = models.IntegerField() > > database connection is ok, filled fields of a record of class Element, > still on element.save() I get the error below: > > Exception Value: > > relation "db_model" does not exist > LINE 1: INSERT INTO "db_model" ("id") VALUES (DEFAULT) > > > Seems like the name of the table is not set to element. > What am I missing? > > Please post the full traceback. The exception message alone is pretty mysterious. Karen -- 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: Check if django is getting a page from memcache
You can telnet to memcached and run the `stats` command. That'll tell you overall hits and misses (plus other info). If you're using Django's page caching middleware, you'll see 2 hits per page because Django caches both headers and page content. The page load you should see 2 misses. Then all subsequent page loads you should see the hits counter increase. -Rob On Feb 13, 2:41 am, Alessandro Ronchiwrote: > I am not sure django is getting a page from memcached. Is there a way to > check it? > > Thanks in advance, > > -- > Alessandro Ronchi > > http://www.soasi.com > SOASI - Sviluppo Software e Sistemi Open Source > > http://hobbygiochi.com > Hobby & Giochi, l'e-commerce del divertimento -- 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: INSERT INTO "db_model" ("id") VALUES (DEFAULT)
Hi, I got at question, that may or may not sound familiar and gives me some direction where to search. I made a normal model description including class Element(models.Model): name = models.CharField() elementtype = models.IntegerField() database connection is ok, filled fields of a record of class Element, still on element.save() I get the error below: Exception Value: relation "db_model" does not exist LINE 1: INSERT INTO "db_model" ("id") VALUES (DEFAULT) Seems like the name of the table is not set to element. What am I missing? Kind regards, Petr van Blokland __ This email has been scanned by the McAfee® Email Security System. For more information please visit http://www.mcafee.com __ -- 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.
Django, randomization of “default” parameter of a model
Hello, I want to set the "default" value as a randomly generated String for the promotion_code part of my Promotion model, for that the code_generate function is used. The issue with the code below that it seems like default=code_generate() generates this random string once every server start thus assigning the same value. I can see that by the admin panel, every time I try to generate a new Promotion, it gives me the exact same string. Here is the code: #generate a string, which is not already existing in the earlier Promotion instances def code_generate(): while 1: from django.conf import settings import random, string prom_code = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(6)) try: Promotion.objects.get(promotion_code=prom_code) except: return prom_code class Promotion(models.Model): purchase = models.ForeignKey('Purchase') promotion_code = models.CharField(max_length=20,unique=True,default=code_generate()) -- 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: weird request.user problem in view
I know. Just a typo in this post. Thanks for trying to help anyway :) the error was in the urls.py /user// /user/page/ When loading /user/page/ /user/ wrote: > On 13 February 2010 13:46, Anders Eidewrote: > > > > > did a stupid PEBCAK i the urls.py file. Works fine now > > > On Feb 13, 1:33 pm, Anders Eide wrote: > >> Why on earth doesn't this user_page view work? Getting "404, No User > >> matches the given query." > > >> from django.contrib.auth.models import User > >> from django.template import RequestContext > >> from django.shortcuts import render_to_response, get_object_or_404 > > >> def user_page(request): > >> user = get_object_or_404(User, > >> username=request.user.username) > >> movies = user.mymovie_set.all() > >> variables = RequestContext(request, { > >> 'movies': movies, > >> }) > >> return render_to_response('user_page/user_page.home.view.html', > >> variables) > > >> The user is loged in > > > -- > > 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 > > athttp://groups.google.com/group/django-users?hl=en. > > user = User.get_object_or_404(User, username=request.user.username) > > I don't think you need this, request.user is already an instance of User. > Try: > > movies = request.user.mymovie_set.all() -- 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: weird request.user problem in view
On 13 February 2010 13:46, Anders Eidewrote: > did a stupid PEBCAK i the urls.py file. Works fine now > > On Feb 13, 1:33 pm, Anders Eide wrote: >> Why on earth doesn't this user_page view work? Getting "404, No User >> matches the given query." >> >> from django.contrib.auth.models import User >> from django.template import RequestContext >> from django.shortcuts import render_to_response, get_object_or_404 >> >> def user_page(request): >> user = get_object_or_404(User, >> username=request.user.username) >> movies = user.mymovie_set.all() >> variables = RequestContext(request, { >> 'movies': movies, >> }) >> return render_to_response('user_page/user_page.home.view.html', >> variables) >> >> The user is loged in > > -- > 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. > > user = User.get_object_or_404(User, username=request.user.username) I don't think you need this, request.user is already an instance of User. Try: movies = request.user.mymovie_set.all() -- 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: weird request.user problem in view
did a stupid PEBCAK i the urls.py file. Works fine now On Feb 13, 1:33 pm, Anders Eidewrote: > Why on earth doesn't this user_page view work? Getting "404, No User > matches the given query." > > from django.contrib.auth.models import User > from django.template import RequestContext > from django.shortcuts import render_to_response, get_object_or_404 > > def user_page(request): > user = get_object_or_404(User, > username=request.user.username) > movies = user.mymovie_set.all() > variables = RequestContext(request, { > 'movies': movies, > }) > return render_to_response('user_page/user_page.home.view.html', > variables) > > The user is loged in -- 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.
weird request.user problem in view
Why on earth doesn't this user_page view work? Getting "404, No User matches the given query." from django.contrib.auth.models import User from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 def user_page(request): user = User.get_object_or_404(User, username=request.user.username) movies = user.mymovie_set.all() variables = RequestContext(request, { 'movies': movies, }) return render_to_response('user_page/user_page.home.view.html', variables) The user is loged in -- 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: choose database manually per-request
Dear Graham, Thanks for the quick answer! Basicly, I would like to handle this problem from the app, so I can't modify the underlying architecture. Your suggestion needs some changes in the apache configuration, I guess. The only thing I have access to is the source of the webapp. Thanks, anyway, and if you have hints for the single instance solution too, please share. Thanks, Daniel On Feb 13, 12:42 pm, Graham Dumpletonwrote: > On Feb 13, 7:43 am, PDani wrote: > > > > > Hi! > > > I would like to set up some database servers in Django 1.2, and then > > use them in this way: when a new request comes, i choose a server > > manually, and then use this ONLY ONE server in that request. I don't > > want to pass around parameters, which server i chosen, so somehow, i > > would like to make the chosen server the "default" server for that > > request. > > Here's an example: > > - somebody gets a page > > - based on who is the person, and what page, i decide which db server > > should i use > > - i select it (how?) > > - then every query will be routed to this server without having to use > > explicitly using(), and friends, until the end of that concrete > > request > > Any idea how should I do this? > > How many databases do you have? > > If it is a small number, then you could be a bit tricky with Apache/ > mod_wsgi and create multiple daemon process groups where the Django > configuration for the database changed based on the name of the > process group a request was handled in. You could then use cookies and/ > or in conjunction with session information, to dynamically control to > which daemon process group mod_wsgi delegated the request. > > In other words, rather than try and switch a single instance to > different databases on the fly, you have one instance per database and > control to which the request actually gets passed to. > > A can explain more later if that would at all be practical. > > Graham -- 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: choose database manually per-request
On Feb 13, 7:43 am, PDaniwrote: > Hi! > > I would like to set up some database servers in Django 1.2, and then > use them in this way: when a new request comes, i choose a server > manually, and then use this ONLY ONE server in that request. I don't > want to pass around parameters, which server i chosen, so somehow, i > would like to make the chosen server the "default" server for that > request. > Here's an example: > - somebody gets a page > - based on who is the person, and what page, i decide which db server > should i use > - i select it (how?) > - then every query will be routed to this server without having to use > explicitly using(), and friends, until the end of that concrete > request > Any idea how should I do this? How many databases do you have? If it is a small number, then you could be a bit tricky with Apache/ mod_wsgi and create multiple daemon process groups where the Django configuration for the database changed based on the name of the process group a request was handled in. You could then use cookies and/ or in conjunction with session information, to dynamically control to which daemon process group mod_wsgi delegated the request. In other words, rather than try and switch a single instance to different databases on the fly, you have one instance per database and control to which the request actually gets passed to. A can explain more later if that would at all be practical. Graham -- 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.
Check if django is getting a page from memcache
I am not sure django is getting a page from memcached. Is there a way to check it? Thanks in advance, -- Alessandro Ronchi http://www.soasi.com SOASI - Sviluppo Software e Sistemi Open Source http://hobbygiochi.com Hobby & Giochi, l'e-commerce del divertimento -- 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: Getting uploaded images to show
Do you have this code in urls.py? if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P.*)$', 'django.views.static.serve', {'document_root':'./media/'}), ) In DEBUG mode you need such a code to serve static media. 2010/2/13 holger: > I am new to django and I am trying to get an image upload to work. > > I am using the admin interface with a ImageField in the model. > > imagefilename = models.ImageField(upload_to = 'uploads/') > > My media url is > MEDIA_URL = 'http://127.0.0.1:8000/media/' > > and my media_root is > MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media') > > where project_root points to the root folder for the project > > So I want the images to be uploaded to http://127.0.0.1:8000/media/uploads/ > > I can see the images being uploaded to the directory but I can´t > access the file through the url in the template. > > What am I missing? > > -- > 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. > > -- Antoni Aloy López Blog: http://trespams.com Site: http://apsl.net -- 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.
Django-CMS: Project name prefix in the URL
The problem is that the project name is beeing appended in the URL when using the URL filter. For example, when I use the filter to get the URL of the news page, the filter returns "/project_name/news/", but it should return just "/news/". I have no idea what should I fix that and hope someone will give me a direction to work at. :) -- 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.
Getting uploaded images to show
I am new to django and I am trying to get an image upload to work. I am using the admin interface with a ImageField in the model. imagefilename = models.ImageField(upload_to = 'uploads/') My media url is MEDIA_URL = 'http://127.0.0.1:8000/media/' and my media_root is MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media') where project_root points to the root folder for the project So I want the images to be uploaded to http://127.0.0.1:8000/media/uploads/ I can see the images being uploaded to the directory but I can´t access the file through the url in the template. What am I missing? -- 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: Middleware for models
Ok, I think I have sorted out my queryset problem, I wrote a custom manager: class UserBranchModelManager(models.Manager): def for_request(self, request): if settings.DO_BRANCH_FILTER: return super(UserBranchModelManager, self).get_query_set().filter(branch__pk = request.userBranchID) return super(UserBranchModelManager, self).get_query_set() class Amodel(models.Model): branch_filter = UserBranchModelManager() def aview(request) queryset.= Amodel.branch_filter.for_request(request) Thanks Shawn for directing me in the right direction. Now I just need to override the get() method. :) -- 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: can't authenticate in template
Just as a suggestion, if you don't need to customize the get_user() method then simply don't have a get_user() method in your custom authentication class. -- 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.
validate_generic from PYCON 2007
Hi, while reading http://toys.jacobian.org/presentations/2007/oscon/tutorial/#s67 I see this nice validate_generic(request, formclass), but I am curious how to select proper formclass from the URL request? At the moment I thing of maintaining dictionary of avaliable forms and its corresponding names, is this correct approach? many thanks, Robert -- 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: Middleware for models
Sorry one more thing, the above filters my querysets but then comes the get() method on each model. I use urls with pk's so a user could just try to change the url to a pk that does not belong to them and view it. To filter this out I run yet another function: def relation_branch_validation(request, relation): if settings.DO_BRANCH_FILTER: if relation.branch.id != request.userBranchID: raise InvalidBranchException('%s is requesting data for relation %s. Request from %s' % (request.user.username, unicode(relation), request.view_name)) def aview(request, obj_id): relation = get_object_or_404(Relation, pk = obj_id) relation_branch_validation(request, relation) This is really no fun adding these functions to each view and I tell you there is a lot of views. :) -- 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: Middleware for models
Just so you have an idea what I am trying to do. :) I have a custom middleware that adds a userBranchID variable to each request according to the users branch in the User model. Now in each view when I use any queryset I have to do the following: def filter_branch(request, queryset): if settings.DO_BRANCH_FILTER: queryset = queryset.filter(branch__pk = request.userBranchID) return queryset def aview(request): queryset = Model.objects.all() queryset = filter_branch(request, queryset) I would like to avoid running the filter_branch function each time I run a queryset. -- 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: Inline Admin and ForeignKey
class EventInline(admin.TabularInline): model = Event extra = 1 will only show one extra event (the next "empty" one, if you like). On Jan 11, 4:11 pm, Igorwrote: > Thanks, you're right... was posting this late at night while > experimenting and copied the experimental version... The way it looks > now is this: > > class EventInline(admin.TabularInline): > model = Event > > class EntryAdmin(admin.ModelAdmin): > prepopulated_fields = { 'slug': ['title'] } > inlines = [ EventInline ] > > Now, I've realized it works, but it always shows at least 3 Event > items in an admin page which is slightly annoying... I'd rather have > none with an option to add more if the user wants to. > > On Jan 11, 2:26 pm, Daniel Roseman wrote: > > > On Jan 11, 12:43 am, Igor wrote: > > > > Hi, > > > > I have a blog model and would like to be able to add an arbitrary > > > number of event dates to it (i.e. turn a blog post into an event > > > announcement). For that I use > > > > class Event(models.Model): > > > entry = models.ForeignKey(Entry) > > > begin_date = models.DateTimeField(default=datetime.datetime.now) > > > end_date = models.DateTimeField(default=datetime.datetime.now) > > > > I hope this is good so far. > > > What I would like to happen is to be able to add those events inline - > > > inside an Entry editing page in the admin interface: > > > > class EventInline(generic.GenericTabularInline): > > > model = Event > > > max_num = 1 #TODO: Fix this > > > > class EntryAdmin(admin.ModelAdmin): > > > prepopulated_fields = { 'slug': ['title'] } > > > inlines = [ EventInline ] > > > > But in the Entry admin page I see three blocks of begin_date and > > > end_date. No option to edit/delete them, or add a new one. The three > > > are basically static. > > > > What am I doing wrong? > > > > Thanks for any ideas! > > > On Jan 11, 12:43 am, Igor wrote: > > > > Hi, > > > > I have a blog model and would like to be able to add an arbitrary > > > number of event dates to it (i.e. turn a blog post into an event > > > announcement). For that I use > > > > class Event(models.Model): > > > entry = models.ForeignKey(Entry) > > > begin_date = models.DateTimeField(default=datetime.datetime.now) > > > end_date = models.DateTimeField(default=datetime.datetime.now) > > > > I hope this is good so far. > > > What I would like to happen is to be able to add those events inline - > > > inside an Entry editing page in the admin interface: > > > > class EventInline(generic.GenericTabularInline): > > > model = Event > > > max_num = 1 #TODO: Fix this > > > > class EntryAdmin(admin.ModelAdmin): > > > prepopulated_fields = { 'slug': ['title'] } > > > inlines = [ EventInline ] > > > > But in the Entry admin page I see three blocks of begin_date and > > > end_date. No option to edit/delete them, or add a new one. The three > > > are basically static. > > > > What am I doing wrong? > > > > Thanks for any ideas! > > > Why are you using generic.GenericTabularInline rather than > > admin.TabularInline? I don't know if that's the cause of your problem, > > but it's bound to lead to some issues since you don't have a generic > > relation. > > -- > > 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: Middleware for models
Hi Shawn, I use Managers often to limit my querysets and add additional fields that I want dynamically calculated using sql. I just don't see how I can get the request object to the models.Manager so it knows what to filter by (user.uid). :( I know I could do a filter in each view queryset.objects.filter(branch__user = request.user) but I don't like this method because I might just forget to add the filter and all data will be visible. Karol -- 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: admin url name
On Sat, Feb 13, 2010 at 4:43 AM, Karen Traceywrote: > On Fri, Feb 12, 2010 at 4:34 PM, Umapathy S wrote: > I don't know how to get this working on the level of code you have. To do > it with 1.1 or higher, you'd want to reverse admin:index, as documented > here: > > > http://docs.djangoproject.com/en/dev/ref/contrib/admin/#reversing-admin-urls > > Karen > > thanks Karen. I tried as per the above document before mailing the list. I had installed 1.1 beta but then switched to 1.1 final. Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.VERSION (1, 1, 0, 'final', 0) Somewhere it has gone wrong. I will delete all the django packages and reinstall again. Thanks Umapathy -- 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: can't authenticate in template
On Feb 13, 2:23 am, paulwrote: > On Feb 12, 5:03 pm, pbzRPA wrote: > > > The middleware looks good. Is your browser maybe not blocking cookies? > > I have really though hard about it, but without code it's really > > difficult to get a picture of where the problem may lie. You also said > > you do custom authentication, then why is it that you printing out the > > request in the django.contrib,auth.views.login? > > In settings.py, I also have: > > AUTHENTICATION_BACKENDS = ('auth.backends.ldap_backend',) > > The following code represents the backend that authenticates against a > LDAP directory. It is working correctly (if the supplied username and > password match, it returns a User -- I've verified this. I'm trying > to not overflow this message with code, hopefully I'm including enough > code to be informative. So basically my understanding is that if I > want to use a different authentication backend, I just specify it > under AUTHENTICATION BACKENDS, and Django will abstract the > authentication and login process as long as my authentication backend > returns a User instance if an entered username and password are > validated. Please see the following code, I'll add some more comments > after it: > > class ldap_backend(ModelBackend): > def authenticate(self, username=None, password=None): > if username is not None and password is not None: > > > if valid: # valid = True if username & password matched > the LDAP entry > return self.get_user(username) > > def get_user(self, username): > try: > return User.objects.get(username=username) > except User.DoesNotExist: > return None > > The following is a portion of the django.contrib.auth.login function. > If I supply the correct username and password, the function executes > all the way to returning HttpResponseRedirect. I am showing where I > put in a print statement to show request.user.is_authenticated(). > This prints "True". > > def login(request, template_name='registration/login.html', > redirect_field_name=REDIRECT_FIELD_NAME): > "Displays the login form and handles the login action." > redirect_to = request.REQUEST.get(redirect_field_name, '') > if request.method == "POST": > > print "end %s" % request.user.is_authenticated() # will > be True if username & pw are validated > return HttpResponseRedirect(redirect_to) > > Now, here is the code of the view that handles redirect_to: > > view.py > def home(request): > context = {'title_prefix' : 'Account Home'} > template = 'accounts/home.html' > rc = RequestContext(request) > return render_to_response(template, context, context_instance=rc) > > In this code, if I check request.user.is_authenticated, it returns > False. request.user is actually AnonymousUser. However, if I look at > request.session.items, I see the correct _auth_user_id for the user > that just logged in. > > I hope that my code might be helpful. I'm quite perplexed about > what's wrong. > > thanks again, > > Paul Hi Paul, I wonder if your problem does not lie in your "get_user" method in your ldap_backend. The normal get_user method requires a used_id and not a username. The authentication method should return it's own user instead of calling get get_user method. Try changing you get_user method to: def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None and in your authenticate method replace: """return self.get_user(username) """ with: try: user = User.objects.get(username=username) except User.DoesNotExist: return None return user I think that django calls the get_user method with a request. The django auth calls " user = backend.get_user(user_id) or AnonymousUser()" Hope that helps. -- 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.