I am using pycharm for a django project. I made an app named 'music' and there I created a model named 'Album'.
Inside Views I am using a for loop to get to the details stored in the database like this
all_albums = Album.objects.all()
for album in all_albums:
album.artist
however when I type album. I don't get autocomplete suggestions for artist or anything else that I have defined in that class.
How to make pycharm include my own modules in the autocomplete?
One way, using docstrings:
for each in qs:
payment = each
"""#type : Payment """
print payment.deadline
Another way, using assert:
for each in qs:
assert isinstance(each, Payment)
print each.deadline
You can Google 'pycharm type hinting' or similar to find out more.
Related
I am using Django oscar(2.0.2), where I have made foreign key relation of merchant ids with product table AbstractProduct with data, (https://prnt.sc/s1ssxx) so that I can fetch merchant-specific products from the database. By default oscar returns all the products in the search results, I want to only return the products specific to a merchant's site.
I am using Haystack simple search as suggested in oscar documentation, I have tried overriding the search app like all other apps, I have overridden the search_indexes.py file, but it seems that it never gets called from the FacetedSearchView. I also tried to override the search handlers, but it was also not getting called.
I tried understanding oscar's search functionality, but on the shell, I get a warning,
UserWarning: The model is not registered for search.
warnings.warn('The model %r is not registered for search.' % (model,))
Model '' not handled by the routers. Model class oscar_apps.catalogue.models.Product not handled by the routers.
How can I register the Product model for search?
where will I have to override the query like that:
Product.objects.filter(user_id=1), to return only merchant-specific products while searching for a product?
I know, how to override apps, but could someone give an overview and explain to me the steps that will be required to override the search app, and get the basic sorting functionality working?
if my question is not clear, let me know in the comments so I can improve it.
#yajant, I'm not sure whether my answer might be useful to you, but I have faced the same issue and struggled to find out the solution. Hope this might help someone facing the same issue. Thanks
fork the search app and import oscar search and overwrite FacetedSearchView class get_results method as below
Override the get_results method in your forked search/views.py
def get_results(self):
# We're only interested in products (there might be other contenttypes
# in the Solr index).
qs = super().get_results().models(Product)
qs = qs.filter(user_id=1)
return qs
I'm building a website with Django. I have a main title for the website in my header template, currently hard-coded in it.
How can I make it editable in the admin by the website administrator (or any user with the right credentials) ? Ideally I'd also like to be able to make more such site-wide (or app-wide) attributes editable in the admin (such as site - or app- description, for instance).
I have in mind something like WordPress' bloginfo() . A practical example of this is washingtonpost.com who changed their moto in their header to "Democracy dies in darkness" a few weeks ago.
Of course once the title (or any other attribute) has been edited in the admin I need to be able to get it from within my template.
You can create a simple model to store dynamic website parameters like this for example:
class WebsiteParam(models.Model):
key = models.CharField(max_length=50)
val = models.CharField(max_length=1024)
Then define custom template context processor settings_processor.py
def settings_processor(request):
vals = {x.key: v.val for x in WebsiteParam.objects.all()}
return {'website_settings': vals}
Add this processor into your django settings.py something like:
from django.conf import global_settings
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
"myapp.settings_processor.settings_processor",
)
And you will be able to use your settings in all of your templates like
<html><head><title>{{website_settings.title}}</title>...
if you have settings with title key added into the database
You should of course add caching into request context processor and other conditions if necessary
I think my question is pretty clear:
I am interested in finding out some ways of using model (DB) data without creating views.
I have already created a website using djangocms and now I would like to develop a little blog.
I am aware of this project but this is not as straight forward as I'd need ( it is pretty complex for my purpose ).
For example, in the first place, I would like to know if there's any possibility to create a basic template in which I will be able to display the users(their names) directly from the database.
In Django, you basically can't get data from a model to a template without a view that puts it there. That's the whole point of views.
You don't necessarily have to create a views.py file, because there might be other mechanisms that you can make use of, such as django CMS's plugin system.
I don't understand what connection your question has to developing a weblog though.
What you can do is create a context processor which essentially is a function which returns a dictionary & it's added to every request context.
For example, I have a model which provides information for the site as a whole, like social links, a name etc. Take a look;
from django.contrib.sites.models import get_current_site
from .models import SiteSettings
def site_settings(request):
current_site = get_current_site(request)
try:
settings = SiteSettings.objects.get(site_id=current_site.id)
except SiteSettings.MultipleObjectsReturned:
settings = SiteSettings.objects.filter(
site_id=current_site.id
).order_by('id')[0]
except SiteSettings.DoesNotExist:
return {
'SITE_SITE_NAME': None,
'SITE_SHORT_NAME': None,
}
# SiteSettings object exists, so assign the attributes you want, to context
# variables returned by the context processor for all views.
data = {
'SITE_SITE_NAME': settings.site_name,
'SITE_SHORT_NAME': settings.short_name,
}
return data
So by doing that you can use things like {{ SITE_SHORT_NAME }} in any template, and this obviously makes any information you hold in a table available via one of these processors. Just make sure you create necessary DoesNotExist exceptions when doing this with models.
I'm trying to find some documentation of how to use the ForeignKeyRawIdWidget in my own forms. Currently I keep getting the error, "init() takes at least 2 non-keyword arguments (1 given)" which tells me nothing.
Any help would be most appreciated. Googling this turns up little but dev conversations and no examples that I can find of how to implement it.
Update: This is solved; see solution below.
As of the Django 1.5, this works to reuse the ForeignKeyRawIdWidget in non-admin forms.
from django.contrib.admin.sites import site
class InvoiceForm(ModelForm):
class Meta:
model = Invoice
widgets = {
'customer': ForeignKeyRawIdWidget(Invoice._meta.get_field('customer').rel, site),
}
Update
Django 2.0 is deprecating field.rel in favor of field.remote_field. You might want to use this instead (also works on Django 1.11):
...
ForeignKeyRawIdWidget(Invoice._meta.get_field('customer').remote_field, site),
...
This is from the source code (django.contrib.admin.widgets):
class ForeignKeyRawIdWidget(forms.TextInput):
"""
A Widget for displaying ForeignKeys in the "raw_id" interface rather than
in a <select> box.
"""
def __init__(self, rel, attrs=None):
self.rel = rel
super(ForeignKeyRawIdWidget, self).__init__(attrs)
#.....
From the remaining code, I would guess that rel is the foreign key field of your model. At one point, the code checks self.rel.limit_choices_to, and this attribute (limit_choices_to) can only be set on a ForgeinKey field.
In my usual django code I use the unicode function to give each object a label...this appears in the admin interface as the oject label in the objects listed...
class apprd(models.Model):
usr = models.ReferenceProperty(User)
approved = models.BooleanProperty(default = True)
def __unicode__(self):
return ('approved one')
but now i have moved to GAE and this feature does not seem to be supported...
is there any work around or am I doin a mistake
This isn't possible in GAE, because the GAE admin console does not read - indeed, has no access to - your model definitions. It only has access to the stored data.
If you use http://code.google.com/p/app-engine-patch/, you can get the full Django admin interface running inside GAE.