Search Results

Search found 4773 results on 191 pages for 'django orm'.

Page 3/191 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Django one form for two models

    - by martinthenext
    Hello! I have a ForeignKey relationship between TextPage and Paragraph and my goal is to make front-end TextPage creating/editing form as if it was in ModelAdmin with 'inlines': several field for the TextPage and then a couple of Paragraph instances stacked inline. The problem is that i have no idea about how to validate and save that: @login_required def textpage_add(request): profile = request.user.profile_set.all()[0] if not (profile.is_admin() or profile.is_editor()): raise Http404 PageFormSet = inlineformset_factory(TextPage, Paragraph, extra=5) if request.POST: try: textpageform = TextPageForm(request.POST) # formset = PageFormSet(request.POST) except forms.ValidationError as error: textpageform = TextPageForm() formset = PageFormSet() return render_to_response('textpages/manage.html', { 'formset' : formset, 'textpageform' : textpageform, 'error' : str(error), }, context_instance=RequestContext(request)) # Saving data if textpageform.is_valid() and formset.is_valid(): textpageform.save() formset.save() return HttpResponseRedirect(reverse(consults)) else: textpageform = TextPageForm() formset = PageFormSet() return render_to_response('textpages/manage.html', { 'formset' : formset, 'textpageform' : textpageform, }, context_instance=RequestContext(request)) I know I't a kind of code-monkey style to post code that you don't even expect to work but I wanted to show what I'm trying to accomplish. Here is the relevant part of models.py: class TextPage(models.Model): title = models.CharField(max_length=100) page_sub_category = models.ForeignKey(PageSubCategory, blank=True, null=True) def __unicode__(self): return self.title class Paragraph(models.Model): article = models.ForeignKey(TextPage) title = models.CharField(max_length=100, blank=True, null=True) text = models.TextField(blank=True, null=True) def __unicode__(self): return self.title Any help would be appreciated. Thanks!

    Read the article

  • Django ForeignKey TemplateSyntaxError and ProgrammingError

    - by Daniel Garcia
    This is are my models i want to relate. i want for collection to appear in the form of occurrence. class Collection(models.Model): id = models.AutoField(primary_key=True, null=True) code = models.CharField(max_length=100, null=True, blank=True) address = models.CharField(max_length=100, null=True, blank=True) collection_name = models.CharField(max_length=100) def __unicode__(self): return self.collection_name class Meta: db_table = u'collection' ordering = ('collection_name',) class Occurrence(models.Model): id = models.AutoField(primary_key=True, null=True) reference = models.IntegerField(null=True, blank=True, editable=False) collection = models.ForeignKey(Collection, null=True, blank=True, unique=True), modified = models.DateTimeField(null=True, blank=True, auto_now=True) class Meta: db_table = u'occurrence' Every time i go to check the Occurrence object i get this error TemplateSyntaxError at /admin/hotiapp/occurrence/ Caught an exception while rendering: column occurrence.collection_id does not exist LINE 1: ...LECT "occurrence"."id", "occurrence"."reference", "occurrenc.. And every time i try to add a new occurrence object i get this error ProgrammingError at /admin/hotiapp/occurrence/add/ column occurrence.collection_id does not exist LINE 1: SELECT (1) AS "a" FROM "occurrence" WHERE "occurrence"."coll... What am i doing wrong? or how does ForeignKey works?

    Read the article

  • Django Formset validation with an optional ForeignKey field

    - by Camilo Díaz
    Having a ModelFormSet built with modelformset_factory and using a model with an optional ForeignKey, how can I make empty (null) associations to validate on that form? Here is a sample code: ### model class Prueba(models.Model): cliente = models.ForeignKey(Cliente, null = True) valor = models.CharField(max_length = 20) ### view def test(request): PruebaFormSet = modelformset_factory(model = Prueba, extra = 1) if request.method == 'GET': formset = PruebaFormSet() return render_to_response('tpls/test.html', {'formset' : formset}, context_instance = RequestContext(request)) else: formset = PruebaFormSet(request.POST) # dumb tests, just to know if validating if formset.is_valid(): return HttpResponse('0') else: return HttpResponse('1') In my template, i'm just calling the {{ form.cliente }} method which renders the combo field, however, I want to be able to choose an empty (labeled "------") value, as the FK is optional... but when the form gets submitted it doesn't validate. Is this normal behaviour? How can i make this field to skip required validation?

    Read the article

  • Django MultiWidget Phone Number Field

    - by Birdman
    I want to create a field for phone number input that has 2 text fields (size 3, 3, and 4 respectively) with the common "(" ")" "-" delimiters. Below is my code for the field and the widget, I'm getting the following error when trying to iterate the fields in my form during initial rendering (it happens when the for loop gets to my phone number field): Caught an exception while rendering: 'NoneType' object is unsubscriptable class PhoneNumberWidget(forms.MultiWidget): def __init__(self,attrs=None): wigs = (forms.TextInput(attrs={'size':'3','maxlength':'3'}),\ forms.TextInput(attrs={'size':'3','maxlength':'3'}),\ forms.TextInput(attrs={'size':'4','maxlength':'4'})) super(PhoneNumberWidget, self).__init__(wigs, attrs) def decompress(self, value): return value or None def format_output(self, rendered_widgets): return '('+rendered_widgets[0]+')'+rendered_widgets[1]+'-'+rendered_widgets[2] class PhoneNumberField(forms.MultiValueField): widget = PhoneNumberWidget def __init__(self, *args, **kwargs): fields=(forms.CharField(max_length=3), forms.CharField(max_length=3), forms.CharField(max_length=4)) super(PhoneNumberField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list[0] in fields.EMPTY_VALUES or data_list[1] in fields.EMPTY_VALUES or data_list[2] in fields.EMPTY_VALUES: raise fields.ValidateError(u'Enter valid phone number') return data_list[0]+data_list[1]+data_list[2] class AdvertiserSumbissionForm(ModelForm): business_phone_number = PhoneNumberField(required=True)

    Read the article

  • Django foreign key question

    - by Hulk
    All, i have the following model defined, class header(models.Model): title = models.CharField(max_length = 255) created_by = models.CharField(max_length = 255) def __unicode__(self): return self.id() class criteria(models.Model): details = models.CharField(max_length = 255) headerid = models.ForeignKey(header) def __unicode__(self): return self.id() class options(models.Model): opt_details = models.CharField(max_length = 255) headerid = models.ForeignKey(header) def __unicode__(self): return self.id() AND IN MY VIEWS I HAVE p= header(title=name,created_by=id) p.save() Now the data will be saved to header table .My question is that for this id generated in header table how will save the data to criteria and options table..Please let me know.. Thanks..

    Read the article

  • Django admin site auto populate combo box based on input

    - by user292652
    hi i have to following model class Match(models.Model): Team_one = models.ForeignKey('Team', related_name='Team_one') Team_two = models.ForeignKey('Team', related_name='Team_two') Stadium = models.CharField(max_length=255, blank=True) Start_time = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) Rafree = models.CharField(max_length=255, blank=True) Judge = models.CharField(max_length=255, blank=True) Winner = models.ForeignKey('Team', related_name='winner', blank=True) updated = models.DateTimeField('update date', auto_now=True ) created = models.DateTimeField('creation date', auto_now_add=True ) def save(self, force_insert=False, force_update=False): pass @models.permalink def get_absolute_url(self): return ('view_or_url_name') class MatchAdmin(admin.ModelAdmin): list_display = ('Team_one','Team_two', 'Winner') search_fields = ['Team_one','Team_tow'] admin.site.register(Match, MatchAdmin) i was wondering is their a way to populated the winner combo box once the team one and team two is selected in admin site ?

    Read the article

  • Default value for field in Django model

    - by Daniel Garcia
    Suppose I have a model: class SomeModel(models.Model): id = models.AutoField(primary_key=True) a = models.IntegerField(max_length=10) b = models.CharField(max_length=7) Currently I am using the default admin to create/edit objects of this type. How do I set the field 'a' to have the same number as id? (default=???) Other question Suppose I have a model: event_date = models.DateTimeField( null=True) year = models.IntegerField( null=True) month = models.CharField(max_length=50, null=True) day = models.IntegerField( null=True) How can i set the year, month and day fields by default to be the same as event_date field?

    Read the article

  • How to manually render a Django template for an inlineformset_factory with can_delete = True / False

    - by chefsmart
    I have an inlineformset with a custom Modelform. So it looks something like this: MyInlineFormSet = inlineformset_factory(MyMainModel, MyInlineModel, form=MyCustomInlineModelForm) I am rendering this inlineformset manually in a template so that I have more control over widgets and javascript. So I go in a loop like {% for form in myformset.forms %} and then manually render each field as described on this page http://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template The formset has can_delete = True or can_delete = False depending on whether the user is creating new objects or editing existing ones. Question is, how do I manually render the can_delete checkbox?

    Read the article

  • Django updating db for selected ids

    - by Hulk
    In the following, New row values in DB are 6,8.They are the ids of a field I want to update these some other fields in the table based on these values row_newid=request.POST.get('row_updated_id') //Array row_newdata=request.POST.get('row_updated_data') //Array for newrow in row_newid: //how to update row_newdata for newrow values No for all the ids in row_newid how do i update row_newdata. row_newdata has the values 'a' and 'b' for example. thanks....

    Read the article

  • Upload Image with Django Model Form

    - by jmitchel3
    I'm having difficulty uploading the following model with model form. I can upload fine in the admin but that's not all that useful for a project that limits admin access. #Models.py class Profile(models.Model): name = models.CharField(max_length=128) user = models.ForeignKey(User) profile_pic = models.ImageField(upload_to='img/profile/%Y/%m/') #views.py def create_profile(request): try: profile = Profile.objects.get(user=request.user) except: pass form = CreateProfileForm(request.POST or None, instance=profile) if form.is_valid(): new = form.save(commit=False) new.user = request.user new.save() return render_to_response('profile.html', locals(), context_instance=RequestContext(request)) #Profile.html <form enctype="multipart/form-data" method="post">{% csrf_token %} <tr><td>{{ form.as_p }}</td></tr> <tr><td><button type="submit" class="btn">Submit</button></td></tr> </form> Note: All the other data in the form saves perfectly well, the photo does not upload at all. Thank you for your help!

    Read the article

  • Django: Prefill a ManytoManyField

    - by Emile Petrone
    I have a ManyToManyField on a settings page that isn't rendering. The data was filled when the user registered, and I am trying to prefill that data when the user tries to change it. Thanks in advance for the help! The HTML: {{form.types.label}} {% if add %} {{form.types}} {% else %} {% for type in form.types.all %} {{type.description}} {% endfor %} {% endif %} The View: @csrf_protect @login_required def edit_host(request, host_id, template_name="host/newhost.html"): host = get_object_or_404(Host, id=host_id) if request.user != host.user: return HttpResponseForbidden() form = HostForm(request.POST) if form.is_valid(): if request.method == 'POST': if form.cleaned_data.get('about') is not None: host.about = form.cleaned_data.get('about') if form.cleaned_data.get('types') is not None: host.types = form.cleaned_data.get('types') host.save() form.save_m2m() return HttpResponseRedirect('/users/%d/' % host.user.id) else: form = HostForm(initial={ "about":host.about, "types":host.types, }) data = { "host":host, "form":form } return render_to_response(template_name, data, context_instance=RequestContext(request)) Form: class HostForm(forms.ModelForm): class Meta: model = Host fields = ('types', 'about', ) types = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Type.objects.all(), required=True) about = forms.CharField( widget=forms.Textarea(), required=True) def __init__(self, *args, **kwargs): super(HostForm, self).__init__(*args, **kwargs) self.fields['about'].widget.attrs = { 'placeholder':'Hello!'}

    Read the article

  • Select a subset of foreign key elements in inlineformset_factory in Django

    - by Enis Afgan
    Hello, I have a model with two foreign keys: class Model1(models.Model): model_a = models.ForeignKey(ModelA) model_b = models.ForeignKey(ModelB) value = models.IntegerField() Then, I create an inline formset class, like so: an_inline_formset = inlineformset_factory(ModelA, Model1, fk_name="model_a") and then instantiate it, like so: a_formset = an_inline_formset(request.POST, instance=model_A_object) Once this formset gets rendered in a template/page, there is ChoiceField associated with the model_b field. The problem I'm having is that the elements in the resulting drop down menu include all of the elements found in ModelB table. I need to select a subset of those based on some criteria from ModelB. At the same time, I need to keep the reference to the instance of model_A_object when instantiating inlineformset_factory and, therefore, I can't just use this example. Any suggestions?

    Read the article

  • Django models avoid duplicates

    - by Hulk
    In models, class Getdata(models.Model): title = models.CharField(max_length=255) state = models.CharField(max_length=2, choices=STATE, default="0") name = models.ForeignKey(School) created_by = models.ForeignKey(profile) def __unicode__(self): return self.id() In templates <form> <input type="submit" save the data/> </form> If the user clicks on the save button and the above data is saved in the table how to avoid the duplicates,i.e, if the user again clicks on the same submit button there should not be another entry for the same values.Or is it some this that has to be handeled in views Thanks..

    Read the article

  • Django models avaoid duplicates

    - by Hulk
    In models, class Getdata(models.Model): title = models.CharField(max_length=255) state = models.CharField(max_length=2, choices=STATE, default="0") name = models.ForeignKey(School) created_by = models.ForeignKey(profile) def __unicode__(self): return self.id() In templates <form> <input type="submit" save the data/> </form> If the user clicks on the save button and the above data is saved in the table how to avoid the duplicates,i.e, if the user again clicks on the same submit button there should not be another entry for the same values.Or is it some this that has to be handeled in views Thanks..

    Read the article

  • Default value for hidden field in Django model

    - by Daniel Garcia
    I have this Model: class Occurrence(models.Model): id = models.AutoField(primary_key=True, null=True) reference = models.IntegerField(null=True, editable=False) def save(self): self.collection = self.id super(Occurrence, self).save() I want for the reference field to be hidden and at the same time have the same value as id. This code works if the editable=True but if i want to hide it it doesnt change the value of reference. how can i fix that?

    Read the article

  • Django make model field name a link

    - by Daniel Garcia
    what Im looking to do is to have a link on the name of a field of a model. So when im filling the form using the admin interface i can access some information. I know this doesn't work but shows what i want to do class A(models.Model): item_type = models.CharField(max_length=100, choices=ITEMTYPE_CHOICES, verbose_name="<a href='http://www.quackit.com/html/codes'>Item Type</a>") Other option would be to put a description next to the field. Im not even sure where to start from.

    Read the article

  • Example of persisting an inheritance relationship using ORM

    - by Schemer
    I have some experience with OOP and RDBs, but very little exposure to web programming. I am trying to understand what non-trivial types of problems are solved by ORM. Of course, I am familiar with the need for data persistence, but I have never encountered a need for persisting relationships between objects, a situation which is indicated in many online articles about ORM. I am not asking about the process of persisting a POJO to a database and restoring it later. Nor am I asking about why ORM frameworks are useful -- or a pain in the butt -- for doing so. I am particularly interested in how the need arises to persist and restore relationships between objects. In various documentation, I have seen many examples of persisting POJOs to a database, but the examples have all been for only very simple objects that are essentially nothing more than records anyway: a constructor, some private fields, and getter/setter methods. The motivation for persisting such an "object-record" seems obvious and trivial. This example: Hibernate ORM Tutorial offers such an example, but goes on to discuss mismatch issues of granularity, inheritance, identity, associations, and navigation that are not motivated by the example. If someone could offer a toy example of an instance where, say, the need arises to persist an inheritance relationship, I would be grateful. This might be blindingly obvious for anyone who has already encountered this situation but I have not and a great deal of searching and reading have not turned up any examples.

    Read the article

  • Problem trying to achieve a join using the `comments` contrib in Django

    - by NiKo
    Hi, Django rookie here. I have this model, comments are managed with the django_comments contrib: class Fortune(models.Model): author = models.CharField(max_length=45, blank=False) title = models.CharField(max_length=200, blank=False) slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date') content = models.TextField(blank=False) pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now()) votes = models.IntegerField(default=0) comments = generic.GenericRelation( Comment, content_type_field='content_type', object_id_field='object_pk' ) I want to retrieve Fortune objects with a supplementary nb_comments value for each, counting their respectve number of comments ; I try this query: >>> Fortune.objects.annotate(nb_comments=models.Count('comments')) From the shell: >>> from django_fortunes.models import Fortune >>> from django.db.models import Count >>> Fortune.objects.annotate(nb_comments=Count('comments')) [<Fortune: My first fortune, from NiKo>, <Fortune: Another One, from Dude>, <Fortune: A funny one, from NiKo>] >>> from django.db import connection >>> connection.queries.pop() {'time': '0.000', 'sql': u'SELECT "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes", COUNT("django_comments"."id") AS "nb_comments" FROM "django_fortunes_fortune" LEFT OUTER JOIN "django_comments" ON ("django_fortunes_fortune"."id" = "django_comments"."object_pk") GROUP BY "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes" LIMIT 21'} Below is the properly formatted sql query: SELECT "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes", COUNT("django_comments"."id") AS "nb_comments" FROM "django_fortunes_fortune" LEFT OUTER JOIN "django_comments" ON ("django_fortunes_fortune"."id" = "django_comments"."object_pk") GROUP BY "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes" LIMIT 21 Can you spot the problem? Django won't LEFT JOIN the django_comments table with the content_type data (which contains a reference to the fortune one). This is the kind of query I'd like to be able to generate using the ORM: SELECT "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", COUNT("django_comments"."id") AS "nb_comments" FROM "django_fortunes_fortune" LEFT OUTER JOIN "django_comments" ON ("django_fortunes_fortune"."id" = "django_comments"."object_pk") LEFT OUTER JOIN "django_content_type" ON ("django_comments"."content_type_id" = "django_content_type"."id") GROUP BY "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes" LIMIT 21 But I don't manage to do it, so help from Django veterans would be much appreciated :) Hint: I'm using Django 1.2-DEV Thanks in advance for your help.

    Read the article

  • How do you handle domain logic that spans multiple model objects in an ORM?

    - by duality_
    So I know that business logic should be placed in the model. But using an ORM it is not as clear where I should place code that handles multiple objects. E.g. let's say we have a Customer model which has a type of either sporty or posh and we wanted to customer.add_bonus() to every posh customer. Where would we do this? Do we create a new class to handle all this? If yes, where do we put it (alongside all the other model classes, but not subclass it from the ORM?)? I'm currently using django framework in python, so specific suggestions are even more wanted.

    Read the article

  • Multiple model forms with some pre-populated fields

    - by jimbocooper
    Hi! Hope somebody can help me, since I've been stuck for a while with this... I switched to another task, but now back to the fight I still can't figure out how to come out from the black hole xD The thing is as follows: Let's say I've got a product model, and then a set of Clients which have rights to submit data for the products they've been subscribed (Many to Many from Client to Product). Whenever my client is going to submit data, I need to create as many forms as products he's subscribed, and pre-populate each one of them with the "product" field as long as perform a quite simple validation (some optional fields have to be completed if it's client's first submission). I would like one form "step" for each product submission, so I've tried formWizards... but the problem is you can't pre-assign values to the forms... this can be solved afterwards when submitting, though... but not the problem that it doesn't allow validation either, so at the end of each step I can check some data before rendering next step. Then I've tried model formsets, but then there's no way to pre-populate the needed fields. I came across some django plugins, but I'm not confident yet if any of them will make it.... Did anybody has a similar problem so he can give me a ray of light? Thanks a lot in advance!! :) edit: The code I used in the formsets way is as follows: prods = Products.objects.filter(Q(start_date__lte=today) & Q(end_date__gte=today), requester=client) num = len(prods) PriceSubmissionFormSet = modelformset_factory(PriceSubmission, extra=num) formset = PriceSubmissionFormSet(queryset=PriceSubmission.objects.none())

    Read the article

  • Is ORM an Anti-Pattern?

    - by derphil
    I had a very stimulating and interessting discussion with a colleague about ORM and it's Pros and Cons. In my opinion, an ORM is useful only in the rarest cases. At least in my experience. But I don't want to list my own arguments at this time. So I ask you, what do you think about ORM? What are the Pros and the Cons? P.S. I've posted this "question" yesterday on Stackoverflow, but some of the user think, that this should better posted here.

    Read the article

  • Should we have a database independent SQL like query language in Django?

    - by Yugal Jindle
    Note : I know we have Django ORM already that keeps things database independent and converts to the database specific SQL queries. Once things starts getting complicated it is preferred to write raw SQL queries for better efficiency. When you write raw sql queries your code gets trapped with the database you are using. I also understand its important to use the full power of your database that can-not be achieved with the django orm alone. My Question : Until I use any database specific feature, why should one be trapped with the database. For instance : We have a query with multiple joins and we decided to write a raw sql query. Now, that makes my website postgres specific. Even when I have not used any postgres specific feature. I feel there should be some fake sql language which can translate to any database's sql query. Even Django's ORM can be built over it. So, that if you go out of ORM but not database specific - you can still remain database independent. I asked the same question to Jacob Kaplan Moss (In person) : He advised me to stay with the database that I like and endure its whole power, to which I agree. But my point was not that we should be database independent. My point is we should be database independent until we use a database specific feature. Please explain, why should be there a fake sql layer over the actual sql ?

    Read the article

  • Django: What's an awesome plugin to maintain images in the admin?

    - by meder
    I have an articles entry model and I have an excerpt and description field. If a user wants to post an image then I have a separate ImageField which has the default standard file browser. I've tried using django-filebrowser but I don't like the fact that it requires django-grappelli nor do I necessarily want a flash upload utility - can anyone recommend a tool where I can manage image uploads, and basically replace the file browse provided by django with an imagepicking browser? In the future I'd probably want it to handle image resizing and specify default image sizes for certain article types. Edit: I'm trying out adminfiles now but I'm having issues installing it. I grabbed it and added it to my python path, added it to INSTALLED_APPS, created the databases for it, uploaded an image. I followed the instructions to modify my Model to specify adminfiles_fields and registered but it's not applying in my admin, here's my admin.py for articles: from django.contrib import admin from django import forms from articles.models import Category, Entry from tinymce.widgets import TinyMCE from adminfiles.admin import FilePickerAdmin class EntryForm( forms.ModelForm ): class Media: js = ['/media/tinymce/tiny_mce.js', '/media/tinymce/load.js']#, '/media/admin/filebrowser/js/TinyMCEAdmin.js'] class Meta: model = Entry class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = { 'slug': ['title'] } class EntryAdmin( FilePickerAdmin ): adminfiles_fields = ('excerpt',) prepopulated_fields = { 'slug': ['title'] } form = EntryForm admin.site.register( Category, CategoryAdmin ) admin.site.register( Entry, EntryAdmin ) Here's my Entry model: class Entry( models.Model ): LIVE_STATUS = 1 DRAFT_STATUS = 2 HIDDEN_STATUS = 3 STATUS_CHOICES = ( ( LIVE_STATUS, 'Live' ), ( DRAFT_STATUS, 'Draft' ), ( HIDDEN_STATUS, 'Hidden' ), ) status = models.IntegerField( choices=STATUS_CHOICES, default=LIVE_STATUS ) tags = TagField() categories = models.ManyToManyField( Category ) title = models.CharField( max_length=250 ) excerpt = models.TextField( blank=True ) excerpt_html = models.TextField(editable=False, blank=True) body_html = models.TextField( editable=False, blank=True ) article_image = models.ImageField(blank=True, upload_to='upload') body = models.TextField() enable_comments = models.BooleanField(default=True) pub_date = models.DateTimeField(default=datetime.datetime.now) slug = models.SlugField(unique_for_date='pub_date') author = models.ForeignKey(User) featured = models.BooleanField(default=False) def save( self, force_insert=False, force_update= False): self.body_html = markdown(self.body) if self.excerpt: self.excerpt_html = markdown( self.excerpt ) super( Entry, self ).save( force_insert, force_update ) class Meta: ordering = ['-pub_date'] verbose_name_plural = "Entries" def __unicode__(self): return self.title Edit #2: To clarify I did move the media files to my media path and they are indeed rendering the image area, I can upload fine, the <<<image>>> tag is inserted into my editable MarkItUp w/ Markdown area but it isn't rendering in the MarkItUp preview - perhaps I just need to apply the |upload_tags into that preview. I'll try adding it to my template which posts the article as well.

    Read the article

  • Problem with messages framework in Django 1.2

    - by Konstantin
    Hello! I'm running Django 1.2 beta and trying out the new feature: message framework. http://docs.djangoproject.com/en/dev/ref/contrib/messages/ Everything seems to work, but when I try to output the messages, I get nothing. Seems that messages variable is empty. I double checked all the settings, they seem to be just like in the manual. What could be wrong? settings.py MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', #send messages to users 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', #debug tool 'debug_toolbar.middleware.DebugToolbarMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.messages.context_processors.messages', #send messages to users 'django.core.context_processors.auth', ) #Store messages in sessions MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'; INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #'django.contrib.sites', 'django.contrib.admin', 'django.contrib.messages', 'debug_toolbar', #my apps #... ) views.py def myview(request): from django.contrib import messages messages.error(request, 'error test'); messages.success(request, 'success test'); return render_to_response('mytemplate.html', locals()); mytemplate.html {% for message in messages %} {{ message }}<br /> {% endfor %} In template nothing is outputted.

    Read the article

  • Django 1.4.1 error loading MySQLdb module when attempting 'python manage.py shell'

    - by Paul
    I am trying to set up MySQL, and can't seem to be able to enter the Django manage.py shell interpreter. Getting the output below: rrdhcp-10-32-44-126:django pavelfage$ python manage.py shell Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 371, in handle return self.handle_noargs(**options) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/shell.py", line 45, in handle_noargs from django.db.models.loading import get_models File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/__init__.py", line 40, in <module> backend = load_backend(connection.settings_dict['ENGINE']) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/__init__.py", line 34, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/utils.py", line 92, in __getitem__ backend = load_backend(db['ENGINE']) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/utils.py", line 24, in load_backend return import_module('.base', backend_name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 16, in <module> raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named _mysql Any suggestions really appreciated.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >