Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django- how to 'merge' two serializers
This is my learning model: class Post(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=40) time = models.DateTimeField() content = models.TextField(max_length=250) rating = models.IntegerField(default=1) I was learning how to create Django REST API from youtube, and 'teacher' said that it's better to make one serializer for different actions like when "POST" method you get 'uuid' and 'time', but when "GET" method you get 'name', 'time', 'content' and 'rating'. But on this lesson he want to show it easier way, so he made two serialisers, depends on method: class PostGetSerializer(serializers.ModelSerializer): class Meta: model = Post fields = [ 'name', 'time', 'content', 'rating' ] class PostCreateSerializer(serializers.ModelSerializer): class Meta: model = Post fields = [ 'uuid', 'time', ] I know it is just a small example but I hope you get it. How can I manipulate response data of ONE serializer depends on method? -
django utf8 encoded mysql legacy database from yii
I have and old mysql db that save the data in utf encoded like this "buen dÃa" in my old backend yii1 my api decoded this in "buen día", now i will trying to migrate to django and using restframework but when i go to endpoint the response is "buen dÃa", some way to decode text before return in endpoint? -
Run code exactly once before the Django runserver command
To be clear, i'm not talking exactly once each time the django server reloads. I am aware that can be done using the AppConfig.ready() method I tried overriding the management command, but even that won't work from django.core.management.commands import runserver class Command(runserver.Command): def handle(self, *fixture_labels, **options): print('I want this to get printed exactly once.') super().handle(*fixture_labels, **options) There was also another iteration of above code that involved using the call_command to call runserver, but even that won't do the job. WHY? I want to start a webpack server, just before the runserver command, and exaclty once, meaning that it doesn't run each time the server reloads. -
How get TEXT from SCANNED PDF with django
I try many solutions for get data from scanned pdf but i can't get this: i try this: Converting PDF to images automatically How to extract table as text from the PDF using Python? Convert scanned pdf to text python how to extract text from scanned documents using python this only get empty result dont get erros dont get the text from my pdf please maybe a little suggest or coment thanks to all !! -
What exactly the reason of Import Error here?
Hello Awesome People! A simple question about a thing that I came across and understand the issue but can't figure out why? Not only I do not know for example whether model1 must have the ForeignKey to model2, or model2 with a ManyToManyField to model1 (Confused). Let's suppose we have two(2) models files and three(3) class Model, app1.models.py with [Model1, ModelA] and app2.models.py with [Model2]. app1.models.py from app2.models import Model2 class Model1(models.Model): field1 = models.ForeignKey(Model2) app2.models.py from app1.models import ModelA class Model2(models.Model): field2 = models.ForeignKey(ModelA) This will definitely raise an error ImportError, But if I do: class Model1(models.Model): field1 = models.ForeignKey("app2.Model2") class Model2(models.Model): field2 = models.ForeignKey("app1.ModelA") this will work well Why exactly? I Know that I can create the model in the file needed, but what I want is to understand why one works, and not the other. Thank you! -
Jupyter notebook and django not open - AttributeError
I created a two virtual environment in my Ubuntu OS. First one is py27 and second one py35. My jupyter notebook and Django worked fine. Problem start when I wanted a install mysql-client and I have run this following two command. sudo apt-get install mysql-client conda install MySQL-python When run jupyter notebook command in terminal show this error. AttributeError: type object 'IOLoop' has no attribute 'initialized' When run python3 manage.py runserver command in terminal show this error. ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? How i can fix it. Thanks in advance. -
serving Django static files with Docker, nginx and gunicorn
I am setting us a Django 2.0 application with Docker, nginx and gunicorn. It's running the server but static files are not working. Here is the settings.py content STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_my_project') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'static_root') While development, I put my static files inside static_my_project which on running collectstatic copies to static_cdn/static_root The directory structure is like app |- myapp |- settings.py |- static_my_project |- static_cdn |- static_root |- config |- nginx |- nginx.conf |- manage.py |- Docker |- docker-compose.yml on runnign docker-compose up --build on running collectstatic, it gives path where static files will be copied koober-dev | --: Running collectstatic koober-dev | koober-dev | You have requested to collect static files at the destination myapp-dev | location as specified in your settings: myapp-dev | myapp-dev | /app/static_cdn/static_root myapp-dev | myapp-dev | This will overwrite existing files! myapp-dev | Are you sure you want to do this? myapp-dev | myapp-dev | Type 'yes' to continue, or 'no' to cancel: myapp-dev | 0 static files copied to '/app/static_cdn/static_root', 210 unmodified. the config/nginx/nginx.conf file contains following settings upstream web { ip_hash; server web:9010; } server { location /app/static_cdn/static_root { autoindex on; alias /static/; } location … -
Create a website to run a numerical model and display the results
I would like to create a webpage to accept user inputs (either as a file or several text boxes where user inputs parameters), then it runs a simple numerical model on the server (written in python). After it detects that the run finishes, the webpage will show the results as a series of plots with buttons to cycle through them or simply show a movie of the results. Also I wonder how to deal with multiple users, maybe I need to limit concurrent users since the server would be busy running the numerical model which can get intensive. I do not have much experience in website programming. What is the best way to achieve this? I know PHP is probably the way to go? Should I use Django or some other frameworks? Another question is where to host it? Detailed ideas and instructions are much appreciated. -
Django ManyToMany chained queryset not giving ANDed result
This is leaving me baffled for a while. I've a ManyToMany Relationship established through a table as shown: class Coupon(TimeStampedUUIDModel): venue = models.ManyToManyField('venues.Venue', through='VenueCouponConfig', related_name='coupons') class Meta: verbose_name = _('Coupon') verbose_name_plural = _('Coupons') ordering = ('-created_at', ) class VenueCouponConfig(UUIDModel): venue = models.ForeignKey( 'venues.Venue', null=True, blank=True, on_delete=models.SET_NULL ) coupon = models.ForeignKey( 'Coupon', null=True, blank=True, on_delete=models.SET_NULL ) is_activated = models.BooleanField(_('Activate Coupon'), null=False, blank=True) Essentially, I wanted to make Coupons associated with multiple venues, so I created through table to have is_activated flag per venue which describes if certain coupon is activated for a venue or not. Now, I've this API which lists all the coupons in particular venue like: ... venue = get_object_or_404(self.queryset, pk=pk) qs = Coupon.objects.all() qs = qs.prefetch_related(Prefetch('venuecouponconfig_set')) qs = qs.filter(venue=venue) qs = qs.filter(venuecouponconfig__is_activated=True) qs = qs.order_by('created_at') ... Now the evaluation of this API gives me some coupons multiple times. But if I attach the filter like: ... venue = get_object_or_404(self.queryset, pk=pk) qs = Coupon.objects.all() qs = qs.prefetch_related(Prefetch('venuecouponconfig_set')) qs = qs.filter(venue=venue, venuecouponconfig__is_activated=True) qs = qs.order_by('created_at') ... This gives me correct result and coupons appear single time. Does chain filters work differently with ManyToManyField? Did it not go for doing an AND unless both the things were mentioned in a single … -
Django - Call command line with arguments from view
I am trying to call a command that alters a database from a view. Basically, once the view is loaded, a parameter changes. If I run the command from the terminal, it works, but if I try to call it from the view I keep on getting this error. I would believe there is an error in the way I pass the dictionary as the command works fine from the terminal. It may also be because I am trying to update a model which is being shown to the user at the moment, but I have also tried passing a different ID as an argument and it raises the same error. CommandError at /sample/45/ Error: argument num: invalid int value: "{'num': 45}" Request Method: GET Request URL: http://127.0.0.1:8000/sample/45/ Django Version: 2.0 Exception Type: CommandError Exception Value: Error: argument num: invalid int value: "{'num': 45}" Exception Location: /usr/local/lib/python3.6/dist-packages/django/core/management/base.py in error, line 60 Python Executable: /usr/bin/python3 Python Version: 3.6.5 Python Path: ['/home/ander/Desktop/Proyecto/meduloblastoma/Code/MedulloblastomaProject', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages', '/home/ander/Desktop/Proyecto/meduloblastoma/Code/MedulloblastomaProject'] Server time: Mon, 4 Jun 2018 18:35:37 +0200 This is the code I have used. classify.py from django.core.management.base import BaseCommand from rpy2.robjects.packages import importr import rpy2.robjects as ro from sample.models import Sample class Command(BaseCommand): … -
Django no blank choices for inline formfield
I have a labs with samples. For each lab, I want to display the related samples as inlines. I want to cache queries for each specified field in a model in a generic way. For that I use the OptimizedField class: class LabAdmin(admin.ModelAdmin): model = Lab inlines = (SampleInline,) class SampleInline(MyBaseModelAdmin, admin.TabularInline): model = Sample list_optimized_fields = ( OptimizedField('condition', SampleCondition), ) def __init__(self, *args, **kwargs): super(SampleInline, self).__init__(*args, **kwargs) self.extra = 2 class OptimizedField(object): def __init__(self, name, cls, cache=True): super(OptimizedField, self).__init__(name, cls) self.name = name self.cls = cls self.cache = cache def choices(self): return [ (o.pk, str(o)) for o in self.cls.objects.all() ] Here for each Lab I display inlines for the Sample model, with two extra inlines as templates (`self.extra = 2`). The Sample model looks like this: class Sample(models.Model): name = models.SlugField() lab = models.ForeignKey(Lab) condition = models.ForeignKey( SampleCondition, blank=True, null=True) condition is a foreign key. A Lab page displays an inline for all the samples related to the lab, Each SampleInline has formfield with choices for all existing SampleCondition. This works, but produces duplicated queries. To cache the relevant queries, I overwrite the admin.options.BaseModelAdmin class as follow: class MyBaseModelAdmin(admin.options.BaseModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): formfield = super(MyBaseModelAdmin, self) \ … -
Initialize TypedChoiceField field form dinamically
I need help on how to initialize a django form field, depending on a specific object. The context is: I would like to show the maximum stock of a product to add the shopping cart. forms.py class ShoppingCartForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int, help_text = 'Uds.') models.py @autoconnect class Product(models.Model): category = models.ForeignKey(ShopCategory) name = models.CharField(max_length=100, db_index=True, unique=True) slug = models.SlugField(max_length=100, db_index=True, unique=True, blank=True) description = models.CharField(max_length=500, blank=True) updated_date = models.DateTimeField(auto_now_add=True) created_date = models.DateTimeField(auto_now=True) stock = models.PositiveIntegerField() price = models.DecimalField(max_digits=8, decimal_places=2) # images class Meta: verbose_name = 'product' verbose_name_plural = 'products' def __unicode__(self): return self.name def pre_save(self): self.slug = self.name.replace(' ', '_').lower() views.py def product_list(request, shop_category_slug=None): category = None products = shop_models.Product.objects.filter(stock__gte=1) if shop_category_slug: category = get_object_or_404(shop_models.ShopCategory, slug=shop_category_slug) products = products.filter(category=category) if request.method == 'POST': shop_filter_form = shop_forms.ProductFilter(request.POST) products = products.filter( category=shop_filter_form.cleaned_data['category'], name__contains=shop_filter_form.cleaned_data['name']) else: shop_filter_form = getShopFilter(request) return render(request, 'product_list.html', { 'category': category, 'products': products.order_by("-created_date"), 'categories': getShopCategories(), 'shop_filter_form': shop_filter_form, 'shoppingcart_form': getShoppingCart(), }) -
Django Rest Framework: field name 'likes' is not valid for model 'userPost' improperlyConfigured
In my Django Rest Framework api I am attempting to add a property to my model UserPosts that returns all likes for said post. Despite my best efforts I keep running into this error. Here is my post model below: class UserPosts(models.Model): userProfile = models.ForeignKey(UserProfile, related_name="posts", on_delete=models.CASCADE) image = models.ImageField() caption = models.CharField(max_length=240) @property def get_likes(self): from liked.models import Like return Like(post=self) and here is my like model: class Like(models.Model): user = models.OneToOneField(UserProfile, on_delete=models.CASCADE,) post = models.ForeignKey(UserPosts, on_delete=models.CASCADE) liked_at = models.DateTimeField() and lastly the post serializer: class postSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.UserPosts fields = ('userProfile', 'image', 'caption', 'likes') Thanks. -
Using oauth2 for a Django REST and a client app I'm having trouble with staying logged in at the client side
I'm not really that experienced with Django, and certainly not with authorization, but somehow I haven`t found a good answer to my problem yet. I have two Django applications: one acts more as a server side application (server app) while the other acts more as a client side application (client app). The server app provides a REST api using the django-rest-framework. This api should not be publicly visible, and therefore I've decided to use django-auth-toolkit (oauth 2.0). I've registered an app on the Authorization Server as described here. The app uses authorization type authorization_code and is a public client type. I'm able to obtain the authorization after logging in to the server app and pressing the authorize button for the application subsequently. I`m also able to exchange the authorization code for an access token. So far so good. However at the start of the entire flow I need to login on the client app. Then this client needs to obtain the authorization code using a get request and access code using a post request (which goes fine as mentionedd). These are only possible after successful login at the server app as mentioned (ideally the same login credentials). However, when this … -
Where to register a django signal if the receiver function lives in a management command
I have, effectively, a standalone script, which gets data from an external source and dumps it into the django channel layers. On startup, the script queries the database for all Product objects, which tells it which datasources it needs to join. I'm trying to implement a signal which tells the script when a new Product instance is saved, so that it can join any further sources that might be necessary. I'm using the following code: from django.db.models.signals import post_save from django.dispatch import receiver from home.models import Product @receiver(post_save, sender=Product) def test(sender, **kwargs): print("SUCESS------------------------------------------------------{}".format(sender)) This script lives in f/data_sources/management/commands/source.py, the product model lives in home/models.y. Apparently, I need to somehow import the 'test' function defined in source.py, but I'm not sure how to. It's a huge script, do I import the whole thing? I'm not even sure what the import command would be. -
Can find cookie data in HTTP header using django channel in aws
i need to implement chat functionality using django-channels and daphne==1.4.2 currently i am using Django==1.11.8 and channels==1.1.8 here is how i connect to web socket every thing works fine on my development machine @channel_session_user_from_http def ws_connect(message, project_id): try: print('===>' +str(message['headers'])) project = Project.objects.get(pk=project_id) except Project.DoesNotExist: log.debug('ws project does not exist =%s', project_id) return project.websocket_group.add(message.reply_channel) message.reply_channel.send({"accept": True}) message.channel_session[PROJECTS_CONSUMER] = [project.id] here is output of print message on mymachine [['origin', 'http://127.0.0.1:8000'], ['upgrade', 'websocket'], ['accept-language', 'en-US,en;q=0.8,ar;q=0.6'], ['accept-encoding', 'gzip, deflate, sdch, br'], ['sec-websocket-version', '13'], ['host', '127.0.0.1:5000'], ['sec-websocket-key', 'rXmk9onyr+FnMrb/pIGMfw=='], ['user-agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'], ['dnt', '1'], ['connection', 'Upgrade'], ['cookie', '__utma=96992031.1243626439.1478882614.1489237630.1494370793.13; sessionid=vqmdzrouih61cp4nkn9cq31yyuxdlwfw; style=green; csrftoken=IrUnYo1svitlJwNQrd5nL3l8fKSJSJR0iylrYng7bpZJfUOPwe53OhWrEon8mMkj'], ['pragma', 'no-cache'], ['cache-control', 'no-cache'], ['sec-websocket-extensions', 'permessage-deflate; client_max_window_bits']] and here is on aws [['origin', 'http://myapp.us-west-2.elasticbeanstalk.com'], ['upgrade', 'websocket'], ['accept-language', 'en-US,en;q=0.8,ar;q=0.6'], ['accept-encoding', 'gzip, deflate, sdch'], ['sec-websocket-version', '13'], ['host', '54.200.16.66:5000'], ['sec-websocket-key', 'TIhxYnLG3uVVJVZY8ne7ag=='], ['user-agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'], ['dnt', '1'], ['connection', 'Upgrade'], ['pragma', 'no-cache'], ['cache-control', 'no-cache'], ['sec-websocket-extensions', 'permessage-deflate; client_max_window_bits']] you will notice that there is no cookie data in returned aws -
How to dynamically update a number of clicks on elements in Django with jQuery and Ajax?
I'm trying to dynamically count a number of clicks on elements. Each click should update a Django model and do it on the fly. My current code does update a Model, but it is only displayed after page reload. My Models: class Item(models.Model): name = models.CharField(max_length=48, default='Item') category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True) manufacturer = models.ForeignKey('Manufacturer', on_delete=models.SET_NULL, null=True) item_image = models.ForeignKey('ItemImage', on_delete=models.SET_NULL, null=True, blank=True) description = models.TextField(max_length=500, help_text='Enter a description of an item', blank=True, null=True) number_of_clicks = models.PositiveIntegerField(default=0) def __str__(self): return "{} by {}".format(self.category, self.manufacturer) # def add_click(self): # self.number_of_clicks += 1 class Meta: ordering = ["-number_of_clicks"] My View: @csrf_exempt def clickCount(request): if request.is_ajax(): item_id = request.POST.get('item_id') item = Item.objects.get(id=item_id) item.number_of_clicks = F("number_of_clicks") + 1 item.save() clicks = item.refresh_from_db() response = serializers.serialize('json', clicks, fields=('click')) return HttpResponse(response, mimetype='application/json') My Template: {% load static %} <div class="row align-items-center click-container" style="padding-bottom: 10px;" data-item-id="{{ item.id }}"> <div class="col-6 mx-auto text-center item-div"> <div class="image-div"> <img src="{{ item.item_image.image.url }}" class="img-responsive" alt='Image of an Item'> </div> <h4>{{ item.category.category }} {{ item.name }}</h4> <p> {{ item.description|truncatechars_html:70 }} </p> <p class="clicks-number">Number of clicks: {{ item.number_of_clicks }}</p> </div> My Script File: $('.click-container').on("click",function(){ let item = $(this).attr("data-item-id"); let $a_children = $(this).children(); let $count_container = $a_children.find(".clicks-number"); $.ajax( { url: '/items/click-count/', type: 'POST', data:{item_id: … -
In django, how can I construct a method that gives the sum of subclasses
My problem is essentially this. I have a class (lets say runners) and a subclass (say with leaptimes or something, for different leaps). Now I want a variable in the class that is the total sum of leaptimes. Basically: class Runner(model.Model): .... def total_time(self): return self.????.annotate(Sum('leap__time')) class Leap(model.Model): runner = ForeignKey('Runner',...) time = models.FloatField(default=0) The ??? is there to demonstrate that this is the kind of thing I want. Is it possible to achieve this along these lines, and is it then possible to define a new function within the class Runner which uses total_time? -
limit_choices_to *like* for model in existing database
I'd like to configure my model in order that when I make a request to my database whatever where from my code, the request include some filter like the option limit_choices_to for the foreignKeyField. Is there a way to achieve that simply ? The fact is I'm using an existing database and I don't need to get all the object which a particular value and it's a bit borring to set the filter foreach request. -
How to resolve KeyError in django etherpad-lite implementation
Recently, I have been trying to integrate the etherpad-lite written for node, with Django. For this, I found django-etherpad-lite- another repo on GitHub . Using the two repos, I tried to implement etherpad using django. Note the django version is too old - 1.3 And python - 2.7 My code runs fine on my device but it gives a KeyError ('sessionID') when the etherpad's pad is opened on some other device. Let me elaborate what I mean: Let's say I have two computers A and B connected to a common wifi C. Now to test for collaborative editing, I ran the django server and the node application on A's localhost. Then I tried to run the same on B using A's ip address and the port. The application was running fine but when I opened a new pad, I received a KeyError . The image of the error is attached below: IMAGE The error and traceback KeyError at /etherpad/2/ 'sessionID' Request Method: GET Request URL: http://10.196.21.186:8000/etherpad/2/ Django Version: 1.3 Exception Type: KeyError Exception Value:'sessionID' Exception Location: /home/aadarsh/Desktop/Etherpad/etherpadproject/etherpadlite/views.py in pad, line 226 Traceback: File "/home/aadarsh/Desktop/Etherpad/venv/local/lib/python2.7/site- packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args,**callback_kwargs) File "/home/aadarsh/Desktop/Etherpad/venv/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, … -
Django redirect to view for processing and then to outputView
I'am currently working on a webapp in Django. On my submittion page ('submission.html' with 'SubmissionView'), users can submit some data and select some checkboxes. This all gets processed (this can take some time) and then a output table is shown in 'output.html' (with 'OutputView'). What I would like to get is when the form is submitted, the user gets redirected to a 'process.html' page (with 'ProcessView') where a dummy progress bar with javascript will be visible, just to let the user know how long it is going to take to process the data. When everything is processed and the results are available the user gets automatically redirected to 'output.html' where the result table will be visible. So far I managed to redirect all the input from request.POST from the SubmissionView to the ProcessView, everything gets processed and again redirected to the OutputView. BUT! When submitting the form, it just stays on the submission.html page (with loading bar underneath the url) and when everything is process then the output is shown in output.html. The process.html page never shows. I can't find how to first show the process.html page, in the background run the analysis (in my ProcessView) and when it's done … -
factory_boy: passing model instances for a RelatedFactory
I figured instead of passing data to a factory's RelatedFactory in the form of ATTR__SUBATTR, you should also be able to just directly pass already existing instances. Unless I'm missing something very obvious, this just doesn't seem to work. Have a look: class Owner(models.Model): name = models.CharField() class Item(models.Model): name = models.CharField() owner = models.ForeignKey(Owner, null = True, related_name = 'items') class ItemFactory(factory.django.DjangoModelFactory): class Meta: model = Item class OwnerFactory(factory.django.DjangoModelFactory): class Meta: model = Owner items = factory.RelatedFactory(ItemFactory, 'owner') item = Item.objects.create(name='Foo') alice = OwnerFactory(name='Alice', items__name='Bar') alice.items.all() <QuerySet [<Item: Bar>]> bob = OwnerFactory(name='Bob', items=item) # or items = [item] doesn't matter bob.items.all() <QuerySet []> Been working on making my factories nice and DRY and hit this roadblock. Wrote my own adaption of RelatedFactory that allows for multiple values to be handled at once, which works fine if you are creating new objects in the process - but not if you are using already existing ones. Example that works: OwnerFactory(items__name=['Foo','Bar'])=> Foo and Bar in owner.items. Example that does not work: OwnerFactory(items=[foo,bar])=> owner.items is empty Note that I have used the default RelatedFactory in the big example at the top. I have been all over the documentation for factory_boy the entire day, … -
Validating dynamically created ModelForm field in Django 2
I am using Django 2.0 and I have a model for Articles and a model for Storylines. A storyline contains many related articles. class Article(models.Model): headline_text = models.CharField(max_length=255, verbose_name='Headline') storylines = models.ManyToManyField(Storyline, verbose_name='Add to Storylines') I have a ModelForm that will allow you to choose an article to add to the Storyline. That ModelForm class looks like this: class StorylineAddArticleForm(forms.Form): articleSearchBox = forms.CharField(label="Search to narrow list below:") include_articles = [article.id for article in Article.objects.order_by('-sub_date')[:5]] articles = forms.ModelMultipleChoiceField(queryset=Article.objects.filter(id__in=include_articles).order_by('-sub_date')) def __init__(self, *args, **kwargs): super(StorylineAddArticleForm, self).__init__(*args, **kwargs) self.fields['articleSearchBox'].required = False self.helper = FormHelper(self) self.helper.layout = Layout( Field('articleSearchBox'), Field('articles'), ButtonHolder( Submit('submit', 'Add', css_class='button white') ) ) So far so good, if I submit any article in the queryset, the form validates and saves as needed. The live site will have many more articles than will be practical to display in the ModelMultipleChoice field, so I do some JQuery to allow the user to use articleSearchBox to replace the ModelMultipleChoice field. This works brilliantly and you can do a search for any article, including those not in the original queryset. Here's that: {% block content %} <h2>Add Article</h2> Add an existing article to <strong>{{ storyline.headline_text }}</strong> storyline:<br> Did you want to add <a href="{% url … -
Django : rendering a TemplateView in another
Using Django, I have multiple template files (A, B and C) that could be rendered in the same TemplateView called GenericView. A, B and C use the same View (let's call it DynamicView), therefore I need to call the rendering method of this DynamicView from GenericView's get_context_data. Is there a way I can render easily DynamicView's template within GenericView's template? EDIT : I am using class based view coding -
how to make my first Item from my form as default in my select field
I'm trying to get my select item to have a default value and with it get rid of this ------ in my select item but I can't use a default in my model because I'm overriding the field like this def __init__(self,researcher, *args,**kwargs): super (ProjectForm,self ).__init__(*args,**kwargs) # populates the post self.fields['ubc'].queryset = Ubc.objects.filter(researcher=researcher) I need the default to be the first item in my filter Is it possible ? thanks