Search Results

Search found 3275 results on 131 pages for 'categories'.

Page 9/131 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Magento data-install script

    - by Vladimir Kerkhoff
    I'm trying to build a data install script that I use to setup a new webstore. This script creates the categories, pages and static blocks and default settings for the specific shop (we use a multistore setup to host the shops). In our dev/staging setup this scripts runs great and all categories are build without any problem. But on our live system this script fails. After some debugging I found the difference is in the Flat catalog usage on the live systems. The problem with creating the category with the flat tables enabled is in getting the parent path information based on the parentId given: $parentCategory = Mage::getModel('catalog/category')->load($parentId); Without flat categories enabled this gives a correct parentCategory, but with flat categories enabled it gives an empty object. Why is this behaviour with flat categories enabled?

    Read the article

  • Querying a self referencing join with NHibernate Linq

    - by Ben
    In my application I have a Category domain object. Category has a property Parent (of type category). So in my NHibernate mapping I have: <many-to-one name="Parent" column="ParentID"/> Before I switched to NHibernate I had the ParentId property on my domain model (mapped to the corresponding database column). This made it easy to query for say all top level categories (ParentID = 0): where(c => c.ParentId == 0) However, I have since removed the ParentId property from my domain model (because of NHibernate) so I now have to do the same query (using NHibernate.Linq) like so: public IList<Category> GetCategories(int parentId) { if (parentId == 0) return _catalogRepository.Categories.Where(x => x.Parent == null).ToList(); else return _catalogRepository.Categories.Where(x => x.Parent.Id == parentId).ToList(); } The real impact that I can see, is the sql generated. Instead of a simple 'select x,y,z from categories where parentid = 0' NHibernate generates a left outer join: SELECT this_.CategoryId as CategoryId4_1_, this_.ParentID as ParentID4_1_, this_.Name as Name4_1_, this_.Slug as Slug4_1_, parent1_.CategoryId as CategoryId4_0_, parent1_.ParentID as ParentID4_0_, parent1_.Name as Name4_0_, parent1_.Slug as Slug4_0_ FROM Categories this_ left outer join Categories parent1_ on this_.ParentID = parent1_.CategoryId WHERE this_.ParentID is null Which doesn't seems much less efficient that what I had before. Is there a better way of querying these self referencing joins as it's very tempting to drop the ParentID back onto my domain model for this reason. Thanks, Ben

    Read the article

  • Can someone describe the nested set model from a C#/LINQ perspective?

    - by Chad
    I know the nested set model doesn't pertain to the C# language or LINQ directly... it's what I'm using to develop my web app. For hierarchical data (categories with sub-categories in my case), I'm currently using something similar to the Adjacency List model. At the moment, I've only got 2 levels of categories, but I'd like to take it further and allow for n levels of categories using the nested set model. I'm not quite clear on how to use it in a C# context. Here's the article I'm reading on the nested set model. Though this article cleared up my confusion some, I still have a big ?? in my head: - Is inserting, updating or deleting categories tedious? It looks like the left and right numbers would require re-numbering... what would the LINQ queries look like for the following scenarios? Delete a child node (re-number all node's left/right values) Delete a parent node (what do you do with the orphans?) Move a child node to a different parent node (renumber again) If my understanding is correct, at all times the child node's left/right values will always be between the parent node's left/right values, am I correct? Seems easy enough, if only the categories were static... most likely I need to spend more time to get my head around the concept. Any help is greatly appreciated!

    Read the article

  • Remaking this loop by user?

    - by Elliot
    I'm wondering if theres a best practice for what I'm trying to accomplish... First we have the model categories, categories, has_many posts. Now lets say, users add posts. Now, I have a page, that I want to display only the current user's posts by category. Lets say we have the following categories: A, B, and C User 1, has posted in Categories A and B. In my view I have something like: <% @categories.select {|cat| cat.posts.count > 0}.each do |category| %> <%= category.name %><br/> <% category.posts.select {|post| post.user == current_user}.each do |post| %> <%= post.content %><br/> <% end %> <% end %> For the most part its almost there. The issue is, it will still show an empty category if any posts have been entered in it at all (even if the current user has not input posts into that category. So the question boils down to: How do I make the following loop only count posts in the category from the current user? <% @categories.select {|cat| cat.posts.count 0}.each do |category| % Best, Elliot

    Read the article

  • sqlite3 - stringWithUTF8String is leaking!

    - by Darko Hebrang
    I would appreciate if someone could help me solve my leaking problem. The leaks occur at: aImage, aCategory, aDescription, category and categories. I release them in dealloc, but obviously that is not sufficient: -(void) readListFromDatabase:(char *) sqlStatement { // Setup some globals databaseName = @"mydatabase.sql"; // Get the path to the documents directory and append the databaseName NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath = [documentsDir stringByAppendingPathComponent:databaseName]; // Setup the database object sqlite3 *database; // Init the categories Array categories = [[NSMutableArray alloc] init]; // Open the database from the users filessytem if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { // Setup the SQL Statement and compile it for faster access sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { // Loop through the results and add them to the feeds array while(sqlite3_step(compiledStatement) == SQLITE_ROW) { // Read the data from the result row aImage = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)]; aCategory = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]; aDescription = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)]; // Create a new category object with the data from the database category=[[Category alloc] initWithName:aImage category_name:aCategory description_text:aDescription]; // Add the category object to the categories Array [categories addObject:category]; [category release]; } } // Release the compiled statement from memory sqlite3_finalize(compiledStatement); } sqlite3_close(database); } - (void)dealloc { [databaseName release]; [databasePath release]; [categories release]; [aImage release]; [aCategory release]; [aDescription release]; [category release]; [super dealloc]; }

    Read the article

  • Using multiple named outlets and a wrapper view with no content in Emberjs

    - by user1889776
    I'm trying to use multiple named outlets with Ember.js. Is my approach below correct? Markup: <script type="text/x-handlebars" data-template-name="application"> <div id="mainArea"> {{outlet main_area}} </div> </script> <script type="text/x-handlebars" data-template-name="home"> <ul id="sections"> {{outlet sections}} </ul> <ul id="categories"> {{outlet categories}} </ul> </script> <script type="text/x-handlebars" data-template-name="sections"> {{#each section in controller}} <li><img {{bindAttr src="section.image"}}></li> {{/each}} </script> <script type="text/x-handlebars" data-template-name="categories"> {{#each category in controller}} <img {{bindAttr src="category.image"}}> {{/each}} </script>? JS Code: Here I set the content of the various controllers to data grabbed from a server and connect outlets with their corresponding views. Since the HomeController has no content, set its content to an empty object - a hack to get the rid of this error message: Uncaught Error: assertion failed: Cannot delegate set('categories' ) to the 'content' property of object proxy : its 'content' is undefined. App.Router = Ember.Router.extend({ enableLogging: false, root: Ember.Route.extend({ index: Ember.Route.extend({ route: '/', connectOutlets: function(router){ router.get('sectionsController').set('content',App.Section.find()); router.get('categoriesController').set('content', App.Category.find()); router.get('applicationController').connectOutlet('main_area', 'home'); router.get('homeController').connectOutlet('home', {}); router.get('homeController').connectOutlet('categories', 'categories'); router.get('homeController').connectOutlet('sections', 'sections'); } }) }) });

    Read the article

  • How can I make this SQL query more efficient? PHP.

    - by Alan Grant
    Hi all, I have a system whereby a user can view categories that they've subscribed to individually, and also those that are available in the region they belong in by default. So, the tables are as follows: Categories UsersCategories RegionsCategories I'm querying the db for all the categories within their region, and also all the individual categories that they've subscribed to. My query is as follows: Select * FROM (categories c) LEFT JOIN users_categories uc on uc.category_id = c.id LEFT JOIN regions_categories rc on rc.category_id = c.id WHERE (rc.region_id = ? OR uc.user_id = ?) At least I believe that's the query, I'm creating it using Cake's ORM layer, so the exact one is: $conditions = array( array( "OR" => array ( 'RegionsCategories.region_id' => $region_id, 'UsersCategories.user_id' => $user_id ) )); $this->find('all', $conditions); This turns out to be incredibly slow (sometimes around 20 seconds or so. Each table has around 5,000 rows). Is my design at fault here? How can I retrieve both the users' individual categories and those within their region all in one query without it taking ages? Thanks!

    Read the article

  • Does new JUnit 4.8 @Category render test suites almost obsolete?

    - by grigory
    Given question 'How to run all tests belonging to a certain Category?' and the answer would the following approach be better for test organization? define master test suite that contains all tests (e.g. using ClasspathSuite) design sufficient set of JUnit categories (sufficient means that every desirable collection of sets is identifiable using one or more categories) define targeted test suites based on master test suite and set of categories For example: identify categories for speed (slow, fast), dependencies (mock, database, integration), function (), domain ( demand that each test is properly qualified (tagged) with relevant set of categories. create master test suite using ClasspathSuite (all tests found in classpath) create targeted suites by qualifying master test suite with categories, e.g. mock test suite, fast database test suite, slow integration for domain X test suite, etc. My question is more like soliciting approval rate for such approach vs. classic test suite approach. One unbeatable benefit is that every new test is immediately contained by relevant suites with no suite maintenance. One concern is proper categorization of each test.

    Read the article

  • How to add sub category on my codeigniter php application ?

    - by sagarmatha
    Hello friends I have a view echo "<label for='parent'>Category</label><br/> "; echo form_dropdown('category_id', $categories). "<p>"; controller function create(){ if($this->input->post('name')){ $this->MProducts->addProduct(); $this->session->set_flashdata('message', 'Products Created'); redirect('admin/products/index', 'refresh'); }else{ $data['title'] = "Create Product"; $data['main'] = 'admin_product_create'; $data['categories']= $this->MCats->getTopCategories(); $this->load->vars($data); $this->load->view('dashboard'); } } and the model is function getTopcategories(){ $data = array(); $data[0] = 'root'; $this->db->where('parentid',0); $Q = $this->db->get('categories'); if($Q->num_rows() > 0){ foreach($Q->result_array() as $row){ $data[$row['id']] = $row['name']; } } $Q->free_result(); return $data; } Basically, what i want is we get sub categories when we click categories and 'selected' subcategory id goes to database when we create products, So that we can list products by sub categories. Please help me how do we do that ?

    Read the article

  • Ubuntu Software Center starts, then crashes before fully loaded [closed]

    - by Nathan Weisser
    Possible Duplicate: Software center not opening I am brand new to Linux and Ubuntu, and I couldn't install GIMP without the software center. I looked up earlier how to fix it, and it said to fix my sources list, and I did, but now i get a new error in the terminal. 2012-08-14 15:29:08,941 - softwarecenter.ui.gtk3.app - INFO - setting up proxy 'None' 2012-08-14 15:29:08,954 - softwarecenter.db.database - INFO - open() database: path=None use_axi=True use_agent=True 2012-08-14 15:29:09,407 - softwarecenter.ui.gtk3.app - INFO - building local database 2012-08-14 15:29:09,408 - softwarecenter.db.pkginfo_impl.aptcache - INFO - aptcache.open() 2012-08-14 15:29:17,308 - softwarecenter.db.update - WARNING - Problem creating rebuild path '/var/cache/software-center/xapian_rb'. 2012-08-14 15:29:17,309 - softwarecenter.db.update - WARNING - Please check you have the relevant permissions. 2012-08-14 15:29:17,309 - softwarecenter.db.database - INFO - open() database: path=None use_axi=True use_agent=True 2012-08-14 15:29:18,039 - softwarecenter.backend.reviews - WARNING - Could not get usefulness from server, no username in config file 2012-08-14 15:29:18,431 - softwarecenter.ui.gtk3.app - INFO - show_available_packages: search_text is '', app is None. 2012-08-14 15:29:19,153 - softwarecenter.db.pkginfo_impl.aptcache - INFO - aptcache.open() Traceback (most recent call last): File "/usr/bin/software-center", line 176, in <module> app.run(args) File "/usr/share/software-center/softwarecenter/ui/gtk3/app.py", line 1422, in run self.show_available_packages(args) File "/usr/share/software-center/softwarecenter/ui/gtk3/app.py", line 1352, in show_available_packages self.view_manager.set_active_view(ViewPages.AVAILABLE) File "/usr/share/software-center/softwarecenter/ui/gtk3/session/viewmanager.py", line 154, in set_active_view view_widget.init_view() File "/usr/share/software-center/softwarecenter/ui/gtk3/panes/availablepane.py", line 136, in init_view SoftwarePane.init_view(self) File "/usr/share/software-center/softwarecenter/ui/gtk3/panes/softwarepane.py", line 215, in init_view self.icons, self.show_ratings) File "/usr/share/software-center/softwarecenter/ui/gtk3/views/appview.py", line 69, in __init__ self.helper = AppPropertiesHelper(db, cache, icons) File "/usr/share/software-center/softwarecenter/ui/gtk3/models/appstore2.py", line 109, in __init__ softwarecenter.paths.APP_INSTALL_PATH) File "/usr/share/software-center/softwarecenter/db/categories.py", line 255, in parse_applications_menu category = self._parse_menu_tag(child) File "/usr/share/software-center/softwarecenter/db/categories.py", line 444, in _parse_menu_tag query = self._parse_include_tag(element) File "/usr/share/software-center/softwarecenter/db/categories.py", line 402, in _parse_include_tag xapian.Query.OP_AND) File "/usr/share/software-center/softwarecenter/db/categories.py", line 341, in _parse_and_or_not_tag operator_elem, xapian.Query(), xapian.Query.OP_OR) File "/usr/share/software-center/softwarecenter/db/categories.py", line 385, in _parse_and_or_not_tag q = self.db.xapian_parser.parse_query(s, File "/usr/share/software-center/softwarecenter/db/database.py", line 174, in xapian_parser xapian_parser = self._get_new_xapian_parser() File "/usr/share/software-center/softwarecenter/db/database.py", line 200, in _get_new_xapian_parser xapian_parser.set_database(self.xapiandb) File "/usr/share/software-center/softwarecenter/db/database.py", line 166, in xapiandb self._db_per_thread[thread_name] = self._get_new_xapiandb() File "/usr/share/software-center/softwarecenter/db/database.py", line 179, in _get_new_xapiandb xapiandb = xapian.Database(self._db_pathname) File "/usr/lib/python2.7/dist-packages/xapian/__init__.py", line 3666, in __init__ _xapian.Database_swiginit(self,_xapian.new_Database(*args)) xapian.DatabaseOpeningError: Couldn't detect type of database I'm not sure how to fix the errors, and I couldn't find a topic on them anywhere. Be nice, because I am a two-day old Linux user :/ Tell me if you need my Sources list

    Read the article

  • Why is ListBoxFor not selecting items, but ListBox is?

    - by Roger Rogers
    I have the following code in my view: <%= Html.ListBoxFor(c => c.Project.Categories, new MultiSelectList(Model.Categories, "Id", "Name", new List<int> { 1, 2 }))%> <%= Html.ListBox("MultiSelectList", new MultiSelectList(Model.Categories, "Id", "Name", new List<int> { 1, 2 }))%> The only difference is that the first helper is strongly typed (ListBoxFor), and it fails to show the selected items (1,2), even though the items appear in the list, etc. The simpler ListBox is working as expected. I'm obviously missing something here. I can use the second approach, but this is really bugging me and I'd like to figure it out. For reference, my model is: public class ProjectEditModel { public Project Project { get; set; } public IEnumerable<Project> Projects { get; set; } public IEnumerable<Client> Clients { get; set; } public IEnumerable<Category> Categories { get; set; } public IEnumerable<Tag> Tags { get; set; } public ProjectSlide SelectedSlide { get; set; } } Update I just changed the ListBox name to Project.Categories (matching my model) and it now FAILS to select the item. <%= Html.ListBox("Project.Categories", new MultiSelectList(Model.Categories, "Id", "Name", new List<int> { 1, 2 }))%> I'm obviously not understanding the magic that is happening here. Update 2 Ok, this is purely naming, for example, this works... <%= Html.ListBox("Project_Tags", new MultiSelectList(Model.Tags, "Id", "Name", Model.Project.Tags.Select(t => t.Id)))%> ...because the field name is Project_Tags, not Project.Tags, in fact, anything other than Tags or Project.Tags will work. I don't get why this would cause a problem (other than that it matches the entity name), and I'm not good enough at this to be able to dig in and find out.

    Read the article

  • How to get the clicked element in a dynamically built JQuery Treeview?

    - by Alexander
    I have a product database with several product categories. Each category has a number of sub-categories, which has sub-sub-categories, which has... Well, quite some levels deep. The tree is too huge to load at once, so I need to built it dynamically as users select specific product categories. Here's a snapshot of the product tree. Initially, only the first level is loaded. The second level (Cat. 1.1 and cat. 1.2) is added when the user clicks on cat. 1: <ul id="navigation"> <li id="625212">Product cat. 1 <ul> <li id="625213">Product cat. 1.1 <ul></ul> </li> <li id="625109">Product cat. 1.2 <ul></ul> </li> </ul> </li> <li id="624990">Product cat. 2 <ul></ul> </li> </ul> I intend to extend the tree as users click on specific product categories. I can get the list of sub-categories from a URL that takes the parent product category ID as input and outputs HTML in the format needed by treeview. I cannot use PHP and have to make this work with the .click() event. Here's the code that I have: $(document).ready(function(){ function doSomethingWithData(htmldata, id) { var branches = $(htmldata).appendTo("#navigation #"+id+" ul"); $("#navigation").treeview({ add: branches }); } $("#navigation").treeview({ collapsed: true, unique: true, persist: "location" }); $("#navigation li[id]").click(function() { var id=$(this).attr("id"); if ($("#"+$(this).attr("id")+" ul li").size()==0) { $.get('someurl?id='+$(this).attr("id"), function(data) { doSomethingWithData(data, id); } ) } }); }); The problem I'm having is with the click-event. When clicking on cat 1.1. to extend it one level deeper, it still returns the ID of the top level product category. How can I change the click events so that it will return the ID of the clicked <LI> instead of the top one? If the product category does not have any sub-categories, how can I remove the <UL></UL> and thus inidcating that the tree cannot be expanded any further?

    Read the article

  • How do you redirect pages from a directory to a subdirectory?

    - by kezzman11
    I had recently moved all the content on my website from being in the www.mysite.com/shop directory to being in the root directory. This means that I needed to redirect any request to visit a page with the /shop directory back to the same page in the root directory eg. www.mysite.com/shop/categories/washroom to www.mysite.com/categories/washroom This needed to happen with all pages in my site that were previously using the /shop directory. I was given a solution on here which was: RedirectMatch (^/shop/)(.*) http://www.mysite.com/$2 and it works perfectly however now I have had to switch back to using our old version of our software which is located at the /shop directory so I need the complete opposite redirect now eg. www.mysite.com/categories/washroom to www.mysite.com/shop/categories/washroom Can anyone help me please?

    Read the article

  • Is there a way to disable specific Spybot Immunization rules?

    - by Iszi
    I've been having problems using a desktop sharing application, which I've traced to the Immunization protections applied via Spybot S&D. Specifically, the problem has been narrowed down to the rules in the \SOFTWARE (Plugins) categories under the Internet Explorer groups. Once I disable these Immunization categories, everything in the application works fine. Each of these categories appears to include ~900 protections on the system. I suspect that the root cause of my problems could be narrowed down to just one, or perhaps a handful, of the settings that get applied in these categories. However, I can't find any options in Spybot S&D which would allow me to drill down to the individual protection rules and choose which to enable or disable. Is there something I'm missing, or is this not a feature available via the GUI? If it's not strictly supported in the application, is there a way to work around it by manually editing some of its files or registry settings? Spybot S&D version: 2.2.21.0 Spybot Start Center version: 2.2.21.129 Windows Ultimate x64

    Read the article

  • Include most recent non empty column value in filter

    - by Domenic
    If my data looks like this: Category Sub Category 1 a b 2 c d Which shows that there are two categories: "1", which has sub categories "a" and "b", and "2", which has sub categories "c" and "d". What can I do in excel (for filtering/sorting) to keep rows 1 and 2 together as category "1", instead of the first row as category "1", and the second as category ""? I'm trying to avoid having to do this: Category Sub Category 1 a 1 b 2 c 2 d

    Read the article

  • Mahout - Clustering - "naming" the cluster elements

    - by Mark Bramnik
    I'm doing some research and I'm playing with Apache Mahout 0.6 My purpose is to build a system which will name different categories of documents based on user input. The documents are not known in advance and I don't know also which categories do I have while collecting these documents. But I do know, that all the documents in the model should belong to one of the predefined categories. For example: Lets say I've collected a N documents, that belong to 3 different groups : Politics Madonna (pop-star) Science fiction I don't know what document belongs to what category, but I know that each one of my N documents belongs to one of those categories (e.g. there are no documents about, say basketball among these N docs) So, I came up with the following idea: Apply mahout clustering (for example k-mean with k=3 on these documents) This should divide the N documents to 3 groups. This should be kind of my model to learn with. I still don't know which document really belongs to which group, but at least the documents are clustered now by group Ask the user to find any document in the web that should be about 'Madonna' (I can't show to the user none of my N documents, its a restriction). Then I want to measure 'similarity' of this document and each one of 3 groups. I expect to see that the measurement for similarity between user_doc and documents in Madonna group in the model will be higher than the similarity between the user_doc and documents about politics. I've managed to produce the cluster of documents using 'Mahout in Action' book. But I don't understand how should I use Mahout to measure similarity between the 'ready' cluster group of document and one given document. I thought about rerunning the cluster with k=3 for N+1 documents with the same centroids (in terms of k-mean clustering) and see whether where the new document falls, but maybe there is any other way to do that? Is it possible to do with Mahout or my idea is conceptually wrong? (example in terms of Mahout API would be really good) Thanks a lot and sorry for a long question (couldn't describe it better) Any help is highly appreciated P.S. This is not a home-work project :)

    Read the article

  • Dynamic website SEO development

    - by Pankaj Upadhyay
    I made a website which stayed online for 6 months. During that period the search results for the site were not at all good. Even typing the domain name yielded just two or three category result. Now, I have taken the site down for total redevelopment and redesign. The aim of this question is to know the basics for SEO to be done while redesigning the site. My site will be in ASP.NET MVC 3 and will have main categories, sub categories and sub-sub if any. Then there will be products in those categories. All the data will come from MSSQL DB. Please tell me just the basics required for a dynamic website during development. I want to ensure that google and other engines index all the pages of my site including products or whatever.

    Read the article

  • Online File Library

    - by janvdl
    I'm looking for a preferably PHP and web based system, to run on Ubuntu server. Basically it should be a "file forum" in the sense that users can register and be approved to post files to categories. Users with "read" privileges can then go through the categories and download files. Basically I sort of want a FTP-like system, but it should be as easy to manage users, categories, etc as that of a forum system like vB or phpBB. If it could have a forum look and feel that would also be great, but I don't want any discussions taking place.

    Read the article

  • LinqToSql - Parallel - DataContext and Parallel

    - by Gregoire
    In .NET 4 and multicore environment, does the linq to sql datacontext object take advantage of the new parallels if we use DataLoadOptions.LoadWith? EDIT I know linq to sql does not parallelize ordinary queries. What I want to know is when we specify DataLoadOption.LoadWith, does it use parallelization to perform the match between each entity and its sub entities? Example: using(MyDataContext context = new MyDataContext()) { DataLaodOptions options =new DataLoadOptions(); options.LoadWith<Product>(p=>p.Category); return this.DataContext.Products.Where(p=>p.SomeCondition); } generates the following sql: Select Id,Name from Categories Select Id,Name, CategoryId from Products where p.SomeCondition when all the products are created, will we have a categories.ToArray(); Parallel.Foreach(products, p => { p.Category == categories.FirstOrDefault(c => c.Id == p.CategoryId); }); or categories.ToArray(); foreach(Product product in products) { product.Category = categories.FirstOrDefault(c => c.Id == product.CategoryId); } ?

    Read the article

  • Django manager for _set in model

    - by Daniel Johansson
    Hello, I'm in the progress of learning Django at the moment but I can't figure out how to solve this problem on my own. I'm reading the book Developers Library - Python Web Development With Django and in one chapter you build a simple CMS system with two models (Story and Category), some generic and custom views together with templates for the views. The book only contains code for listing stories, story details and search. I wanted to expand on that and build a page with nested lists for categories and stories. - Category1 -- Story1 -- Story2 - Category2 - Story3 etc. I managed to figure out how to add my own generic object_list view for the category listing. My problem is that the Story model have STATUS_CHOICES if the Story is public or not and a custom manager that'll only fetch the public Stories per default. I can't figure out how to tell my generic Category list view to also use a custom manager and only fetch the public Stories. Everything works except that small problem. I'm able to create a list for all categories with a sub list for all stories in that category on a single page, the only problem is that the list contains non public Stories. I don't know if I'm on the right track here. My urls.py contains a generic view that fetches all Category objects and in my template I'm using the *category.story_set.all* to get all Story objects for that category, wich I then loop over. I think it would be possible to add a if statement in the template and use the VIEWABLE_STATUS from my model file to check if it should be listed or not. The problem with that solution is that it's not very DRY compatible. Is it possible to add some kind of manager for the Category model too that only will fetch in public Story objects when using the story_set on a category? Or is this the wrong way to attack my problem? Related code urls.py (only category list view): urlpatterns += patterns('django.views.generic.list_detail', url(r'^categories/$', 'object_list', {'queryset': Category.objects.all(), 'template_object_name': 'category' }, name='cms-categories'), models.py: from markdown import markdown import datetime from django.db import models from django.db.models import permalink from django.contrib.auth.models import User VIEWABLE_STATUS = [3, 4] class ViewableManager(models.Manager): def get_query_set(self): default_queryset = super(ViewableManager, self).get_query_set() return default_queryset.filter(status__in=VIEWABLE_STATUS) class Category(models.Model): """A content category""" label = models.CharField(blank=True, max_length=50) slug = models.SlugField() class Meta: verbose_name_plural = "categories" def __unicode__(self): return self.label @permalink def get_absolute_url(self): return ('cms-category', (), {'slug': self.slug}) class Story(models.Model): """A hunk of content for our site, generally corresponding to a page""" STATUS_CHOICES = ( (1, "Needs Edit"), (2, "Needs Approval"), (3, "Published"), (4, "Archived"), ) title = models.CharField(max_length=100) slug = models.SlugField() category = models.ForeignKey(Category) markdown_content = models.TextField() html_content = models.TextField(editable=False) owner = models.ForeignKey(User) status = models.IntegerField(choices=STATUS_CHOICES, default=1) created = models.DateTimeField(default=datetime.datetime.now) modified = models.DateTimeField(default=datetime.datetime.now) class Meta: ordering = ['modified'] verbose_name_plural = "stories" def __unicode__(self): return self.title @permalink def get_absolute_url(self): return ("cms-story", (), {'slug': self.slug}) def save(self): self.html_content = markdown(self.markdown_content) self.modified = datetime.datetime.now() super(Story, self).save() admin_objects = models.Manager() objects = ViewableManager() category_list.html (related template): {% extends "cms/base.html" %} {% block content %} <h1>Categories</h1> {% if category_list %} <ul id="category-list"> {% for category in category_list %} <li><a href="{{ category.get_absolute_url }}">{{ category.label }}</a></li> {% if category.story_set %} <ul> {% for story in category.story_set.all %} <li><a href="{{ story.get_absolute_url }}">{{ story.title }}</a></li> {% endfor %} </ul> {% endif %} {% endfor %} </ul> {% else %} <p> Sorry, no categories at the moment. </p> {% endif %} {% endblock %}

    Read the article

  • Build and render infinite hierarchical category tree from self-referential category table

    - by FreshCode
    I have a Categories table in which each category has a ParentId that can refer to any other category's CategoryId that I want to display as multi-level HTML list, like so: <ul class="tree"> <li>Parent Category <ul> <li>1st Child Category <!-- more sub-categories --> </li> <li>2nd Child Category <!-- more sub-categories --> </li> </ul> </li> </ul> Presently I am recursively rendering a partial view and passing down the next category. It works great, but it's wrong because I'm executing queries in a view. How can I render the list into a tree object and cache it for quick display every time I need a list of all hierarchical categories?

    Read the article

  • Entity Framework with ASP.NET MVC. Updating entity problem

    - by Kitaly
    Hi people. I'm trying to update an entity and its related entities as well. For instance, I have a class Car with a property Category and I want to change its Category. So, I have the following methods in the Controller: public ActionResult Edit(int id) { var categories = context.Categories.ToList(); ViewData["categories"] = new SelectList(categories, "Id", "Name"); var car = context.Cars.Where(c => c.Id == id).First(); return PartialView("Form", car); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(Car car) { var category = context.Categories.Where(c => c.Id == car.Category.Id).First(); car.Category = category; context.UpdateCar(car); context.SaveChanges(); return RedirectToAction("Index"); } The UpdateCar method, in ObjectContext class, follows: public void UpdateCar(Car car) { var attachedCar = Cars.Where(c => c.Id == car.Id).First(); ApplyItemUpdates(attachedCar, car); } private void ApplyItemUpdates(EntityObject originalItem, EntityObject updatedItem) { try { ApplyPropertyChanges(originalItem.EntityKey.EntitySetName, updatedItem); ApplyReferencePropertyChanges(updatedItem, originalItem); } catch (InvalidOperationException ex) { Console.WriteLine(ex.ToString()); } } public void ApplyReferencePropertyChanges(IEntityWithRelationships newEntity, IEntityWithRelationships oldEntity) { foreach (var relatedEnd in oldEntity.RelationshipManager.GetAllRelatedEnds()) { var oldRef = relatedEnd as EntityReference; if (oldRef != null) { var newRef = newEntity.RelationshipManager.GetRelatedEnd(oldRef.RelationshipName, oldRef.TargetRoleName) as EntityReference; oldRef.EntityKey = newRef.EntityKey; } } } The problem is that when I set the Category property after the POST in my controller, the entity state changes to Added instead of remaining as Detached. How can I update one-to-one relationship with Entity Framework and ASP.NET MVC without setting all the properties, one by one like this post?

    Read the article

  • How to generate following xml

    - by Mohsan
    hi. i want to generate XML for the following tree type structure. i attached picture. generated xml should be <services> <service> <name>Service 1</name> <categories> <category> <name>Cateogry 1</name> <methods> <method> <name>Method 1</name> </method> </methods> </category> </categories> </service> <service> <name>Service 2</name> <categories> <category> <name>Cateogry 1</name> <methods> <method> <name>Method 1</name> </method> </methods> </category> </categories> </service> <service> <name>Service 3</name> <categories> <category> <name>Cateogry 1</name> <methods> <method> <name>Method 1</name> </method> </methods> </category> </categories> </service> </services>

    Read the article

  • XML Parsing Error - C#

    - by Indebi
    My code is having an XML parsing error at line 7 position 32 and I'm not really sure why Exact Error Dump 5/1/2010 10:21:42 AM System.Xml.XmlException: An error occurred while parsing EntityName. Line 7, position 32. at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.Throw(String res, Int32 lineNo, Int32 linePos) at System.Xml.XmlTextReaderImpl.HandleEntityReference(Boolean isInAttributeValue, EntityExpandType expandType, Int32& charRefEndPos) at System.Xml.XmlTextReaderImpl.ParseAttributeValueSlow(Int32 curPos, Char quoteChar, NodeData attr) at System.Xml.XmlTextReaderImpl.ParseAttributes() at System.Xml.XmlTextReaderImpl.ParseElement() at System.Xml.XmlTextReaderImpl.ParseElementContent() at System.Xml.XmlTextReaderImpl.Read() at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace) at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc) at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace) at System.Xml.XmlDocument.Load(XmlReader reader) at System.Xml.XmlDocument.Load(String filename) at Lookoa.LoadingPackages.LoadingPackages_Load(Object sender, EventArgs e) in C:\Users\Administrator\Documents\Visual Studio 2010\Projects\Lookoa\Lookoa\LoadingPackages.cs:line 30 Xml File, please note this is just a sample because I want the program to work before I begin to fill this repository <repo> <Packages> <TheFirstPackage id="00001" longname="Mozilla Firefox" appver="3.6.3" pkgver="0.01" description="Mozilla Firefox is a free and open source web browser descended from the Mozilla Application Suite and managed by Mozilla Corporation. A Net Applications statistic put Firefox at 24.52% of the recorded usage share of web browsers as of March 2010[update], making it the second most popular browser in terms of current use worldwide after Microsoft's Internet Explorer." cat="WWW" rlsdate="4/8/10" pkgloc="http://google.com"/> </Packages> <categories> <WWW longname="World Wide Web" description="Software that's focus is communication or primarily uses the web for any particular reason."> </WWW> <Fun longname="Entertainment & Other" description="Music Players, Video Players, Games, or anything that doesn't fit in any of the other categories."> </Fun> <Work longname="Productivity" description="Application's commonly used for occupational needs or, stuff you work on"> </Work> <Advanced longname="System & Security" description="Applications that protect the computer from malware, clean the computer, and other utilities."> </Advanced> </categories> </repo> Small part of C# Code //Loading the Package and Category lists //The info from them is gonna populate the listboxes for Category and Packages Repository.Load("repo.info"); XmlNodeList Categories = Repository.GetElementsByTagName("categories"); foreach (XmlNode Category in Categories) { CategoryNumber++; CategoryNames[CategoryNumber] = Category.Name; MessageBox.Show(CategoryNames[CategoryNumber]); } The Messagebox.Show() is just to make sure it's getting the correct results

    Read the article

  • Dynamically adding meta tags using php

    - by rekhasathvika
    Hi, In my site I have a list of categories and I have to put meta keywords and description for them.I have a single page where I will retrieve the categories from the database. Can anyone tell me how to make this much simpler to put meta tags for all the categories. Regards, Rekha http://hiox.org

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >