Search Results

Search found 4736 results on 190 pages for 'django profiles'.

Page 12/190 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Debugging "Premature end of script headers" - WSGI/Django [migrated]

    - by Marcin
    I have recently deployed an app to a shared host (webfaction), and for no apparent reason, my site will not load at all (it worked until today). It is a django app, but the django.log is not even created; the only clue is that in one of the logs, I get the error message: "Premature end of script headers", identifying my wsgi file as the source. I've tried to add logging to my wsgi file, but I can't find any log created for it. Is there any recommended way to debug this error? I am on the point of tearing my hair out. My WSGI file: import os import sys from django.core.handlers.wsgi import WSGIHandler import logging logger = logging.getLogger(__name__) os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' os.environ['CELERY_LOADER'] = 'django' virtenv = os.path.expanduser("~/webapps/django/oneclickcosvirt/") activate_this = virtenv + "bin/activate_this.py" execfile(activate_this, dict(__file__=activate_this)) # if 'VIRTUAL_ENV' not in os.environ: # os.environ['VIRTUAL_ENV'] = virtenv sys.path.append(os.path.dirname(virtenv+'oneclickcos/')) logger.debug('About to run WSGIHandler') try: application = WSGIHandler() except (Exception,), e: logger.debug('Exception starting wsgihandler: %s' % e) raise e

    Read the article

  • Django - how to write users and profiles handling in best way?

    - by SpankMe
    Hey, I am writing simple site that requires users and profiles to be handled. The first initial thought is to use django's build in user handling, but then the user model is too narrow and does not contain fields that I need. The documentation mentions user profiles, but user profiles section has been removed from djangobook covering django 1.0 (ideally, the solution should work with django 1.2), and the Internet is full of different solutions, not making the choice easier (like user model inheritance, user profiles and django signals, and so on). I would like to know, how to write this in good, modern, fast and secure way. Should I try to extend django builtin user model, or maybe should I create my own user model wide enough to keep all the information I need? Below you may find some specifications and expectations from the working solution: users should be able to register and authenticate every user should have profile (or model with all required fields) users dont need django builtin admin panel, but they need to edit their profiles/models via simple web form Please, let me know how do you solve those issues in your applications, and what is the best current way to handle users with django. Any links to articles/blogs or code examples are highly appreciated!

    Read the article

  • Disabling email-style usernames in Django 1.2 with django-registration

    - by shacker
    Django 1.2 allows usernames to take the form of an email address. Changed in Django 1.2: Usernames may now contain @, +, . and - characters I know that's a much-requested feature, but what if you don't want the new behavior? It makes for messy usernames in profile URLs and seems to break django-registration (if a user registers an account with an email-style username, the link in the django-registration activation email returns 404). Does anyone have a recipe for restoring the old behavior and disabling email-style usernames?

    Read the article

  • Does Django cache url regex patterns somehow?

    - by Emre Sevinç
    I'm a Django newbie who needs help: Even though I change some urls in my urls.py I keep on getting the same error message from Django. Here is the relevant line from my settings.py: ROOT_URLCONF = 'mydjango.urls' Here is my urls.py: from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^mydjango/', include('mydjango.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: #(r'^admin/doc/', include(django.contrib.admindocs.urls)), # (r'^polls/', include('mydjango.polls.urls')), (r'^$', 'mydjango.polls.views.homepage'), (r'^polls/$', 'mydjango.polls.views.index'), (r'^polls/(?P<poll_id>\d+)/$', 'mydjango.polls.views.detail'), (r'^polls/(?P<poll_id>\d+)/results/$', 'mydjango.polls.views.results'), (r'^polls/(?P<poll_id>\d+)/vote/$', 'mydjango.polls.views.vote'), (r'^polls/randomTest1/', 'mydjango.polls.views.randomTest1'), (r'^admin/', include(admin.site.urls)), ) So I expect that whenever I visit http://mydjango.yafz.org/polls/randomTest1/ the mydjango.polls.views.randomTest1 function should run because in my polls/views.py I have the relevant function: def randomTest1(request): # mainText = request.POST['mainText'] return HttpResponse("Default random test") However I keep on getting the following error message: Page not found (404) Request Method: GET Request URL: http://mydjango.yafz.org/polls/randomTest1 Using the URLconf defined in mydjango.urls, Django tried these URL patterns, in this order: 1. ^$ 2. ^polls/$ 3. ^polls/(?P<poll_id>\d+)/$ 4. ^polls/(?P<poll_id>\d+)/results/$ 5. ^polls/(?P<poll_id>\d+)/vote/$ 6. ^admin/ 7. ^polls/randomTest/$ The current URL, polls/randomTest1, didn't match any of these. I'm surprised because again and again I check urls.py and there is no ^polls/randomTest/$ in it, but there is ^polls/randomTest1/' It seems like Django is somehow storing the previous contents of urls.py and I just don't know how to make my latest changes effective. Any ideas? Why do I keep on seeing some old version of regexes when I try to load that page even though I changed my urls.py?

    Read the article

  • force delete row on django app after migration

    - by unsorted
    After a migration with south, I ended up deleting a column. Now the current data in one of my tables is screwed up and I want to delete it, but attempts to delete just result in an error: >>> d = Degree.objects.all() >>> d.delete() Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Python26\lib\site-packages\django\db\models\query.py", line 440, in d elete for i, obj in izip(xrange(CHUNK_SIZE), del_itr): File "C:\Python26\lib\site-packages\django\db\models\query.py", line 106, in _ result_iter self._fill_cache() File "C:\Python26\lib\site-packages\django\db\models\query.py", line 760, in _ fill_cache self._result_cache.append(self._iter.next()) File "C:\Python26\lib\site-packages\django\db\models\query.py", line 269, in i terator for row in compiler.results_iter(): File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py", line 67 2, in results_iter for rows in self.execute_sql(MULTI): File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py", line 72 7, in execute_sql cursor.execute(sql, params) File "C:\Python26\lib\site-packages\django\db\backends\util.py", line 15, in e xecute return self.cursor.execute(sql, params) File "C:\Python26\lib\site-packages\django\db\backends\sqlite3\base.py", line 200, in execute return Database.Cursor.execute(self, query, params) DatabaseError: no such column: students_degree.abbrev >>> Is there a simple way to just force a delete? Do I drop the table and then rerun manage.py schemamigration to recreate the table in south?

    Read the article

  • 2-step user registration with Django

    - by David S
    I'm creating a website with Django and want a fairly common 2-step user registration. What I mean by this is that the user fills in the some basic user information + some application specific information (sort of like a coupon value). Upon submit, an email is sent to ensure email address is valid. This email should contain a link to click on to "finish" the registration. When the link is clicked, the user is marked as validated and they are directed to a new page to complete optional "user profile" type information. So, pretty basic stuff. I have done some research and found django-registration by James Bennett. I do know who James is and have seen him at PyCons and DjanoCons in the past. There is obviously very few people in the world that know Django better than James (so, I know the quality of the code/app is good). But, it almost seems like a bit of over kill. I've read through the docs and was a bit confused (maybe I'm just being a bit dense today). I believe that if I do use django-registration, I will need to have some custom forms, etc. Is there anything else out there I should evaluate? Or are there any good tutorials or videos on using django-registration? I've done a bit of googling, but haven't found anything. But, I suspect that it might be a case of a lot of very common words that don't really find what you are looking for (django user registration tutorial/example). Or is just a case where it would be just about as easy to build your own solution with Django forms, etc? Here is the tech stack I'm using: Python 2.7.2 Django 1.3.1 PostgreSQL 9.1 psycopg2 2.4.1 Twitter Bootstrap 2.0.2

    Read the article

  • error in implementing static files in django

    - by POOJA GUPTA
    my settings.py file:- STATIC_ROOT = '/home/pooja/Desktop/static/' # URL prefix for static files. STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( '/home/pooja/Desktop/mysite/search/static', ) my urls.py file:- from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^search/$','search.views.front_page'), url(r'^admin/', include(admin.site.urls)), ) urlpatterns += staticfiles_urlpatterns() I have created an app using django which seraches the keywords in 10 xml documents and then return their frequency count displayed as graphical representation and list of filenames and their respective counts.Now the list has filenames hyperlinked, I want to display them on the django server when user clicks them , for that I have used static files provision in django. Hyperlinking has been done in this manner: <ul> {% for l in list1 %} <li><a href="{{STATIC_URL}}static/{{l.file_name}}">{{l.file_name}}</a{{l.frequency_count</li> {% endfor %} </ul> Now when I run my app on the server, everything is running fine but as soon as I click on the filename, it gives me this error : Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^search/$ ^admin/ ^static\/(?P<path>.*)$ The current URL, search/static/books.xml, didn't match any of these. I don't know why this error is coming, because I have followed the steps required to achieve this. I have posted my urls.py file and it is showing error in that only. I'm new to django , so Please help

    Read the article

  • How to make a model instance read-only after saving it once?

    - by Ryszard Szopa
    One of the functionalities in a Django project I am writing is sending a newsletter. I have a model, Newsletter and a function, send_newsletter, which I have registered to listen to Newsletter's post_save signal. When the newsletter object is saved via the admin interface, send_newsletter checks if created is True, and if yes it actually sends the mail. However, it doesn't make much sense to edit a newsletter that has already been sent, for the obvious reasons. Is there a way of making the Newsletter object read-only once it has been saved? Edit: I know I can override the save method of the object to raise an error or do nothin if the object existed. However, I don't see the point of doing that. As for the former, I don't know where to catch that error and how to communicate the user the fact that the object wasn't saved. As for the latter, giving the user false feedback (the admin interface saying that the save succeded) doesn't seem like a Good Thing. What I really want is allow the user to use the Admin interface to write the newsletter and send it, and then browse the newsletters that have already been sent. I would like the admin interface to show the data for sent newsletters in an non-editable input box, without the "Save" button. Alternatively I would like the "Save" button to be inactive.

    Read the article

  • django internationalization doesn't work

    - by xRobot
    I have: * created translation strings in the template and in the application view. * run this command: django-admin.py makemessages -l it and the file it/LC_MESSAGES/django.po has been created * translated strings in the django.po file. * run this command: django-admin.py compilemessages and I receive: processing file django.po in /home/jobber/Desktop/library/books/locale/it/LC_MESSAGES * set this in settings.py: LANGUAGE_CODE = 'it' TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", ) USE_I18N = True MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) but.... translation doesn't work !! I always see english text. Why ?

    Read the article

  • Programmatically specifying Django model attributes

    - by mojbro
    Hi! I would like to add attributes to a Django models programmatically, at run time. For instance, lets say I have a Car model class and want to add one price attribute (database column) per currency, given a list of currencies. What is the best way to do this? I had an approach that I thought would work, but it didn't exactly. This is how I tried doing it, using the car example above: from django.db import models class Car(models.Model): name = models.CharField(max_length=50) currencies = ['EUR', 'USD'] for currency in currencies: Car.add_to_class('price_%s' % currency.lower(), models.IntegerField()) This does seem to work pretty well at first sight: $ ./manage.py syncdb Creating table shop_car $ ./manage.py dbshell shop=# \d shop_car Table "public.shop_car" Column | Type | Modifiers -----------+-----------------------+------------------------------------------------------- id | integer | not null default nextval('shop_car_id_seq'::regclass) name | character varying(50) | not null price_eur | integer | not null price_usd | integer | not null Indexes: "shop_car_pkey" PRIMARY KEY, btree (id) But when I try to create a new Car, it doesn't really work anymore: >>> from shop.models import Car >>> mycar = Car(name='VW Jetta', price_eur=100, price_usd=130) >>> mycar <Car: Car object> >>> mycar.save() Traceback (most recent call last): File "<console>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/base.py", line 410, in save self.save_base(force_insert=force_insert, force_update=force_update) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/base.py", line 495, in save_base result = manager._insert(values, return_id=update_pk) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/manager.py", line 177, in _insert return insert_query(self.model, values, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/query.py", line 1087, in insert_query return query.execute_sql(return_id) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/sql/subqueries.py", line 320, in execute_sql cursor = super(InsertQuery, self).execute_sql(None) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/sql/query.py", line 2369, in execute_sql cursor.execute(sql, params) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/util.py", line 19, in execute return self.cursor.execute(sql, params) ProgrammingError: column "price_eur" specified more than once LINE 1: ...NTO "shop_car" ("name", "price_eur", "price_usd", "price_eur... ^

    Read the article

  • Django: CharField with fixed length, how?

    - by Giovanni Di Milia
    Hi everybody, I wold like to have in my model a CharField with fixed length. In other words I want that only a specified length is valid. I tried to do something like volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) but it gives me an error (it seems that I can use both max_length and min_length at the same time). Is there another quick way? Thanks EDIT: Following the suggestions of some people I will be a bit more specific: My model is this: class Volume(models.Model): vid = models.AutoField(primary_key=True) jid = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal") volumenumber = models.CharField('Volume Number') date_publication = models.CharField('Date of Publication', max_length=6, blank=True) class Meta: db_table = u'volume' verbose_name = "Volume" ordering = ['jid', 'volumenumber'] unique_together = ('jid', 'volumenumber') def __unicode__(self): return (str(self.jid) + ' - ' + str(self.volumenumber)) What I want is that the volumenumber must be exactly 4 characters. I.E. if someone insert '4b' django gives an error because it expects a string of 4 characters. So I tried with volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) but it gives me this error: Validating models... Unhandled exception in thread started by <function inner_run at 0x70feb0> Traceback (most recent call last): File "/Library/Python/2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Python/2.5/site-packages/django/core/management/validation.py", line 28, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 131, in get_app_errors self._populate() File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 58, in _populate self.load_app(app_name, True) File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 74, in load_app models = import_module('.models', app_name) File "/Library/Python/2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 120, in <module> class Volume(models.Model): File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 123, in Volume volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) TypeError: __init__() got an unexpected keyword argument 'min_length' That obviously doesn't appear if I use only "max_length" OR "min_length". I read the documentation on the django web site and it seems that I'm right (I cannot use both together) so I'm asking if there is another way to solve the problem. Thanks again

    Read the article

  • django-registration with paypal integration

    - by GrumpyCanuck
    I'm trying to figure out how to integrate django-registration with django-paypal. Being a Django n00b, I'm trying to figure out how to implement a flow like this: User signs up using django-registation with 'active' flag set to 0 After registering, send user to PayPal for a subscription When they come back from PayPal successfully, I want to set 'active' to 1 I've been looking at the django-registration documentation and don't quite understand how to use different backends or implement a flow the way I want. Any tips on how to accomplish this would be greatly appreciated. django-paypal won't be a problem for me as I've done PayPal integration before (in PHP for a self-published book about CakePHP).

    Read the article

  • extending django usermodel

    - by imran-glt
    Hi i am trying to create a signup form for my django app. for this i have extended the user model. This is my Forms.py from contact.models import register from django import forms from django.contrib import auth class registerForm(forms.ModelForm): class Meta: model=register fields = ('latitude', 'longitude', 'status') class Meta: model = auth.models.User # this gives me the User fields fields = ('username', 'first_name', 'last_name', 'email') and this is my model.py from django.db import models from django.contrib.auth.models import User STATUS_CHOICES = ( ('Online', 'Online.'), ('Busy', 'Busy.'), ('AppearOffline', 'AppearOffline.'),) class register(models.Model): user = models.ForeignKey('auth.User', unique = True) latitude = models.DecimalField(max_digits=8, decimal_places=6) longitude = models.DecimalField(max_digits=8, decimal_places=6) status = models.CharField(max_length=8,choices=STATUS_CHOICES, blank= True, null=True) i dont know where i am making a mistake. the users passwords are not accepted at the login and the latitude and logitude are not saved against the created user user. i am fiarly new to django and dont know what to do any body have any solution .?

    Read the article

  • django objects.all() method issue

    - by xlione
    after I saved one item using MyModelClass.save() method of django in one view/page , at another view I use MyModelClass.objects.all() to list all items in MyModelClass but the newly added one always is missing at the new page. i am using django 1.1 i am using mysql middleware setting MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.locale.LocaleMiddleware', ) my model: class Company(models.Model): name = models.CharField(max_length=500) description = models.CharField(max_length=500,null=True) addcompany view def addcompany(request): if request.POST: form = AddCompanyForm(request.POST) if form.is_valid(): companyname = form.cleaned_data['companyname'] c = Company(name=companyname,description='description') c.save() return HttpResponseRedirect('/admins/') else: form = AddCompanyForm() return render_to_response('user/addcompany.html',{'form':form},context_instance=RequestContext(request)) after this page in another view i called this form in another view class CompanyForm(forms.Form): companies=((0,' '),) for o in CcicCompany.objects.all(): x=o.id,o.name companies+=(x,) company = forms.ChoiceField(choices=companies,label='Company Name') to list all companies but the recently added one is missing. The transaction should be successful, since after i do a apache server reboot , i can see the newly added company name Thanks for any help...

    Read the article

  • Profiles and using the local profile for a domain user

    - by Harry
    I’m having some trouble with profiles and would like to reach out for some help. I’ve tried to do some research to help myself along, but I’m not making much progress on my own. I’ve pretty much taken over the sys admin duties for my small lab, I don’t have much experience to justify it besides I’m the only with the time and dedication to go at it (The environment was in a state of disrepair). My network and domain I look over are extremely small by most standards, about 10 users at a time. They are pretty intensive activity on the network, and we do work with fairly large files. None of the network is online, which is nice at the moment because it allows me not to have another headache. On to my profile problem, I have set up roaming profiles for the users in the network. Now after a little research, I think I will be switching this to a hybrid of folder redirection and roaming profiles as this seems to best practice. I also don’t want the users having to wait for a long time if they have a bloated profile. Now I’ve finally got a build working using MDT. We have Mac Pros, and it wasn’t fun getting everything to play nice. The way I did this was by setting up a reference computer and installing all the software and tools that each user would need and editing the settings preferences to how we would need them. I think used MDT to do a sys prep and capture to create the image of my reference computer. Using the reference image I can push out my images to the rest of the desktops in my environment. The issue I’m having is when we join the computer to domain. The user can login and operate fine on the computer, but I’d like a more. When the user is logged on with their domain user name they lose a lot of the icons I had on my reference image, as well as the desktop background and some other miscellaneous settings. I would love to have the user log on using their domain user name and see the icons and desktop environment as I had it setup on the reference computer. I’m not sure if it is possible, or something simple that I’m missing, but any help would be greatly appreciated!

    Read the article

  • Transfer Win8 user settings between profiles [closed]

    - by GlennFerrieLive
    Possible Duplicate: How do I sync grouped Windows Store apps between devices? Is there a way for me to copy/save/transfer my "start menu" configuration, meaning the grouping and ordering of the elements on the Start screen, between user profiles? Is it in the registry? I am open to manual or "coded" suggestions. UPDATE: I'd like to VETO this closing. I am aware of the "roaming" profile behavior. I want to COPY my configuration BETWEEN profiles on the same machine.... DIFFERENT profile DIFFERENT person. I like the way my start screen is set up. i want to set my wife up with the same layout.

    Read the article

  • Profile System: User share the same id

    - by Malcolm Frexner
    I have a strange effect on my site when it is under heavy load. I randomly get the properties of other users settings. I have my own implementation of the profile system so I guess I can not blame the profile system itself. I just need a point to start debugging from. I guess there is a cookie-value that maps to an Profile entry somewhere. Is there any chance to see how this mapping works? Here is my profile provider: using System; using System.Text; using System.Configuration; using System.Web; using System.Web.Profile; using System.Collections; using System.Collections.Specialized; using B2CShop.Model; using log4net; using System.Collections.Generic; using System.Diagnostics; using B2CShop.DAL; using B2CShop.Model.RepositoryInterfaces; [assembly: log4net.Config.XmlConfigurator()] namespace B2CShop.Profile { public class B2CShopProfileProvider : ProfileProvider { private static readonly ILog _log = LogManager.GetLogger(typeof(B2CShopProfileProvider)); // Get an instance of the Profile DAL using the ProfileDALFactory private static readonly B2CShop.DAL.UserRepository dal = new B2CShop.DAL.UserRepository(); // Private members private const string ERR_INVALID_PARAMETER = "Invalid Profile parameter:"; private const string PROFILE_USER = "User"; private static string applicationName = B2CShop.Model.Configuration.ApplicationConfiguration.MembershipApplicationName; /// <summary> /// The name of the application using the custom profile provider. /// </summary> public override string ApplicationName { get { return applicationName; } set { applicationName = value; } } /// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "B2C Shop Custom Provider"); } if (string.IsNullOrEmpty(name)) name = "b2c_shop"; if (config["applicationName"] != null && !string.IsNullOrEmpty(config["applicationName"].Trim())) applicationName = config["applicationName"]; base.Initialize(name, config); } /// <summary> /// Returns the collection of settings property values for the specified application instance and settings property group. /// </summary> /// <param name="context">A System.Configuration.SettingsContext describing the current application use.</param> /// <param name="collection">A System.Configuration.SettingsPropertyCollection containing the settings property group whose values are to be retrieved.</param> /// <returns>A System.Configuration.SettingsPropertyValueCollection containing the values for the specified settings property group.</returns> public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection) { string username = (string)context["UserName"]; bool isAuthenticated = (bool)context["IsAuthenticated"]; //if (!isAuthenticated) return null; int uniqueID = dal.GetUniqueID(username, isAuthenticated, false, ApplicationName); SettingsPropertyValueCollection svc = new SettingsPropertyValueCollection(); foreach (SettingsProperty prop in collection) { SettingsPropertyValue pv = new SettingsPropertyValue(prop); switch (pv.Property.Name) { case PROFILE_USER: if (!String.IsNullOrEmpty(username)) { pv.PropertyValue = GetUser(uniqueID); } break; default: throw new ApplicationException(ERR_INVALID_PARAMETER + " name."); } svc.Add(pv); } return svc; } /// <summary> /// Sets the values of the specified group of property settings. /// </summary> /// <param name="context">A System.Configuration.SettingsContext describing the current application usage.</param> /// <param name="collection">A System.Configuration.SettingsPropertyValueCollection representing the group of property settings to set.</param> public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { string username = (string)context["UserName"]; CheckUserName(username); bool isAuthenticated = (bool)context["IsAuthenticated"]; int uniqueID = dal.GetUniqueID(username, isAuthenticated, false, ApplicationName); if (uniqueID == 0) { uniqueID = dal.CreateProfileForUser(username, isAuthenticated, ApplicationName); } foreach (SettingsPropertyValue pv in collection) { if (pv.PropertyValue != null) { switch (pv.Property.Name) { case PROFILE_USER: SetUser(uniqueID, (UserInfo)pv.PropertyValue); break; default: throw new ApplicationException(ERR_INVALID_PARAMETER + " name."); } } } UpdateActivityDates(username, false); } // Profile gettters // Retrieve UserInfo private static UserInfo GetUser(int userID) { return dal.GetUser(userID); } // Update account info private static void SetUser(int uniqueID, UserInfo user) { user.UserID = uniqueID; dal.SetUser(user); } // UpdateActivityDates // Updates the LastActivityDate and LastUpdatedDate values // when profile properties are accessed by the // GetPropertyValues and SetPropertyValues methods. // Passing true as the activityOnly parameter will update // only the LastActivityDate. private static void UpdateActivityDates(string username, bool activityOnly) { dal.UpdateActivityDates(username, activityOnly, applicationName); } /// <summary> /// Deletes profile properties and information for the supplied list of profiles. /// </summary> /// <param name="profiles">A System.Web.Profile.ProfileInfoCollection of information about profiles that are to be deleted.</param> /// <returns>The number of profiles deleted from the data source.</returns> public override int DeleteProfiles(ProfileInfoCollection profiles) { int deleteCount = 0; foreach (ProfileInfo p in profiles) if (DeleteProfile(p.UserName)) deleteCount++; return deleteCount; } /// <summary> /// Deletes profile properties and information for profiles that match the supplied list of user names. /// </summary> /// <param name="usernames">A string array of user names for profiles to be deleted.</param> /// <returns>The number of profiles deleted from the data source.</returns> public override int DeleteProfiles(string[] usernames) { int deleteCount = 0; foreach (string user in usernames) if (DeleteProfile(user)) deleteCount++; return deleteCount; } // DeleteProfile // Deletes profile data from the database for the specified user name. private static bool DeleteProfile(string username) { CheckUserName(username); return dal.DeleteAnonymousProfile(username, applicationName); } // Verifies user name for sise and comma private static void CheckUserName(string userName) { if (string.IsNullOrEmpty(userName) || userName.Length > 256 || userName.IndexOf(",") > 0) throw new ApplicationException(ERR_INVALID_PARAMETER + " user name."); } /// <summary> /// Deletes all user-profile data for profiles in which the last activity date occurred before the specified date. /// </summary> /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are deleted.</param> /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the System.Web.Profile.ProfileInfo.LastActivityDate value of a user profile occurs on or before this date and time, the profile is considered inactive.</param> /// <returns>The number of profiles deleted from the data source.</returns> public override int DeleteInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { string[] userArray = new string[0]; dal.GetInactiveProfiles((int)authenticationOption, userInactiveSinceDate, ApplicationName).CopyTo(userArray, 0); return DeleteProfiles(userArray); } /// <summary> /// Retrieves profile information for profiles in which the user name matches the specified user names. /// </summary> /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param> /// <param name="usernameToMatch">The user name to search for.</param> /// <param name="pageIndex">The index of the page of results to return.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">When this method returns, contains the total number of profiles.</param> /// <returns>A System.Web.Profile.ProfileInfoCollection containing user-profile information // for profiles where the user name matches the supplied usernameToMatch parameter.</returns> public override ProfileInfoCollection FindProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { CheckParameters(pageIndex, pageSize); return GetProfileInfo(authenticationOption, usernameToMatch, null, pageIndex, pageSize, out totalRecords); } /// <summary> /// Retrieves profile information for profiles in which the last activity date occurred on or before the specified date and the user name matches the specified user name. /// </summary> /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param> /// <param name="usernameToMatch">The user name to search for.</param> /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the System.Web.Profile.ProfileInfo.LastActivityDate value of a user profile occurs on or before this date and time, the profile is considered inactive.</param> /// <param name="pageIndex">The index of the page of results to return.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">When this method returns, contains the total number of profiles.</param> /// <returns>A System.Web.Profile.ProfileInfoCollection containing user profile information for inactive profiles where the user name matches the supplied usernameToMatch parameter.</returns> public override ProfileInfoCollection FindInactiveProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { CheckParameters(pageIndex, pageSize); return GetProfileInfo(authenticationOption, usernameToMatch, userInactiveSinceDate, pageIndex, pageSize, out totalRecords); } /// <summary> /// Retrieves user profile data for all profiles in the data source. /// </summary> /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param> /// <param name="pageIndex">The index of the page of results to return.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">When this method returns, contains the total number of profiles.</param> /// <returns>A System.Web.Profile.ProfileInfoCollection containing user-profile information for all profiles in the data source.</returns> public override ProfileInfoCollection GetAllProfiles(ProfileAuthenticationOption authenticationOption, int pageIndex, int pageSize, out int totalRecords) { CheckParameters(pageIndex, pageSize); return GetProfileInfo(authenticationOption, null, null, pageIndex, pageSize, out totalRecords); } /// <summary> /// Retrieves user-profile data from the data source for profiles in which the last activity date occurred on or before the specified date. /// </summary> /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param> /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the System.Web.Profile.ProfileInfo.LastActivityDate of a user profile occurs on or before this date and time, the profile is considered inactive.</param> /// <param name="pageIndex">The index of the page of results to return.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">When this method returns, contains the total number of profiles.</param> /// <returns>A System.Web.Profile.ProfileInfoCollection containing user-profile information about the inactive profiles.</returns> public override ProfileInfoCollection GetAllInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { CheckParameters(pageIndex, pageSize); return GetProfileInfo(authenticationOption, null, userInactiveSinceDate, pageIndex, pageSize, out totalRecords); } /// <summary> /// Returns the number of profiles in which the last activity date occurred on or before the specified date. /// </summary> /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param> /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the System.Web.Profile.ProfileInfo.LastActivityDate of a user profile occurs on or before this date and time, the profile is considered inactive.</param> /// <returns>The number of profiles in which the last activity date occurred on or before the specified date.</returns> public override int GetNumberOfInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { int inactiveProfiles = 0; ProfileInfoCollection profiles = GetProfileInfo(authenticationOption, null, userInactiveSinceDate, 0, 0, out inactiveProfiles); return inactiveProfiles; } //Verifies input parameters for page size and page index. private static void CheckParameters(int pageIndex, int pageSize) { if (pageIndex < 1 || pageSize < 1) throw new ApplicationException(ERR_INVALID_PARAMETER + " page index."); } //GetProfileInfo //Retrieves a count of profiles and creates a //ProfileInfoCollection from the profile data in the //database. Called by GetAllProfiles, GetAllInactiveProfiles, //FindProfilesByUserName, FindInactiveProfilesByUserName, //and GetNumberOfInactiveProfiles. //Specifying a pageIndex of 0 retrieves a count of the results only. private static ProfileInfoCollection GetProfileInfo(ProfileAuthenticationOption authenticationOption, string usernameToMatch, object userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { ProfileInfoCollection profiles = new ProfileInfoCollection(); totalRecords = 0; // Count profiles only. if (pageSize == 0) return profiles; int counter = 0; int startIndex = pageSize * (pageIndex - 1); int endIndex = startIndex + pageSize - 1; DateTime dt = new DateTime(1900, 1, 1); if (userInactiveSinceDate != null) dt = (DateTime)userInactiveSinceDate; /* foreach(CustomProfileInfo profile in dal.GetProfileInfo((int)authenticationOption, usernameToMatch, dt, applicationName, out totalRecords)) { if(counter >= startIndex) { ProfileInfo p = new ProfileInfo(profile.UserName, profile.IsAnonymous, profile.LastActivityDate, profile.LastUpdatedDate, 0); profiles.Add(p); } if(counter >= endIndex) { break; } counter++; } */ return profiles; } } } This is how I use it in the controller: public ActionResult AddTyreToCart(CartViewModel model) { string profile = Request.IsAuthenticated ? Request.AnonymousID : User.Identity.Name; } I would like to debug: How can 2 users who provide different cookies get the same profileid? EDIT Here is the code for getuniqueid public int GetUniqueID(string userName, bool isAuthenticated, bool ignoreAuthenticationType, string appName) { SqlParameter[] parms = { new SqlParameter("@Username", SqlDbType.VarChar, 256), new SqlParameter("@ApplicationName", SqlDbType.VarChar, 256)}; parms[0].Value = userName; parms[1].Value = appName; if (!ignoreAuthenticationType) { Array.Resize(ref parms, parms.Length + 1); parms[2] = new SqlParameter("@IsAnonymous", SqlDbType.Bit) { Value = !isAuthenticated }; } int userID; object retVal = null; retVal = SqlHelper.ExecuteScalar(ConfigurationManager.ConnectionStrings["SQLOrderB2CConnString"].ConnectionString, CommandType.StoredProcedure, "getProfileUniqueID", parms); if (retVal == null) userID = CreateProfileForUser(userName, isAuthenticated, appName); else userID = Convert.ToInt32(retVal); return userID; } And this is the SP: CREATE PROCEDURE [dbo].[getProfileUniqueID] @Username VarChar( 256), @ApplicationName VarChar( 256), @IsAnonymous bit = null AS BEGIN SET NOCOUNT ON; /* [getProfileUniqueID] created 08.07.2009 mf Retrive unique id for current user */ SELECT UniqueID FROM dbo.Profiles WHERE Username = @Username AND ApplicationName = @ApplicationName AND IsAnonymous = @IsAnonymous or @IsAnonymous = null END

    Read the article

  • django shopping cart as a beginner

    - by Jacques Knie
    Hi, i'm quite new to django and trying to add a shopping cart to a simple webshop. What I need is a simple cart that can be filled and presents its content, which is then sent to the vendor via email. So Satchmo might be too big for this task. Therefore i chose django-cart (http://code.google.com/p/django-cart/) which causes some problems now. 1. Is django-cart the right thing? Or are there any better approaches to this task? 2. As I am a beginner even django-cart makes me struggle. I used the view and the template of the django-cart-website, but writing a form that can be used to add products to the cart took me hours. I probably need help in understanding the general layout of a shopping cart and its integration into a website. 3. Two more specific questions: Is it possible to dynamically populate a formfield in a template (e.g. with {{ object.id }})? Is django-cart able to change (update) the contents of a cart? I hope it's not too many questions at once. Thanks in advance Jacques

    Read the article

  • How to add manytomany field to flatpage admin

    - by valya
    Hello! I have a site with Flatpages, and now I need to be able to add galleries (Gallery model) to the page. This is going to be ManyToManyField, so there is no need to change the flatpages table. But I still can't define ManyToManyField in proxy class. I can define ManyToManyField in Gallery model, but it isn't comfortable for the client. How can I change FlatPage Admin to add a ManyToManyField from Galleries model?

    Read the article

  • Copying contents of a model

    - by Hulk
    If there exists an old data of a model say , query=Emp.objects.filter(pk=profile.id) Is there a easier way to copy the same values into the same model again.. Now that the id will be different so.. I have this requirement. Thanks..

    Read the article

  • Cannot assign - must be a "UserProfile" instance

    - by webvulture
    I have a class UserProfile defined which takes the default user as a foreign key. Now another class A has a foreign key to UserProfile. So for saving any instance in class A, how do i give it the userprofile object. Also, does making a class UserProfile mean that class user is still used and class UserProfile is just some other table? I need to know this as I have to take care of the user profile creation, so I should know what gets stored where? -- Confused

    Read the article

  • Copying contents of a module

    - by Hulk
    If there exists an old data of a model say , query=Emp.objects.filter(pk=profile.id) Is there a easier way to copy the same values into the same model again.. Now that the id will be different so.. I have this requirement. Thanks..

    Read the article

  • MultiWidget in MultiWidget how to compress the first one?

    - by sacabuche
    I have two MultiWidget one inside the other, but the problem is that the MultiWidget contained don't return compress, how do i do to get the right value from the first widget? In this case from SplitTimeWidget class SplitTimeWidget(forms.MultiWidget): """ Widget written to split widget into hours and minutes. """ def __init__(self, attrs=None): widgets = ( forms.Select(attrs=attrs, choices=([(hour,hour) for hour in range(0,24)])), forms.Select(attrs=attrs, choices=([(minute, str(minute).zfill(2)) for minute in range(0,60)])), ) super(SplitTimeWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return [value.hour, value.minute] return [None, None] class DateTimeSelectWidget (forms.MultiWidget): """ A widget that splits date into Date and Hours, minutes, seconds with selects """ date_format = DateInput.format def __init__(self, attrs=None, date_format=None): if date_format: self.date_format = date_format #if time_format: # self.time_format = time_format hours = [(hour,str(hour)+' h') for hour in range(0,24)] minutes = [(minute,minute) for minute in range(0,60)] seconds = minutes #not used always in 0s widgets = ( DateInput(attrs=attrs, format=self.date_format), SplitTimeWidget(attrs=attrs), ) super(DateTimeSelectWidget,self).__init__(widgets, attrs) def decompress(self, value): if value: return [value.date(), value.time()] else: [None, None, None]

    Read the article

  • extending satchmo user profile

    - by z3a
    I'm trying to extend the basic user registration form and profile included in satchmo store, but I'm in problems with that. This what I've done: Create a new app "extendedprofile" Wrote a models.py that extends the satchmo_store.contact.models class and add the custom name fields. wrote an admin.py that unregister the Contact class and register my newapp but this still showing me the default user profile form. Maybe some one can show me the correct way to do this?

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >