Haystack login required - django-haystack

I am using Haystack default URLConf to setup the views. As such:
(r'^search/', include('haystack.urls')),
How would I wrap it in a login_required decorator, since I only want logged in users to access the search. Thank you.

in root urls.py add
from django.contrib.auth.decorators import login_required
from haystack.views import basic_search
and change:
url(r'search/*', include(haystack.urls)),
to the following line:
url(r'search/$', login_required(basic_search), name='basic_search'),

You can't wrap a URL inclusion with the login_required decorator.
What you should do is either add some middleware for just that URL path or explicitly add your search view. The default urls.py configuration only defines one URL:
from django.conf.urls.defaults import *
from haystack.views import SearchView
urlpatterns = patterns('haystack.views',
url(r'^$', SearchView(), name='haystack_search'),
)
So in your own URLs configuration you could import the SearchView (probably a good idea if you want to configure at all) and then wrap that view. In your own urls.py:
urlpatterns = patterns('haystack.views',
url(r'^$', login_required(SearchView()), name='haystack_search'),
)

Related

Can you instantiate another `BrowserRouter` inside a `BrowserRouter` based App?

Background: I am trying to use sweetalert2-react-content to let me put a react <Link> inside a Sweetalert2 footer.
Generally speaking sweetalert2-react-content is supposed to let you place react JSX into its fields, like this:
MySwal.fire({
text: "Fire fire",
footer: <div>Call the firebrigade</div>
});
... and indeed that sort of thing does work.
However, putting a <Link> there does not work: it renders empty.
In this issue resolution message the the advice is "wrap your element in BrowserRouter like this:
MySwal.fire({
html: (
<BrowserRouter>
...
</BrowserRouter>
),
})
Is this "legitimate"? What does it "mean" to have a BrowserRouter inside an app that is routed using BrowserRouter already?
No, it is an invariant violation to nest a router within another router. I think your situation is not a case of invalid nesting, but more to do with where sweetalert is rendering the React JSX. From what I recall of sweetalert it renders content outside the ReactTree.
You can certainly render more than one router, so long as they are not nested, but then the issue is that you've separate routing contexts that each individually handle routing/navigation, and navigating within one routing context doesn't update the others.
I suspect you could use a single custom history reference and pass these to the routers you need, so they all reference the same history context internally.
react-router-dom#6 exports a HistoryRouter for this purpose.
Example:
import { createBrowserHistory } from "history";
const history = createBrowserHistory({ window });
export default history;
...
import * as React from "react";
import * as ReactDOM from "react-dom";
import { unstable_HistoryRouter as HistoryRouter } from "react-router-dom";
import history from "../path/to/history";
ReactDOM.render(
<HistoryRouter history={history}>
{/* The rest of your app goes here */}
</HistoryRouter>,
root
);
...
import { unstable_HistoryRouter as HistoryRouter } from "react-router-dom";
import history from "../path/to/history";
MySwal.fire({
html: (
<HistoryRouter history={history}>
...
</HistoryRouter>
),
})
Note about unstable_HistoryRouter:
This API is currently prefixed as unstable_ because you may
unintentionally add two versions of the history library to your app,
the one you have added to your package.json and whatever version React
Router uses internally. If it is allowed by your tooling, it's
recommended to not add history as a direct dependency and instead rely
on the nested dependency from the react-router package. Once we have a
mechanism to detect mis-matched versions, this API will remove its
unstable_ prefix.
No, this is wrong and will usually throw an error.
What you would like to do is to render it like this:
<UNSAFE_LocationContext.Provider value={null as any}>
<BrowserRouter>
...
</BrowserRouter>
</UNSAFE_LocationContext.Provider>

How to import new dynamic module in service?

I have dynamic module with params. I use params in his service.
How to import this module in service another module.
If I use this, I must add all parameters and another services, which I use there.
const serviceDynamicModule = new ServiceDynamicModule(param, service, ...);
I have found ModuleRef, but it doesn't contain this functionality.
You can import your module in another module by listing module you want to import to import section of another module's #module decorator.
Here is a explanation on Modules and dynamic module please check that out for more detail explanation. Nest_docs#dynamicModule
eg:-
lets say you want to import your dynamic module here.
import {Module} from '#nestjs/common';
#Module(
import:[yourDynamicModule.forRoot(neededParams)]
)
export calss MyModule{}

How to access user details in all pages in django?

After login I want to access User details when ever I want (Particularly in navigation bar).
I did not use user model provided in django. I created my own model like this for authentication.
My database is stored in mysql on phpmyadmin(Xampp).
AdminUser Model
class adminUser(models.Model):
username=models.CharField(max_length=50)
firstname=models.CharField(max_length=50)
department=models.CharField(max_length=50)
name=models.CharField(max_length=50)
mail=models.CharField(max_length=50)
id=models.IntegerField(primary_key=True)
password=models.CharField(max_length=200)
class Meta:
db_table="admin_users"
admin_users.py
def login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username is not None and password is not None:
user=adminUser.objects.get(username=username)
hashed_password = user.password
is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8'))
print(is_check)
if is_check==True:
return redirect(reverse('faq_index'))
else:
return render(request,'AdminUsers/login.html')
return render(request,'AdminUsers/login.html')
During the login User Details can be only access by login function but I want to access user details in all pages for navigation bar and also want to find out whether user is authenticated or not. As I am not using User Model defined in django so I can not use user.is_authenticated(). So How do I do this?
First, inherit your user model from AbstractBaseUser. It gives you some features like is_authenticated, set_password and etc
Then define your custom user model as AUTH_USER_MODEL in your settings.py
After these, django treats to your custom user as its default user
models.py
from django.contrib.auth.base_user import AbstractBaseUser
class CustomUser(AbstractBaseUser):
...
settings.py
AUTH_USER_MODEL = 'myapp.MyUser'
Docs in https://docs.djangoproject.com/en/3.2/topics/auth/customizing/
I'm gonna recommend you take a step back, and extend the built-in User model instead of creating your own.
As mentioned by #Amin, you can extend the AbstractBaseUser class to create a custom User model, and override the AUTH_USER_MODEL in settings.py.
However, you can easily add a Profile model that has a one-to-one relationship with the built-in User model that does not require any overrides (which method is better escapes me at the moment, but I use the following method without issue):
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
UserModel = get_user_model()
class Profile(models.Model):
user = models.OneToOneField(UserModel, on_delete=models.CASCADE)
# add your desired fields here
department=models.CharField(max_length=50)
Then, in the same folder as contains your models.py, create a file called signals.py, and add the following code:
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Profile
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_user_settings(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
This will trigger the creation of a new Profile object whenever a User object is created.
Then, add the following to the same folder's apps.py (Assuming the app's name is users... make it match the name of the app that contains your Profile model):
from django.apps import AppConfig
class UsersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'users'
def ready(self):
import users.signals
Now, after you run your migrations, you will be able to use the built-in User model, and add additional fields to it as desired in the Profile model.
The only downside is that it will require a little extra work if you want to modify the User model and the Profile model on the same page (ie. you won't just be able to specify the model name in an UpdateView).
I don't remember where I found this method. I believe it was adapted from this page on simpleisbetterthancomplex.com, but I'm not 100% sure.
At any rate, Django automatically creates a primary key id for you, so you probably don't need to manually define that in your model.

Django viewflow: not receiving flow_finished signal

I'm trying to catch the flow_finished signal from django viewflow like this
flow_finished.connect(function)
but it's not working. The function isn't called even if the flow finishes.
Any help please, I'm pretty lost.
In my app's init.py I added this
from django.apps import AppConfig
default_app_config = 'test.TestConfig'
class TestConfig(AppConfig):
name = 'test'
verbose_name = 'Test'
def ready(self):
import viewflow.signals
First, you need to ensure that you properly configured you app config, and the ready method really been called. Check your installed apps that you properly included your TestConfig, or if you use shortcuts, check you test/__init__.py default_app_config value
from viewflow.signals import flow_finished
def receiver(sender, **kwargs):
print('hi')
class TestConfig(AppConfig):
name = 'test'
def ready(self):
flow_finished.connect(receiver)
But generally, using signals to weave your codebase is a bad taste. To call an action before flow.End you can explicitly add flow.Handler. That's the recommended solution.

How to import node module in Angular?

I'm developing an Angular app.
For some reason I want to use querystring.escape().
I wrote import { escape } from 'querystring', but I got querystring.escape is not a function error.
How can I import a node module in typescript?
You are destructuring querystring trying to get the escape property, but then you want to call querystring.escape() which you haven't imported.
What you want to do is this:
import * as querystring from 'querystring';
or
import querystring from 'querystring'

Resources