Search Results

Search found 5330 results on 214 pages for 'django auth'.

Page 126/214 | < Previous Page | 122 123 124 125 126 127 128 129 130 131 132 133  | Next Page >

  • Removing a fields from a dynamic ModelForm

    - by Jérôme Pigeot
    In a ModelForm, i have to test user permissions to let them filling the right fields : It is defined like this: class TitleForm(ModelForm): def __init__(self, user, *args, **kwargs): super(TitleForm,self).__init__(*args, **kwargs) choices = [] # company if user.has_perm("myapp.perm_company"): self.fields['company'] = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=Company.objects.all(), required=False) choices.append('Company') # association if user.has_perm("myapp.perm_association") self.fields['association'] = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=Association.objects.all(), required=False) choices.append('Association') # choices self.fields['type_resource'] = forms.ChoiceField(choices = choices) class Meta: Model = Title This ModelForm does the work : i hide each field on the template and make them appearing thanks to javascript... The problem is this ModelForm is that each field defined in the model will be displayed on the template. I would like to remove them from the form if they are not needed: exemple : if the user has no right on the model Company, it won't be used it in the rendered form in the template. The problem of that is you have to put the list of fields in the Meta class of the form with fields or exclude attribute, but i don't know how to manage them dynamically. Any Idea?? Thanks by advance for any answer.

    Read the article

  • How can I test to see if a class contains a particular attribute?

    - by BryanWheelock
    How can I test to see if a class contains a particular attribute? In [14]: user = User.objects.get(pk=2) In [18]: user.__dict__ Out[18]: {'date_joined': datetime.datetime(2010, 3, 17, 15, 20, 45), 'email': u'[email protected]', 'first_name': u'', 'id': 2L, 'is_active': 1, 'is_staff': 0, 'is_superuser': 0, 'last_login': datetime.datetime(2010, 3, 17, 16, 15, 35), 'last_name': u'', 'password': u'sha1$44a2055f5', 'username': u'DickCheney'} In [25]: hasattr(user, 'username') Out[25]: True In [26]: hasattr(User, 'username') Out[26]: False I'm having a weird bug where more attributes are showing up than I actually define. I want to conditionally stop this. e.g. if not hasattr(User, 'karma'): User.add_to_class('karma', models.PositiveIntegerField(default=1))

    Read the article

  • Is it possible to calculate distance on GeoDjango in a SELECT statement?

    - by alex
    I am using MYSQL. I have a table with 1 column, a Point field. I want to SELECT all rows that have a point with a distance less than 50 meters of my given point. Simple enough, right? Below is how it's done in RAW SQL. But of course, I want to use GeoDjango to do this. cursor.execute("SELECT * FROM project_location WHERE\ (GLength(LineStringFromWKB(LineString(asbinary(utm), asbinary(PointFromWKB(point(%s, %s)))))) < 50)\

    Read the article

  • Avoiding thumbnail name collisions with sorl-thumbnail

    - by Owen Nelson
    Understanding that I should probably just dig into the source to come up with a solution, I'm wondering if anyone has come up with a tactic for dealing with this. In my project, I have a lot of images being generated outside of the application. I'm isolating them on the filesystem based on a model's pk. For example, a model instance with a pk of 121 might have the following images: .../thumbs/1/2/1/img.1.jpg .../thumbs/1/2/1/img.2.jpg ... .../thumbs/1/2/1/img.27.jpg Since the image filenames themselves are not guaranteed to be unique, I'm looking for a way to inform sorl (at runtime) that I'd like to prefix thumbs for this model with the instance pk value. Is this even possible without patching sorl?

    Read the article

  • Edit form not being instantiated

    - by 47
    I have two models like this: class OptionsAndFeatures(models.Model): options = models.TextField(blank=True, null=True) entertainment = models.TextField(blank=True, null=True) seats_trim = models.TextField(blank=True, null=True) convenience = models.TextField(blank=True, null=True) body_exterior = models.TextField(blank=True, null=True) lighting = models.TextField(blank=True, null=True) safety = models.TextField(blank=True, null=True) powertrain = models.TextField(blank=True, null=True) suspension_handling = models.TextField(blank=True, null=True) specs_dimensions = models.TextField(blank=True, null=True) offroad_capability = models.TextField(blank=True, null=True) class Vehicle(models.Model): ... options_and_features = models.ForeignKey(OptionsAndFeatures, blank=True, null=True) I have a model form for the OptionsAndFeaturesclass that I'm using in both the add and edit views. In the add view it works just fine. But the edit view renders the OptionsAndFeatures as blank. The code for the edit view is as follows: def edit_vehicle(request, stock_number=None): vehicle = get_object_or_404(Vehicle, stock_number=stock_number) if request.method == 'POST': # save info else: vehicle_form = VehicleForm(instance=vehicle) photos = PhotosFormSet(instance=vehicle) options = OptionsForm(instance=vehicle) #render_to_reponse What could be the problem here?

    Read the article

  • Searching for Records

    - by 47
    I've come up with a simple search view to search for records in my app. The user just enters all parameters in the search box then all this is matched against the database, then results are returned. One of these fields is the phone number....now in the database it's stored in the format XXX-XXX-XXX. A search, for example, for "765-4321" pull up only "416-765-4321...however I want it to return both "416-765-4321" and "4167654321" My view is as below: def search(request, page_by=None): query = request.GET.get('q', '') if query: term_list = query.split(' ') q = Q(first_name__icontains=term_list[0]) | Q(last_name__icontains=term_list[0]) | Q(email_address__icontains=term_list[0]) | Q(phone_number__icontains=term_list[0]) for term in term_list[1:]: q.add((Q(first_name__icontains=term) | Q(last_name__icontains=term) | Q(email_address__icontains=term) | Q(phone_number__icontains=term)), q.connector) results = Customer.objects.filter(q).distinct() all = results.count() else: results = [] if 'page_by' in request.GET: page_by = int(request.REQUEST['page_by']) else: page_by = 50 return render_to_response('customers/customers-all.html', locals(), context_instance=RequestContext(request))

    Read the article

  • sorl-thumbnail: random name in Thumbnail field

    - by xRobot
    I want to use str(uuid.uuid4()) instead of the name uploaded. I have this model: class foo(models.Model): pic = ThumbnailField(upload_to='pics', size=(200, 200)) I am uploading hello_world.jpg and I should save these named versions should be saved for example in 4ba9b397-da69-4307-9bce-e92887e84d2f.jpg. How can I do that?

    Read the article

  • registration 0.8 alpha activation problem

    - by craphunter
    Got the following error: Exception Type: TypeError at /accounts/account/activate/success/ Exception Value: activate() takes at least 2 non-keyword arguments (1 given) My view: def activate(request, backend, template_name='registration/activation_complete.html', success_url=None, extra_context=None, **kwargs): backend = get_backend(backend) account = backend.activate(request, **kwargs) if account: if success_url is None: to, args, kwargs = backend.post_activation_redirect(request, account) return redirect(to, *args, **kwargs) else: return redirect(success_url) if extra_context is None: extra_context = {} context = RequestContext(request) for key, value in extra_context.items(): context[key] = callable(value) and value() or value return render_to_response(template_name, kwargs, context_instance=context) My url: urlpatterns = patterns('', url(r'^activate/complete/$', direct_to_template, { 'template': 'registration/activation_complete.html' }, name='registration_activation_complete'), # Activation keys get matched by \w+ instead of the more specific # [a-fA-F0-9]{40} because a bad activation key should still get to the view; # that way it can return a sensible "invalid key" message instead of a # confusing 404. url(r'^activate/(?P<activation_key>\w+)/$', activate, { 'backend': 'registration.backends.default.DefaultBackend' }, name='registration_activate'), url(r'^register/$', register, { 'backend': 'registration.backends.default.DefaultBackend' }, name='registration_register'), url(r'^register/complete/$', direct_to_template, { 'template': 'registration/registration_complete.html' }, name='registration_complete'), url(r'^register/closed/$', direct_to_template, { 'template': 'registration/registration_closed.html' }, name='registration_disallowed'), (r'', include('registration.auth_urls')), url(r'^account/activate/(?P<activation_key>\w+)/$', 'registration.views.activate', {'success_url': 'account/activate/success/'}, name='registration_activate2'), url(r'^account/activate/success/$', direct_to_template, {'template': 'registration/activation_complete.html'}, name='registration_activation_complete'), ) What do I do wrong? Thanks!

    Read the article

  • Virtualenv with Eclipse (Galileo)

    - by Adam Nelson
    Does anybody have directions for getting Eclipse (Galileo), PyDev, and Virtualenv working together? I'm specifically trying to run Pinax but any instructions are fine. I thought I had it (and even blogged everything but the final step - interactive debugging) and still there is no solution. I'm specifically on OS X but any answer should be sufficient. This is the best resource I've found so far: http://blog.vlku.com/index.php/2009/06/10/djangoeclipse-with-code-complete-screencast/

    Read the article

  • How come I get a timed-out when I try to download something off my own domain?

    - by alex
    def download(source_url): socket.setdefaulttimeout(10) agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','Microsoft Internet Explorer/4.0b1 (Windows 95)','Opera/8.00 (Windows NT 5.1; U; en)'] ree = urllib2.Request(source_url) ree.add_header('User-Agent',random.choice(agents)) resp = urllib2.urlopen(ree) htmlSource = resp.read() return htmlSource url = "http://myIP/details/?id=4" result_html = download(url) It shouldn't time out...even with the 10 second timeout..

    Read the article

  • how do i install mod_wsgi2.6 in ubuntu

    - by subhransu
    I am getting problem while installing mod_wsgi 2.6 which supports python2.5 but i have python 2.6 as default in ubuntu. can you plz tell me whether i have to find a mod_wsgi V supporting python2.6 or i have to install python 2.5 and set the path.

    Read the article

  • Changing the admin edit window display values

    - by Henri
    I have a database table with e.g. a weight value e.g. CREATE TABLE product ( id SERIAL NOT NULL, product_name item_name NOT NULL, . . weight NUMERIC(7,3), -- the weight in kg . . CONSTRAINT PK_product PRIMARY KEY (id) ); This results is the model: class Product(models.Model): . weight = models.DecimalField(max_digits=7, decimal_places=3, blank=True, null=True) . I store the weight in kg's, i.e. 1 kg is stores as 1, 0.1 kg or 100g is stored as 0.1 To make it easier for the user, I display the weight in the Admin list display in grams by specifying: def show_weight(self): if self.weight: weight_in_g = self.weight * 1000 return '%0f' % weight_in_g So if a product weighs e.g. 0.5 kg and is stored in the database as such, the admin list display shows 500 Is there also a way to alter the number shown in the 'Change product' window. This window now shows the value extracted from the database, i.e. 0.5. This will confuse a user when I tell him with the help_text to enter the number in g, while seeing the number of kgs. Before saving the product I override save as follows: def save(self): if self.weight: self.weight = self.weight / 1000 This converts the number entered in grams to kgs.

    Read the article

  • Defining the context of a word - Python

    - by RadiantHex
    Hi folks, I think this is an interesting question, at least for me. I have a list of words, let's say: photo, free, search, image, css3, css, tutorials, webdesign, tutorial, google, china, censorship, politics, internet and I have a list of contexts: Programming World news Technology Web Design I need to try and match words with the appropriate context/contexts if possible. Maybe discovering word relationships in some way. Any ideas? Help would be much appreciated!

    Read the article

  • Customizing RadioSelect

    - by Kugel
    Hello I have a form with ChoiceField whose widget is set to RadioSelect Now to override default html output one needs to subclass RadioFieldRenderer like this: class SimpleRadioFieldRenderer(forms.widgets.RadioFieldRenderer): def render(self): """Outputs widget without <ul> or <li> tags.""" return mark_safe(u'\n'.join([u'%s' % force_unicode(w.tag()) for w in self])) All is good now except I'd like to be able to render 1 radio button at a time from template. Something like this: {{ form.myfield.0 }}} Or perhaps hanging it onto widget itself: {{ form.myfield.field.widget.0 }} What bugs me is that RadioFieldRenderer already implements __get_item__ to get just one RadioInput. The problem is that the renderer does not contain data, neither does the widget. And I'd really hate to mess with Field and BoundField. I need this to inject html before/after each radiobutton and I'd like it to be done in the template. From the code it would be easy. Any ideas are welcome.

    Read the article

  • Subclassing Satchmo's Category model, but then getting the error "'Manager' object has no attribute 'root_categories'"

    - by hellsgate
    I'm using Satchmo as part of a website I'm currently building. At the moment I'm trying add more functions to the Satchmo Category class, but obviously I'm not going to make any changes to the Satchmo files. So, I thought that subclassing the Category class would give me a new class which contains all the Satchmo Category properties and methods while allowing me to add my own. However, either Python subclassing doesn't work like that, or I am doing it wrong. Here is the code I'm using to subclass Category: from product.models import Category class MyCategory(Category): """ additional functions to pull data from the Satchmo store app """ One of the methods I can normally use from the Category class is: Category.objects.root_categories() however, when I try to access MyCategory.objects.root_categories() I get the following error: AttributeError: 'Manager' object has no attribute 'root_categories' Can anyone point me in the right direction for solving this?

    Read the article

  • appcfg.py upload_data entity kind problem

    - by Dingo
    Hi, I am developing application on app-engine-path and I would like to upload some data to datastore. For example I have a model models/places.py: class Place(db.Model): name = db.StringProperty() longitude = db.FloatProperty() latitude = db.FloatProperty() If I save this in view, kind() of this entity is "models_place". All is ok, Place.all() in view work fine. But: If I upload some next row using appcfg.py upload_data, the kind() of this entities is Place. loader.py look like this: import datetime, os, sys from google.appengine.ext import db from google.appengine.tools import bulkloader libs_path = os.path.join("/home/martin/myproject/src/") if libs_path not in sys.path: sys.path.insert(0, libs_path) from models import places class AlbumLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'Place', [('name', lambda x: x.decode('utf-8')), ('longitude', float), ('latitude', float), ]) loaders = [AlbumLoader] and command for uploading: python /usr/local/google_appengine/appcfg.py upload_data --config_file=places_loader.py --kind=models_place --filename=data/places.csv --url=http://localhost:8000/remote_api /home/martin/myproject/src/

    Read the article

  • PDF Form Field Manipulation

    - by 108039818756939362532
    I'm making a web interface to autofill pdf forms with user data from a database. The admin needs to be able to upload a pdf (right now targeted at IRS pdf forms) and then associate the fields in the pdf with data fields in the database. I need a way to help the admin associate the field names (stuff like "topmostSubform[0].Page2[0].p2-t66[0]") with the the data fields in the database. I'm looking for a way to modify the PDF programatically to in some way provide this information. Basically I'm open to suggestions on how I might make the field names appear in an obvious manner on a modified version of the original pdf. The closest I've gotten is being able to insert Tooltips into the fields in the pdf by just editting the raw pdf line by line. However when editting the pdf in this manner the field names are gibberish, and so I can't just use them. An optimal solution would be anything that could automatically parse a pdf and set each field's tooltip to be the fields name. Anything that can be run from the command line, or any python tool, or just a basic how to correctly parse a field's name from a raw pdf file would be amazing.

    Read the article

  • Creating form using Generic_inlineformset_factory from the Model Form

    - by Prateek
    hello dear all, I wanted to create a edit form with the help of ModelForm. and my models contain a Generic relation b/w classes, so if any one could suggest me the view and a bit of template for the purpose I would be very thankful, as I am new to the language. My models look like:- class Employee(Person): nickname = models.CharField(_('nickname'), max_length=25, null=True, blank=True) blood_type = models.CharField(_('blood group'), max_length=3, null=True, blank=True, choices=BLOOD_TYPE_CHOICES) marital_status = models.CharField(_('marital status'), max_length=1, null=True, blank=True, choices=MARITAL_STATUS_CHOICES) nationality = CountryField(_('nationality'), default='IN', null=True, blank=True) about = models.TextField(_('about'), blank=True, null=True) dependent = models.ManyToManyField(Dependent, through='DependentRelationship') pan_card_number = models.CharField(_('PAN card number'), max_length=50, blank=True, null=True) policy_number = models.CharField(_('policy number'), max_length=50, null=True, blank=True) # code specific details user = models.OneToOneField(User, blank=True, null=True, verbose_name=_('user')) class Person(models.Model): """Person model""" title = models.CharField(_('title'), max_length=20, null=True, blank=True) first_name = models.CharField(_('first name'), max_length=100) middle_name = models.CharField(_('middle name'), max_length=100, null=True, blank=True) last_name = models.CharField(_('last name'), max_length=100, null=True, blank=True) suffix = models.CharField(_('suffix'), max_length=20, null=True, blank=True) slug = models.SlugField(_('slug'), max_length=50, unique=True) class PhoneNumber(models.Model) : phone_number = generic.GenericRelation('PhoneNumber') email_address = generic.GenericRelation('EmailAddress') address = generic.GenericRelation('Address') date_of_birth = models.DateField(_('date of birth'), null=True, blank=True) gender = models.CharField(_('gender'), max_length=1, null=True, blank=True, choices=GENDER_CHOICES) content_type = models.ForeignKey(ContentType, If anyone could suggest me a link or so. it would be a great help........

    Read the article

  • Replace textfields with dropdown select fields

    - by 47
    I have three model classes that look as below: class Model(models.Model): model = models.CharField(max_length=20, blank=False) manufacturer = models.ForeignKey(Manufacturer) date_added = models.DateField(default=datetime.today) def __unicode__(self): name = ''+str(self.manufacturer)+" "+str(self.model) return name class Series(models.Model): series = models.CharField(max_length=20, blank=True, null=True) model = models.ForeignKey(Model) date_added = models.DateField(default=datetime.today) def __unicode__(self): name = str(self.model)+" "+str(self.series) return name class Manufacturer(models.Model): MANUFACTURER_POPULARITY_CHOICES = ( ('1', 'Primary'), ('2', 'Secondary'), ('3', 'Tertiary'), ) manufacturer = models.CharField(max_length=15, blank=False) date_added = models.DateField(default=datetime.today) manufacturer_popularity = models.CharField(max_length=1, choices=MANUFACTURER_POPULARITY_CHOICES) def __unicode__(self): return self.manufacturer I want to have the fields for model series and manufacturer represented as dropdowns instead of text fields. I have customized the model forms as below: class SeriesForm(ModelForm): series = forms.ModelChoiceField(queryset=Series.objects.all()) class Meta: model = Series exclude = ('model', 'date_added',) class ModelForm(ModelForm): model = forms.ModelChoiceField(queryset=Model.objects.all()) class Meta: model = Model exclude = ('manufacturer', 'date_added',) class ManufacturerForm(ModelForm): manufacturer = forms.ModelChoiceField(queryset=Manufacturer.objects.all()) class Meta: model = Manufacturer exclude = ('date_added',) However, the dropdowns are populated with the unicode in the respective class...how can I further customize this to get the end result I want? Also, how can I populate the forms with the correct data for editing? Currently only SeriesForm is populated. The starting point of all this is from another class whose declaration is as below: class CommonVehicle(models.Model): year = models.ForeignKey(Year) series = models.ForeignKey(Series) .... def __unicode__(self): name = ''+str(self.year)+" "+str(self.series) return name

    Read the article

  • Python SUDS - problem with sending a message encoded not in UTF-8

    - by bartekb
    I need to send a SOAP message (with Python SUDS) with strings encoded in 'iso-8859-2'. Does anybody know how to do it? SUDS raises the following exception when I invoke a method on a client with parameters encoded in 'iso-8859-2': File "/home/bartek/myenv/lib/python2.5/site-packages/suds/sax/text.py", line 43, in __new__ result = super(Text, cls).__new__(cls, *args, **kwargs) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 10: ordinal not in range(128)

    Read the article

  • Performing text processing on flatpage content to include handling of custom tag

    - by Dzejkob
    Hi. I'm using flatpages app in my project to manage some html content. That content will include images, so I've made a ContentImage model allowing user to upload images using admin panel. The user should then be able to include those images in content of the flatpages. He can of course do that by manually typing image url into <img> tag, but that's not what I'm looking for. To make including images more convenient, I'm thinking about something like this: User edits an additional, let's say pre_content field of CustomFlatPage model (I'm using custom flatpage model already) instead of defining <img> tags directly, he uses a custom tag, something like [img=...] where ... is name of the ContentImage instance now the hardest part: before CustomFlatPage is saved, pre_content field is checked for all [img=...] occurences and they are processed like this: ContentImage model is searched if there's image instance with given name and if so, [img=...] is replaced with proper <img> tag. flatpage actual content is filled with processed pre_content and then flatpage is saved (pre_content is leaved unchanged, as edited by user) The part that I can't cope with is text processing. Should I use regular expressions? Apparently they can be slow for large strings. And how to organize logic? I assume it's rather algorithmic question, but I'm not familliar with text processing in Python enough, to do it myself. Can somebody give me any clues?

    Read the article

< Previous Page | 122 123 124 125 126 127 128 129 130 131 132 133  | Next Page >